1 //===-- DwarfEHPrepare - Prepare exception handling for code generation ---===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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/Target/TargetLowering.h"
26 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
27 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
30 STATISTIC(NumLandingPadsSplit, "Number of landing pads split");
31 STATISTIC(NumUnwindsLowered, "Number of unwind instructions lowered");
32 STATISTIC(NumExceptionValuesMoved, "Number of eh.exception calls moved");
33 STATISTIC(NumStackTempsIntroduced, "Number of stack temporaries introduced");
36 class DwarfEHPrepare : public FunctionPass {
37 const TargetMachine *TM;
38 const TargetLowering *TLI;
41 // The eh.exception intrinsic.
42 Function *ExceptionValueIntrinsic;
44 // The eh.selector intrinsic.
45 Function *SelectorIntrinsic;
47 // _Unwind_Resume_or_Rethrow call.
50 // The EH language-specific catch-all type.
51 GlobalVariable *EHCatchAllValue;
53 // _Unwind_Resume or the target equivalent.
54 Constant *RewindFunction;
56 // Dominator info is used when turning stack temporaries into registers.
58 DominanceFrontier *DF;
60 // The function we are running on.
63 // The landing pads for this function.
64 typedef SmallPtrSet<BasicBlock*, 8> BBSet;
67 // Stack temporary used to hold eh.exception values.
68 AllocaInst *ExceptionValueVar;
70 bool NormalizeLandingPads();
72 bool MoveExceptionValueCalls();
73 bool FinishStackTemporaries();
74 bool PromoteStackTemporaries();
76 Instruction *CreateExceptionValueCall(BasicBlock *BB);
77 Instruction *CreateValueLoad(BasicBlock *BB);
79 /// CreateReadOfExceptionValue - Return the result of the eh.exception
80 /// intrinsic by calling the intrinsic if in a landing pad, or loading it
81 /// from the exception value variable otherwise.
82 Instruction *CreateReadOfExceptionValue(BasicBlock *BB) {
83 return LandingPads.count(BB) ?
84 CreateExceptionValueCall(BB) : CreateValueLoad(BB);
87 /// CleanupSelectors - Any remaining eh.selector intrinsic calls which still
88 /// use the ".llvm.eh.catch.all.value" call need to convert to using its
89 /// initializer instead.
90 bool CleanupSelectors();
92 bool HasCatchAllInSelector(IntrinsicInst *);
94 /// FindAllCleanupSelectors - Find all eh.selector calls that are clean-ups.
95 void FindAllCleanupSelectors(SmallPtrSet<IntrinsicInst*, 32> &Sels);
97 /// FindAllURoRInvokes - Find all URoR invokes in the function.
98 void FindAllURoRInvokes(SmallPtrSet<InvokeInst*, 32> &URoRInvokes);
100 /// HandleURoRInvokes - Handle invokes of "_Unwind_Resume_or_Rethrow"
101 /// calls. The "unwind" part of these invokes jump to a landing pad within
102 /// the current function. This is a candidate to merge the selector
103 /// associated with the URoR invoke with the one from the URoR's landing
105 bool HandleURoRInvokes();
107 /// FindSelectorAndURoR - Find the eh.selector call and URoR call associated
108 /// with the eh.exception call. This recursively looks past instructions
109 /// which don't change the EH pointer value, like casts or PHI nodes.
110 bool FindSelectorAndURoR(Instruction *Inst, bool &URoRInvoke,
111 SmallPtrSet<IntrinsicInst*, 8> &SelCalls);
113 /// DoMem2RegPromotion - Take an alloca call and promote it from memory to a
115 bool DoMem2RegPromotion(Value *V) {
116 AllocaInst *AI = dyn_cast<AllocaInst>(V);
117 if (!AI || !isAllocaPromotable(AI)) return false;
119 // Turn the alloca into a register.
120 std::vector<AllocaInst*> Allocas(1, AI);
121 PromoteMemToReg(Allocas, *DT, *DF);
125 /// PromoteStoreInst - Perform Mem2Reg on a StoreInst.
126 bool PromoteStoreInst(StoreInst *SI) {
127 if (!SI || !DT || !DF) return false;
128 if (DoMem2RegPromotion(SI->getOperand(1)))
133 /// PromoteEHPtrStore - Promote the storing of an EH pointer into a
134 /// register. This should get rid of the store and subsequent loads.
135 bool PromoteEHPtrStore(IntrinsicInst *II) {
136 if (!DT || !DF) return false;
138 bool Changed = false;
143 for (Value::use_iterator
144 I = II->use_begin(), E = II->use_end(); I != E; ++I) {
145 SI = dyn_cast<StoreInst>(I);
149 if (!PromoteStoreInst(SI))
159 static char ID; // Pass identification, replacement for typeid.
160 DwarfEHPrepare(const TargetMachine *tm, bool fast) :
161 FunctionPass(&ID), TM(tm), TLI(TM->getTargetLowering()),
163 ExceptionValueIntrinsic(0), SelectorIntrinsic(0),
164 URoR(0), EHCatchAllValue(0), RewindFunction(0) {}
166 virtual bool runOnFunction(Function &Fn);
168 // getAnalysisUsage - We need dominance frontiers for memory promotion.
169 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
171 AU.addRequired<DominatorTree>();
172 AU.addPreserved<DominatorTree>();
174 AU.addRequired<DominanceFrontier>();
175 AU.addPreserved<DominanceFrontier>();
178 const char *getPassName() const {
179 return "Exception handling preparation";
183 } // end anonymous namespace
185 char DwarfEHPrepare::ID = 0;
187 FunctionPass *llvm::createDwarfEHPass(const TargetMachine *tm, bool fast) {
188 return new DwarfEHPrepare(tm, fast);
191 /// HasCatchAllInSelector - Return true if the intrinsic instruction has a
193 bool DwarfEHPrepare::HasCatchAllInSelector(IntrinsicInst *II) {
194 if (!EHCatchAllValue) return false;
196 unsigned OpIdx = II->getNumOperands() - 1;
197 GlobalVariable *GV = dyn_cast<GlobalVariable>(II->getOperand(OpIdx));
198 return GV == EHCatchAllValue;
201 /// FindAllCleanupSelectors - Find all eh.selector calls that are clean-ups.
202 void DwarfEHPrepare::
203 FindAllCleanupSelectors(SmallPtrSet<IntrinsicInst*, 32> &Sels) {
204 for (Value::use_iterator
205 I = SelectorIntrinsic->use_begin(),
206 E = SelectorIntrinsic->use_end(); I != E; ++I) {
207 IntrinsicInst *II = cast<IntrinsicInst>(I);
209 if (II->getParent()->getParent() != F)
212 if (!HasCatchAllInSelector(II))
217 /// FindAllURoRInvokes - Find all URoR invokes in the function.
218 void DwarfEHPrepare::
219 FindAllURoRInvokes(SmallPtrSet<InvokeInst*, 32> &URoRInvokes) {
220 for (Value::use_iterator
221 I = URoR->use_begin(),
222 E = URoR->use_end(); I != E; ++I) {
223 if (InvokeInst *II = dyn_cast<InvokeInst>(I))
224 URoRInvokes.insert(II);
228 /// CleanupSelectors - Any remaining eh.selector intrinsic calls which still use
229 /// the ".llvm.eh.catch.all.value" call need to convert to using its
230 /// initializer instead.
231 bool DwarfEHPrepare::CleanupSelectors() {
232 if (!EHCatchAllValue) return false;
234 if (!SelectorIntrinsic) {
236 Intrinsic::getDeclaration(F->getParent(), Intrinsic::eh_selector);
237 if (!SelectorIntrinsic) return false;
240 bool Changed = false;
241 for (Value::use_iterator
242 I = SelectorIntrinsic->use_begin(),
243 E = SelectorIntrinsic->use_end(); I != E; ++I) {
244 IntrinsicInst *Sel = dyn_cast<IntrinsicInst>(I);
245 if (!Sel || Sel->getParent()->getParent() != F) continue;
247 // Index of the ".llvm.eh.catch.all.value" variable.
248 unsigned OpIdx = Sel->getNumOperands() - 1;
249 GlobalVariable *GV = dyn_cast<GlobalVariable>(Sel->getOperand(OpIdx));
250 if (GV != EHCatchAllValue) continue;
251 Sel->setOperand(OpIdx, EHCatchAllValue->getInitializer());
258 /// FindSelectorAndURoR - Find the eh.selector call associated with the
259 /// eh.exception call. And indicate if there is a URoR "invoke" associated with
260 /// the eh.exception call. This recursively looks past instructions which don't
261 /// change the EH pointer value, like casts or PHI nodes.
263 DwarfEHPrepare::FindSelectorAndURoR(Instruction *Inst, bool &URoRInvoke,
264 SmallPtrSet<IntrinsicInst*, 8> &SelCalls) {
265 SmallPtrSet<PHINode*, 32> SeenPHIs;
266 bool Changed = false;
269 for (Value::use_iterator
270 I = Inst->use_begin(), E = Inst->use_end(); I != E; ++I) {
271 Instruction *II = dyn_cast<Instruction>(I);
272 if (!II || II->getParent()->getParent() != F) continue;
274 if (IntrinsicInst *Sel = dyn_cast<IntrinsicInst>(II)) {
275 if (Sel->getIntrinsicID() == Intrinsic::eh_selector)
276 SelCalls.insert(Sel);
277 } else if (InvokeInst *Invoke = dyn_cast<InvokeInst>(II)) {
278 if (Invoke->getCalledFunction() == URoR)
280 } else if (CastInst *CI = dyn_cast<CastInst>(II)) {
281 Changed |= FindSelectorAndURoR(CI, URoRInvoke, SelCalls);
282 } else if (StoreInst *SI = dyn_cast<StoreInst>(II)) {
283 if (!PromoteStoreInst(SI)) continue;
286 goto restart; // Uses may have changed, restart loop.
287 } else if (PHINode *PN = dyn_cast<PHINode>(II)) {
288 if (SeenPHIs.insert(PN))
289 // Don't process a PHI node more than once.
290 Changed |= FindSelectorAndURoR(PN, URoRInvoke, SelCalls);
297 /// HandleURoRInvokes - Handle invokes of "_Unwind_Resume_or_Rethrow" calls. The
298 /// "unwind" part of these invokes jump to a landing pad within the current
299 /// function. This is a candidate to merge the selector associated with the URoR
300 /// invoke with the one from the URoR's landing pad.
301 bool DwarfEHPrepare::HandleURoRInvokes() {
302 if (!DT) return CleanupSelectors(); // We require DominatorTree information.
304 if (!EHCatchAllValue) {
306 F->getParent()->getNamedGlobal(".llvm.eh.catch.all.value");
307 if (!EHCatchAllValue) return false;
310 if (!SelectorIntrinsic) {
312 Intrinsic::getDeclaration(F->getParent(), Intrinsic::eh_selector);
313 if (!SelectorIntrinsic) return false;
317 URoR = F->getParent()->getFunction("_Unwind_Resume_or_Rethrow");
318 if (!URoR) return CleanupSelectors();
321 SmallPtrSet<IntrinsicInst*, 32> Sels;
322 SmallPtrSet<InvokeInst*, 32> URoRInvokes;
323 FindAllCleanupSelectors(Sels);
324 FindAllURoRInvokes(URoRInvokes);
326 SmallPtrSet<IntrinsicInst*, 32> SelsToConvert;
328 for (SmallPtrSet<IntrinsicInst*, 32>::iterator
329 SI = Sels.begin(), SE = Sels.end(); SI != SE; ++SI) {
330 const BasicBlock *SelBB = (*SI)->getParent();
331 for (SmallPtrSet<InvokeInst*, 32>::iterator
332 UI = URoRInvokes.begin(), UE = URoRInvokes.end(); UI != UE; ++UI) {
333 const BasicBlock *URoRBB = (*UI)->getParent();
334 if (SelBB == URoRBB || DT->dominates(SelBB, URoRBB)) {
335 SelsToConvert.insert(*SI);
341 bool Changed = false;
343 if (Sels.size() != SelsToConvert.size()) {
344 // If we haven't been able to convert all of the clean-up selectors, then
345 // loop through the slow way to see if they still need to be converted.
346 if (!ExceptionValueIntrinsic) {
347 ExceptionValueIntrinsic =
348 Intrinsic::getDeclaration(F->getParent(), Intrinsic::eh_exception);
349 if (!ExceptionValueIntrinsic) return CleanupSelectors();
352 for (Value::use_iterator
353 I = ExceptionValueIntrinsic->use_begin(),
354 E = ExceptionValueIntrinsic->use_end(); I != E; ++I) {
355 IntrinsicInst *EHPtr = dyn_cast<IntrinsicInst>(I);
356 if (!EHPtr || EHPtr->getParent()->getParent() != F) continue;
358 Changed |= PromoteEHPtrStore(EHPtr);
360 bool URoRInvoke = false;
361 SmallPtrSet<IntrinsicInst*, 8> SelCalls;
362 Changed |= FindSelectorAndURoR(EHPtr, URoRInvoke, SelCalls);
365 // This EH pointer is being used by an invoke of an URoR instruction and
366 // an eh.selector intrinsic call. If the eh.selector is a 'clean-up', we
367 // need to convert it to a 'catch-all'.
368 for (SmallPtrSet<IntrinsicInst*, 8>::iterator
369 SI = SelCalls.begin(), SE = SelCalls.end(); SI != SE; ++SI)
370 if (!HasCatchAllInSelector(*SI))
371 SelsToConvert.insert(*SI);
376 if (!SelsToConvert.empty()) {
377 // Convert all clean-up eh.selectors, which are associated with "invokes" of
378 // URoR calls, into catch-all eh.selectors.
381 for (SmallPtrSet<IntrinsicInst*, 8>::iterator
382 SI = SelsToConvert.begin(), SE = SelsToConvert.end();
384 IntrinsicInst *II = *SI;
385 SmallVector<Value*, 8> Args;
387 // Use the exception object pointer and the personality function
388 // from the original selector.
389 Args.push_back(II->getOperand(1)); // Exception object pointer.
390 Args.push_back(II->getOperand(2)); // Personality function.
393 unsigned E = II->getNumOperands() -
394 (isa<ConstantInt>(II->getOperand(II->getNumOperands() - 1)) ? 1 : 0);
396 // Add in any filter IDs.
398 Args.push_back(II->getOperand(I));
400 Args.push_back(EHCatchAllValue->getInitializer()); // Catch-all indicator.
402 CallInst *NewSelector =
403 CallInst::Create(SelectorIntrinsic, Args.begin(), Args.end(),
404 "eh.sel.catch.all", II);
406 NewSelector->setTailCall(II->isTailCall());
407 NewSelector->setAttributes(II->getAttributes());
408 NewSelector->setCallingConv(II->getCallingConv());
410 II->replaceAllUsesWith(NewSelector);
411 II->eraseFromParent();
415 Changed |= CleanupSelectors();
419 /// NormalizeLandingPads - Normalize and discover landing pads, noting them
420 /// in the LandingPads set. A landing pad is normal if the only CFG edges
421 /// that end at it are unwind edges from invoke instructions. If we inlined
422 /// through an invoke we could have a normal branch from the previous
423 /// unwind block through to the landing pad for the original invoke.
424 /// Abnormal landing pads are fixed up by redirecting all unwind edges to
425 /// a new basic block which falls through to the original.
426 bool DwarfEHPrepare::NormalizeLandingPads() {
427 bool Changed = false;
429 const MCAsmInfo *MAI = TM->getMCAsmInfo();
430 bool usingSjLjEH = MAI->getExceptionHandlingType() == ExceptionHandling::SjLj;
432 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
433 TerminatorInst *TI = I->getTerminator();
434 if (!isa<InvokeInst>(TI))
436 BasicBlock *LPad = TI->getSuccessor(1);
437 // Skip landing pads that have already been normalized.
438 if (LandingPads.count(LPad))
441 // Check that only invoke unwind edges end at the landing pad.
442 bool OnlyUnwoundTo = true;
443 bool SwitchOK = usingSjLjEH;
444 for (pred_iterator PI = pred_begin(LPad), PE = pred_end(LPad);
446 TerminatorInst *PT = (*PI)->getTerminator();
447 // The SjLj dispatch block uses a switch instruction. This is effectively
448 // an unwind edge, so we can disregard it here. There will only ever
449 // be one dispatch, however, so if there are multiple switches, one
450 // of them truly is a normal edge, not an unwind edge.
451 if (SwitchOK && isa<SwitchInst>(PT)) {
455 if (!isa<InvokeInst>(PT) || LPad == PT->getSuccessor(0)) {
456 OnlyUnwoundTo = false;
462 // Only unwind edges lead to the landing pad. Remember the landing pad.
463 LandingPads.insert(LPad);
467 // At least one normal edge ends at the landing pad. Redirect the unwind
468 // edges to a new basic block which falls through into this one.
470 // Create the new basic block.
471 BasicBlock *NewBB = BasicBlock::Create(F->getContext(),
472 LPad->getName() + "_unwind_edge");
474 // Insert it into the function right before the original landing pad.
475 LPad->getParent()->getBasicBlockList().insert(LPad, NewBB);
477 // Redirect unwind edges from the original landing pad to NewBB.
478 for (pred_iterator PI = pred_begin(LPad), PE = pred_end(LPad); PI != PE; ) {
479 TerminatorInst *PT = (*PI++)->getTerminator();
480 if (isa<InvokeInst>(PT) && PT->getSuccessor(1) == LPad)
481 // Unwind to the new block.
482 PT->setSuccessor(1, NewBB);
485 // If there are any PHI nodes in LPad, we need to update them so that they
486 // merge incoming values from NewBB instead.
487 for (BasicBlock::iterator II = LPad->begin(); isa<PHINode>(II); ++II) {
488 PHINode *PN = cast<PHINode>(II);
489 pred_iterator PB = pred_begin(NewBB), PE = pred_end(NewBB);
491 // Check to see if all of the values coming in via unwind edges are the
492 // same. If so, we don't need to create a new PHI node.
493 Value *InVal = PN->getIncomingValueForBlock(*PB);
494 for (pred_iterator PI = PB; PI != PE; ++PI) {
495 if (PI != PB && InVal != PN->getIncomingValueForBlock(*PI)) {
502 // Different unwind edges have different values. Create a new PHI node
504 PHINode *NewPN = PHINode::Create(PN->getType(), PN->getName()+".unwind",
506 // Add an entry for each unwind edge, using the value from the old PHI.
507 for (pred_iterator PI = PB; PI != PE; ++PI)
508 NewPN->addIncoming(PN->getIncomingValueForBlock(*PI), *PI);
510 // Now use this new PHI as the common incoming value for NewBB in PN.
514 // Revector exactly one entry in the PHI node to come from NewBB
515 // and delete all other entries that come from unwind edges. If
516 // there are both normal and unwind edges from the same predecessor,
517 // this leaves an entry for the normal edge.
518 for (pred_iterator PI = PB; PI != PE; ++PI)
519 PN->removeIncomingValue(*PI);
520 PN->addIncoming(InVal, NewBB);
523 // Add a fallthrough from NewBB to the original landing pad.
524 BranchInst::Create(LPad, NewBB);
526 // Now update DominatorTree and DominanceFrontier analysis information.
528 DT->splitBlock(NewBB);
530 DF->splitBlock(NewBB);
532 // Remember the newly constructed landing pad. The original landing pad
533 // LPad is no longer a landing pad now that all unwind edges have been
534 // revectored to NewBB.
535 LandingPads.insert(NewBB);
536 ++NumLandingPadsSplit;
543 /// LowerUnwinds - Turn unwind instructions into calls to _Unwind_Resume,
544 /// rethrowing any previously caught exception. This will crash horribly
545 /// at runtime if there is no such exception: using unwind to throw a new
546 /// exception is currently not supported.
547 bool DwarfEHPrepare::LowerUnwinds() {
548 SmallVector<TerminatorInst*, 16> UnwindInsts;
550 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
551 TerminatorInst *TI = I->getTerminator();
552 if (isa<UnwindInst>(TI))
553 UnwindInsts.push_back(TI);
556 if (UnwindInsts.empty()) return false;
558 // Find the rewind function if we didn't already.
559 if (!RewindFunction) {
560 LLVMContext &Ctx = UnwindInsts[0]->getContext();
561 std::vector<const Type*>
562 Params(1, Type::getInt8PtrTy(Ctx));
563 FunctionType *FTy = FunctionType::get(Type::getVoidTy(Ctx),
565 const char *RewindName = TLI->getLibcallName(RTLIB::UNWIND_RESUME);
566 RewindFunction = F->getParent()->getOrInsertFunction(RewindName, FTy);
569 bool Changed = false;
571 for (SmallVectorImpl<TerminatorInst*>::iterator
572 I = UnwindInsts.begin(), E = UnwindInsts.end(); I != E; ++I) {
573 TerminatorInst *TI = *I;
575 // Replace the unwind instruction with a call to _Unwind_Resume (or the
576 // appropriate target equivalent) followed by an UnreachableInst.
578 // Create the call...
579 CallInst *CI = CallInst::Create(RewindFunction,
580 CreateReadOfExceptionValue(TI->getParent()),
582 CI->setCallingConv(TLI->getLibcallCallingConv(RTLIB::UNWIND_RESUME));
583 // ...followed by an UnreachableInst.
584 new UnreachableInst(TI->getContext(), TI);
586 // Nuke the unwind instruction.
587 TI->eraseFromParent();
595 /// MoveExceptionValueCalls - Ensure that eh.exception is only ever called from
596 /// landing pads by replacing calls outside of landing pads with loads from a
597 /// stack temporary. Move eh.exception calls inside landing pads to the start
598 /// of the landing pad (optional, but may make things simpler for later passes).
599 bool DwarfEHPrepare::MoveExceptionValueCalls() {
600 // If the eh.exception intrinsic is not declared in the module then there is
601 // nothing to do. Speed up compilation by checking for this common case.
602 if (!ExceptionValueIntrinsic &&
603 !F->getParent()->getFunction(Intrinsic::getName(Intrinsic::eh_exception)))
606 bool Changed = false;
608 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
609 for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E;)
610 if (IntrinsicInst *CI = dyn_cast<IntrinsicInst>(II++))
611 if (CI->getIntrinsicID() == Intrinsic::eh_exception) {
612 if (!CI->use_empty()) {
613 Value *ExceptionValue = CreateReadOfExceptionValue(BB);
614 if (CI == ExceptionValue) {
615 // The call was at the start of a landing pad - leave it alone.
616 assert(LandingPads.count(BB) &&
617 "Created eh.exception call outside landing pad!");
620 CI->replaceAllUsesWith(ExceptionValue);
622 CI->eraseFromParent();
623 ++NumExceptionValuesMoved;
631 /// FinishStackTemporaries - If we introduced a stack variable to hold the
632 /// exception value then initialize it in each landing pad.
633 bool DwarfEHPrepare::FinishStackTemporaries() {
634 if (!ExceptionValueVar)
638 bool Changed = false;
640 // Make sure that there is a store of the exception value at the start of
642 for (BBSet::iterator LI = LandingPads.begin(), LE = LandingPads.end();
644 Instruction *ExceptionValue = CreateReadOfExceptionValue(*LI);
645 Instruction *Store = new StoreInst(ExceptionValue, ExceptionValueVar);
646 Store->insertAfter(ExceptionValue);
653 /// PromoteStackTemporaries - Turn any stack temporaries we introduced into
654 /// registers if possible.
655 bool DwarfEHPrepare::PromoteStackTemporaries() {
656 if (ExceptionValueVar && DT && DF && isAllocaPromotable(ExceptionValueVar)) {
657 // Turn the exception temporary into registers and phi nodes if possible.
658 std::vector<AllocaInst*> Allocas(1, ExceptionValueVar);
659 PromoteMemToReg(Allocas, *DT, *DF);
665 /// CreateExceptionValueCall - Insert a call to the eh.exception intrinsic at
666 /// the start of the basic block (unless there already is one, in which case
667 /// the existing call is returned).
668 Instruction *DwarfEHPrepare::CreateExceptionValueCall(BasicBlock *BB) {
669 Instruction *Start = BB->getFirstNonPHIOrDbg();
670 // Is this a call to eh.exception?
671 if (IntrinsicInst *CI = dyn_cast<IntrinsicInst>(Start))
672 if (CI->getIntrinsicID() == Intrinsic::eh_exception)
673 // Reuse the existing call.
676 // Find the eh.exception intrinsic if we didn't already.
677 if (!ExceptionValueIntrinsic)
678 ExceptionValueIntrinsic = Intrinsic::getDeclaration(F->getParent(),
679 Intrinsic::eh_exception);
682 return CallInst::Create(ExceptionValueIntrinsic, "eh.value.call", Start);
685 /// CreateValueLoad - Insert a load of the exception value stack variable
686 /// (creating it if necessary) at the start of the basic block (unless
687 /// there already is a load, in which case the existing load is returned).
688 Instruction *DwarfEHPrepare::CreateValueLoad(BasicBlock *BB) {
689 Instruction *Start = BB->getFirstNonPHIOrDbg();
690 // Is this a load of the exception temporary?
691 if (ExceptionValueVar)
692 if (LoadInst* LI = dyn_cast<LoadInst>(Start))
693 if (LI->getPointerOperand() == ExceptionValueVar)
694 // Reuse the existing load.
697 // Create the temporary if we didn't already.
698 if (!ExceptionValueVar) {
699 ExceptionValueVar = new AllocaInst(PointerType::getUnqual(
700 Type::getInt8Ty(BB->getContext())), "eh.value", F->begin()->begin());
701 ++NumStackTempsIntroduced;
705 return new LoadInst(ExceptionValueVar, "eh.value.load", Start);
708 bool DwarfEHPrepare::runOnFunction(Function &Fn) {
709 bool Changed = false;
711 // Initialize internal state.
712 DT = getAnalysisIfAvailable<DominatorTree>();
713 DF = getAnalysisIfAvailable<DominanceFrontier>();
714 ExceptionValueVar = 0;
717 // Ensure that only unwind edges end at landing pads (a landing pad is a
718 // basic block where an invoke unwind edge ends).
719 Changed |= NormalizeLandingPads();
721 // Turn unwind instructions into libcalls.
722 Changed |= LowerUnwinds();
724 // TODO: Move eh.selector calls to landing pads and combine them.
726 // Move eh.exception calls to landing pads.
727 Changed |= MoveExceptionValueCalls();
729 // Initialize any stack temporaries we introduced.
730 Changed |= FinishStackTemporaries();
732 // Turn any stack temporaries into registers if possible.
734 Changed |= PromoteStackTemporaries();
736 Changed |= HandleURoRInvokes();