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