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