Return if we changed anything or not.
[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/Function.h"
17 #include "llvm/Instructions.h"
18 #include "llvm/IntrinsicInst.h"
19 #include "llvm/Module.h"
20 #include "llvm/Pass.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/Analysis/Dominators.h"
23 #include "llvm/CodeGen/Passes.h"
24 #include "llvm/MC/MCAsmInfo.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 DwarfEHPrepare : public FunctionPass {
37     const TargetLowering *TLI;
38     bool CompileFast;
39
40     // The eh.exception intrinsic.
41     Function *ExceptionValueIntrinsic;
42
43     // The eh.selector intrinsic.
44     Function *SelectorIntrinsic;
45
46     // _Unwind_Resume_or_Rethrow call.
47     Constant *URoR;
48
49     // The EH language-specific catch-all type.
50     GlobalVariable *EHCatchAllValue;
51
52     // _Unwind_Resume or the target equivalent.
53     Constant *RewindFunction;
54
55     // Dominator info is used when turning stack temporaries into registers.
56     DominatorTree *DT;
57     DominanceFrontier *DF;
58
59     // The function we are running on.
60     Function *F;
61
62     // The landing pads for this function.
63     typedef SmallPtrSet<BasicBlock*, 8> BBSet;
64     BBSet LandingPads;
65
66     // Stack temporary used to hold eh.exception values.
67     AllocaInst *ExceptionValueVar;
68
69     bool NormalizeLandingPads();
70     bool LowerUnwinds();
71     bool MoveExceptionValueCalls();
72     bool FinishStackTemporaries();
73     bool PromoteStackTemporaries();
74
75     Instruction *CreateExceptionValueCall(BasicBlock *BB);
76     Instruction *CreateValueLoad(BasicBlock *BB);
77
78     /// CreateReadOfExceptionValue - Return the result of the eh.exception
79     /// intrinsic by calling the intrinsic if in a landing pad, or loading it
80     /// from the exception value variable otherwise.
81     Instruction *CreateReadOfExceptionValue(BasicBlock *BB) {
82       return LandingPads.count(BB) ?
83         CreateExceptionValueCall(BB) : CreateValueLoad(BB);
84     }
85
86     /// CleanupSelectors - Any remaining eh.selector intrinsic calls which still
87     /// use the ".llvm.eh.catch.all.value" call need to convert to using it's
88     /// initializer instead.
89     bool CleanupSelectors();
90
91     /// HandleURoRInvokes - Handle invokes of "_Unwind_Resume_or_Rethrow"
92     /// calls. The "unwind" part of these invokes jump to a landing pad within
93     /// the current function. This is a candidate to merge the selector
94     /// associated with the URoR invoke with the one from the URoR's landing
95     /// pad.
96     bool HandleURoRInvokes();
97
98     /// FindSelectorAndURoR - Find the eh.selector call and URoR call associated
99     /// with the eh.exception call. This recursively looks past instructions
100     /// which don't change the EH pointer value, like casts or PHI nodes.
101     bool FindSelectorAndURoR(Instruction *Inst, bool &URoRInvoke,
102                              SmallPtrSet<IntrinsicInst*, 8> &SelCalls);
103       
104     /// DoMem2RegPromotion - Take an alloca call and promote it from memory to a
105     /// register.
106     bool DoMem2RegPromotion(Value *V) {
107       AllocaInst *AI = dyn_cast<AllocaInst>(V);
108       if (!AI || !isAllocaPromotable(AI)) return false;
109
110       // Turn the alloca into a register.
111       std::vector<AllocaInst*> Allocas(1, AI);
112       PromoteMemToReg(Allocas, *DT, *DF);
113       return true;
114     }
115
116     /// PromoteStoreInst - Perform Mem2Reg on a StoreInst.
117     bool PromoteStoreInst(StoreInst *SI) {
118       if (!SI || !DT || !DF) return false;
119       if (DoMem2RegPromotion(SI->getOperand(1)))
120         return true;
121       return false;
122     }
123
124     /// PromoteEHPtrStore - Promote the storing of an EH pointer into a
125     /// register. This should get rid of the store and subsequent loads.
126     bool PromoteEHPtrStore(IntrinsicInst *II) {
127       if (!DT || !DF) return false;
128
129       bool Changed = false;
130       StoreInst *SI;
131
132       while (1) {
133         SI = 0;
134         for (Value::use_iterator
135                I = II->use_begin(), E = II->use_end(); I != E; ++I) {
136           SI = dyn_cast<StoreInst>(I);
137           if (SI) break;
138         }
139
140         if (!PromoteStoreInst(SI))
141           break;
142
143         Changed = true;
144       }
145
146       return false;
147     }
148
149   public:
150     static char ID; // Pass identification, replacement for typeid.
151     DwarfEHPrepare(const TargetLowering *tli, bool fast) :
152       FunctionPass(&ID), TLI(tli), CompileFast(fast),
153       ExceptionValueIntrinsic(0), SelectorIntrinsic(0),
154       URoR(0), EHCatchAllValue(0), RewindFunction(0) {}
155
156     virtual bool runOnFunction(Function &Fn);
157
158     // getAnalysisUsage - We need dominance frontiers for memory promotion.
159     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
160       if (!CompileFast)
161         AU.addRequired<DominatorTree>();
162       AU.addPreserved<DominatorTree>();
163       if (!CompileFast)
164         AU.addRequired<DominanceFrontier>();
165       AU.addPreserved<DominanceFrontier>();
166     }
167
168     const char *getPassName() const {
169       return "Exception handling preparation";
170     }
171
172   };
173 } // end anonymous namespace
174
175 char DwarfEHPrepare::ID = 0;
176
177 FunctionPass *llvm::createDwarfEHPass(const TargetLowering *tli, bool fast) {
178   return new DwarfEHPrepare(tli, fast);
179 }
180
181 /// FindSelectorAndURoR - Find the eh.selector call associated with the
182 /// eh.exception call. And indicate if there is a URoR "invoke" associated with
183 /// the eh.exception call. This recursively looks past instructions which don't
184 /// change the EH pointer value, like casts or PHI nodes.
185 bool
186 DwarfEHPrepare::FindSelectorAndURoR(Instruction *Inst, bool &URoRInvoke,
187                                     SmallPtrSet<IntrinsicInst*, 8> &SelCalls) {
188   SmallPtrSet<PHINode*, 32> SeenPHIs;
189   bool Changed = false;
190
191  restart:
192   for (Value::use_iterator
193          I = Inst->use_begin(), E = Inst->use_end(); I != E; ++I) {
194     Instruction *II = dyn_cast<Instruction>(I);
195     if (!II || II->getParent()->getParent() != F) continue;
196     
197     if (IntrinsicInst *Sel = dyn_cast<IntrinsicInst>(II)) {
198       if (Sel->getIntrinsicID() == Intrinsic::eh_selector)
199         SelCalls.insert(Sel);
200     } else if (InvokeInst *Invoke = dyn_cast<InvokeInst>(II)) {
201       if (Invoke->getCalledFunction() == URoR)
202         URoRInvoke = true;
203     } else if (CastInst *CI = dyn_cast<CastInst>(II)) {
204       Changed |= FindSelectorAndURoR(CI, URoRInvoke, SelCalls);
205     } else if (StoreInst *SI = dyn_cast<StoreInst>(II)) {
206       if (!PromoteStoreInst(SI)) continue;
207       Changed = true;
208       SeenPHIs.clear();
209       goto restart;             // Uses may have changed, restart loop.
210     } else if (PHINode *PN = dyn_cast<PHINode>(II)) {
211       if (SeenPHIs.insert(PN))
212         // Don't process a PHI node more than once.
213         Changed |= FindSelectorAndURoR(PN, URoRInvoke, SelCalls);
214     }
215   }
216
217   return Changed;
218 }
219
220 /// CleanupSelectors - Any remaining eh.selector intrinsic calls which still use
221 /// the ".llvm.eh.catch.all.value" call need to convert to using it's
222 /// initializer instead.
223 bool DwarfEHPrepare::CleanupSelectors() {
224   bool Changed = false;
225   for (Value::use_iterator
226          I = SelectorIntrinsic->use_begin(),
227          E = SelectorIntrinsic->use_end(); I != E; ++I) {
228     IntrinsicInst *Sel = dyn_cast<IntrinsicInst>(I);
229     if (!Sel || Sel->getParent()->getParent() != F) continue;
230
231     // Index of the ".llvm.eh.catch.all.value" variable.
232     unsigned OpIdx = Sel->getNumOperands() - 1;
233     GlobalVariable *GV = dyn_cast<GlobalVariable>(Sel->getOperand(OpIdx));
234     if (GV != EHCatchAllValue) continue;
235     Sel->setOperand(OpIdx, EHCatchAllValue->getInitializer());
236     Changed = true;
237   }
238
239   return Changed;
240 }
241
242 /// HandleURoRInvokes - Handle invokes of "_Unwind_Resume_or_Rethrow" calls. The
243 /// "unwind" part of these invokes jump to a landing pad within the current
244 /// function. This is a candidate to merge the selector associated with the URoR
245 /// invoke with the one from the URoR's landing pad.
246 bool DwarfEHPrepare::HandleURoRInvokes() {
247   if (!EHCatchAllValue) {
248     EHCatchAllValue =
249       F->getParent()->getNamedGlobal(".llvm.eh.catch.all.value");
250     if (!EHCatchAllValue) return false;
251   }
252
253   if (!SelectorIntrinsic) {
254     SelectorIntrinsic =
255       Intrinsic::getDeclaration(F->getParent(), Intrinsic::eh_selector);
256     if (!SelectorIntrinsic) return false;
257   }
258
259   if (!URoR) {
260     URoR = F->getParent()->getFunction("_Unwind_Resume_or_Rethrow");
261     if (!URoR) return CleanupSelectors();
262   }
263
264   if (!ExceptionValueIntrinsic) {
265     ExceptionValueIntrinsic =
266       Intrinsic::getDeclaration(F->getParent(), Intrinsic::eh_exception);
267     if (!ExceptionValueIntrinsic) return CleanupSelectors();
268   }
269
270   bool Changed = false;
271   SmallPtrSet<IntrinsicInst*, 32> SelsToConvert;
272
273   for (Value::use_iterator
274          I = ExceptionValueIntrinsic->use_begin(),
275          E = ExceptionValueIntrinsic->use_end(); I != E; ++I) {
276     IntrinsicInst *EHPtr = dyn_cast<IntrinsicInst>(I);
277     if (!EHPtr || EHPtr->getParent()->getParent() != F) continue;
278
279     Changed |= PromoteEHPtrStore(EHPtr);
280
281     bool URoRInvoke = false;
282     SmallPtrSet<IntrinsicInst*, 8> SelCalls;
283     Changed |= FindSelectorAndURoR(EHPtr, URoRInvoke, SelCalls);
284
285     if (URoRInvoke) {
286       // This EH pointer is being used by an invoke of an URoR instruction and
287       // an eh.selector intrinsic call. If the eh.selector is a 'clean-up', we
288       // need to convert it to a 'catch-all'.
289       for (SmallPtrSet<IntrinsicInst*, 8>::iterator
290              SI = SelCalls.begin(), SE = SelCalls.end(); SI != SE; ++SI) {
291         IntrinsicInst *II = *SI;
292         unsigned NumOps = II->getNumOperands();
293
294         if (NumOps <= 4) {
295           bool IsCleanUp = (NumOps == 3);
296
297           if (!IsCleanUp)
298             if (ConstantInt *CI = dyn_cast<ConstantInt>(II->getOperand(3)))
299               IsCleanUp = (CI->getZExtValue() == 0);
300
301           if (IsCleanUp)
302             SelsToConvert.insert(II);
303         }
304       }
305     }
306   }
307
308   if (!SelsToConvert.empty()) {
309     // Convert all clean-up eh.selectors, which are associated with "invokes" of
310     // URoR calls, into catch-all eh.selectors.
311     Changed = true;
312
313     for (SmallPtrSet<IntrinsicInst*, 8>::iterator
314            SI = SelsToConvert.begin(), SE = SelsToConvert.end();
315          SI != SE; ++SI) {
316       IntrinsicInst *II = *SI;
317       SmallVector<Value*, 8> Args;
318
319       // Use the exception object pointer and the personality function
320       // from the original selector.
321       Args.push_back(II->getOperand(1)); // Exception object pointer.
322       Args.push_back(II->getOperand(2)); // Personality function.
323       Args.push_back(EHCatchAllValue->getInitializer()); // Catch-all indicator.
324
325       CallInst *NewSelector =
326         CallInst::Create(SelectorIntrinsic, Args.begin(), Args.end(),
327                          "eh.sel.catch.all", II);
328
329       NewSelector->setTailCall(II->isTailCall());
330       NewSelector->setAttributes(II->getAttributes());
331       NewSelector->setCallingConv(II->getCallingConv());
332
333       II->replaceAllUsesWith(NewSelector);
334       II->eraseFromParent();
335     }
336   }
337
338   Changed |= CleanupSelectors();
339   return Changed;
340 }
341
342 /// NormalizeLandingPads - Normalize and discover landing pads, noting them
343 /// in the LandingPads set.  A landing pad is normal if the only CFG edges
344 /// that end at it are unwind edges from invoke instructions. If we inlined
345 /// through an invoke we could have a normal branch from the previous
346 /// unwind block through to the landing pad for the original invoke.
347 /// Abnormal landing pads are fixed up by redirecting all unwind edges to
348 /// a new basic block which falls through to the original.
349 bool DwarfEHPrepare::NormalizeLandingPads() {
350   bool Changed = false;
351
352   const MCAsmInfo *MAI = TLI->getTargetMachine().getMCAsmInfo();
353   bool usingSjLjEH = MAI->getExceptionHandlingType() == ExceptionHandling::SjLj;
354
355   for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
356     TerminatorInst *TI = I->getTerminator();
357     if (!isa<InvokeInst>(TI))
358       continue;
359     BasicBlock *LPad = TI->getSuccessor(1);
360     // Skip landing pads that have already been normalized.
361     if (LandingPads.count(LPad))
362       continue;
363
364     // Check that only invoke unwind edges end at the landing pad.
365     bool OnlyUnwoundTo = true;
366     bool SwitchOK = usingSjLjEH;
367     for (pred_iterator PI = pred_begin(LPad), PE = pred_end(LPad);
368          PI != PE; ++PI) {
369       TerminatorInst *PT = (*PI)->getTerminator();
370       // The SjLj dispatch block uses a switch instruction. This is effectively
371       // an unwind edge, so we can disregard it here. There will only ever
372       // be one dispatch, however, so if there are multiple switches, one
373       // of them truly is a normal edge, not an unwind edge.
374       if (SwitchOK && isa<SwitchInst>(PT)) {
375         SwitchOK = false;
376         continue;
377       }
378       if (!isa<InvokeInst>(PT) || LPad == PT->getSuccessor(0)) {
379         OnlyUnwoundTo = false;
380         break;
381       }
382     }
383
384     if (OnlyUnwoundTo) {
385       // Only unwind edges lead to the landing pad.  Remember the landing pad.
386       LandingPads.insert(LPad);
387       continue;
388     }
389
390     // At least one normal edge ends at the landing pad.  Redirect the unwind
391     // edges to a new basic block which falls through into this one.
392
393     // Create the new basic block.
394     BasicBlock *NewBB = BasicBlock::Create(F->getContext(),
395                                            LPad->getName() + "_unwind_edge");
396
397     // Insert it into the function right before the original landing pad.
398     LPad->getParent()->getBasicBlockList().insert(LPad, NewBB);
399
400     // Redirect unwind edges from the original landing pad to NewBB.
401     for (pred_iterator PI = pred_begin(LPad), PE = pred_end(LPad); PI != PE; ) {
402       TerminatorInst *PT = (*PI++)->getTerminator();
403       if (isa<InvokeInst>(PT) && PT->getSuccessor(1) == LPad)
404         // Unwind to the new block.
405         PT->setSuccessor(1, NewBB);
406     }
407
408     // If there are any PHI nodes in LPad, we need to update them so that they
409     // merge incoming values from NewBB instead.
410     for (BasicBlock::iterator II = LPad->begin(); isa<PHINode>(II); ++II) {
411       PHINode *PN = cast<PHINode>(II);
412       pred_iterator PB = pred_begin(NewBB), PE = pred_end(NewBB);
413
414       // Check to see if all of the values coming in via unwind edges are the
415       // same.  If so, we don't need to create a new PHI node.
416       Value *InVal = PN->getIncomingValueForBlock(*PB);
417       for (pred_iterator PI = PB; PI != PE; ++PI) {
418         if (PI != PB && InVal != PN->getIncomingValueForBlock(*PI)) {
419           InVal = 0;
420           break;
421         }
422       }
423
424       if (InVal == 0) {
425         // Different unwind edges have different values.  Create a new PHI node
426         // in NewBB.
427         PHINode *NewPN = PHINode::Create(PN->getType(), PN->getName()+".unwind",
428                                          NewBB);
429         // Add an entry for each unwind edge, using the value from the old PHI.
430         for (pred_iterator PI = PB; PI != PE; ++PI)
431           NewPN->addIncoming(PN->getIncomingValueForBlock(*PI), *PI);
432
433         // Now use this new PHI as the common incoming value for NewBB in PN.
434         InVal = NewPN;
435       }
436
437       // Revector exactly one entry in the PHI node to come from NewBB
438       // and delete all other entries that come from unwind edges.  If
439       // there are both normal and unwind edges from the same predecessor,
440       // this leaves an entry for the normal edge.
441       for (pred_iterator PI = PB; PI != PE; ++PI)
442         PN->removeIncomingValue(*PI);
443       PN->addIncoming(InVal, NewBB);
444     }
445
446     // Add a fallthrough from NewBB to the original landing pad.
447     BranchInst::Create(LPad, NewBB);
448
449     // Now update DominatorTree and DominanceFrontier analysis information.
450     if (DT)
451       DT->splitBlock(NewBB);
452     if (DF)
453       DF->splitBlock(NewBB);
454
455     // Remember the newly constructed landing pad.  The original landing pad
456     // LPad is no longer a landing pad now that all unwind edges have been
457     // revectored to NewBB.
458     LandingPads.insert(NewBB);
459     ++NumLandingPadsSplit;
460     Changed = true;
461   }
462
463   return Changed;
464 }
465
466 /// LowerUnwinds - Turn unwind instructions into calls to _Unwind_Resume,
467 /// rethrowing any previously caught exception.  This will crash horribly
468 /// at runtime if there is no such exception: using unwind to throw a new
469 /// exception is currently not supported.
470 bool DwarfEHPrepare::LowerUnwinds() {
471   SmallVector<TerminatorInst*, 16> UnwindInsts;
472
473   for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
474     TerminatorInst *TI = I->getTerminator();
475     if (isa<UnwindInst>(TI))
476       UnwindInsts.push_back(TI);
477   }
478
479   if (UnwindInsts.empty()) return false;
480
481   // Find the rewind function if we didn't already.
482   if (!RewindFunction) {
483     LLVMContext &Ctx = UnwindInsts[0]->getContext();
484     std::vector<const Type*>
485       Params(1, Type::getInt8PtrTy(Ctx));
486     FunctionType *FTy = FunctionType::get(Type::getVoidTy(Ctx),
487                                           Params, false);
488     const char *RewindName = TLI->getLibcallName(RTLIB::UNWIND_RESUME);
489     RewindFunction = F->getParent()->getOrInsertFunction(RewindName, FTy);
490   }
491
492   bool Changed = false;
493
494   for (SmallVectorImpl<TerminatorInst*>::iterator
495          I = UnwindInsts.begin(), E = UnwindInsts.end(); I != E; ++I) {
496     TerminatorInst *TI = *I;
497
498     // Replace the unwind instruction with a call to _Unwind_Resume (or the
499     // appropriate target equivalent) followed by an UnreachableInst.
500
501     // Create the call...
502     CallInst *CI = CallInst::Create(RewindFunction,
503                                     CreateReadOfExceptionValue(TI->getParent()),
504                                     "", TI);
505     CI->setCallingConv(TLI->getLibcallCallingConv(RTLIB::UNWIND_RESUME));
506     // ...followed by an UnreachableInst.
507     new UnreachableInst(TI->getContext(), TI);
508
509     // Nuke the unwind instruction.
510     TI->eraseFromParent();
511     ++NumUnwindsLowered;
512     Changed = true;
513   }
514
515   return Changed;
516 }
517
518 /// MoveExceptionValueCalls - Ensure that eh.exception is only ever called from
519 /// landing pads by replacing calls outside of landing pads with loads from a
520 /// stack temporary.  Move eh.exception calls inside landing pads to the start
521 /// of the landing pad (optional, but may make things simpler for later passes).
522 bool DwarfEHPrepare::MoveExceptionValueCalls() {
523   // If the eh.exception intrinsic is not declared in the module then there is
524   // nothing to do.  Speed up compilation by checking for this common case.
525   if (!ExceptionValueIntrinsic &&
526       !F->getParent()->getFunction(Intrinsic::getName(Intrinsic::eh_exception)))
527     return false;
528
529   bool Changed = false;
530
531   for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
532     for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E;)
533       if (IntrinsicInst *CI = dyn_cast<IntrinsicInst>(II++))
534         if (CI->getIntrinsicID() == Intrinsic::eh_exception) {
535           if (!CI->use_empty()) {
536             Value *ExceptionValue = CreateReadOfExceptionValue(BB);
537             if (CI == ExceptionValue) {
538               // The call was at the start of a landing pad - leave it alone.
539               assert(LandingPads.count(BB) &&
540                      "Created eh.exception call outside landing pad!");
541               continue;
542             }
543             CI->replaceAllUsesWith(ExceptionValue);
544           }
545           CI->eraseFromParent();
546           ++NumExceptionValuesMoved;
547           Changed = true;
548         }
549   }
550
551   return Changed;
552 }
553
554 /// FinishStackTemporaries - If we introduced a stack variable to hold the
555 /// exception value then initialize it in each landing pad.
556 bool DwarfEHPrepare::FinishStackTemporaries() {
557   if (!ExceptionValueVar)
558     // Nothing to do.
559     return false;
560
561   bool Changed = false;
562
563   // Make sure that there is a store of the exception value at the start of
564   // each landing pad.
565   for (BBSet::iterator LI = LandingPads.begin(), LE = LandingPads.end();
566        LI != LE; ++LI) {
567     Instruction *ExceptionValue = CreateReadOfExceptionValue(*LI);
568     Instruction *Store = new StoreInst(ExceptionValue, ExceptionValueVar);
569     Store->insertAfter(ExceptionValue);
570     Changed = true;
571   }
572
573   return Changed;
574 }
575
576 /// PromoteStackTemporaries - Turn any stack temporaries we introduced into
577 /// registers if possible.
578 bool DwarfEHPrepare::PromoteStackTemporaries() {
579   if (ExceptionValueVar && DT && DF && isAllocaPromotable(ExceptionValueVar)) {
580     // Turn the exception temporary into registers and phi nodes if possible.
581     std::vector<AllocaInst*> Allocas(1, ExceptionValueVar);
582     PromoteMemToReg(Allocas, *DT, *DF);
583     return true;
584   }
585   return false;
586 }
587
588 /// CreateExceptionValueCall - Insert a call to the eh.exception intrinsic at
589 /// the start of the basic block (unless there already is one, in which case
590 /// the existing call is returned).
591 Instruction *DwarfEHPrepare::CreateExceptionValueCall(BasicBlock *BB) {
592   Instruction *Start = BB->getFirstNonPHI();
593   // Is this a call to eh.exception?
594   if (IntrinsicInst *CI = dyn_cast<IntrinsicInst>(Start))
595     if (CI->getIntrinsicID() == Intrinsic::eh_exception)
596       // Reuse the existing call.
597       return Start;
598
599   // Find the eh.exception intrinsic if we didn't already.
600   if (!ExceptionValueIntrinsic)
601     ExceptionValueIntrinsic = Intrinsic::getDeclaration(F->getParent(),
602                                                        Intrinsic::eh_exception);
603
604   // Create the call.
605   return CallInst::Create(ExceptionValueIntrinsic, "eh.value.call", Start);
606 }
607
608 /// CreateValueLoad - Insert a load of the exception value stack variable
609 /// (creating it if necessary) at the start of the basic block (unless
610 /// there already is a load, in which case the existing load is returned).
611 Instruction *DwarfEHPrepare::CreateValueLoad(BasicBlock *BB) {
612   Instruction *Start = BB->getFirstNonPHI();
613   // Is this a load of the exception temporary?
614   if (ExceptionValueVar)
615     if (LoadInst* LI = dyn_cast<LoadInst>(Start))
616       if (LI->getPointerOperand() == ExceptionValueVar)
617         // Reuse the existing load.
618         return Start;
619
620   // Create the temporary if we didn't already.
621   if (!ExceptionValueVar) {
622     ExceptionValueVar = new AllocaInst(PointerType::getUnqual(
623            Type::getInt8Ty(BB->getContext())), "eh.value", F->begin()->begin());
624     ++NumStackTempsIntroduced;
625   }
626
627   // Load the value.
628   return new LoadInst(ExceptionValueVar, "eh.value.load", Start);
629 }
630
631 bool DwarfEHPrepare::runOnFunction(Function &Fn) {
632   bool Changed = false;
633
634   // Initialize internal state.
635   DT = getAnalysisIfAvailable<DominatorTree>();
636   DF = getAnalysisIfAvailable<DominanceFrontier>();
637   ExceptionValueVar = 0;
638   F = &Fn;
639
640   // Ensure that only unwind edges end at landing pads (a landing pad is a
641   // basic block where an invoke unwind edge ends).
642   Changed |= NormalizeLandingPads();
643
644   // Turn unwind instructions into libcalls.
645   Changed |= LowerUnwinds();
646
647   // TODO: Move eh.selector calls to landing pads and combine them.
648
649   // Move eh.exception calls to landing pads.
650   Changed |= MoveExceptionValueCalls();
651
652   // Initialize any stack temporaries we introduced.
653   Changed |= FinishStackTemporaries();
654
655   // Turn any stack temporaries into registers if possible.
656   if (!CompileFast)
657     Changed |= PromoteStackTemporaries();
658
659   Changed |= HandleURoRInvokes();
660
661   LandingPads.clear();
662
663   return Changed;
664 }