the various ConstantExpr::get*Ty methods existed to work with issues around
[llvm/stm8.git] / lib / CodeGen / DwarfEHPrepare.cpp
blob22c5465bf9fa0678b05b2d8380736743836a899c
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.
13 //===----------------------------------------------------------------------===//
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;
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");
36 namespace {
37 class DwarfEHPrepare : public FunctionPass {
38 const TargetMachine *TM;
39 const TargetLowering *TLI;
41 // The eh.exception intrinsic.
42 Function *ExceptionValueIntrinsic;
44 // The eh.selector intrinsic.
45 Function *SelectorIntrinsic;
47 // _Unwind_Resume_or_Rethrow or _Unwind_SjLj_Resume call.
48 Constant *URoR;
50 // The EH language-specific catch-all type.
51 GlobalVariable *EHCatchAllValue;
53 // _Unwind_Resume or the target equivalent.
54 Constant *RewindFunction;
56 // We both use and preserve dominator info.
57 DominatorTree *DT;
59 // The function we are running on.
60 Function *F;
62 // The landing pads for this function.
63 typedef SmallPtrSet<BasicBlock*, 8> BBSet;
64 BBSet LandingPads;
66 bool NormalizeLandingPads();
67 bool LowerUnwindsAndResumes();
68 bool MoveExceptionValueCalls();
70 Instruction *CreateExceptionValueCall(BasicBlock *BB);
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);
77 bool HasCatchAllInSelector(IntrinsicInst *);
79 /// FindAllCleanupSelectors - Find all eh.selector calls that are clean-ups.
80 void FindAllCleanupSelectors(SmallPtrSet<IntrinsicInst*, 32> &Sels,
81 SmallPtrSet<IntrinsicInst*, 32> &CatchAllSels);
83 /// FindAllURoRInvokes - Find all URoR invokes in the function.
84 void FindAllURoRInvokes(SmallPtrSet<InvokeInst*, 32> &URoRInvokes);
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();
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);
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());
109 virtual bool runOnFunction(Function &Fn);
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>();
117 const char *getPassName() const {
118 return "Exception handling preparation";
122 } // end anonymous namespace
124 char DwarfEHPrepare::ID = 0;
126 FunctionPass *llvm::createDwarfEHPass(const TargetMachine *tm) {
127 return new DwarfEHPrepare(tm);
130 /// HasCatchAllInSelector - Return true if the intrinsic instruction has a
131 /// catch-all.
132 bool DwarfEHPrepare::HasCatchAllInSelector(IntrinsicInst *II) {
133 if (!EHCatchAllValue) return false;
135 unsigned ArgIdx = II->getNumArgOperands() - 1;
136 GlobalVariable *GV = dyn_cast<GlobalVariable>(II->getArgOperand(ArgIdx));
137 return GV == EHCatchAllValue;
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);
149 if (II->getParent()->getParent() != F)
150 continue;
152 if (!HasCatchAllInSelector(II))
153 Sels.insert(II);
154 else
155 CatchAllSels.insert(II);
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);
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;
176 if (!SelectorIntrinsic) {
177 SelectorIntrinsic =
178 Intrinsic::getDeclaration(F->getParent(), Intrinsic::eh_selector);
179 if (!SelectorIntrinsic) return false;
182 bool Changed = false;
183 for (SmallPtrSet<IntrinsicInst*, 32>::iterator
184 I = Sels.begin(), E = Sels.end(); I != E; ++I) {
185 IntrinsicInst *Sel = *I;
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;
195 return Changed;
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;
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;
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);
228 return Changed;
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;
243 if (!SelectorIntrinsic) {
244 SelectorIntrinsic =
245 Intrinsic::getDeclaration(F->getParent(), Intrinsic::eh_selector);
246 if (!SelectorIntrinsic) return false;
249 SmallPtrSet<IntrinsicInst*, 32> Sels;
250 SmallPtrSet<IntrinsicInst*, 32> CatchAllSels;
251 FindAllCleanupSelectors(Sels, CatchAllSels);
253 if (!URoR) {
254 URoR = F->getParent()->getFunction("_Unwind_Resume_or_Rethrow");
255 if (!URoR) return CleanupSelectors(CatchAllSels);
258 SmallPtrSet<InvokeInst*, 32> URoRInvokes;
259 FindAllURoRInvokes(URoRInvokes);
261 SmallPtrSet<IntrinsicInst*, 32> SelsToConvert;
263 for (SmallPtrSet<IntrinsicInst*, 32>::iterator
264 SI = Sels.begin(), SE = Sels.end(); SI != SE; ++SI) {
265 const BasicBlock *SelBB = (*SI)->getParent();
266 for (SmallPtrSet<InvokeInst*, 32>::iterator
267 UI = URoRInvokes.begin(), UE = URoRInvokes.end(); UI != UE; ++UI) {
268 const BasicBlock *URoRBB = (*UI)->getParent();
269 if (DT->dominates(SelBB, URoRBB)) {
270 SelsToConvert.insert(*SI);
271 break;
276 bool Changed = false;
278 if (Sels.size() != SelsToConvert.size()) {
279 // If we haven't been able to convert all of the clean-up selectors, then
280 // loop through the slow way to see if they still need to be converted.
281 if (!ExceptionValueIntrinsic) {
282 ExceptionValueIntrinsic =
283 Intrinsic::getDeclaration(F->getParent(), Intrinsic::eh_exception);
284 if (!ExceptionValueIntrinsic)
285 return CleanupSelectors(CatchAllSels);
288 for (Value::use_iterator
289 I = ExceptionValueIntrinsic->use_begin(),
290 E = ExceptionValueIntrinsic->use_end(); I != E; ++I) {
291 IntrinsicInst *EHPtr = dyn_cast<IntrinsicInst>(*I);
292 if (!EHPtr || EHPtr->getParent()->getParent() != F) continue;
294 bool URoRInvoke = false;
295 SmallPtrSet<IntrinsicInst*, 8> SelCalls;
296 SmallPtrSet<PHINode*, 32> SeenPHIs;
297 Changed |= FindSelectorAndURoR(EHPtr, URoRInvoke, SelCalls, SeenPHIs);
299 if (URoRInvoke) {
300 // This EH pointer is being used by an invoke of an URoR instruction and
301 // an eh.selector intrinsic call. If the eh.selector is a 'clean-up', we
302 // need to convert it to a 'catch-all'.
303 for (SmallPtrSet<IntrinsicInst*, 8>::iterator
304 SI = SelCalls.begin(), SE = SelCalls.end(); SI != SE; ++SI)
305 if (!HasCatchAllInSelector(*SI))
306 SelsToConvert.insert(*SI);
311 if (!SelsToConvert.empty()) {
312 // Convert all clean-up eh.selectors, which are associated with "invokes" of
313 // URoR calls, into catch-all eh.selectors.
314 Changed = true;
316 for (SmallPtrSet<IntrinsicInst*, 8>::iterator
317 SI = SelsToConvert.begin(), SE = SelsToConvert.end();
318 SI != SE; ++SI) {
319 IntrinsicInst *II = *SI;
321 // Use the exception object pointer and the personality function
322 // from the original selector.
323 CallSite CS(II);
324 IntrinsicInst::op_iterator I = CS.arg_begin();
325 IntrinsicInst::op_iterator E = CS.arg_end();
326 IntrinsicInst::op_iterator B = prior(E);
328 // Exclude last argument if it is an integer.
329 if (isa<ConstantInt>(B)) E = B;
331 // Add exception object pointer (front).
332 // Add personality function (next).
333 // Add in any filter IDs (rest).
334 SmallVector<Value*, 8> Args(I, E);
336 Args.push_back(EHCatchAllValue->getInitializer()); // Catch-all indicator.
338 CallInst *NewSelector =
339 CallInst::Create(SelectorIntrinsic, Args.begin(), Args.end(),
340 "eh.sel.catch.all", II);
342 NewSelector->setTailCall(II->isTailCall());
343 NewSelector->setAttributes(II->getAttributes());
344 NewSelector->setCallingConv(II->getCallingConv());
346 II->replaceAllUsesWith(NewSelector);
347 II->eraseFromParent();
351 Changed |= CleanupSelectors(CatchAllSels);
352 return Changed;
355 /// NormalizeLandingPads - Normalize and discover landing pads, noting them
356 /// in the LandingPads set. A landing pad is normal if the only CFG edges
357 /// that end at it are unwind edges from invoke instructions. If we inlined
358 /// through an invoke we could have a normal branch from the previous
359 /// unwind block through to the landing pad for the original invoke.
360 /// Abnormal landing pads are fixed up by redirecting all unwind edges to
361 /// a new basic block which falls through to the original.
362 bool DwarfEHPrepare::NormalizeLandingPads() {
363 bool Changed = false;
365 const MCAsmInfo *MAI = TM->getMCAsmInfo();
366 bool usingSjLjEH = MAI->getExceptionHandlingType() == ExceptionHandling::SjLj;
368 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
369 TerminatorInst *TI = I->getTerminator();
370 if (!isa<InvokeInst>(TI))
371 continue;
372 BasicBlock *LPad = TI->getSuccessor(1);
373 // Skip landing pads that have already been normalized.
374 if (LandingPads.count(LPad))
375 continue;
377 // Check that only invoke unwind edges end at the landing pad.
378 bool OnlyUnwoundTo = true;
379 bool SwitchOK = usingSjLjEH;
380 for (pred_iterator PI = pred_begin(LPad), PE = pred_end(LPad);
381 PI != PE; ++PI) {
382 TerminatorInst *PT = (*PI)->getTerminator();
383 // The SjLj dispatch block uses a switch instruction. This is effectively
384 // an unwind edge, so we can disregard it here. There will only ever
385 // be one dispatch, however, so if there are multiple switches, one
386 // of them truly is a normal edge, not an unwind edge.
387 if (SwitchOK && isa<SwitchInst>(PT)) {
388 SwitchOK = false;
389 continue;
391 if (!isa<InvokeInst>(PT) || LPad == PT->getSuccessor(0)) {
392 OnlyUnwoundTo = false;
393 break;
397 if (OnlyUnwoundTo) {
398 // Only unwind edges lead to the landing pad. Remember the landing pad.
399 LandingPads.insert(LPad);
400 continue;
403 // At least one normal edge ends at the landing pad. Redirect the unwind
404 // edges to a new basic block which falls through into this one.
406 // Create the new basic block.
407 BasicBlock *NewBB = BasicBlock::Create(F->getContext(),
408 LPad->getName() + "_unwind_edge");
410 // Insert it into the function right before the original landing pad.
411 LPad->getParent()->getBasicBlockList().insert(LPad, NewBB);
413 // Redirect unwind edges from the original landing pad to NewBB.
414 for (pred_iterator PI = pred_begin(LPad), PE = pred_end(LPad); PI != PE; ) {
415 TerminatorInst *PT = (*PI++)->getTerminator();
416 if (isa<InvokeInst>(PT) && PT->getSuccessor(1) == LPad)
417 // Unwind to the new block.
418 PT->setSuccessor(1, NewBB);
421 // If there are any PHI nodes in LPad, we need to update them so that they
422 // merge incoming values from NewBB instead.
423 for (BasicBlock::iterator II = LPad->begin(); isa<PHINode>(II); ++II) {
424 PHINode *PN = cast<PHINode>(II);
425 pred_iterator PB = pred_begin(NewBB), PE = pred_end(NewBB);
427 // Check to see if all of the values coming in via unwind edges are the
428 // same. If so, we don't need to create a new PHI node.
429 Value *InVal = PN->getIncomingValueForBlock(*PB);
430 for (pred_iterator PI = PB; PI != PE; ++PI) {
431 if (PI != PB && InVal != PN->getIncomingValueForBlock(*PI)) {
432 InVal = 0;
433 break;
437 if (InVal == 0) {
438 // Different unwind edges have different values. Create a new PHI node
439 // in NewBB.
440 PHINode *NewPN = PHINode::Create(PN->getType(),
441 PN->getNumIncomingValues(),
442 PN->getName()+".unwind", NewBB);
443 // Add an entry for each unwind edge, using the value from the old PHI.
444 for (pred_iterator PI = PB; PI != PE; ++PI)
445 NewPN->addIncoming(PN->getIncomingValueForBlock(*PI), *PI);
447 // Now use this new PHI as the common incoming value for NewBB in PN.
448 InVal = NewPN;
451 // Revector exactly one entry in the PHI node to come from NewBB
452 // and delete all other entries that come from unwind edges. If
453 // there are both normal and unwind edges from the same predecessor,
454 // this leaves an entry for the normal edge.
455 for (pred_iterator PI = PB; PI != PE; ++PI)
456 PN->removeIncomingValue(*PI);
457 PN->addIncoming(InVal, NewBB);
460 // Add a fallthrough from NewBB to the original landing pad.
461 BranchInst::Create(LPad, NewBB);
463 // Now update DominatorTree analysis information.
464 DT->splitBlock(NewBB);
466 // Remember the newly constructed landing pad. The original landing pad
467 // LPad is no longer a landing pad now that all unwind edges have been
468 // revectored to NewBB.
469 LandingPads.insert(NewBB);
470 ++NumLandingPadsSplit;
471 Changed = true;
474 return Changed;
477 /// LowerUnwinds - Turn unwind instructions into calls to _Unwind_Resume,
478 /// rethrowing any previously caught exception. This will crash horribly
479 /// at runtime if there is no such exception: using unwind to throw a new
480 /// exception is currently not supported.
481 bool DwarfEHPrepare::LowerUnwindsAndResumes() {
482 SmallVector<Instruction*, 16> ResumeInsts;
484 for (Function::iterator fi = F->begin(), fe = F->end(); fi != fe; ++fi) {
485 for (BasicBlock::iterator bi = fi->begin(), be = fi->end(); bi != be; ++bi){
486 if (isa<UnwindInst>(bi))
487 ResumeInsts.push_back(bi);
488 else if (CallInst *call = dyn_cast<CallInst>(bi))
489 if (Function *fn = dyn_cast<Function>(call->getCalledValue()))
490 if (fn->getName() == "llvm.eh.resume")
491 ResumeInsts.push_back(bi);
495 if (ResumeInsts.empty()) return false;
497 // Find the rewind function if we didn't already.
498 if (!RewindFunction) {
499 LLVMContext &Ctx = ResumeInsts[0]->getContext();
500 std::vector<const Type*>
501 Params(1, Type::getInt8PtrTy(Ctx));
502 FunctionType *FTy = FunctionType::get(Type::getVoidTy(Ctx),
503 Params, false);
504 const char *RewindName = TLI->getLibcallName(RTLIB::UNWIND_RESUME);
505 RewindFunction = F->getParent()->getOrInsertFunction(RewindName, FTy);
508 bool Changed = false;
510 for (SmallVectorImpl<Instruction*>::iterator
511 I = ResumeInsts.begin(), E = ResumeInsts.end(); I != E; ++I) {
512 Instruction *RI = *I;
514 // Replace the resuming instruction with a call to _Unwind_Resume (or the
515 // appropriate target equivalent).
517 llvm::Value *ExnValue;
518 if (isa<UnwindInst>(RI))
519 ExnValue = CreateExceptionValueCall(RI->getParent());
520 else
521 ExnValue = cast<CallInst>(RI)->getArgOperand(0);
523 // Create the call...
524 CallInst *CI = CallInst::Create(RewindFunction, ExnValue, "", RI);
525 CI->setCallingConv(TLI->getLibcallCallingConv(RTLIB::UNWIND_RESUME));
527 // ...followed by an UnreachableInst, if it was an unwind.
528 // Calls to llvm.eh.resume are typically already followed by this.
529 if (isa<UnwindInst>(RI))
530 new UnreachableInst(RI->getContext(), RI);
532 if (isa<UnwindInst>(RI))
533 ++NumUnwindsLowered;
534 else
535 ++NumResumesLowered;
537 // Nuke the resume instruction.
538 RI->eraseFromParent();
540 Changed = true;
543 return Changed;
546 /// MoveExceptionValueCalls - Ensure that eh.exception is only ever called from
547 /// landing pads by replacing calls outside of landing pads with direct use of
548 /// a register holding the appropriate value; this requires adding calls inside
549 /// all landing pads to initialize the register. Also, move eh.exception calls
550 /// inside landing pads to the start of the landing pad (optional, but may make
551 /// things simpler for later passes).
552 bool DwarfEHPrepare::MoveExceptionValueCalls() {
553 // If the eh.exception intrinsic is not declared in the module then there is
554 // nothing to do. Speed up compilation by checking for this common case.
555 if (!ExceptionValueIntrinsic &&
556 !F->getParent()->getFunction(Intrinsic::getName(Intrinsic::eh_exception)))
557 return false;
559 bool Changed = false;
561 // Move calls to eh.exception that are inside a landing pad to the start of
562 // the landing pad.
563 for (BBSet::const_iterator LI = LandingPads.begin(), LE = LandingPads.end();
564 LI != LE; ++LI) {
565 BasicBlock *LP = *LI;
566 for (BasicBlock::iterator II = LP->getFirstNonPHIOrDbg(), IE = LP->end();
567 II != IE;)
568 if (EHExceptionInst *EI = dyn_cast<EHExceptionInst>(II++)) {
569 // Found a call to eh.exception.
570 if (!EI->use_empty()) {
571 // If there is already a call to eh.exception at the start of the
572 // landing pad, then get hold of it; otherwise create such a call.
573 Value *CallAtStart = CreateExceptionValueCall(LP);
575 // If the call was at the start of a landing pad then leave it alone.
576 if (EI == CallAtStart)
577 continue;
578 EI->replaceAllUsesWith(CallAtStart);
580 EI->eraseFromParent();
581 ++NumExceptionValuesMoved;
582 Changed = true;
586 // Look for calls to eh.exception that are not in a landing pad. If one is
587 // found, then a register that holds the exception value will be created in
588 // each landing pad, and the SSAUpdater will be used to compute the values
589 // returned by eh.exception calls outside of landing pads.
590 SSAUpdater SSA;
592 // Remember where we found the eh.exception call, to avoid rescanning earlier
593 // basic blocks which we already know contain no eh.exception calls.
594 bool FoundCallOutsideLandingPad = false;
595 Function::iterator BB = F->begin();
596 for (Function::iterator BE = F->end(); BB != BE; ++BB) {
597 // Skip over landing pads.
598 if (LandingPads.count(BB))
599 continue;
601 for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end();
602 II != IE; ++II)
603 if (isa<EHExceptionInst>(II)) {
604 SSA.Initialize(II->getType(), II->getName());
605 FoundCallOutsideLandingPad = true;
606 break;
609 if (FoundCallOutsideLandingPad)
610 break;
613 // If all calls to eh.exception are in landing pads then we are done.
614 if (!FoundCallOutsideLandingPad)
615 return Changed;
617 // Add a call to eh.exception at the start of each landing pad, and tell the
618 // SSAUpdater that this is the value produced by the landing pad.
619 for (BBSet::iterator LI = LandingPads.begin(), LE = LandingPads.end();
620 LI != LE; ++LI)
621 SSA.AddAvailableValue(*LI, CreateExceptionValueCall(*LI));
623 // Now turn all calls to eh.exception that are not in a landing pad into a use
624 // of the appropriate register.
625 for (Function::iterator BE = F->end(); BB != BE; ++BB) {
626 // Skip over landing pads.
627 if (LandingPads.count(BB))
628 continue;
630 for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end();
631 II != IE;)
632 if (EHExceptionInst *EI = dyn_cast<EHExceptionInst>(II++)) {
633 // Found a call to eh.exception, replace it with the value from any
634 // upstream landing pad(s).
635 EI->replaceAllUsesWith(SSA.GetValueAtEndOfBlock(BB));
636 EI->eraseFromParent();
637 ++NumExceptionValuesMoved;
641 return true;
644 /// CreateExceptionValueCall - Insert a call to the eh.exception intrinsic at
645 /// the start of the basic block (unless there already is one, in which case
646 /// the existing call is returned).
647 Instruction *DwarfEHPrepare::CreateExceptionValueCall(BasicBlock *BB) {
648 Instruction *Start = BB->getFirstNonPHIOrDbg();
649 // Is this a call to eh.exception?
650 if (IntrinsicInst *CI = dyn_cast<IntrinsicInst>(Start))
651 if (CI->getIntrinsicID() == Intrinsic::eh_exception)
652 // Reuse the existing call.
653 return Start;
655 // Find the eh.exception intrinsic if we didn't already.
656 if (!ExceptionValueIntrinsic)
657 ExceptionValueIntrinsic = Intrinsic::getDeclaration(F->getParent(),
658 Intrinsic::eh_exception);
660 // Create the call.
661 return CallInst::Create(ExceptionValueIntrinsic, "eh.value.call", Start);
664 bool DwarfEHPrepare::runOnFunction(Function &Fn) {
665 bool Changed = false;
667 // Initialize internal state.
668 DT = &getAnalysis<DominatorTree>();
669 F = &Fn;
671 // Ensure that only unwind edges end at landing pads (a landing pad is a
672 // basic block where an invoke unwind edge ends).
673 Changed |= NormalizeLandingPads();
675 // Turn unwind instructions and eh.resume calls into libcalls.
676 Changed |= LowerUnwindsAndResumes();
678 // TODO: Move eh.selector calls to landing pads and combine them.
680 // Move eh.exception calls to landing pads.
681 Changed |= MoveExceptionValueCalls();
683 Changed |= HandleURoRInvokes();
685 LandingPads.clear();
687 return Changed;