zpu: managed to compile program that writes constant to global variable
[llvm/zpu.git] / lib / CodeGen / DwarfEHPrepare.cpp
blob0ebb5b0db70e1417ab13a5b355b18f2ec36e7716
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(NumExceptionValuesMoved, "Number of eh.exception calls moved");
35 namespace {
36 class DwarfEHPrepare : public FunctionPass {
37 const TargetMachine *TM;
38 const TargetLowering *TLI;
40 // The eh.exception intrinsic.
41 Function *ExceptionValueIntrinsic;
43 // The eh.selector intrinsic.
44 Function *SelectorIntrinsic;
46 // _Unwind_Resume_or_Rethrow or _Unwind_SjLj_Resume call.
47 Constant *URoR;
49 // The EH language-specific catch-all type.
50 GlobalVariable *EHCatchAllValue;
52 // _Unwind_Resume or the target equivalent.
53 Constant *RewindFunction;
55 // We both use and preserve dominator info.
56 DominatorTree *DT;
58 // The function we are running on.
59 Function *F;
61 // The landing pads for this function.
62 typedef SmallPtrSet<BasicBlock*, 8> BBSet;
63 BBSet LandingPads;
65 bool NormalizeLandingPads();
66 bool LowerUnwinds();
67 bool MoveExceptionValueCalls();
69 Instruction *CreateExceptionValueCall(BasicBlock *BB);
71 /// CleanupSelectors - Any remaining eh.selector intrinsic calls which still
72 /// use the "llvm.eh.catch.all.value" call need to convert to using its
73 /// initializer instead.
74 bool CleanupSelectors(SmallPtrSet<IntrinsicInst*, 32> &Sels);
76 bool HasCatchAllInSelector(IntrinsicInst *);
78 /// FindAllCleanupSelectors - Find all eh.selector calls that are clean-ups.
79 void FindAllCleanupSelectors(SmallPtrSet<IntrinsicInst*, 32> &Sels,
80 SmallPtrSet<IntrinsicInst*, 32> &CatchAllSels);
82 /// FindAllURoRInvokes - Find all URoR invokes in the function.
83 void FindAllURoRInvokes(SmallPtrSet<InvokeInst*, 32> &URoRInvokes);
85 /// HandleURoRInvokes - Handle invokes of "_Unwind_Resume_or_Rethrow" or
86 /// "_Unwind_SjLj_Resume" calls. The "unwind" part of these invokes jump to
87 /// a landing pad within the current function. This is a candidate to merge
88 /// the selector associated with the URoR invoke with the one from the
89 /// URoR's landing pad.
90 bool HandleURoRInvokes();
92 /// FindSelectorAndURoR - Find the eh.selector call and URoR call associated
93 /// with the eh.exception call. This recursively looks past instructions
94 /// which don't change the EH pointer value, like casts or PHI nodes.
95 bool FindSelectorAndURoR(Instruction *Inst, bool &URoRInvoke,
96 SmallPtrSet<IntrinsicInst*, 8> &SelCalls);
98 public:
99 static char ID; // Pass identification, replacement for typeid.
100 DwarfEHPrepare(const TargetMachine *tm) :
101 FunctionPass(ID), TM(tm), TLI(TM->getTargetLowering()),
102 ExceptionValueIntrinsic(0), SelectorIntrinsic(0),
103 URoR(0), EHCatchAllValue(0), RewindFunction(0) {
104 initializeDominatorTreePass(*PassRegistry::getPassRegistry());
107 virtual bool runOnFunction(Function &Fn);
109 // getAnalysisUsage - We need the dominator tree for handling URoR.
110 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
111 AU.addRequired<DominatorTree>();
112 AU.addPreserved<DominatorTree>();
115 const char *getPassName() const {
116 return "Exception handling preparation";
120 } // end anonymous namespace
122 char DwarfEHPrepare::ID = 0;
124 FunctionPass *llvm::createDwarfEHPass(const TargetMachine *tm) {
125 return new DwarfEHPrepare(tm);
128 /// HasCatchAllInSelector - Return true if the intrinsic instruction has a
129 /// catch-all.
130 bool DwarfEHPrepare::HasCatchAllInSelector(IntrinsicInst *II) {
131 if (!EHCatchAllValue) return false;
133 unsigned ArgIdx = II->getNumArgOperands() - 1;
134 GlobalVariable *GV = dyn_cast<GlobalVariable>(II->getArgOperand(ArgIdx));
135 return GV == EHCatchAllValue;
138 /// FindAllCleanupSelectors - Find all eh.selector calls that are clean-ups.
139 void DwarfEHPrepare::
140 FindAllCleanupSelectors(SmallPtrSet<IntrinsicInst*, 32> &Sels,
141 SmallPtrSet<IntrinsicInst*, 32> &CatchAllSels) {
142 for (Value::use_iterator
143 I = SelectorIntrinsic->use_begin(),
144 E = SelectorIntrinsic->use_end(); I != E; ++I) {
145 IntrinsicInst *II = cast<IntrinsicInst>(*I);
147 if (II->getParent()->getParent() != F)
148 continue;
150 if (!HasCatchAllInSelector(II))
151 Sels.insert(II);
152 else
153 CatchAllSels.insert(II);
157 /// FindAllURoRInvokes - Find all URoR invokes in the function.
158 void DwarfEHPrepare::
159 FindAllURoRInvokes(SmallPtrSet<InvokeInst*, 32> &URoRInvokes) {
160 for (Value::use_iterator
161 I = URoR->use_begin(),
162 E = URoR->use_end(); I != E; ++I) {
163 if (InvokeInst *II = dyn_cast<InvokeInst>(*I))
164 URoRInvokes.insert(II);
168 /// CleanupSelectors - Any remaining eh.selector intrinsic calls which still use
169 /// the "llvm.eh.catch.all.value" call need to convert to using its
170 /// initializer instead.
171 bool DwarfEHPrepare::CleanupSelectors(SmallPtrSet<IntrinsicInst*, 32> &Sels) {
172 if (!EHCatchAllValue) return false;
174 if (!SelectorIntrinsic) {
175 SelectorIntrinsic =
176 Intrinsic::getDeclaration(F->getParent(), Intrinsic::eh_selector);
177 if (!SelectorIntrinsic) return false;
180 bool Changed = false;
181 for (SmallPtrSet<IntrinsicInst*, 32>::iterator
182 I = Sels.begin(), E = Sels.end(); I != E; ++I) {
183 IntrinsicInst *Sel = *I;
185 // Index of the "llvm.eh.catch.all.value" variable.
186 unsigned OpIdx = Sel->getNumArgOperands() - 1;
187 GlobalVariable *GV = dyn_cast<GlobalVariable>(Sel->getArgOperand(OpIdx));
188 if (GV != EHCatchAllValue) continue;
189 Sel->setArgOperand(OpIdx, EHCatchAllValue->getInitializer());
190 Changed = true;
193 return Changed;
196 /// FindSelectorAndURoR - Find the eh.selector call associated with the
197 /// eh.exception call. And indicate if there is a URoR "invoke" associated with
198 /// the eh.exception call. This recursively looks past instructions which don't
199 /// change the EH pointer value, like casts or PHI nodes.
200 bool
201 DwarfEHPrepare::FindSelectorAndURoR(Instruction *Inst, bool &URoRInvoke,
202 SmallPtrSet<IntrinsicInst*, 8> &SelCalls) {
203 SmallPtrSet<PHINode*, 32> SeenPHIs;
204 bool Changed = false;
206 for (Value::use_iterator
207 I = Inst->use_begin(), E = Inst->use_end(); I != E; ++I) {
208 Instruction *II = dyn_cast<Instruction>(*I);
209 if (!II || II->getParent()->getParent() != F) continue;
211 if (IntrinsicInst *Sel = dyn_cast<IntrinsicInst>(II)) {
212 if (Sel->getIntrinsicID() == Intrinsic::eh_selector)
213 SelCalls.insert(Sel);
214 } else if (InvokeInst *Invoke = dyn_cast<InvokeInst>(II)) {
215 if (Invoke->getCalledFunction() == URoR)
216 URoRInvoke = true;
217 } else if (CastInst *CI = dyn_cast<CastInst>(II)) {
218 Changed |= FindSelectorAndURoR(CI, URoRInvoke, SelCalls);
219 } else if (PHINode *PN = dyn_cast<PHINode>(II)) {
220 if (SeenPHIs.insert(PN))
221 // Don't process a PHI node more than once.
222 Changed |= FindSelectorAndURoR(PN, URoRInvoke, SelCalls);
226 return Changed;
229 /// HandleURoRInvokes - Handle invokes of "_Unwind_Resume_or_Rethrow" or
230 /// "_Unwind_SjLj_Resume" calls. The "unwind" part of these invokes jump to a
231 /// landing pad within the current function. This is a candidate to merge the
232 /// selector associated with the URoR invoke with the one from the URoR's
233 /// landing pad.
234 bool DwarfEHPrepare::HandleURoRInvokes() {
235 if (!EHCatchAllValue) {
236 EHCatchAllValue =
237 F->getParent()->getNamedGlobal("llvm.eh.catch.all.value");
238 if (!EHCatchAllValue) return false;
241 if (!SelectorIntrinsic) {
242 SelectorIntrinsic =
243 Intrinsic::getDeclaration(F->getParent(), Intrinsic::eh_selector);
244 if (!SelectorIntrinsic) return false;
247 SmallPtrSet<IntrinsicInst*, 32> Sels;
248 SmallPtrSet<IntrinsicInst*, 32> CatchAllSels;
249 FindAllCleanupSelectors(Sels, CatchAllSels);
251 if (!URoR) {
252 URoR = F->getParent()->getFunction("_Unwind_Resume_or_Rethrow");
253 if (!URoR) {
254 URoR = F->getParent()->getFunction("_Unwind_SjLj_Resume");
255 if (!URoR) return CleanupSelectors(CatchAllSels);
259 SmallPtrSet<InvokeInst*, 32> URoRInvokes;
260 FindAllURoRInvokes(URoRInvokes);
262 SmallPtrSet<IntrinsicInst*, 32> SelsToConvert;
264 for (SmallPtrSet<IntrinsicInst*, 32>::iterator
265 SI = Sels.begin(), SE = Sels.end(); SI != SE; ++SI) {
266 const BasicBlock *SelBB = (*SI)->getParent();
267 for (SmallPtrSet<InvokeInst*, 32>::iterator
268 UI = URoRInvokes.begin(), UE = URoRInvokes.end(); UI != UE; ++UI) {
269 const BasicBlock *URoRBB = (*UI)->getParent();
270 if (DT->dominates(SelBB, URoRBB)) {
271 SelsToConvert.insert(*SI);
272 break;
277 bool Changed = false;
279 if (Sels.size() != SelsToConvert.size()) {
280 // If we haven't been able to convert all of the clean-up selectors, then
281 // loop through the slow way to see if they still need to be converted.
282 if (!ExceptionValueIntrinsic) {
283 ExceptionValueIntrinsic =
284 Intrinsic::getDeclaration(F->getParent(), Intrinsic::eh_exception);
285 if (!ExceptionValueIntrinsic)
286 return CleanupSelectors(CatchAllSels);
289 for (Value::use_iterator
290 I = ExceptionValueIntrinsic->use_begin(),
291 E = ExceptionValueIntrinsic->use_end(); I != E; ++I) {
292 IntrinsicInst *EHPtr = dyn_cast<IntrinsicInst>(*I);
293 if (!EHPtr || EHPtr->getParent()->getParent() != F) continue;
295 bool URoRInvoke = false;
296 SmallPtrSet<IntrinsicInst*, 8> SelCalls;
297 Changed |= FindSelectorAndURoR(EHPtr, URoRInvoke, SelCalls);
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(), PN->getName()+".unwind",
441 NewBB);
442 // Add an entry for each unwind edge, using the value from the old PHI.
443 for (pred_iterator PI = PB; PI != PE; ++PI)
444 NewPN->addIncoming(PN->getIncomingValueForBlock(*PI), *PI);
446 // Now use this new PHI as the common incoming value for NewBB in PN.
447 InVal = NewPN;
450 // Revector exactly one entry in the PHI node to come from NewBB
451 // and delete all other entries that come from unwind edges. If
452 // there are both normal and unwind edges from the same predecessor,
453 // this leaves an entry for the normal edge.
454 for (pred_iterator PI = PB; PI != PE; ++PI)
455 PN->removeIncomingValue(*PI);
456 PN->addIncoming(InVal, NewBB);
459 // Add a fallthrough from NewBB to the original landing pad.
460 BranchInst::Create(LPad, NewBB);
462 // Now update DominatorTree analysis information.
463 DT->splitBlock(NewBB);
465 // Remember the newly constructed landing pad. The original landing pad
466 // LPad is no longer a landing pad now that all unwind edges have been
467 // revectored to NewBB.
468 LandingPads.insert(NewBB);
469 ++NumLandingPadsSplit;
470 Changed = true;
473 return Changed;
476 /// LowerUnwinds - Turn unwind instructions into calls to _Unwind_Resume,
477 /// rethrowing any previously caught exception. This will crash horribly
478 /// at runtime if there is no such exception: using unwind to throw a new
479 /// exception is currently not supported.
480 bool DwarfEHPrepare::LowerUnwinds() {
481 SmallVector<TerminatorInst*, 16> UnwindInsts;
483 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
484 TerminatorInst *TI = I->getTerminator();
485 if (isa<UnwindInst>(TI))
486 UnwindInsts.push_back(TI);
489 if (UnwindInsts.empty()) return false;
491 // Find the rewind function if we didn't already.
492 if (!RewindFunction) {
493 LLVMContext &Ctx = UnwindInsts[0]->getContext();
494 std::vector<const Type*>
495 Params(1, Type::getInt8PtrTy(Ctx));
496 FunctionType *FTy = FunctionType::get(Type::getVoidTy(Ctx),
497 Params, false);
498 const char *RewindName = TLI->getLibcallName(RTLIB::UNWIND_RESUME);
499 RewindFunction = F->getParent()->getOrInsertFunction(RewindName, FTy);
502 bool Changed = false;
504 for (SmallVectorImpl<TerminatorInst*>::iterator
505 I = UnwindInsts.begin(), E = UnwindInsts.end(); I != E; ++I) {
506 TerminatorInst *TI = *I;
508 // Replace the unwind instruction with a call to _Unwind_Resume (or the
509 // appropriate target equivalent) followed by an UnreachableInst.
511 // Create the call...
512 CallInst *CI = CallInst::Create(RewindFunction,
513 CreateExceptionValueCall(TI->getParent()),
514 "", TI);
515 CI->setCallingConv(TLI->getLibcallCallingConv(RTLIB::UNWIND_RESUME));
516 // ...followed by an UnreachableInst.
517 new UnreachableInst(TI->getContext(), TI);
519 // Nuke the unwind instruction.
520 TI->eraseFromParent();
521 ++NumUnwindsLowered;
522 Changed = true;
525 return Changed;
528 /// MoveExceptionValueCalls - Ensure that eh.exception is only ever called from
529 /// landing pads by replacing calls outside of landing pads with direct use of
530 /// a register holding the appropriate value; this requires adding calls inside
531 /// all landing pads to initialize the register. Also, move eh.exception calls
532 /// inside landing pads to the start of the landing pad (optional, but may make
533 /// things simpler for later passes).
534 bool DwarfEHPrepare::MoveExceptionValueCalls() {
535 // If the eh.exception intrinsic is not declared in the module then there is
536 // nothing to do. Speed up compilation by checking for this common case.
537 if (!ExceptionValueIntrinsic &&
538 !F->getParent()->getFunction(Intrinsic::getName(Intrinsic::eh_exception)))
539 return false;
541 bool Changed = false;
543 // Move calls to eh.exception that are inside a landing pad to the start of
544 // the landing pad.
545 for (BBSet::const_iterator LI = LandingPads.begin(), LE = LandingPads.end();
546 LI != LE; ++LI) {
547 BasicBlock *LP = *LI;
548 for (BasicBlock::iterator II = LP->getFirstNonPHIOrDbg(), IE = LP->end();
549 II != IE;)
550 if (EHExceptionInst *EI = dyn_cast<EHExceptionInst>(II++)) {
551 // Found a call to eh.exception.
552 if (!EI->use_empty()) {
553 // If there is already a call to eh.exception at the start of the
554 // landing pad, then get hold of it; otherwise create such a call.
555 Value *CallAtStart = CreateExceptionValueCall(LP);
557 // If the call was at the start of a landing pad then leave it alone.
558 if (EI == CallAtStart)
559 continue;
560 EI->replaceAllUsesWith(CallAtStart);
562 EI->eraseFromParent();
563 ++NumExceptionValuesMoved;
564 Changed = true;
568 // Look for calls to eh.exception that are not in a landing pad. If one is
569 // found, then a register that holds the exception value will be created in
570 // each landing pad, and the SSAUpdater will be used to compute the values
571 // returned by eh.exception calls outside of landing pads.
572 SSAUpdater SSA;
574 // Remember where we found the eh.exception call, to avoid rescanning earlier
575 // basic blocks which we already know contain no eh.exception calls.
576 bool FoundCallOutsideLandingPad = false;
577 Function::iterator BB = F->begin();
578 for (Function::iterator BE = F->end(); BB != BE; ++BB) {
579 // Skip over landing pads.
580 if (LandingPads.count(BB))
581 continue;
583 for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end();
584 II != IE; ++II)
585 if (isa<EHExceptionInst>(II)) {
586 SSA.Initialize(II->getType(), II->getName());
587 FoundCallOutsideLandingPad = true;
588 break;
591 if (FoundCallOutsideLandingPad)
592 break;
595 // If all calls to eh.exception are in landing pads then we are done.
596 if (!FoundCallOutsideLandingPad)
597 return Changed;
599 // Add a call to eh.exception at the start of each landing pad, and tell the
600 // SSAUpdater that this is the value produced by the landing pad.
601 for (BBSet::iterator LI = LandingPads.begin(), LE = LandingPads.end();
602 LI != LE; ++LI)
603 SSA.AddAvailableValue(*LI, CreateExceptionValueCall(*LI));
605 // Now turn all calls to eh.exception that are not in a landing pad into a use
606 // of the appropriate register.
607 for (Function::iterator BE = F->end(); BB != BE; ++BB) {
608 // Skip over landing pads.
609 if (LandingPads.count(BB))
610 continue;
612 for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end();
613 II != IE;)
614 if (EHExceptionInst *EI = dyn_cast<EHExceptionInst>(II++)) {
615 // Found a call to eh.exception, replace it with the value from any
616 // upstream landing pad(s).
617 EI->replaceAllUsesWith(SSA.GetValueAtEndOfBlock(BB));
618 EI->eraseFromParent();
619 ++NumExceptionValuesMoved;
623 return true;
626 /// CreateExceptionValueCall - Insert a call to the eh.exception intrinsic at
627 /// the start of the basic block (unless there already is one, in which case
628 /// the existing call is returned).
629 Instruction *DwarfEHPrepare::CreateExceptionValueCall(BasicBlock *BB) {
630 Instruction *Start = BB->getFirstNonPHIOrDbg();
631 // Is this a call to eh.exception?
632 if (IntrinsicInst *CI = dyn_cast<IntrinsicInst>(Start))
633 if (CI->getIntrinsicID() == Intrinsic::eh_exception)
634 // Reuse the existing call.
635 return Start;
637 // Find the eh.exception intrinsic if we didn't already.
638 if (!ExceptionValueIntrinsic)
639 ExceptionValueIntrinsic = Intrinsic::getDeclaration(F->getParent(),
640 Intrinsic::eh_exception);
642 // Create the call.
643 return CallInst::Create(ExceptionValueIntrinsic, "eh.value.call", Start);
646 bool DwarfEHPrepare::runOnFunction(Function &Fn) {
647 bool Changed = false;
649 // Initialize internal state.
650 DT = &getAnalysis<DominatorTree>();
651 F = &Fn;
653 // Ensure that only unwind edges end at landing pads (a landing pad is a
654 // basic block where an invoke unwind edge ends).
655 Changed |= NormalizeLandingPads();
657 // Turn unwind instructions into libcalls.
658 Changed |= LowerUnwinds();
660 // TODO: Move eh.selector calls to landing pads and combine them.
662 // Move eh.exception calls to landing pads.
663 Changed |= MoveExceptionValueCalls();
665 Changed |= HandleURoRInvokes();
667 LandingPads.clear();
669 return Changed;