Expand on comment.
[oota-llvm.git] / lib / CodeGen / DwarfEHPrepare.cpp
1 //===-- DwarfEHPrepare - Prepare exception handling for code generation ---===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass mulches exception handling code into a form adapted to code
11 // generation.  Required if using dwarf exception handling.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "dwarfehprepare"
16 #include "llvm/ADT/Statistic.h"
17 #include "llvm/Analysis/Dominators.h"
18 #include "llvm/CodeGen/Passes.h"
19 #include "llvm/Function.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/IntrinsicInst.h"
22 #include "llvm/Module.h"
23 #include "llvm/Pass.h"
24 #include "llvm/Support/Compiler.h"
25 #include "llvm/Target/TargetLowering.h"
26 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
27 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
28 using namespace llvm;
29
30 STATISTIC(NumLandingPadsSplit,     "Number of landing pads split");
31 STATISTIC(NumUnwindsLowered,       "Number of unwind instructions lowered");
32 STATISTIC(NumExceptionValuesMoved, "Number of eh.exception calls moved");
33 STATISTIC(NumStackTempsIntroduced, "Number of stack temporaries introduced");
34
35 namespace {
36   class VISIBILITY_HIDDEN DwarfEHPrepare : public FunctionPass {
37     const TargetLowering *TLI;
38     bool CompileFast;
39
40     // The eh.exception intrinsic.
41     Function *ExceptionValueIntrinsic;
42
43     // _Unwind_Resume or the target equivalent.
44     Constant *RewindFunction;
45
46     // Dominator info is used when turning stack temporaries into registers.
47     DominatorTree *DT;
48     DominanceFrontier *DF;
49
50     // The function we are running on.
51     Function *F;
52
53     // The landing pads for this function.
54     typedef SmallPtrSet<BasicBlock*, 8> BBSet;
55     BBSet LandingPads;
56
57     // Stack temporary used to hold eh.exception values.
58     AllocaInst *ExceptionValueVar;
59
60     bool NormalizeLandingPads();
61     bool LowerUnwinds();
62     bool MoveExceptionValueCalls();
63     bool FinishStackTemporaries();
64     bool PromoteStackTemporaries();
65
66     Instruction *CreateExceptionValueCall(BasicBlock *BB);
67     Instruction *CreateValueLoad(BasicBlock *BB);
68
69     /// CreateReadOfExceptionValue - Return the result of the eh.exception
70     /// intrinsic by calling the intrinsic if in a landing pad, or loading
71     /// it from the exception value variable otherwise.
72     Instruction *CreateReadOfExceptionValue(BasicBlock *BB) {
73       return LandingPads.count(BB) ?
74         CreateExceptionValueCall(BB) : CreateValueLoad(BB);
75     }
76
77   public:
78     static char ID; // Pass identification, replacement for typeid.
79     DwarfEHPrepare(const TargetLowering *tli, bool fast) :
80       FunctionPass(&ID), TLI(tli), CompileFast(fast),
81       ExceptionValueIntrinsic(0), RewindFunction(0) {}
82
83     virtual bool runOnFunction(Function &Fn);
84
85     // getAnalysisUsage - We need dominance frontiers for memory promotion.
86     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
87       if (!CompileFast)
88         AU.addRequired<DominatorTree>();
89       AU.addPreserved<DominatorTree>();
90       if (!CompileFast)
91         AU.addRequired<DominanceFrontier>();
92       AU.addPreserved<DominanceFrontier>();
93     }
94
95     const char *getPassName() const {
96       return "Exception handling preparation";
97     }
98
99   };
100 } // end anonymous namespace
101
102 char DwarfEHPrepare::ID = 0;
103
104 FunctionPass *llvm::createDwarfEHPass(const TargetLowering *tli, bool fast) {
105   return new DwarfEHPrepare(tli, fast);
106 }
107
108 /// NormalizeLandingPads - Normalize and discover landing pads, noting them
109 /// in the LandingPads set.  A landing pad is normal if the only CFG edges
110 /// that end at it are unwind edges from invoke instructions. If we inlined
111 /// through an invoke we could have a normal branch from the previous
112 /// unwind block through to the landing pad for the original invoke.
113 /// Abnormal landing pads are fixed up by redirecting all unwind edges to
114 /// a new basic block which falls through to the original.
115 bool DwarfEHPrepare::NormalizeLandingPads() {
116   bool Changed = false;
117
118   for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
119     TerminatorInst *TI = I->getTerminator();
120     if (!isa<InvokeInst>(TI))
121       continue;
122     BasicBlock *LPad = TI->getSuccessor(1);
123     // Skip landing pads that have already been normalized.
124     if (LandingPads.count(LPad))
125       continue;
126
127     // Check that only invoke unwind edges end at the landing pad.
128     bool OnlyUnwoundTo = true;
129     for (pred_iterator PI = pred_begin(LPad), PE = pred_end(LPad);
130          PI != PE; ++PI) {
131       TerminatorInst *PT = (*PI)->getTerminator();
132       if (!isa<InvokeInst>(PT) || LPad == PT->getSuccessor(0)) {
133         OnlyUnwoundTo = false;
134         break;
135       }
136     }
137     
138     if (OnlyUnwoundTo) {
139       // Only unwind edges lead to the landing pad.  Remember the landing pad.
140       LandingPads.insert(LPad);
141       continue;
142     }
143
144     // At least one normal edge ends at the landing pad.  Redirect the unwind
145     // edges to a new basic block which falls through into this one.
146
147     // Create the new basic block.
148     BasicBlock *NewBB = BasicBlock::Create(F->getContext(),
149                                            LPad->getName() + "_unwind_edge");
150
151     // Insert it into the function right before the original landing pad.
152     LPad->getParent()->getBasicBlockList().insert(LPad, NewBB);
153
154     // Redirect unwind edges from the original landing pad to NewBB.
155     for (pred_iterator PI = pred_begin(LPad), PE = pred_end(LPad); PI != PE; ) {
156       TerminatorInst *PT = (*PI++)->getTerminator();
157       if (isa<InvokeInst>(PT) && PT->getSuccessor(1) == LPad)
158         // Unwind to the new block.
159         PT->setSuccessor(1, NewBB);
160     }
161
162     // If there are any PHI nodes in LPad, we need to update them so that they
163     // merge incoming values from NewBB instead.
164     for (BasicBlock::iterator II = LPad->begin(); isa<PHINode>(II); ++II) {
165       PHINode *PN = cast<PHINode>(II);
166       pred_iterator PB = pred_begin(NewBB), PE = pred_end(NewBB);
167
168       // Check to see if all of the values coming in via unwind edges are the
169       // same.  If so, we don't need to create a new PHI node.
170       Value *InVal = PN->getIncomingValueForBlock(*PB);
171       for (pred_iterator PI = PB; PI != PE; ++PI) {
172         if (PI != PB && InVal != PN->getIncomingValueForBlock(*PI)) {
173           InVal = 0;
174           break;
175         }
176       }
177
178       if (InVal == 0) {
179         // Different unwind edges have different values.  Create a new PHI node
180         // in NewBB.
181         PHINode *NewPN = PHINode::Create(PN->getType(), PN->getName()+".unwind",
182                                          NewBB);
183         // Add an entry for each unwind edge, using the value from the old PHI.
184         for (pred_iterator PI = PB; PI != PE; ++PI)
185           NewPN->addIncoming(PN->getIncomingValueForBlock(*PI), *PI);
186
187         // Now use this new PHI as the common incoming value for NewBB in PN.
188         InVal = NewPN;
189       }
190
191       // Revector exactly one entry in the PHI node to come from NewBB
192       // and delete all other entries that come from unwind edges.  If
193       // there are both normal and unwind edges from the same predecessor,
194       // this leaves an entry for the normal edge.
195       for (pred_iterator PI = PB; PI != PE; ++PI)
196         PN->removeIncomingValue(*PI);
197       PN->addIncoming(InVal, NewBB);
198     }
199
200     // Add a fallthrough from NewBB to the original landing pad.
201     BranchInst::Create(LPad, NewBB);
202
203     // Now update DominatorTree and DominanceFrontier analysis information.
204     if (DT)
205       DT->splitBlock(NewBB);
206     if (DF)
207       DF->splitBlock(NewBB);
208
209     // Remember the newly constructed landing pad.  The original landing pad
210     // LPad is no longer a landing pad now that all unwind edges have been
211     // revectored to NewBB.
212     LandingPads.insert(NewBB);
213     ++NumLandingPadsSplit;
214     Changed = true;
215   }
216
217   return Changed;
218 }
219
220 /// LowerUnwinds - Turn unwind instructions into calls to _Unwind_Resume,
221 /// rethrowing any previously caught exception.  This will crash horribly
222 /// at runtime if there is no such exception: using unwind to throw a new
223 /// exception is currently not supported.
224 bool DwarfEHPrepare::LowerUnwinds() {
225   SmallVector<TerminatorInst*, 16> UnwindInsts;
226
227   for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
228     TerminatorInst *TI = I->getTerminator();
229     if (isa<UnwindInst>(TI))
230       UnwindInsts.push_back(TI);
231   }
232
233   if (UnwindInsts.empty()) return false;
234
235   // Find the rewind function if we didn't already.
236   if (!RewindFunction) {
237     LLVMContext &Ctx = UnwindInsts[0]->getContext();
238     std::vector<const Type*>
239       Params(1, PointerType::getUnqual(Type::getInt8Ty(Ctx)));
240     FunctionType *FTy = FunctionType::get(Type::getVoidTy(Ctx),
241                                           Params, false);
242     const char *RewindName = TLI->getLibcallName(RTLIB::UNWIND_RESUME);
243     RewindFunction = F->getParent()->getOrInsertFunction(RewindName, FTy);
244   }
245
246   bool Changed = false;
247
248   for (SmallVectorImpl<TerminatorInst*>::iterator
249          I = UnwindInsts.begin(), E = UnwindInsts.end(); I != E; ++I) {
250     TerminatorInst *TI = *I;
251
252     // Replace the unwind instruction with a call to _Unwind_Resume (or the
253     // appropriate target equivalent) followed by an UnreachableInst.
254
255     // Create the call...
256     CallInst *CI = CallInst::Create(RewindFunction,
257                                     CreateReadOfExceptionValue(TI->getParent()),
258                                     "", TI);
259     CI->setCallingConv(TLI->getLibcallCallingConv(RTLIB::UNWIND_RESUME));
260     // ...followed by an UnreachableInst.
261     new UnreachableInst(TI->getContext(), TI);
262
263     // Nuke the unwind instruction.
264     TI->eraseFromParent();
265     ++NumUnwindsLowered;
266     Changed = true;
267   }
268
269   return Changed;
270 }
271
272 /// MoveExceptionValueCalls - Ensure that eh.exception is only ever called from
273 /// landing pads by replacing calls outside of landing pads with loads from a
274 /// stack temporary.  Move eh.exception calls inside landing pads to the start
275 /// of the landing pad (optional, but may make things simpler for later passes).
276 bool DwarfEHPrepare::MoveExceptionValueCalls() {
277   // If the eh.exception intrinsic is not declared in the module then there is
278   // nothing to do.  Speed up compilation by checking for this common case.
279   if (!ExceptionValueIntrinsic &&
280       !F->getParent()->getFunction(Intrinsic::getName(Intrinsic::eh_exception)))
281     return false;
282
283   bool Changed = false;
284
285   for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
286     for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E;)
287       if (IntrinsicInst *CI = dyn_cast<IntrinsicInst>(II++))
288         if (CI->getIntrinsicID() == Intrinsic::eh_exception) {
289           if (!CI->use_empty()) {
290             Value *ExceptionValue = CreateReadOfExceptionValue(BB);
291             if (CI == ExceptionValue) {
292               // The call was at the start of a landing pad - leave it alone.
293               assert(LandingPads.count(BB) &&
294                      "Created eh.exception call outside landing pad!");
295               continue;
296             }
297             CI->replaceAllUsesWith(ExceptionValue);
298           }
299           CI->eraseFromParent();
300           ++NumExceptionValuesMoved;
301           Changed = true;
302         }
303   }
304
305   return Changed;
306 }
307
308 /// FinishStackTemporaries - If we introduced a stack variable to hold the
309 /// exception value then initialize it in each landing pad.
310 bool DwarfEHPrepare::FinishStackTemporaries() {
311   if (!ExceptionValueVar)
312     // Nothing to do.
313     return false;
314
315   bool Changed = false;
316
317   // Make sure that there is a store of the exception value at the start of
318   // each landing pad.
319   for (BBSet::iterator LI = LandingPads.begin(), LE = LandingPads.end();
320        LI != LE; ++LI) {
321     Instruction *ExceptionValue = CreateReadOfExceptionValue(*LI);
322     Instruction *Store = new StoreInst(ExceptionValue, ExceptionValueVar);
323     Store->insertAfter(ExceptionValue);
324     Changed = true;
325   }
326
327   return Changed;
328 }
329
330 /// PromoteStackTemporaries - Turn any stack temporaries we introduced into
331 /// registers if possible.
332 bool DwarfEHPrepare::PromoteStackTemporaries() {
333   if (ExceptionValueVar && DT && DF && isAllocaPromotable(ExceptionValueVar)) {
334     // Turn the exception temporary into registers and phi nodes if possible.
335     std::vector<AllocaInst*> Allocas(1, ExceptionValueVar);
336     PromoteMemToReg(Allocas, *DT, *DF, ExceptionValueVar->getContext());
337     return true;
338   }
339   return false;
340 }
341
342 /// CreateExceptionValueCall - Insert a call to the eh.exception intrinsic at
343 /// the start of the basic block (unless there already is one, in which case
344 /// the existing call is returned).
345 Instruction *DwarfEHPrepare::CreateExceptionValueCall(BasicBlock *BB) {
346   Instruction *Start = BB->getFirstNonPHI();
347   // Is this a call to eh.exception?
348   if (IntrinsicInst *CI = dyn_cast<IntrinsicInst>(Start))
349     if (CI->getIntrinsicID() == Intrinsic::eh_exception)
350       // Reuse the existing call.
351       return Start;
352
353   // Find the eh.exception intrinsic if we didn't already.
354   if (!ExceptionValueIntrinsic)
355     ExceptionValueIntrinsic = Intrinsic::getDeclaration(F->getParent(),
356                                                        Intrinsic::eh_exception);
357
358   // Create the call.
359   return CallInst::Create(ExceptionValueIntrinsic, "eh.value.call", Start);
360 }
361
362 /// CreateValueLoad - Insert a load of the exception value stack variable
363 /// (creating it if necessary) at the start of the basic block (unless
364 /// there already is a load, in which case the existing load is returned).
365 Instruction *DwarfEHPrepare::CreateValueLoad(BasicBlock *BB) {
366   Instruction *Start = BB->getFirstNonPHI();
367   // Is this a load of the exception temporary?
368   if (ExceptionValueVar)
369     if (LoadInst* LI = dyn_cast<LoadInst>(Start))
370       if (LI->getPointerOperand() == ExceptionValueVar)
371         // Reuse the existing load.
372         return Start;
373
374   // Create the temporary if we didn't already.
375   if (!ExceptionValueVar) {
376     ExceptionValueVar = new AllocaInst(PointerType::getUnqual(
377            Type::getInt8Ty(BB->getContext())), "eh.value", F->begin()->begin());
378     ++NumStackTempsIntroduced;
379   }
380
381   // Load the value.
382   return new LoadInst(ExceptionValueVar, "eh.value.load", Start);
383 }
384
385 bool DwarfEHPrepare::runOnFunction(Function &Fn) {
386   bool Changed = false;
387
388   // Initialize internal state.
389   DT = getAnalysisIfAvailable<DominatorTree>();
390   DF = getAnalysisIfAvailable<DominanceFrontier>();
391   ExceptionValueVar = 0;
392   F = &Fn;
393
394   // Ensure that only unwind edges end at landing pads (a landing pad is a
395   // basic block where an invoke unwind edge ends).
396   Changed |= NormalizeLandingPads();
397
398   // Turn unwind instructions into libcalls.
399   Changed |= LowerUnwinds();
400
401   // TODO: Move eh.selector calls to landing pads and combine them.
402
403   // Move eh.exception calls to landing pads.
404   Changed |= MoveExceptionValueCalls();
405
406   // Initialize any stack temporaries we introduced.
407   Changed |= FinishStackTemporaries();
408
409   // Turn any stack temporaries into registers if possible.
410   if (!CompileFast)
411     Changed |= PromoteStackTemporaries();
412
413   LandingPads.clear();
414
415   return Changed;
416 }