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