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 TargetLowering *TLI;
40 // The eh.exception intrinsic.
41 Function *ExceptionValueIntrinsic;
43 // The eh.selector intrinsic.
44 Function *SelectorIntrinsic;
46 // _Unwind_Resume_or_Rethrow call.
49 // The EH language-specific catch-all type.
50 GlobalVariable *EHCatchAllValue;
52 // _Unwind_Resume or the target equivalent.
53 Constant *RewindFunction;
55 // Dominator info is used when turning stack temporaries into registers.
57 DominanceFrontier *DF;
59 // The function we are running on.
62 // The landing pads for this function.
63 typedef SmallPtrSet<BasicBlock*, 8> BBSet;
66 // Stack temporary used to hold eh.exception values.
67 AllocaInst *ExceptionValueVar;
69 bool NormalizeLandingPads();
71 bool MoveExceptionValueCalls();
72 bool FinishStackTemporaries();
73 bool PromoteStackTemporaries();
75 Instruction *CreateExceptionValueCall(BasicBlock *BB);
76 Instruction *CreateValueLoad(BasicBlock *BB);
78 /// CreateReadOfExceptionValue - Return the result of the eh.exception
79 /// intrinsic by calling the intrinsic if in a landing pad, or loading it
80 /// from the exception value variable otherwise.
81 Instruction *CreateReadOfExceptionValue(BasicBlock *BB) {
82 return LandingPads.count(BB) ?
83 CreateExceptionValueCall(BB) : CreateValueLoad(BB);
86 /// HandleURoRInvokes - Handle invokes of "_Unwind_Resume_or_Rethrow"
87 /// calls. The "unwind" part of these invokes jump to a landing pad within
88 /// the current function. This is a candidate to merge the selector
89 /// associated with the URoR invoke with the one from the URoR's landing
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);
99 /// DoMem2RegPromotion - Take an alloca call and promote it from memory to a
101 bool DoMem2RegPromotion(Value *V) {
102 AllocaInst *AI = dyn_cast<AllocaInst>(V);
103 if (!AI || !isAllocaPromotable(AI)) return false;
105 // Turn the alloca into a register.
106 std::vector<AllocaInst*> Allocas(1, AI);
107 PromoteMemToReg(Allocas, *DT, *DF);
111 /// PromoteStoreInst - Perform Mem2Reg on a StoreInst.
112 bool PromoteStoreInst(StoreInst *SI) {
113 if (!SI || !DT || !DF) return false;
114 if (DoMem2RegPromotion(SI->getOperand(1)))
119 /// PromoteEHPtrStore - Promote the storing of an EH pointer into a
120 /// register. This should get rid of the store and subsequent loads.
121 bool PromoteEHPtrStore(IntrinsicInst *II) {
122 if (!DT || !DF) return false;
124 bool Changed = false;
129 for (Value::use_iterator
130 I = II->use_begin(), E = II->use_end(); I != E; ++I) {
131 SI = dyn_cast<StoreInst>(I);
135 if (!PromoteStoreInst(SI))
145 static char ID; // Pass identification, replacement for typeid.
146 DwarfEHPrepare(const TargetLowering *tli, bool fast) :
147 FunctionPass(&ID), TLI(tli), CompileFast(fast),
148 ExceptionValueIntrinsic(0), SelectorIntrinsic(0),
149 URoR(0), EHCatchAllValue(0), RewindFunction(0) {}
151 virtual bool runOnFunction(Function &Fn);
153 // getAnalysisUsage - We need dominance frontiers for memory promotion.
154 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
156 AU.addRequired<DominatorTree>();
157 AU.addPreserved<DominatorTree>();
159 AU.addRequired<DominanceFrontier>();
160 AU.addPreserved<DominanceFrontier>();
163 const char *getPassName() const {
164 return "Exception handling preparation";
168 } // end anonymous namespace
170 char DwarfEHPrepare::ID = 0;
172 FunctionPass *llvm::createDwarfEHPass(const TargetLowering *tli, bool fast) {
173 return new DwarfEHPrepare(tli, fast);
176 /// FindSelectorAndURoR - Find the eh.selector call associated with the
177 /// eh.exception call. And indicate if there is a URoR "invoke" associated with
178 /// the eh.exception call. This recursively looks past instructions which don't
179 /// change the EH pointer value, like casts or PHI nodes.
181 DwarfEHPrepare::FindSelectorAndURoR(Instruction *Inst, bool &URoRInvoke,
182 SmallPtrSet<IntrinsicInst*, 8> &SelCalls) {
183 SmallPtrSet<PHINode*, 32> SeenPHIs;
184 bool Changed = false;
187 for (Value::use_iterator
188 I = Inst->use_begin(), E = Inst->use_end(); I != E; ++I) {
189 Instruction *II = dyn_cast<Instruction>(I);
190 if (!II || II->getParent()->getParent() != F) continue;
192 if (IntrinsicInst *Sel = dyn_cast<IntrinsicInst>(II)) {
193 if (Sel->getIntrinsicID() == Intrinsic::eh_selector)
194 SelCalls.insert(Sel);
195 } else if (InvokeInst *Invoke = dyn_cast<InvokeInst>(II)) {
196 if (Invoke->getCalledFunction() == URoR)
198 } else if (CastInst *CI = dyn_cast<CastInst>(II)) {
199 Changed |= FindSelectorAndURoR(CI, URoRInvoke, SelCalls);
200 } else if (StoreInst *SI = dyn_cast<StoreInst>(II)) {
201 if (!PromoteStoreInst(SI)) continue;
204 goto restart; // Uses may have changed, restart loop.
205 } else if (PHINode *PN = dyn_cast<PHINode>(II)) {
206 if (SeenPHIs.insert(PN))
207 // Don't process a PHI node more than once.
208 Changed |= FindSelectorAndURoR(PN, URoRInvoke, SelCalls);
215 /// HandleURoRInvokes - Handle invokes of "_Unwind_Resume_or_Rethrow" calls. The
216 /// "unwind" part of these invokes jump to a landing pad within the current
217 /// function. This is a candidate to merge the selector associated with the URoR
218 /// invoke with the one from the URoR's landing pad.
219 bool DwarfEHPrepare::HandleURoRInvokes() {
220 if (!EHCatchAllValue) {
222 F->getParent()->getNamedGlobal(".llvm.eh.catch.all.value");
223 if (!EHCatchAllValue) return false;
227 URoR = F->getParent()->getFunction("_Unwind_Resume_or_Rethrow");
228 if (!URoR) return false;
231 if (!ExceptionValueIntrinsic) {
232 ExceptionValueIntrinsic =
233 Intrinsic::getDeclaration(F->getParent(), Intrinsic::eh_exception);
234 if (!ExceptionValueIntrinsic) return false;
237 if (!SelectorIntrinsic) {
239 Intrinsic::getDeclaration(F->getParent(), Intrinsic::eh_selector);
240 if (!SelectorIntrinsic) return false;
243 bool Changed = false;
244 SmallPtrSet<IntrinsicInst*, 32> SelsToConvert;
246 for (Value::use_iterator
247 I = ExceptionValueIntrinsic->use_begin(),
248 E = ExceptionValueIntrinsic->use_end(); I != E; ++I) {
249 IntrinsicInst *EHPtr = dyn_cast<IntrinsicInst>(I);
250 if (!EHPtr || EHPtr->getParent()->getParent() != F) continue;
252 Changed |= PromoteEHPtrStore(EHPtr);
254 bool URoRInvoke = false;
255 SmallPtrSet<IntrinsicInst*, 8> SelCalls;
256 Changed |= FindSelectorAndURoR(EHPtr, URoRInvoke, SelCalls);
259 // This EH pointer is being used by an invoke of an URoR instruction and
260 // an eh.selector intrinsic call. If the eh.selector is a 'clean-up', we
261 // need to convert it to a 'catch-all'.
262 for (SmallPtrSet<IntrinsicInst*, 8>::iterator
263 SI = SelCalls.begin(), SE = SelCalls.end(); SI != SE; ++SI) {
264 IntrinsicInst *II = *SI;
265 unsigned NumOps = II->getNumOperands();
268 bool IsCleanUp = (NumOps == 3);
271 if (ConstantInt *CI = dyn_cast<ConstantInt>(II->getOperand(3)))
272 IsCleanUp = (CI->getZExtValue() == 0);
275 SelsToConvert.insert(II);
281 if (!SelsToConvert.empty()) {
282 // Convert all clean-up eh.selectors, which are associated with "invokes" of
283 // URoR calls, into catch-all eh.selectors.
286 for (SmallPtrSet<IntrinsicInst*, 8>::iterator
287 SI = SelsToConvert.begin(), SE = SelsToConvert.end();
289 IntrinsicInst *II = *SI;
290 SmallVector<Value*, 8> Args;
292 // Use the exception object pointer and the personality function
293 // from the original selector.
294 Args.push_back(II->getOperand(1)); // Exception object pointer.
295 Args.push_back(II->getOperand(2)); // Personality function.
296 Args.push_back(EHCatchAllValue->getInitializer()); // Catch-all indicator.
298 CallInst *NewSelector =
299 CallInst::Create(SelectorIntrinsic, Args.begin(), Args.end(),
300 "eh.sel.catch.all", II);
302 NewSelector->setTailCall(II->isTailCall());
303 NewSelector->setAttributes(II->getAttributes());
304 NewSelector->setCallingConv(II->getCallingConv());
306 II->replaceAllUsesWith(NewSelector);
307 II->eraseFromParent();
314 /// NormalizeLandingPads - Normalize and discover landing pads, noting them
315 /// in the LandingPads set. A landing pad is normal if the only CFG edges
316 /// that end at it are unwind edges from invoke instructions. If we inlined
317 /// through an invoke we could have a normal branch from the previous
318 /// unwind block through to the landing pad for the original invoke.
319 /// Abnormal landing pads are fixed up by redirecting all unwind edges to
320 /// a new basic block which falls through to the original.
321 bool DwarfEHPrepare::NormalizeLandingPads() {
322 bool Changed = false;
324 const MCAsmInfo *MAI = TLI->getTargetMachine().getMCAsmInfo();
325 bool usingSjLjEH = MAI->getExceptionHandlingType() == ExceptionHandling::SjLj;
327 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
328 TerminatorInst *TI = I->getTerminator();
329 if (!isa<InvokeInst>(TI))
331 BasicBlock *LPad = TI->getSuccessor(1);
332 // Skip landing pads that have already been normalized.
333 if (LandingPads.count(LPad))
336 // Check that only invoke unwind edges end at the landing pad.
337 bool OnlyUnwoundTo = true;
338 bool SwitchOK = usingSjLjEH;
339 for (pred_iterator PI = pred_begin(LPad), PE = pred_end(LPad);
341 TerminatorInst *PT = (*PI)->getTerminator();
342 // The SjLj dispatch block uses a switch instruction. This is effectively
343 // an unwind edge, so we can disregard it here. There will only ever
344 // be one dispatch, however, so if there are multiple switches, one
345 // of them truly is a normal edge, not an unwind edge.
346 if (SwitchOK && isa<SwitchInst>(PT)) {
350 if (!isa<InvokeInst>(PT) || LPad == PT->getSuccessor(0)) {
351 OnlyUnwoundTo = false;
357 // Only unwind edges lead to the landing pad. Remember the landing pad.
358 LandingPads.insert(LPad);
362 // At least one normal edge ends at the landing pad. Redirect the unwind
363 // edges to a new basic block which falls through into this one.
365 // Create the new basic block.
366 BasicBlock *NewBB = BasicBlock::Create(F->getContext(),
367 LPad->getName() + "_unwind_edge");
369 // Insert it into the function right before the original landing pad.
370 LPad->getParent()->getBasicBlockList().insert(LPad, NewBB);
372 // Redirect unwind edges from the original landing pad to NewBB.
373 for (pred_iterator PI = pred_begin(LPad), PE = pred_end(LPad); PI != PE; ) {
374 TerminatorInst *PT = (*PI++)->getTerminator();
375 if (isa<InvokeInst>(PT) && PT->getSuccessor(1) == LPad)
376 // Unwind to the new block.
377 PT->setSuccessor(1, NewBB);
380 // If there are any PHI nodes in LPad, we need to update them so that they
381 // merge incoming values from NewBB instead.
382 for (BasicBlock::iterator II = LPad->begin(); isa<PHINode>(II); ++II) {
383 PHINode *PN = cast<PHINode>(II);
384 pred_iterator PB = pred_begin(NewBB), PE = pred_end(NewBB);
386 // Check to see if all of the values coming in via unwind edges are the
387 // same. If so, we don't need to create a new PHI node.
388 Value *InVal = PN->getIncomingValueForBlock(*PB);
389 for (pred_iterator PI = PB; PI != PE; ++PI) {
390 if (PI != PB && InVal != PN->getIncomingValueForBlock(*PI)) {
397 // Different unwind edges have different values. Create a new PHI node
399 PHINode *NewPN = PHINode::Create(PN->getType(), PN->getName()+".unwind",
401 // Add an entry for each unwind edge, using the value from the old PHI.
402 for (pred_iterator PI = PB; PI != PE; ++PI)
403 NewPN->addIncoming(PN->getIncomingValueForBlock(*PI), *PI);
405 // Now use this new PHI as the common incoming value for NewBB in PN.
409 // Revector exactly one entry in the PHI node to come from NewBB
410 // and delete all other entries that come from unwind edges. If
411 // there are both normal and unwind edges from the same predecessor,
412 // this leaves an entry for the normal edge.
413 for (pred_iterator PI = PB; PI != PE; ++PI)
414 PN->removeIncomingValue(*PI);
415 PN->addIncoming(InVal, NewBB);
418 // Add a fallthrough from NewBB to the original landing pad.
419 BranchInst::Create(LPad, NewBB);
421 // Now update DominatorTree and DominanceFrontier analysis information.
423 DT->splitBlock(NewBB);
425 DF->splitBlock(NewBB);
427 // Remember the newly constructed landing pad. The original landing pad
428 // LPad is no longer a landing pad now that all unwind edges have been
429 // revectored to NewBB.
430 LandingPads.insert(NewBB);
431 ++NumLandingPadsSplit;
438 /// LowerUnwinds - Turn unwind instructions into calls to _Unwind_Resume,
439 /// rethrowing any previously caught exception. This will crash horribly
440 /// at runtime if there is no such exception: using unwind to throw a new
441 /// exception is currently not supported.
442 bool DwarfEHPrepare::LowerUnwinds() {
443 SmallVector<TerminatorInst*, 16> UnwindInsts;
445 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
446 TerminatorInst *TI = I->getTerminator();
447 if (isa<UnwindInst>(TI))
448 UnwindInsts.push_back(TI);
451 if (UnwindInsts.empty()) return false;
453 // Find the rewind function if we didn't already.
454 if (!RewindFunction) {
455 LLVMContext &Ctx = UnwindInsts[0]->getContext();
456 std::vector<const Type*>
457 Params(1, Type::getInt8PtrTy(Ctx));
458 FunctionType *FTy = FunctionType::get(Type::getVoidTy(Ctx),
460 const char *RewindName = TLI->getLibcallName(RTLIB::UNWIND_RESUME);
461 RewindFunction = F->getParent()->getOrInsertFunction(RewindName, FTy);
464 bool Changed = false;
466 for (SmallVectorImpl<TerminatorInst*>::iterator
467 I = UnwindInsts.begin(), E = UnwindInsts.end(); I != E; ++I) {
468 TerminatorInst *TI = *I;
470 // Replace the unwind instruction with a call to _Unwind_Resume (or the
471 // appropriate target equivalent) followed by an UnreachableInst.
473 // Create the call...
474 CallInst *CI = CallInst::Create(RewindFunction,
475 CreateReadOfExceptionValue(TI->getParent()),
477 CI->setCallingConv(TLI->getLibcallCallingConv(RTLIB::UNWIND_RESUME));
478 // ...followed by an UnreachableInst.
479 new UnreachableInst(TI->getContext(), TI);
481 // Nuke the unwind instruction.
482 TI->eraseFromParent();
490 /// MoveExceptionValueCalls - Ensure that eh.exception is only ever called from
491 /// landing pads by replacing calls outside of landing pads with loads from a
492 /// stack temporary. Move eh.exception calls inside landing pads to the start
493 /// of the landing pad (optional, but may make things simpler for later passes).
494 bool DwarfEHPrepare::MoveExceptionValueCalls() {
495 // If the eh.exception intrinsic is not declared in the module then there is
496 // nothing to do. Speed up compilation by checking for this common case.
497 if (!ExceptionValueIntrinsic &&
498 !F->getParent()->getFunction(Intrinsic::getName(Intrinsic::eh_exception)))
501 bool Changed = false;
503 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
504 for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E;)
505 if (IntrinsicInst *CI = dyn_cast<IntrinsicInst>(II++))
506 if (CI->getIntrinsicID() == Intrinsic::eh_exception) {
507 if (!CI->use_empty()) {
508 Value *ExceptionValue = CreateReadOfExceptionValue(BB);
509 if (CI == ExceptionValue) {
510 // The call was at the start of a landing pad - leave it alone.
511 assert(LandingPads.count(BB) &&
512 "Created eh.exception call outside landing pad!");
515 CI->replaceAllUsesWith(ExceptionValue);
517 CI->eraseFromParent();
518 ++NumExceptionValuesMoved;
526 /// FinishStackTemporaries - If we introduced a stack variable to hold the
527 /// exception value then initialize it in each landing pad.
528 bool DwarfEHPrepare::FinishStackTemporaries() {
529 if (!ExceptionValueVar)
533 bool Changed = false;
535 // Make sure that there is a store of the exception value at the start of
537 for (BBSet::iterator LI = LandingPads.begin(), LE = LandingPads.end();
539 Instruction *ExceptionValue = CreateReadOfExceptionValue(*LI);
540 Instruction *Store = new StoreInst(ExceptionValue, ExceptionValueVar);
541 Store->insertAfter(ExceptionValue);
548 /// PromoteStackTemporaries - Turn any stack temporaries we introduced into
549 /// registers if possible.
550 bool DwarfEHPrepare::PromoteStackTemporaries() {
551 if (ExceptionValueVar && DT && DF && isAllocaPromotable(ExceptionValueVar)) {
552 // Turn the exception temporary into registers and phi nodes if possible.
553 std::vector<AllocaInst*> Allocas(1, ExceptionValueVar);
554 PromoteMemToReg(Allocas, *DT, *DF);
560 /// CreateExceptionValueCall - Insert a call to the eh.exception intrinsic at
561 /// the start of the basic block (unless there already is one, in which case
562 /// the existing call is returned).
563 Instruction *DwarfEHPrepare::CreateExceptionValueCall(BasicBlock *BB) {
564 Instruction *Start = BB->getFirstNonPHI();
565 // Is this a call to eh.exception?
566 if (IntrinsicInst *CI = dyn_cast<IntrinsicInst>(Start))
567 if (CI->getIntrinsicID() == Intrinsic::eh_exception)
568 // Reuse the existing call.
571 // Find the eh.exception intrinsic if we didn't already.
572 if (!ExceptionValueIntrinsic)
573 ExceptionValueIntrinsic = Intrinsic::getDeclaration(F->getParent(),
574 Intrinsic::eh_exception);
577 return CallInst::Create(ExceptionValueIntrinsic, "eh.value.call", Start);
580 /// CreateValueLoad - Insert a load of the exception value stack variable
581 /// (creating it if necessary) at the start of the basic block (unless
582 /// there already is a load, in which case the existing load is returned).
583 Instruction *DwarfEHPrepare::CreateValueLoad(BasicBlock *BB) {
584 Instruction *Start = BB->getFirstNonPHI();
585 // Is this a load of the exception temporary?
586 if (ExceptionValueVar)
587 if (LoadInst* LI = dyn_cast<LoadInst>(Start))
588 if (LI->getPointerOperand() == ExceptionValueVar)
589 // Reuse the existing load.
592 // Create the temporary if we didn't already.
593 if (!ExceptionValueVar) {
594 ExceptionValueVar = new AllocaInst(PointerType::getUnqual(
595 Type::getInt8Ty(BB->getContext())), "eh.value", F->begin()->begin());
596 ++NumStackTempsIntroduced;
600 return new LoadInst(ExceptionValueVar, "eh.value.load", Start);
603 bool DwarfEHPrepare::runOnFunction(Function &Fn) {
604 bool Changed = false;
606 // Initialize internal state.
607 DT = getAnalysisIfAvailable<DominatorTree>();
608 DF = getAnalysisIfAvailable<DominanceFrontier>();
609 ExceptionValueVar = 0;
612 // Ensure that only unwind edges end at landing pads (a landing pad is a
613 // basic block where an invoke unwind edge ends).
614 Changed |= NormalizeLandingPads();
616 // Turn unwind instructions into libcalls.
617 Changed |= LowerUnwinds();
619 // TODO: Move eh.selector calls to landing pads and combine them.
621 // Move eh.exception calls to landing pads.
622 Changed |= MoveExceptionValueCalls();
624 // Initialize any stack temporaries we introduced.
625 Changed |= FinishStackTemporaries();
627 // Turn any stack temporaries into registers if possible.
629 Changed |= PromoteStackTemporaries();
631 Changed |= HandleURoRInvokes();