@@ -191,6 +191,46 @@ pipeline.
191
191
192
192
Please refer to the document “High-Level SIL Optimizations” for more details.
193
193
194
+
195
+ ### Instruction Invalidation in SIL
196
+
197
+ Swift Passes and Analysis often keep instruction pointers in internal data
198
+ structures such as Map or Set. A good example of such data structure is a list
199
+ of visited instructions, or a map between a SILValue and the memory aliasing
200
+ effects of the value.
201
+
202
+ Passes and utilities delete instructions in many different places in the
203
+ optimizer. When instructions are deleted pointers that are saved inside maps in
204
+ the different data structures become invalid. These pointers point to
205
+ deallocated memory locations. In some cases malloc allocates new instructions
206
+ with the same address as the freed instruction. Instruction reallocation bugs
207
+ are often difficult to detect because hash maps return values that are logically
208
+ incorrect.
209
+
210
+ LLVM handles this problem by keeping ValueHandles, which are a kind of smart
211
+ pointers that handle instruction deletion and replaceAllUsesWith events.
212
+ ValueHandles are special uses of llvm values. One problem with this approach is
213
+ that value handles require additional memory per-value and require doing extra
214
+ work when working with values.
215
+
216
+ The Swift optimizer approach is to let the Context (currently a part of the
217
+ SILModule) handle the invalidation of instructions. When instructions are
218
+ deleted the context notifies a list of listeners. The invalidation mechanism is
219
+ relatively efficient and incur a cost only when instructions are deleted. Every
220
+ time an instruction is deleted the context notifies all of the listeners that
221
+ requested to be notified. A typical notifications list is very short and is made
222
+ of the registered Analysis and the currently executed Pass.
223
+
224
+ Passes and Analysis are registered by the PassManager to receive instruction
225
+ deletion notifications. Passes and Analysis simply need to implement the
226
+ following virtual method:
227
+
228
+ ```
229
+ virtual void handleNotification(swift::ValueBase *Value) override {
230
+ llvm::errs()<<"SILCombine Deleting: " << Value<<"\n";
231
+ }
232
+ ```
233
+
194
234
### Debugging the optimizer
195
235
196
236
TODO.
0 commit comments