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/Support/CallSite.h"
26 #include "llvm/Target/TargetLowering.h"
27 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
28 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
29 #include "llvm/Transforms/Utils/SSAUpdater.h"
32 STATISTIC(NumLandingPadsSplit, "Number of landing pads split");
33 STATISTIC(NumUnwindsLowered, "Number of unwind instructions lowered");
34 STATISTIC(NumExceptionValuesMoved, "Number of eh.exception calls moved");
35 STATISTIC(NumStackTempsIntroduced, "Number of stack temporaries introduced");
37 static void PromoteAlloca(AllocaInst *AI);
40 class DwarfEHPrepare : public FunctionPass {
41 const TargetMachine *TM;
42 const TargetLowering *TLI;
45 // The eh.exception intrinsic.
46 Function *ExceptionValueIntrinsic;
48 // The eh.selector intrinsic.
49 Function *SelectorIntrinsic;
51 // _Unwind_Resume_or_Rethrow call.
54 // The EH language-specific catch-all type.
55 GlobalVariable *EHCatchAllValue;
57 // _Unwind_Resume or the target equivalent.
58 Constant *RewindFunction;
60 // Dominator info is used when turning stack temporaries into registers.
63 // The function we are running on.
66 // The landing pads for this function.
67 typedef SmallPtrSet<BasicBlock*, 8> BBSet;
70 // Stack temporary used to hold eh.exception values.
71 AllocaInst *ExceptionValueVar;
73 bool NormalizeLandingPads();
75 bool MoveExceptionValueCalls();
76 bool FinishStackTemporaries();
77 bool PromoteStackTemporaries();
79 Instruction *CreateExceptionValueCall(BasicBlock *BB);
80 Instruction *CreateValueLoad(BasicBlock *BB);
82 /// CreateReadOfExceptionValue - Return the result of the eh.exception
83 /// intrinsic by calling the intrinsic if in a landing pad, or loading it
84 /// from the exception value variable otherwise.
85 Instruction *CreateReadOfExceptionValue(BasicBlock *BB) {
86 return LandingPads.count(BB) ?
87 CreateExceptionValueCall(BB) : CreateValueLoad(BB);
90 /// CleanupSelectors - Any remaining eh.selector intrinsic calls which still
91 /// use the "llvm.eh.catch.all.value" call need to convert to using its
92 /// initializer instead.
93 bool CleanupSelectors(SmallPtrSet<IntrinsicInst*, 32> &Sels);
95 bool HasCatchAllInSelector(IntrinsicInst *);
97 /// FindAllCleanupSelectors - Find all eh.selector calls that are clean-ups.
98 void FindAllCleanupSelectors(SmallPtrSet<IntrinsicInst*, 32> &Sels,
99 SmallPtrSet<IntrinsicInst*, 32> &CatchAllSels);
101 /// FindAllURoRInvokes - Find all URoR invokes in the function.
102 void FindAllURoRInvokes(SmallPtrSet<InvokeInst*, 32> &URoRInvokes);
104 /// HandleURoRInvokes - Handle invokes of "_Unwind_Resume_or_Rethrow"
105 /// calls. The "unwind" part of these invokes jump to a landing pad within
106 /// the current function. This is a candidate to merge the selector
107 /// associated with the URoR invoke with the one from the URoR's landing
109 bool HandleURoRInvokes();
111 /// FindSelectorAndURoR - Find the eh.selector call and URoR call associated
112 /// with the eh.exception call. This recursively looks past instructions
113 /// which don't change the EH pointer value, like casts or PHI nodes.
114 bool FindSelectorAndURoR(Instruction *Inst, bool &URoRInvoke,
115 SmallPtrSet<IntrinsicInst*, 8> &SelCalls);
117 /// PromoteStoreInst - Perform Mem2Reg on a StoreInst.
118 bool PromoteStoreInst(StoreInst *SI) {
119 AllocaInst *AI = dyn_cast<AllocaInst>(SI->getOperand(1));
120 if (!AI || !isAllocaPromotable(AI)) return false;
126 /// PromoteEHPtrStore - Promote the storing of an EH pointer into a
127 /// register. This should get rid of the store and subsequent loads.
128 bool PromoteEHPtrStore(IntrinsicInst *II) {
129 if (!CompileFast) return false;
131 bool Changed = false;
136 for (Value::use_iterator
137 I = II->use_begin(), E = II->use_end(); I != E; ++I) {
138 SI = dyn_cast<StoreInst>(*I);
142 if (SI && !PromoteStoreInst(SI))
152 static char ID; // Pass identification, replacement for typeid.
153 DwarfEHPrepare(const TargetMachine *tm, bool fast) :
154 FunctionPass(ID), TM(tm), TLI(TM->getTargetLowering()),
156 ExceptionValueIntrinsic(0), SelectorIntrinsic(0),
157 URoR(0), EHCatchAllValue(0), RewindFunction(0) {}
159 virtual bool runOnFunction(Function &Fn);
161 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
162 AU.addPreserved<DominatorTree>();
165 const char *getPassName() const {
166 return "Exception handling preparation";
170 } // end anonymous namespace
172 char DwarfEHPrepare::ID = 0;
174 FunctionPass *llvm::createDwarfEHPass(const TargetMachine *tm, bool fast) {
175 return new DwarfEHPrepare(tm, fast);
178 /// PromoteAlloca - This promotes an alloca to registers when we know that it
179 /// only has non-volatile loads and stores to it.
180 static void PromoteAlloca(AllocaInst *AI) {
181 assert(isAllocaPromotable(AI));
183 // First step: bucket up uses of the pointers by the block they occur in.
184 // This is important because we have to handle multiple defs/uses in a block
185 // ourselves: SSAUpdater is purely for cross-block references.
186 // FIXME: Want a TinyVector<Instruction*> since there is usually 0/1 element.
187 DenseMap<BasicBlock*, std::vector<Instruction*> > UsesByBlock;
188 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
190 Instruction *User = cast<Instruction>(*UI);
191 UsesByBlock[User->getParent()].push_back(User);
196 // It wants to know some value of the same type as what we'll be inserting.
198 if (isa<LoadInst>(*AI->use_begin()))
199 SomeValue = *AI->use_begin();
201 SomeValue = cast<StoreInst>(*AI->use_begin())->getOperand(0);
202 SSA.Initialize(SomeValue);
204 // Okay, now we can iterate over all the blocks in the loop with uses,
205 // processing them. Keep track of which loads are loading a live-in value.
206 SmallVector<LoadInst*, 32> LiveInLoads;
208 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
210 Instruction *User = cast<Instruction>(*UI);
211 std::vector<Instruction*> &BlockUses = UsesByBlock[User->getParent()];
213 // If this block has already been processed, ignore this repeat use.
214 if (BlockUses.empty()) continue;
216 // Okay, this is the first use in the block. If this block just has a
217 // single user in it, we can rewrite it trivially.
218 if (BlockUses.size() == 1) {
219 // If it is a store, it is a trivial def of the value in the block.
220 if (isa<StoreInst>(User)) {
221 SSA.AddAvailableValue(User->getParent(),
222 cast<StoreInst>(User)->getOperand(0));
224 // Otherwise it is a load, queue it to rewrite as a live-in load.
225 LiveInLoads.push_back(cast<LoadInst>(User));
231 // Otherwise, check to see if this block is all loads. If so, we can queue
232 // them all as live in loads.
233 bool HasStore = false;
234 for (unsigned i = 0, e = BlockUses.size(); i != e; ++i) {
235 if (isa<StoreInst>(BlockUses[i])) {
242 for (unsigned i = 0, e = BlockUses.size(); i != e; ++i)
243 LiveInLoads.push_back(cast<LoadInst>(BlockUses[i]));
248 // Otherwise, we have mixed loads and stores (or just a bunch of stores).
249 // Since SSAUpdater is purely for cross-block values, we need to determine
250 // the order of these instructions in the block. If the first use in the
251 // block is a load, then it uses the live in value. The last store defines
252 // the live out value. We handle this by doing a linear scan of the block.
253 BasicBlock *BB = User->getParent();
254 Value *StoredValue = 0;
255 for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E; ++II) {
256 if (LoadInst *L = dyn_cast<LoadInst>(II)) {
257 // If this is a load to an unrelated pointer, ignore it.
258 if (L->getOperand(0) != AI) continue;
260 // If we haven't seen a store yet, this is a live in use, otherwise
261 // use the stored value.
263 L->replaceAllUsesWith(StoredValue);
265 LiveInLoads.push_back(L);
269 if (StoreInst *S = dyn_cast<StoreInst>(II)) {
270 // If this is a store to an unrelated pointer, ignore it.
271 if (S->getOperand(1) != AI) continue;
273 // Remember that this is the active value in the block.
274 StoredValue = S->getOperand(0);
278 // The last stored value that happened is the live-out for the block.
279 assert(StoredValue && "Already checked that there is a store in block");
280 SSA.AddAvailableValue(BB, StoredValue);
284 // Okay, now we rewrite all loads that use live-in values in the loop,
285 // inserting PHI nodes as necessary.
286 for (unsigned i = 0, e = LiveInLoads.size(); i != e; ++i) {
287 LoadInst *ALoad = LiveInLoads[i];
288 ALoad->replaceAllUsesWith(SSA.GetValueInMiddleOfBlock(ALoad->getParent()));
291 // Now that everything is rewritten, delete the old instructions from the body
292 // of the loop. They should all be dead now.
293 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
295 cast<Instruction>(*UI)->eraseFromParent();
300 /// HasCatchAllInSelector - Return true if the intrinsic instruction has a
302 bool DwarfEHPrepare::HasCatchAllInSelector(IntrinsicInst *II) {
303 if (!EHCatchAllValue) return false;
305 unsigned ArgIdx = II->getNumArgOperands() - 1;
306 GlobalVariable *GV = dyn_cast<GlobalVariable>(II->getArgOperand(ArgIdx));
307 return GV == EHCatchAllValue;
310 /// FindAllCleanupSelectors - Find all eh.selector calls that are clean-ups.
311 void DwarfEHPrepare::
312 FindAllCleanupSelectors(SmallPtrSet<IntrinsicInst*, 32> &Sels,
313 SmallPtrSet<IntrinsicInst*, 32> &CatchAllSels) {
314 for (Value::use_iterator
315 I = SelectorIntrinsic->use_begin(),
316 E = SelectorIntrinsic->use_end(); I != E; ++I) {
317 IntrinsicInst *II = cast<IntrinsicInst>(*I);
319 if (II->getParent()->getParent() != F)
322 if (!HasCatchAllInSelector(II))
325 CatchAllSels.insert(II);
329 /// FindAllURoRInvokes - Find all URoR invokes in the function.
330 void DwarfEHPrepare::
331 FindAllURoRInvokes(SmallPtrSet<InvokeInst*, 32> &URoRInvokes) {
332 for (Value::use_iterator
333 I = URoR->use_begin(),
334 E = URoR->use_end(); I != E; ++I) {
335 if (InvokeInst *II = dyn_cast<InvokeInst>(*I))
336 URoRInvokes.insert(II);
340 /// CleanupSelectors - Any remaining eh.selector intrinsic calls which still use
341 /// the "llvm.eh.catch.all.value" call need to convert to using its
342 /// initializer instead.
343 bool DwarfEHPrepare::CleanupSelectors(SmallPtrSet<IntrinsicInst*, 32> &Sels) {
344 if (!EHCatchAllValue) return false;
346 if (!SelectorIntrinsic) {
348 Intrinsic::getDeclaration(F->getParent(), Intrinsic::eh_selector);
349 if (!SelectorIntrinsic) return false;
352 bool Changed = false;
353 for (SmallPtrSet<IntrinsicInst*, 32>::iterator
354 I = Sels.begin(), E = Sels.end(); I != E; ++I) {
355 IntrinsicInst *Sel = *I;
357 // Index of the "llvm.eh.catch.all.value" variable.
358 unsigned OpIdx = Sel->getNumArgOperands() - 1;
359 GlobalVariable *GV = dyn_cast<GlobalVariable>(Sel->getArgOperand(OpIdx));
360 if (GV != EHCatchAllValue) continue;
361 Sel->setArgOperand(OpIdx, EHCatchAllValue->getInitializer());
368 /// FindSelectorAndURoR - Find the eh.selector call associated with the
369 /// eh.exception call. And indicate if there is a URoR "invoke" associated with
370 /// the eh.exception call. This recursively looks past instructions which don't
371 /// change the EH pointer value, like casts or PHI nodes.
373 DwarfEHPrepare::FindSelectorAndURoR(Instruction *Inst, bool &URoRInvoke,
374 SmallPtrSet<IntrinsicInst*, 8> &SelCalls) {
375 SmallPtrSet<PHINode*, 32> SeenPHIs;
376 bool Changed = false;
379 for (Value::use_iterator
380 I = Inst->use_begin(), E = Inst->use_end(); I != E; ++I) {
381 Instruction *II = dyn_cast<Instruction>(*I);
382 if (!II || II->getParent()->getParent() != F) continue;
384 if (IntrinsicInst *Sel = dyn_cast<IntrinsicInst>(II)) {
385 if (Sel->getIntrinsicID() == Intrinsic::eh_selector)
386 SelCalls.insert(Sel);
387 } else if (InvokeInst *Invoke = dyn_cast<InvokeInst>(II)) {
388 if (Invoke->getCalledFunction() == URoR)
390 } else if (CastInst *CI = dyn_cast<CastInst>(II)) {
391 Changed |= FindSelectorAndURoR(CI, URoRInvoke, SelCalls);
392 } else if (StoreInst *SI = dyn_cast<StoreInst>(II)) {
393 if (!PromoteStoreInst(SI)) continue;
396 goto restart; // Uses may have changed, restart loop.
397 } else if (PHINode *PN = dyn_cast<PHINode>(II)) {
398 if (SeenPHIs.insert(PN))
399 // Don't process a PHI node more than once.
400 Changed |= FindSelectorAndURoR(PN, URoRInvoke, SelCalls);
407 /// HandleURoRInvokes - Handle invokes of "_Unwind_Resume_or_Rethrow" calls. The
408 /// "unwind" part of these invokes jump to a landing pad within the current
409 /// function. This is a candidate to merge the selector associated with the URoR
410 /// invoke with the one from the URoR's landing pad.
411 bool DwarfEHPrepare::HandleURoRInvokes() {
412 if (!EHCatchAllValue) {
414 F->getParent()->getNamedGlobal("llvm.eh.catch.all.value");
415 if (!EHCatchAllValue) return false;
418 if (!SelectorIntrinsic) {
420 Intrinsic::getDeclaration(F->getParent(), Intrinsic::eh_selector);
421 if (!SelectorIntrinsic) return false;
424 SmallPtrSet<IntrinsicInst*, 32> Sels;
425 SmallPtrSet<IntrinsicInst*, 32> CatchAllSels;
426 FindAllCleanupSelectors(Sels, CatchAllSels);
429 // We require DominatorTree information.
430 return CleanupSelectors(CatchAllSels);
433 URoR = F->getParent()->getFunction("_Unwind_Resume_or_Rethrow");
434 if (!URoR) return CleanupSelectors(CatchAllSels);
437 SmallPtrSet<InvokeInst*, 32> URoRInvokes;
438 FindAllURoRInvokes(URoRInvokes);
440 SmallPtrSet<IntrinsicInst*, 32> SelsToConvert;
442 for (SmallPtrSet<IntrinsicInst*, 32>::iterator
443 SI = Sels.begin(), SE = Sels.end(); SI != SE; ++SI) {
444 const BasicBlock *SelBB = (*SI)->getParent();
445 for (SmallPtrSet<InvokeInst*, 32>::iterator
446 UI = URoRInvokes.begin(), UE = URoRInvokes.end(); UI != UE; ++UI) {
447 const BasicBlock *URoRBB = (*UI)->getParent();
448 if (DT->dominates(SelBB, URoRBB)) {
449 SelsToConvert.insert(*SI);
455 bool Changed = false;
457 if (Sels.size() != SelsToConvert.size()) {
458 // If we haven't been able to convert all of the clean-up selectors, then
459 // loop through the slow way to see if they still need to be converted.
460 if (!ExceptionValueIntrinsic) {
461 ExceptionValueIntrinsic =
462 Intrinsic::getDeclaration(F->getParent(), Intrinsic::eh_exception);
463 if (!ExceptionValueIntrinsic)
464 return CleanupSelectors(CatchAllSels);
467 for (Value::use_iterator
468 I = ExceptionValueIntrinsic->use_begin(),
469 E = ExceptionValueIntrinsic->use_end(); I != E; ++I) {
470 IntrinsicInst *EHPtr = dyn_cast<IntrinsicInst>(*I);
471 if (!EHPtr || EHPtr->getParent()->getParent() != F) continue;
473 Changed |= PromoteEHPtrStore(EHPtr);
475 bool URoRInvoke = false;
476 SmallPtrSet<IntrinsicInst*, 8> SelCalls;
477 Changed |= FindSelectorAndURoR(EHPtr, URoRInvoke, SelCalls);
480 // This EH pointer is being used by an invoke of an URoR instruction and
481 // an eh.selector intrinsic call. If the eh.selector is a 'clean-up', we
482 // need to convert it to a 'catch-all'.
483 for (SmallPtrSet<IntrinsicInst*, 8>::iterator
484 SI = SelCalls.begin(), SE = SelCalls.end(); SI != SE; ++SI)
485 if (!HasCatchAllInSelector(*SI))
486 SelsToConvert.insert(*SI);
491 if (!SelsToConvert.empty()) {
492 // Convert all clean-up eh.selectors, which are associated with "invokes" of
493 // URoR calls, into catch-all eh.selectors.
496 for (SmallPtrSet<IntrinsicInst*, 8>::iterator
497 SI = SelsToConvert.begin(), SE = SelsToConvert.end();
499 IntrinsicInst *II = *SI;
501 // Use the exception object pointer and the personality function
502 // from the original selector.
504 IntrinsicInst::op_iterator I = CS.arg_begin();
505 IntrinsicInst::op_iterator E = CS.arg_end();
506 IntrinsicInst::op_iterator B = prior(E);
508 // Exclude last argument if it is an integer.
509 if (isa<ConstantInt>(B)) E = B;
511 // Add exception object pointer (front).
512 // Add personality function (next).
513 // Add in any filter IDs (rest).
514 SmallVector<Value*, 8> Args(I, E);
516 Args.push_back(EHCatchAllValue->getInitializer()); // Catch-all indicator.
518 CallInst *NewSelector =
519 CallInst::Create(SelectorIntrinsic, Args.begin(), Args.end(),
520 "eh.sel.catch.all", II);
522 NewSelector->setTailCall(II->isTailCall());
523 NewSelector->setAttributes(II->getAttributes());
524 NewSelector->setCallingConv(II->getCallingConv());
526 II->replaceAllUsesWith(NewSelector);
527 II->eraseFromParent();
531 Changed |= CleanupSelectors(CatchAllSels);
535 /// NormalizeLandingPads - Normalize and discover landing pads, noting them
536 /// in the LandingPads set. A landing pad is normal if the only CFG edges
537 /// that end at it are unwind edges from invoke instructions. If we inlined
538 /// through an invoke we could have a normal branch from the previous
539 /// unwind block through to the landing pad for the original invoke.
540 /// Abnormal landing pads are fixed up by redirecting all unwind edges to
541 /// a new basic block which falls through to the original.
542 bool DwarfEHPrepare::NormalizeLandingPads() {
543 bool Changed = false;
545 const MCAsmInfo *MAI = TM->getMCAsmInfo();
546 bool usingSjLjEH = MAI->getExceptionHandlingType() == ExceptionHandling::SjLj;
548 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
549 TerminatorInst *TI = I->getTerminator();
550 if (!isa<InvokeInst>(TI))
552 BasicBlock *LPad = TI->getSuccessor(1);
553 // Skip landing pads that have already been normalized.
554 if (LandingPads.count(LPad))
557 // Check that only invoke unwind edges end at the landing pad.
558 bool OnlyUnwoundTo = true;
559 bool SwitchOK = usingSjLjEH;
560 for (pred_iterator PI = pred_begin(LPad), PE = pred_end(LPad);
562 TerminatorInst *PT = (*PI)->getTerminator();
563 // The SjLj dispatch block uses a switch instruction. This is effectively
564 // an unwind edge, so we can disregard it here. There will only ever
565 // be one dispatch, however, so if there are multiple switches, one
566 // of them truly is a normal edge, not an unwind edge.
567 if (SwitchOK && isa<SwitchInst>(PT)) {
571 if (!isa<InvokeInst>(PT) || LPad == PT->getSuccessor(0)) {
572 OnlyUnwoundTo = false;
578 // Only unwind edges lead to the landing pad. Remember the landing pad.
579 LandingPads.insert(LPad);
583 // At least one normal edge ends at the landing pad. Redirect the unwind
584 // edges to a new basic block which falls through into this one.
586 // Create the new basic block.
587 BasicBlock *NewBB = BasicBlock::Create(F->getContext(),
588 LPad->getName() + "_unwind_edge");
590 // Insert it into the function right before the original landing pad.
591 LPad->getParent()->getBasicBlockList().insert(LPad, NewBB);
593 // Redirect unwind edges from the original landing pad to NewBB.
594 for (pred_iterator PI = pred_begin(LPad), PE = pred_end(LPad); PI != PE; ) {
595 TerminatorInst *PT = (*PI++)->getTerminator();
596 if (isa<InvokeInst>(PT) && PT->getSuccessor(1) == LPad)
597 // Unwind to the new block.
598 PT->setSuccessor(1, NewBB);
601 // If there are any PHI nodes in LPad, we need to update them so that they
602 // merge incoming values from NewBB instead.
603 for (BasicBlock::iterator II = LPad->begin(); isa<PHINode>(II); ++II) {
604 PHINode *PN = cast<PHINode>(II);
605 pred_iterator PB = pred_begin(NewBB), PE = pred_end(NewBB);
607 // Check to see if all of the values coming in via unwind edges are the
608 // same. If so, we don't need to create a new PHI node.
609 Value *InVal = PN->getIncomingValueForBlock(*PB);
610 for (pred_iterator PI = PB; PI != PE; ++PI) {
611 if (PI != PB && InVal != PN->getIncomingValueForBlock(*PI)) {
618 // Different unwind edges have different values. Create a new PHI node
620 PHINode *NewPN = PHINode::Create(PN->getType(), PN->getName()+".unwind",
622 // Add an entry for each unwind edge, using the value from the old PHI.
623 for (pred_iterator PI = PB; PI != PE; ++PI)
624 NewPN->addIncoming(PN->getIncomingValueForBlock(*PI), *PI);
626 // Now use this new PHI as the common incoming value for NewBB in PN.
630 // Revector exactly one entry in the PHI node to come from NewBB
631 // and delete all other entries that come from unwind edges. If
632 // there are both normal and unwind edges from the same predecessor,
633 // this leaves an entry for the normal edge.
634 for (pred_iterator PI = PB; PI != PE; ++PI)
635 PN->removeIncomingValue(*PI);
636 PN->addIncoming(InVal, NewBB);
639 // Add a fallthrough from NewBB to the original landing pad.
640 BranchInst::Create(LPad, NewBB);
642 // Now update DominatorTree analysis information if it is around.
644 DT->splitBlock(NewBB);
646 // Remember the newly constructed landing pad. The original landing pad
647 // LPad is no longer a landing pad now that all unwind edges have been
648 // revectored to NewBB.
649 LandingPads.insert(NewBB);
650 ++NumLandingPadsSplit;
657 /// LowerUnwinds - Turn unwind instructions into calls to _Unwind_Resume,
658 /// rethrowing any previously caught exception. This will crash horribly
659 /// at runtime if there is no such exception: using unwind to throw a new
660 /// exception is currently not supported.
661 bool DwarfEHPrepare::LowerUnwinds() {
662 SmallVector<TerminatorInst*, 16> UnwindInsts;
664 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
665 TerminatorInst *TI = I->getTerminator();
666 if (isa<UnwindInst>(TI))
667 UnwindInsts.push_back(TI);
670 if (UnwindInsts.empty()) return false;
672 // Find the rewind function if we didn't already.
673 if (!RewindFunction) {
674 LLVMContext &Ctx = UnwindInsts[0]->getContext();
675 std::vector<const Type*>
676 Params(1, Type::getInt8PtrTy(Ctx));
677 FunctionType *FTy = FunctionType::get(Type::getVoidTy(Ctx),
679 const char *RewindName = TLI->getLibcallName(RTLIB::UNWIND_RESUME);
680 RewindFunction = F->getParent()->getOrInsertFunction(RewindName, FTy);
683 bool Changed = false;
685 for (SmallVectorImpl<TerminatorInst*>::iterator
686 I = UnwindInsts.begin(), E = UnwindInsts.end(); I != E; ++I) {
687 TerminatorInst *TI = *I;
689 // Replace the unwind instruction with a call to _Unwind_Resume (or the
690 // appropriate target equivalent) followed by an UnreachableInst.
692 // Create the call...
693 CallInst *CI = CallInst::Create(RewindFunction,
694 CreateReadOfExceptionValue(TI->getParent()),
696 CI->setCallingConv(TLI->getLibcallCallingConv(RTLIB::UNWIND_RESUME));
697 // ...followed by an UnreachableInst.
698 new UnreachableInst(TI->getContext(), TI);
700 // Nuke the unwind instruction.
701 TI->eraseFromParent();
709 /// MoveExceptionValueCalls - Ensure that eh.exception is only ever called from
710 /// landing pads by replacing calls outside of landing pads with loads from a
711 /// stack temporary. Move eh.exception calls inside landing pads to the start
712 /// of the landing pad (optional, but may make things simpler for later passes).
713 bool DwarfEHPrepare::MoveExceptionValueCalls() {
714 // If the eh.exception intrinsic is not declared in the module then there is
715 // nothing to do. Speed up compilation by checking for this common case.
716 if (!ExceptionValueIntrinsic &&
717 !F->getParent()->getFunction(Intrinsic::getName(Intrinsic::eh_exception)))
720 bool Changed = false;
722 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
723 for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E;)
724 if (IntrinsicInst *CI = dyn_cast<IntrinsicInst>(II++))
725 if (CI->getIntrinsicID() == Intrinsic::eh_exception) {
726 if (!CI->use_empty()) {
727 Value *ExceptionValue = CreateReadOfExceptionValue(BB);
728 if (CI == ExceptionValue) {
729 // The call was at the start of a landing pad - leave it alone.
730 assert(LandingPads.count(BB) &&
731 "Created eh.exception call outside landing pad!");
734 CI->replaceAllUsesWith(ExceptionValue);
736 CI->eraseFromParent();
737 ++NumExceptionValuesMoved;
745 /// FinishStackTemporaries - If we introduced a stack variable to hold the
746 /// exception value then initialize it in each landing pad.
747 bool DwarfEHPrepare::FinishStackTemporaries() {
748 if (!ExceptionValueVar)
752 bool Changed = false;
754 // Make sure that there is a store of the exception value at the start of
756 for (BBSet::iterator LI = LandingPads.begin(), LE = LandingPads.end();
758 Instruction *ExceptionValue = CreateReadOfExceptionValue(*LI);
759 Instruction *Store = new StoreInst(ExceptionValue, ExceptionValueVar);
760 Store->insertAfter(ExceptionValue);
767 /// PromoteStackTemporaries - Turn any stack temporaries we introduced into
768 /// registers if possible.
769 bool DwarfEHPrepare::PromoteStackTemporaries() {
770 // Turn the exception temporary into registers and phi nodes if possible.
771 if (ExceptionValueVar && isAllocaPromotable(ExceptionValueVar)) {
772 PromoteAlloca(ExceptionValueVar);
778 /// CreateExceptionValueCall - Insert a call to the eh.exception intrinsic at
779 /// the start of the basic block (unless there already is one, in which case
780 /// the existing call is returned).
781 Instruction *DwarfEHPrepare::CreateExceptionValueCall(BasicBlock *BB) {
782 Instruction *Start = BB->getFirstNonPHIOrDbg();
783 // Is this a call to eh.exception?
784 if (IntrinsicInst *CI = dyn_cast<IntrinsicInst>(Start))
785 if (CI->getIntrinsicID() == Intrinsic::eh_exception)
786 // Reuse the existing call.
789 // Find the eh.exception intrinsic if we didn't already.
790 if (!ExceptionValueIntrinsic)
791 ExceptionValueIntrinsic = Intrinsic::getDeclaration(F->getParent(),
792 Intrinsic::eh_exception);
795 return CallInst::Create(ExceptionValueIntrinsic, "eh.value.call", Start);
798 /// CreateValueLoad - Insert a load of the exception value stack variable
799 /// (creating it if necessary) at the start of the basic block (unless
800 /// there already is a load, in which case the existing load is returned).
801 Instruction *DwarfEHPrepare::CreateValueLoad(BasicBlock *BB) {
802 Instruction *Start = BB->getFirstNonPHIOrDbg();
803 // Is this a load of the exception temporary?
804 if (ExceptionValueVar)
805 if (LoadInst* LI = dyn_cast<LoadInst>(Start))
806 if (LI->getPointerOperand() == ExceptionValueVar)
807 // Reuse the existing load.
810 // Create the temporary if we didn't already.
811 if (!ExceptionValueVar) {
812 ExceptionValueVar = new AllocaInst(PointerType::getUnqual(
813 Type::getInt8Ty(BB->getContext())), "eh.value", F->begin()->begin());
814 ++NumStackTempsIntroduced;
818 return new LoadInst(ExceptionValueVar, "eh.value.load", Start);
821 bool DwarfEHPrepare::runOnFunction(Function &Fn) {
822 bool Changed = false;
824 // Initialize internal state.
825 DT = getAnalysisIfAvailable<DominatorTree>();
826 ExceptionValueVar = 0;
829 // Ensure that only unwind edges end at landing pads (a landing pad is a
830 // basic block where an invoke unwind edge ends).
831 Changed |= NormalizeLandingPads();
833 // Turn unwind instructions into libcalls.
834 Changed |= LowerUnwinds();
836 // TODO: Move eh.selector calls to landing pads and combine them.
838 // Move eh.exception calls to landing pads.
839 Changed |= MoveExceptionValueCalls();
841 // Initialize any stack temporaries we introduced.
842 Changed |= FinishStackTemporaries();
844 // Turn any stack temporaries into registers.
846 Changed |= PromoteStackTemporaries();
848 Changed |= HandleURoRInvokes();