blob: 550fd3e25fb7a2045e12dc9b31e350974debe244 [file] [log] [blame]
Duncan Sandsb0f1e172009-05-22 20:36:31 +00001//===-- 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
Bill Wendling2ad4aca2010-03-26 23:41:30 +000011// generation. Required if using dwarf exception handling.
Duncan Sandsb0f1e172009-05-22 20:36:31 +000012//
13//===----------------------------------------------------------------------===//
14
15#define DEBUG_TYPE "dwarfehprepare"
Duncan Sandsb0f1e172009-05-22 20:36:31 +000016#include "llvm/Function.h"
17#include "llvm/Instructions.h"
18#include "llvm/IntrinsicInst.h"
19#include "llvm/Module.h"
20#include "llvm/Pass.h"
Bill Wendling2ad4aca2010-03-26 23:41:30 +000021#include "llvm/ADT/Statistic.h"
22#include "llvm/Analysis/Dominators.h"
23#include "llvm/CodeGen/Passes.h"
Jim Grosbach8d77cc82010-01-20 23:03:55 +000024#include "llvm/MC/MCAsmInfo.h"
Gabor Greif2bf4b3b2010-06-25 11:25:30 +000025#include "llvm/Support/CallSite.h"
Duncan Sandsb0f1e172009-05-22 20:36:31 +000026#include "llvm/Target/TargetLowering.h"
27#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Duncan Sandsfb4e8ab2010-09-01 14:07:47 +000028#include "llvm/Transforms/Utils/SSAUpdater.h"
Duncan Sandsb0f1e172009-05-22 20:36:31 +000029using namespace llvm;
30
Bill Wendlingf58898f2009-10-29 00:22:16 +000031STATISTIC(NumLandingPadsSplit, "Number of landing pads split");
Bill Wendlingf58898f2009-10-29 00:22:16 +000032STATISTIC(NumUnwindsLowered, "Number of unwind instructions lowered");
Bill Wendling8bedf972009-10-29 00:37:35 +000033STATISTIC(NumExceptionValuesMoved, "Number of eh.exception calls moved");
Duncan Sandsb0f1e172009-05-22 20:36:31 +000034
35namespace {
Nick Lewycky6726b6d2009-10-25 06:33:48 +000036 class DwarfEHPrepare : public FunctionPass {
Dan Gohman55e59c12010-04-19 19:05:59 +000037 const TargetMachine *TM;
Duncan Sandsb0f1e172009-05-22 20:36:31 +000038 const TargetLowering *TLI;
Duncan Sandsb0f1e172009-05-22 20:36:31 +000039
40 // The eh.exception intrinsic.
Bill Wendling8bedf972009-10-29 00:37:35 +000041 Function *ExceptionValueIntrinsic;
Duncan Sandsb0f1e172009-05-22 20:36:31 +000042
Bill Wendling2ad4aca2010-03-26 23:41:30 +000043 // The eh.selector intrinsic.
44 Function *SelectorIntrinsic;
45
46 // _Unwind_Resume_or_Rethrow call.
47 Constant *URoR;
48
49 // The EH language-specific catch-all type.
50 GlobalVariable *EHCatchAllValue;
51
Duncan Sandsb0f1e172009-05-22 20:36:31 +000052 // _Unwind_Resume or the target equivalent.
53 Constant *RewindFunction;
54
Duncan Sands22efc182010-08-31 09:05:06 +000055 // We both use and preserve dominator info.
Duncan Sandsb0f1e172009-05-22 20:36:31 +000056 DominatorTree *DT;
Duncan Sandsb0f1e172009-05-22 20:36:31 +000057
58 // The function we are running on.
59 Function *F;
60
61 // The landing pads for this function.
62 typedef SmallPtrSet<BasicBlock*, 8> BBSet;
63 BBSet LandingPads;
64
Duncan Sandsb0f1e172009-05-22 20:36:31 +000065 bool NormalizeLandingPads();
66 bool LowerUnwinds();
67 bool MoveExceptionValueCalls();
Duncan Sandsb0f1e172009-05-22 20:36:31 +000068
69 Instruction *CreateExceptionValueCall(BasicBlock *BB);
Duncan Sandsb0f1e172009-05-22 20:36:31 +000070
Bill Wendlingbfbd8532010-03-27 01:19:12 +000071 /// CleanupSelectors - Any remaining eh.selector intrinsic calls which still
Bill Wendling23295cc2010-07-26 22:36:52 +000072 /// use the "llvm.eh.catch.all.value" call need to convert to using its
Bill Wendlingbfbd8532010-03-27 01:19:12 +000073 /// initializer instead.
Bill Wendlingd9e3b2b2010-06-30 22:49:53 +000074 bool CleanupSelectors(SmallPtrSet<IntrinsicInst*, 32> &Sels);
Bill Wendlingbfbd8532010-03-27 01:19:12 +000075
Bill Wendlingefbf3062010-06-24 18:49:10 +000076 bool HasCatchAllInSelector(IntrinsicInst *);
Bill Wendling94366112010-06-12 02:34:29 +000077
Bill Wendlingbfde6442010-03-29 23:02:46 +000078 /// FindAllCleanupSelectors - Find all eh.selector calls that are clean-ups.
Bill Wendlingd9e3b2b2010-06-30 22:49:53 +000079 void FindAllCleanupSelectors(SmallPtrSet<IntrinsicInst*, 32> &Sels,
80 SmallPtrSet<IntrinsicInst*, 32> &CatchAllSels);
Bill Wendlingbfde6442010-03-29 23:02:46 +000081
82 /// FindAllURoRInvokes - Find all URoR invokes in the function.
83 void FindAllURoRInvokes(SmallPtrSet<InvokeInst*, 32> &URoRInvokes);
84
Bill Wendling2ad4aca2010-03-26 23:41:30 +000085 /// HandleURoRInvokes - Handle invokes of "_Unwind_Resume_or_Rethrow"
86 /// calls. The "unwind" part of these invokes jump to a landing pad within
87 /// the current function. This is a candidate to merge the selector
88 /// associated with the URoR invoke with the one from the URoR's landing
89 /// pad.
90 bool HandleURoRInvokes();
91
Bill Wendling201f5f02010-03-29 23:37:07 +000092 /// 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);
97
Duncan Sandsb0f1e172009-05-22 20:36:31 +000098 public:
99 static char ID; // Pass identification, replacement for typeid.
Duncan Sands22efc182010-08-31 09:05:06 +0000100 DwarfEHPrepare(const TargetMachine *tm) :
Owen Anderson90c579d2010-08-06 18:33:48 +0000101 FunctionPass(ID), TM(tm), TLI(TM->getTargetLowering()),
Bill Wendling2ad4aca2010-03-26 23:41:30 +0000102 ExceptionValueIntrinsic(0), SelectorIntrinsic(0),
103 URoR(0), EHCatchAllValue(0), RewindFunction(0) {}
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000104
105 virtual bool runOnFunction(Function &Fn);
106
Duncan Sandsfb4e8ab2010-09-01 14:07:47 +0000107 // getAnalysisUsage - We need the dominator tree for handling URoR.
Bill Wendling8bedf972009-10-29 00:37:35 +0000108 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Duncan Sands22efc182010-08-31 09:05:06 +0000109 AU.addRequired<DominatorTree>();
Bill Wendling8bedf972009-10-29 00:37:35 +0000110 AU.addPreserved<DominatorTree>();
Bill Wendling8bedf972009-10-29 00:37:35 +0000111 }
112
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000113 const char *getPassName() const {
114 return "Exception handling preparation";
115 }
116
117 };
118} // end anonymous namespace
119
120char DwarfEHPrepare::ID = 0;
121
Duncan Sands22efc182010-08-31 09:05:06 +0000122FunctionPass *llvm::createDwarfEHPass(const TargetMachine *tm) {
123 return new DwarfEHPrepare(tm);
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000124}
125
Bill Wendlingefbf3062010-06-24 18:49:10 +0000126/// HasCatchAllInSelector - Return true if the intrinsic instruction has a
127/// catch-all.
128bool DwarfEHPrepare::HasCatchAllInSelector(IntrinsicInst *II) {
129 if (!EHCatchAllValue) return false;
Bill Wendling94366112010-06-12 02:34:29 +0000130
Gabor Greif2bf4b3b2010-06-25 11:25:30 +0000131 unsigned ArgIdx = II->getNumArgOperands() - 1;
132 GlobalVariable *GV = dyn_cast<GlobalVariable>(II->getArgOperand(ArgIdx));
Bill Wendlingefbf3062010-06-24 18:49:10 +0000133 return GV == EHCatchAllValue;
Bill Wendling94366112010-06-12 02:34:29 +0000134}
135
Bill Wendlingbfde6442010-03-29 23:02:46 +0000136/// FindAllCleanupSelectors - Find all eh.selector calls that are clean-ups.
137void DwarfEHPrepare::
Bill Wendlingd9e3b2b2010-06-30 22:49:53 +0000138FindAllCleanupSelectors(SmallPtrSet<IntrinsicInst*, 32> &Sels,
139 SmallPtrSet<IntrinsicInst*, 32> &CatchAllSels) {
Bill Wendling2ad4aca2010-03-26 23:41:30 +0000140 for (Value::use_iterator
Bill Wendlingbfde6442010-03-29 23:02:46 +0000141 I = SelectorIntrinsic->use_begin(),
142 E = SelectorIntrinsic->use_end(); I != E; ++I) {
Gabor Greif96f1d8e2010-07-22 13:36:47 +0000143 IntrinsicInst *II = cast<IntrinsicInst>(*I);
Bill Wendling2ad4aca2010-03-26 23:41:30 +0000144
Bill Wendling94366112010-06-12 02:34:29 +0000145 if (II->getParent()->getParent() != F)
146 continue;
Bill Wendlingbfde6442010-03-29 23:02:46 +0000147
Bill Wendlingefbf3062010-06-24 18:49:10 +0000148 if (!HasCatchAllInSelector(II))
Bill Wendling94366112010-06-12 02:34:29 +0000149 Sels.insert(II);
Bill Wendlingd9e3b2b2010-06-30 22:49:53 +0000150 else
151 CatchAllSels.insert(II);
Bill Wendlingbfde6442010-03-29 23:02:46 +0000152 }
153}
154
155/// FindAllURoRInvokes - Find all URoR invokes in the function.
156void DwarfEHPrepare::
157FindAllURoRInvokes(SmallPtrSet<InvokeInst*, 32> &URoRInvokes) {
158 for (Value::use_iterator
159 I = URoR->use_begin(),
160 E = URoR->use_end(); I != E; ++I) {
Gabor Greif96f1d8e2010-07-22 13:36:47 +0000161 if (InvokeInst *II = dyn_cast<InvokeInst>(*I))
Bill Wendlingbfde6442010-03-29 23:02:46 +0000162 URoRInvokes.insert(II);
163 }
Bill Wendling2ad4aca2010-03-26 23:41:30 +0000164}
165
Bill Wendlingbfbd8532010-03-27 01:19:12 +0000166/// CleanupSelectors - Any remaining eh.selector intrinsic calls which still use
Bill Wendling23295cc2010-07-26 22:36:52 +0000167/// the "llvm.eh.catch.all.value" call need to convert to using its
Bill Wendlingbfbd8532010-03-27 01:19:12 +0000168/// initializer instead.
Bill Wendlingd9e3b2b2010-06-30 22:49:53 +0000169bool DwarfEHPrepare::CleanupSelectors(SmallPtrSet<IntrinsicInst*, 32> &Sels) {
Bill Wendlingbfde6442010-03-29 23:02:46 +0000170 if (!EHCatchAllValue) return false;
171
172 if (!SelectorIntrinsic) {
173 SelectorIntrinsic =
174 Intrinsic::getDeclaration(F->getParent(), Intrinsic::eh_selector);
175 if (!SelectorIntrinsic) return false;
176 }
177
Bill Wendling43de15f2010-03-27 01:22:38 +0000178 bool Changed = false;
Bill Wendlingd9e3b2b2010-06-30 22:49:53 +0000179 for (SmallPtrSet<IntrinsicInst*, 32>::iterator
180 I = Sels.begin(), E = Sels.end(); I != E; ++I) {
181 IntrinsicInst *Sel = *I;
Bill Wendlingbfbd8532010-03-27 01:19:12 +0000182
Bill Wendling23295cc2010-07-26 22:36:52 +0000183 // Index of the "llvm.eh.catch.all.value" variable.
Gabor Greif9d677682010-06-29 13:03:46 +0000184 unsigned OpIdx = Sel->getNumArgOperands() - 1;
185 GlobalVariable *GV = dyn_cast<GlobalVariable>(Sel->getArgOperand(OpIdx));
Bill Wendlingbfbd8532010-03-27 01:19:12 +0000186 if (GV != EHCatchAllValue) continue;
Gabor Greif9d677682010-06-29 13:03:46 +0000187 Sel->setArgOperand(OpIdx, EHCatchAllValue->getInitializer());
Bill Wendling43de15f2010-03-27 01:22:38 +0000188 Changed = true;
Bill Wendlingbfbd8532010-03-27 01:19:12 +0000189 }
Bill Wendling43de15f2010-03-27 01:22:38 +0000190
191 return Changed;
Bill Wendlingbfbd8532010-03-27 01:19:12 +0000192}
193
Bill Wendling201f5f02010-03-29 23:37:07 +0000194/// FindSelectorAndURoR - Find the eh.selector call associated with the
195/// eh.exception call. And indicate if there is a URoR "invoke" associated with
196/// the eh.exception call. This recursively looks past instructions which don't
197/// change the EH pointer value, like casts or PHI nodes.
198bool
199DwarfEHPrepare::FindSelectorAndURoR(Instruction *Inst, bool &URoRInvoke,
200 SmallPtrSet<IntrinsicInst*, 8> &SelCalls) {
201 SmallPtrSet<PHINode*, 32> SeenPHIs;
202 bool Changed = false;
203
Bill Wendling201f5f02010-03-29 23:37:07 +0000204 for (Value::use_iterator
205 I = Inst->use_begin(), E = Inst->use_end(); I != E; ++I) {
Gabor Greif96f1d8e2010-07-22 13:36:47 +0000206 Instruction *II = dyn_cast<Instruction>(*I);
Bill Wendling201f5f02010-03-29 23:37:07 +0000207 if (!II || II->getParent()->getParent() != F) continue;
208
209 if (IntrinsicInst *Sel = dyn_cast<IntrinsicInst>(II)) {
210 if (Sel->getIntrinsicID() == Intrinsic::eh_selector)
211 SelCalls.insert(Sel);
212 } else if (InvokeInst *Invoke = dyn_cast<InvokeInst>(II)) {
213 if (Invoke->getCalledFunction() == URoR)
214 URoRInvoke = true;
215 } else if (CastInst *CI = dyn_cast<CastInst>(II)) {
216 Changed |= FindSelectorAndURoR(CI, URoRInvoke, SelCalls);
Bill Wendling201f5f02010-03-29 23:37:07 +0000217 } else if (PHINode *PN = dyn_cast<PHINode>(II)) {
218 if (SeenPHIs.insert(PN))
219 // Don't process a PHI node more than once.
220 Changed |= FindSelectorAndURoR(PN, URoRInvoke, SelCalls);
221 }
222 }
223
224 return Changed;
225}
226
Bill Wendling2ad4aca2010-03-26 23:41:30 +0000227/// HandleURoRInvokes - Handle invokes of "_Unwind_Resume_or_Rethrow" calls. The
228/// "unwind" part of these invokes jump to a landing pad within the current
229/// function. This is a candidate to merge the selector associated with the URoR
230/// invoke with the one from the URoR's landing pad.
231bool DwarfEHPrepare::HandleURoRInvokes() {
232 if (!EHCatchAllValue) {
233 EHCatchAllValue =
Bill Wendling23295cc2010-07-26 22:36:52 +0000234 F->getParent()->getNamedGlobal("llvm.eh.catch.all.value");
Bill Wendling2ad4aca2010-03-26 23:41:30 +0000235 if (!EHCatchAllValue) return false;
236 }
237
Bill Wendlingbfbd8532010-03-27 01:19:12 +0000238 if (!SelectorIntrinsic) {
239 SelectorIntrinsic =
240 Intrinsic::getDeclaration(F->getParent(), Intrinsic::eh_selector);
241 if (!SelectorIntrinsic) return false;
242 }
243
Bill Wendlingd9e3b2b2010-06-30 22:49:53 +0000244 SmallPtrSet<IntrinsicInst*, 32> Sels;
245 SmallPtrSet<IntrinsicInst*, 32> CatchAllSels;
246 FindAllCleanupSelectors(Sels, CatchAllSels);
247
Bill Wendling2ad4aca2010-03-26 23:41:30 +0000248 if (!URoR) {
249 URoR = F->getParent()->getFunction("_Unwind_Resume_or_Rethrow");
Bill Wendlingd9e3b2b2010-06-30 22:49:53 +0000250 if (!URoR) return CleanupSelectors(CatchAllSels);
Bill Wendling2ad4aca2010-03-26 23:41:30 +0000251 }
252
Bill Wendlingbfde6442010-03-29 23:02:46 +0000253 SmallPtrSet<InvokeInst*, 32> URoRInvokes;
Bill Wendlingbfde6442010-03-29 23:02:46 +0000254 FindAllURoRInvokes(URoRInvokes);
Bill Wendling2ad4aca2010-03-26 23:41:30 +0000255
Bill Wendling2ad4aca2010-03-26 23:41:30 +0000256 SmallPtrSet<IntrinsicInst*, 32> SelsToConvert;
257
Bill Wendlingbfde6442010-03-29 23:02:46 +0000258 for (SmallPtrSet<IntrinsicInst*, 32>::iterator
259 SI = Sels.begin(), SE = Sels.end(); SI != SE; ++SI) {
260 const BasicBlock *SelBB = (*SI)->getParent();
261 for (SmallPtrSet<InvokeInst*, 32>::iterator
262 UI = URoRInvokes.begin(), UE = URoRInvokes.end(); UI != UE; ++UI) {
263 const BasicBlock *URoRBB = (*UI)->getParent();
Dan Gohmance0fe5d2010-07-26 17:38:15 +0000264 if (DT->dominates(SelBB, URoRBB)) {
Bill Wendlingbfde6442010-03-29 23:02:46 +0000265 SelsToConvert.insert(*SI);
266 break;
Bill Wendling2ad4aca2010-03-26 23:41:30 +0000267 }
268 }
269 }
270
Bill Wendlingbfde6442010-03-29 23:02:46 +0000271 bool Changed = false;
272
Bill Wendling201f5f02010-03-29 23:37:07 +0000273 if (Sels.size() != SelsToConvert.size()) {
274 // If we haven't been able to convert all of the clean-up selectors, then
275 // loop through the slow way to see if they still need to be converted.
276 if (!ExceptionValueIntrinsic) {
277 ExceptionValueIntrinsic =
278 Intrinsic::getDeclaration(F->getParent(), Intrinsic::eh_exception);
Bill Wendlingd9e3b2b2010-06-30 22:49:53 +0000279 if (!ExceptionValueIntrinsic)
280 return CleanupSelectors(CatchAllSels);
Bill Wendling201f5f02010-03-29 23:37:07 +0000281 }
282
283 for (Value::use_iterator
284 I = ExceptionValueIntrinsic->use_begin(),
285 E = ExceptionValueIntrinsic->use_end(); I != E; ++I) {
Gabor Greif96f1d8e2010-07-22 13:36:47 +0000286 IntrinsicInst *EHPtr = dyn_cast<IntrinsicInst>(*I);
Bill Wendling201f5f02010-03-29 23:37:07 +0000287 if (!EHPtr || EHPtr->getParent()->getParent() != F) continue;
288
Bill Wendling201f5f02010-03-29 23:37:07 +0000289 bool URoRInvoke = false;
290 SmallPtrSet<IntrinsicInst*, 8> SelCalls;
291 Changed |= FindSelectorAndURoR(EHPtr, URoRInvoke, SelCalls);
292
293 if (URoRInvoke) {
294 // This EH pointer is being used by an invoke of an URoR instruction and
295 // an eh.selector intrinsic call. If the eh.selector is a 'clean-up', we
296 // need to convert it to a 'catch-all'.
297 for (SmallPtrSet<IntrinsicInst*, 8>::iterator
Bill Wendling94366112010-06-12 02:34:29 +0000298 SI = SelCalls.begin(), SE = SelCalls.end(); SI != SE; ++SI)
Bill Wendlingefbf3062010-06-24 18:49:10 +0000299 if (!HasCatchAllInSelector(*SI))
Bill Wendling94366112010-06-12 02:34:29 +0000300 SelsToConvert.insert(*SI);
Bill Wendling201f5f02010-03-29 23:37:07 +0000301 }
302 }
303 }
304
Bill Wendling2ad4aca2010-03-26 23:41:30 +0000305 if (!SelsToConvert.empty()) {
306 // Convert all clean-up eh.selectors, which are associated with "invokes" of
307 // URoR calls, into catch-all eh.selectors.
308 Changed = true;
309
310 for (SmallPtrSet<IntrinsicInst*, 8>::iterator
311 SI = SelsToConvert.begin(), SE = SelsToConvert.end();
312 SI != SE; ++SI) {
313 IntrinsicInst *II = *SI;
Bill Wendling2ad4aca2010-03-26 23:41:30 +0000314
315 // Use the exception object pointer and the personality function
316 // from the original selector.
Gabor Greif2bf4b3b2010-06-25 11:25:30 +0000317 CallSite CS(II);
318 IntrinsicInst::op_iterator I = CS.arg_begin();
Gabor Greif2bf4b3b2010-06-25 11:25:30 +0000319 IntrinsicInst::op_iterator E = CS.arg_end();
320 IntrinsicInst::op_iterator B = prior(E);
321
322 // Exclude last argument if it is an integer.
323 if (isa<ConstantInt>(B)) E = B;
Bill Wendling94366112010-06-12 02:34:29 +0000324
Gabor Greif32621ad2010-06-28 16:40:52 +0000325 // Add exception object pointer (front).
326 // Add personality function (next).
327 // Add in any filter IDs (rest).
328 SmallVector<Value*, 8> Args(I, E);
Bill Wendling94366112010-06-12 02:34:29 +0000329
Bill Wendling2ad4aca2010-03-26 23:41:30 +0000330 Args.push_back(EHCatchAllValue->getInitializer()); // Catch-all indicator.
331
332 CallInst *NewSelector =
333 CallInst::Create(SelectorIntrinsic, Args.begin(), Args.end(),
334 "eh.sel.catch.all", II);
335
336 NewSelector->setTailCall(II->isTailCall());
337 NewSelector->setAttributes(II->getAttributes());
338 NewSelector->setCallingConv(II->getCallingConv());
339
340 II->replaceAllUsesWith(NewSelector);
341 II->eraseFromParent();
342 }
343 }
344
Bill Wendlingd9e3b2b2010-06-30 22:49:53 +0000345 Changed |= CleanupSelectors(CatchAllSels);
Bill Wendling2ad4aca2010-03-26 23:41:30 +0000346 return Changed;
347}
348
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000349/// NormalizeLandingPads - Normalize and discover landing pads, noting them
350/// in the LandingPads set. A landing pad is normal if the only CFG edges
Eric Christopherec26bf72009-09-15 21:56:46 +0000351/// that end at it are unwind edges from invoke instructions. If we inlined
352/// through an invoke we could have a normal branch from the previous
353/// unwind block through to the landing pad for the original invoke.
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000354/// Abnormal landing pads are fixed up by redirecting all unwind edges to
355/// a new basic block which falls through to the original.
356bool DwarfEHPrepare::NormalizeLandingPads() {
357 bool Changed = false;
358
Dan Gohman55e59c12010-04-19 19:05:59 +0000359 const MCAsmInfo *MAI = TM->getMCAsmInfo();
Jim Grosbach8d77cc82010-01-20 23:03:55 +0000360 bool usingSjLjEH = MAI->getExceptionHandlingType() == ExceptionHandling::SjLj;
361
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000362 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
363 TerminatorInst *TI = I->getTerminator();
364 if (!isa<InvokeInst>(TI))
365 continue;
366 BasicBlock *LPad = TI->getSuccessor(1);
367 // Skip landing pads that have already been normalized.
368 if (LandingPads.count(LPad))
369 continue;
370
371 // Check that only invoke unwind edges end at the landing pad.
372 bool OnlyUnwoundTo = true;
Jim Grosbach8d77cc82010-01-20 23:03:55 +0000373 bool SwitchOK = usingSjLjEH;
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000374 for (pred_iterator PI = pred_begin(LPad), PE = pred_end(LPad);
375 PI != PE; ++PI) {
376 TerminatorInst *PT = (*PI)->getTerminator();
Jim Grosbach8d77cc82010-01-20 23:03:55 +0000377 // The SjLj dispatch block uses a switch instruction. This is effectively
378 // an unwind edge, so we can disregard it here. There will only ever
379 // be one dispatch, however, so if there are multiple switches, one
380 // of them truly is a normal edge, not an unwind edge.
381 if (SwitchOK && isa<SwitchInst>(PT)) {
382 SwitchOK = false;
383 continue;
384 }
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000385 if (!isa<InvokeInst>(PT) || LPad == PT->getSuccessor(0)) {
386 OnlyUnwoundTo = false;
387 break;
388 }
389 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000390
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000391 if (OnlyUnwoundTo) {
392 // Only unwind edges lead to the landing pad. Remember the landing pad.
393 LandingPads.insert(LPad);
394 continue;
395 }
396
397 // At least one normal edge ends at the landing pad. Redirect the unwind
398 // edges to a new basic block which falls through into this one.
399
400 // Create the new basic block.
Bill Wendling8bedf972009-10-29 00:37:35 +0000401 BasicBlock *NewBB = BasicBlock::Create(F->getContext(),
Owen Anderson1d0be152009-08-13 21:58:54 +0000402 LPad->getName() + "_unwind_edge");
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000403
404 // Insert it into the function right before the original landing pad.
405 LPad->getParent()->getBasicBlockList().insert(LPad, NewBB);
406
407 // Redirect unwind edges from the original landing pad to NewBB.
408 for (pred_iterator PI = pred_begin(LPad), PE = pred_end(LPad); PI != PE; ) {
409 TerminatorInst *PT = (*PI++)->getTerminator();
410 if (isa<InvokeInst>(PT) && PT->getSuccessor(1) == LPad)
411 // Unwind to the new block.
412 PT->setSuccessor(1, NewBB);
413 }
414
415 // If there are any PHI nodes in LPad, we need to update them so that they
416 // merge incoming values from NewBB instead.
417 for (BasicBlock::iterator II = LPad->begin(); isa<PHINode>(II); ++II) {
418 PHINode *PN = cast<PHINode>(II);
419 pred_iterator PB = pred_begin(NewBB), PE = pred_end(NewBB);
420
421 // Check to see if all of the values coming in via unwind edges are the
422 // same. If so, we don't need to create a new PHI node.
423 Value *InVal = PN->getIncomingValueForBlock(*PB);
424 for (pred_iterator PI = PB; PI != PE; ++PI) {
425 if (PI != PB && InVal != PN->getIncomingValueForBlock(*PI)) {
426 InVal = 0;
427 break;
428 }
429 }
430
431 if (InVal == 0) {
432 // Different unwind edges have different values. Create a new PHI node
433 // in NewBB.
434 PHINode *NewPN = PHINode::Create(PN->getType(), PN->getName()+".unwind",
435 NewBB);
436 // Add an entry for each unwind edge, using the value from the old PHI.
437 for (pred_iterator PI = PB; PI != PE; ++PI)
438 NewPN->addIncoming(PN->getIncomingValueForBlock(*PI), *PI);
439
440 // Now use this new PHI as the common incoming value for NewBB in PN.
441 InVal = NewPN;
442 }
443
444 // Revector exactly one entry in the PHI node to come from NewBB
445 // and delete all other entries that come from unwind edges. If
446 // there are both normal and unwind edges from the same predecessor,
447 // this leaves an entry for the normal edge.
448 for (pred_iterator PI = PB; PI != PE; ++PI)
449 PN->removeIncomingValue(*PI);
450 PN->addIncoming(InVal, NewBB);
451 }
452
453 // Add a fallthrough from NewBB to the original landing pad.
454 BranchInst::Create(LPad, NewBB);
455
Duncan Sands22efc182010-08-31 09:05:06 +0000456 // Now update DominatorTree analysis information.
457 DT->splitBlock(NewBB);
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000458
459 // Remember the newly constructed landing pad. The original landing pad
460 // LPad is no longer a landing pad now that all unwind edges have been
461 // revectored to NewBB.
462 LandingPads.insert(NewBB);
463 ++NumLandingPadsSplit;
464 Changed = true;
465 }
466
467 return Changed;
468}
469
470/// LowerUnwinds - Turn unwind instructions into calls to _Unwind_Resume,
471/// rethrowing any previously caught exception. This will crash horribly
472/// at runtime if there is no such exception: using unwind to throw a new
473/// exception is currently not supported.
474bool DwarfEHPrepare::LowerUnwinds() {
Bill Wendling43488712009-09-14 20:52:37 +0000475 SmallVector<TerminatorInst*, 16> UnwindInsts;
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000476
477 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
478 TerminatorInst *TI = I->getTerminator();
Bill Wendling43488712009-09-14 20:52:37 +0000479 if (isa<UnwindInst>(TI))
480 UnwindInsts.push_back(TI);
481 }
482
483 if (UnwindInsts.empty()) return false;
484
485 // Find the rewind function if we didn't already.
486 if (!RewindFunction) {
Bill Wendling8bedf972009-10-29 00:37:35 +0000487 LLVMContext &Ctx = UnwindInsts[0]->getContext();
Bill Wendling43488712009-09-14 20:52:37 +0000488 std::vector<const Type*>
Bill Wendling8bedf972009-10-29 00:37:35 +0000489 Params(1, Type::getInt8PtrTy(Ctx));
490 FunctionType *FTy = FunctionType::get(Type::getVoidTy(Ctx),
Bill Wendling43488712009-09-14 20:52:37 +0000491 Params, false);
492 const char *RewindName = TLI->getLibcallName(RTLIB::UNWIND_RESUME);
493 RewindFunction = F->getParent()->getOrInsertFunction(RewindName, FTy);
494 }
495
Bill Wendling8bedf972009-10-29 00:37:35 +0000496 bool Changed = false;
497
Bill Wendling43488712009-09-14 20:52:37 +0000498 for (SmallVectorImpl<TerminatorInst*>::iterator
499 I = UnwindInsts.begin(), E = UnwindInsts.end(); I != E; ++I) {
500 TerminatorInst *TI = *I;
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000501
502 // Replace the unwind instruction with a call to _Unwind_Resume (or the
503 // appropriate target equivalent) followed by an UnreachableInst.
504
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000505 // Create the call...
Eric Christopher82f149d2009-09-04 01:14:14 +0000506 CallInst *CI = CallInst::Create(RewindFunction,
Duncan Sandsfb4e8ab2010-09-01 14:07:47 +0000507 CreateExceptionValueCall(TI->getParent()),
Bill Wendling43488712009-09-14 20:52:37 +0000508 "", TI);
Eric Christopher82f149d2009-09-04 01:14:14 +0000509 CI->setCallingConv(TLI->getLibcallCallingConv(RTLIB::UNWIND_RESUME));
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000510 // ...followed by an UnreachableInst.
Bill Wendling8bedf972009-10-29 00:37:35 +0000511 new UnreachableInst(TI->getContext(), TI);
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000512
513 // Nuke the unwind instruction.
514 TI->eraseFromParent();
515 ++NumUnwindsLowered;
516 Changed = true;
517 }
518
519 return Changed;
520}
521
522/// MoveExceptionValueCalls - Ensure that eh.exception is only ever called from
Duncan Sandsfb4e8ab2010-09-01 14:07:47 +0000523/// landing pads by replacing calls outside of landing pads with direct use of
524/// a register holding the appropriate value; this requires adding calls inside
525/// all landing pads to initialize the register. Also, move eh.exception calls
526/// inside landing pads to the start of the landing pad (optional, but may make
527/// things simpler for later passes).
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000528bool DwarfEHPrepare::MoveExceptionValueCalls() {
529 // If the eh.exception intrinsic is not declared in the module then there is
530 // nothing to do. Speed up compilation by checking for this common case.
Bill Wendling8bedf972009-10-29 00:37:35 +0000531 if (!ExceptionValueIntrinsic &&
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000532 !F->getParent()->getFunction(Intrinsic::getName(Intrinsic::eh_exception)))
533 return false;
534
535 bool Changed = false;
536
Duncan Sandsfb4e8ab2010-09-01 14:07:47 +0000537 // Move calls to eh.exception that are inside a landing pad to the start of
538 // the landing pad.
539 for (BBSet::const_iterator LI = LandingPads.begin(), LE = LandingPads.end();
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000540 LI != LE; ++LI) {
Duncan Sandsfb4e8ab2010-09-01 14:07:47 +0000541 BasicBlock *LP = *LI;
542 for (BasicBlock::iterator II = LP->getFirstNonPHIOrDbg(), IE = LP->end();
543 II != IE;)
544 if (EHExceptionInst *EI = dyn_cast<EHExceptionInst>(II++)) {
545 // Found a call to eh.exception.
546 if (!EI->use_empty()) {
547 // If there is already a call to eh.exception at the start of the
548 // landing pad, then get hold of it; otherwise create such a call.
549 Value *CallAtStart = CreateExceptionValueCall(LP);
550
551 // If the call was at the start of a landing pad then leave it alone.
552 if (EI == CallAtStart)
553 continue;
554 EI->replaceAllUsesWith(CallAtStart);
555 }
556 EI->eraseFromParent();
557 ++NumExceptionValuesMoved;
558 Changed = true;
559 }
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000560 }
561
Duncan Sandsfb4e8ab2010-09-01 14:07:47 +0000562 // Look for calls to eh.exception that are not in a landing pad. If one is
563 // found, then a register that holds the exception value will be created in
564 // each landing pad, and the SSAUpdater will be used to compute the values
565 // returned by eh.exception calls outside of landing pads.
566 SSAUpdater SSA;
567
568 // Remember where we found the eh.exception call, to avoid rescanning earlier
569 // basic blocks which we already know contain no eh.exception calls.
570 bool FoundCallOutsideLandingPad = false;
571 Function::iterator BB = F->begin();
572 for (Function::iterator BE = F->end(); BB != BE; ++BB) {
573 // Skip over landing pads.
574 if (LandingPads.count(BB))
575 continue;
576
577 for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end();
578 II != IE; ++II)
579 if (isa<EHExceptionInst>(II)) {
580 SSA.Initialize(II->getType(), II->getName());
581 FoundCallOutsideLandingPad = true;
582 break;
583 }
584
585 if (FoundCallOutsideLandingPad)
586 break;
587 }
588
589 // If all calls to eh.exception are in landing pads then we are done.
590 if (!FoundCallOutsideLandingPad)
591 return Changed;
592
593 // Add a call to eh.exception at the start of each landing pad, and tell the
594 // SSAUpdater that this is the value produced by the landing pad.
595 for (BBSet::iterator LI = LandingPads.begin(), LE = LandingPads.end();
596 LI != LE; ++LI)
597 SSA.AddAvailableValue(*LI, CreateExceptionValueCall(*LI));
598
599 // Now turn all calls to eh.exception that are not in a landing pad into a use
600 // of the appropriate register.
601 for (Function::iterator BE = F->end(); BB != BE; ++BB) {
602 // Skip over landing pads.
603 if (LandingPads.count(BB))
604 continue;
605
606 for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end();
607 II != IE;)
608 if (EHExceptionInst *EI = dyn_cast<EHExceptionInst>(II++)) {
609 // Found a call to eh.exception, replace it with the value from any
610 // upstream landing pad(s).
611 EI->replaceAllUsesWith(SSA.GetValueAtEndOfBlock(BB));
612 EI->eraseFromParent();
613 ++NumExceptionValuesMoved;
614 }
615 }
616
617 return true;
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000618}
619
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000620/// CreateExceptionValueCall - Insert a call to the eh.exception intrinsic at
621/// the start of the basic block (unless there already is one, in which case
622/// the existing call is returned).
623Instruction *DwarfEHPrepare::CreateExceptionValueCall(BasicBlock *BB) {
Dale Johannesen7249ef02010-04-02 21:49:27 +0000624 Instruction *Start = BB->getFirstNonPHIOrDbg();
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000625 // Is this a call to eh.exception?
626 if (IntrinsicInst *CI = dyn_cast<IntrinsicInst>(Start))
627 if (CI->getIntrinsicID() == Intrinsic::eh_exception)
628 // Reuse the existing call.
629 return Start;
630
631 // Find the eh.exception intrinsic if we didn't already.
Bill Wendling8bedf972009-10-29 00:37:35 +0000632 if (!ExceptionValueIntrinsic)
633 ExceptionValueIntrinsic = Intrinsic::getDeclaration(F->getParent(),
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000634 Intrinsic::eh_exception);
635
636 // Create the call.
Bill Wendling8bedf972009-10-29 00:37:35 +0000637 return CallInst::Create(ExceptionValueIntrinsic, "eh.value.call", Start);
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000638}
639
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000640bool DwarfEHPrepare::runOnFunction(Function &Fn) {
641 bool Changed = false;
642
643 // Initialize internal state.
Duncan Sands22efc182010-08-31 09:05:06 +0000644 DT = &getAnalysis<DominatorTree>();
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000645 F = &Fn;
646
647 // Ensure that only unwind edges end at landing pads (a landing pad is a
648 // basic block where an invoke unwind edge ends).
649 Changed |= NormalizeLandingPads();
650
651 // Turn unwind instructions into libcalls.
652 Changed |= LowerUnwinds();
653
Bill Wendling8bedf972009-10-29 00:37:35 +0000654 // TODO: Move eh.selector calls to landing pads and combine them.
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000655
656 // Move eh.exception calls to landing pads.
657 Changed |= MoveExceptionValueCalls();
658
Bill Wendling2ad4aca2010-03-26 23:41:30 +0000659 Changed |= HandleURoRInvokes();
660
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000661 LandingPads.clear();
662
663 return Changed;
664}