blob: 0ebb5b0db70e1417ab13a5b355b18f2ec36e7716 [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 Sands850fcd42010-09-03 08:31:48 +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
Bill Wendling49ad7312010-10-29 07:46:01 +000046 // _Unwind_Resume_or_Rethrow or _Unwind_SjLj_Resume call.
Bill Wendling2ad4aca2010-03-26 23:41:30 +000047 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 Wendling49ad7312010-10-29 07:46:01 +000085 /// 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.
Bill Wendling2ad4aca2010-03-26 23:41:30 +000090 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),
Owen Anderson081c34b2010-10-19 17:21:58 +0000103 URoR(0), EHCatchAllValue(0), RewindFunction(0) {
104 initializeDominatorTreePass(*PassRegistry::getPassRegistry());
105 }
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000106
107 virtual bool runOnFunction(Function &Fn);
108
Duncan Sands850fcd42010-09-03 08:31:48 +0000109 // getAnalysisUsage - We need the dominator tree for handling URoR.
Bill Wendling8bedf972009-10-29 00:37:35 +0000110 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Duncan Sands22efc182010-08-31 09:05:06 +0000111 AU.addRequired<DominatorTree>();
Bill Wendling8bedf972009-10-29 00:37:35 +0000112 AU.addPreserved<DominatorTree>();
Bill Wendling8bedf972009-10-29 00:37:35 +0000113 }
114
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000115 const char *getPassName() const {
116 return "Exception handling preparation";
117 }
118
119 };
120} // end anonymous namespace
121
122char DwarfEHPrepare::ID = 0;
123
Duncan Sands22efc182010-08-31 09:05:06 +0000124FunctionPass *llvm::createDwarfEHPass(const TargetMachine *tm) {
125 return new DwarfEHPrepare(tm);
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000126}
127
Bill Wendlingefbf3062010-06-24 18:49:10 +0000128/// HasCatchAllInSelector - Return true if the intrinsic instruction has a
129/// catch-all.
130bool DwarfEHPrepare::HasCatchAllInSelector(IntrinsicInst *II) {
131 if (!EHCatchAllValue) return false;
Bill Wendling94366112010-06-12 02:34:29 +0000132
Gabor Greif2bf4b3b2010-06-25 11:25:30 +0000133 unsigned ArgIdx = II->getNumArgOperands() - 1;
134 GlobalVariable *GV = dyn_cast<GlobalVariable>(II->getArgOperand(ArgIdx));
Bill Wendlingefbf3062010-06-24 18:49:10 +0000135 return GV == EHCatchAllValue;
Bill Wendling94366112010-06-12 02:34:29 +0000136}
137
Bill Wendlingbfde6442010-03-29 23:02:46 +0000138/// FindAllCleanupSelectors - Find all eh.selector calls that are clean-ups.
139void DwarfEHPrepare::
Bill Wendlingd9e3b2b2010-06-30 22:49:53 +0000140FindAllCleanupSelectors(SmallPtrSet<IntrinsicInst*, 32> &Sels,
141 SmallPtrSet<IntrinsicInst*, 32> &CatchAllSels) {
Bill Wendling2ad4aca2010-03-26 23:41:30 +0000142 for (Value::use_iterator
Bill Wendlingbfde6442010-03-29 23:02:46 +0000143 I = SelectorIntrinsic->use_begin(),
144 E = SelectorIntrinsic->use_end(); I != E; ++I) {
Gabor Greif96f1d8e2010-07-22 13:36:47 +0000145 IntrinsicInst *II = cast<IntrinsicInst>(*I);
Bill Wendling2ad4aca2010-03-26 23:41:30 +0000146
Bill Wendling94366112010-06-12 02:34:29 +0000147 if (II->getParent()->getParent() != F)
148 continue;
Bill Wendlingbfde6442010-03-29 23:02:46 +0000149
Bill Wendlingefbf3062010-06-24 18:49:10 +0000150 if (!HasCatchAllInSelector(II))
Bill Wendling94366112010-06-12 02:34:29 +0000151 Sels.insert(II);
Bill Wendlingd9e3b2b2010-06-30 22:49:53 +0000152 else
153 CatchAllSels.insert(II);
Bill Wendlingbfde6442010-03-29 23:02:46 +0000154 }
155}
156
157/// FindAllURoRInvokes - Find all URoR invokes in the function.
158void DwarfEHPrepare::
159FindAllURoRInvokes(SmallPtrSet<InvokeInst*, 32> &URoRInvokes) {
160 for (Value::use_iterator
161 I = URoR->use_begin(),
162 E = URoR->use_end(); I != E; ++I) {
Gabor Greif96f1d8e2010-07-22 13:36:47 +0000163 if (InvokeInst *II = dyn_cast<InvokeInst>(*I))
Bill Wendlingbfde6442010-03-29 23:02:46 +0000164 URoRInvokes.insert(II);
165 }
Bill Wendling2ad4aca2010-03-26 23:41:30 +0000166}
167
Bill Wendlingbfbd8532010-03-27 01:19:12 +0000168/// CleanupSelectors - Any remaining eh.selector intrinsic calls which still use
Bill Wendling23295cc2010-07-26 22:36:52 +0000169/// the "llvm.eh.catch.all.value" call need to convert to using its
Bill Wendlingbfbd8532010-03-27 01:19:12 +0000170/// initializer instead.
Bill Wendlingd9e3b2b2010-06-30 22:49:53 +0000171bool DwarfEHPrepare::CleanupSelectors(SmallPtrSet<IntrinsicInst*, 32> &Sels) {
Bill Wendlingbfde6442010-03-29 23:02:46 +0000172 if (!EHCatchAllValue) return false;
173
174 if (!SelectorIntrinsic) {
175 SelectorIntrinsic =
176 Intrinsic::getDeclaration(F->getParent(), Intrinsic::eh_selector);
177 if (!SelectorIntrinsic) return false;
178 }
179
Bill Wendling43de15f2010-03-27 01:22:38 +0000180 bool Changed = false;
Bill Wendlingd9e3b2b2010-06-30 22:49:53 +0000181 for (SmallPtrSet<IntrinsicInst*, 32>::iterator
182 I = Sels.begin(), E = Sels.end(); I != E; ++I) {
183 IntrinsicInst *Sel = *I;
Bill Wendlingbfbd8532010-03-27 01:19:12 +0000184
Bill Wendling23295cc2010-07-26 22:36:52 +0000185 // Index of the "llvm.eh.catch.all.value" variable.
Gabor Greif9d677682010-06-29 13:03:46 +0000186 unsigned OpIdx = Sel->getNumArgOperands() - 1;
187 GlobalVariable *GV = dyn_cast<GlobalVariable>(Sel->getArgOperand(OpIdx));
Bill Wendlingbfbd8532010-03-27 01:19:12 +0000188 if (GV != EHCatchAllValue) continue;
Gabor Greif9d677682010-06-29 13:03:46 +0000189 Sel->setArgOperand(OpIdx, EHCatchAllValue->getInitializer());
Bill Wendling43de15f2010-03-27 01:22:38 +0000190 Changed = true;
Bill Wendlingbfbd8532010-03-27 01:19:12 +0000191 }
Bill Wendling43de15f2010-03-27 01:22:38 +0000192
193 return Changed;
Bill Wendlingbfbd8532010-03-27 01:19:12 +0000194}
195
Bill Wendling201f5f02010-03-29 23:37:07 +0000196/// 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.
200bool
201DwarfEHPrepare::FindSelectorAndURoR(Instruction *Inst, bool &URoRInvoke,
202 SmallPtrSet<IntrinsicInst*, 8> &SelCalls) {
203 SmallPtrSet<PHINode*, 32> SeenPHIs;
204 bool Changed = false;
205
Bill Wendling201f5f02010-03-29 23:37:07 +0000206 for (Value::use_iterator
207 I = Inst->use_begin(), E = Inst->use_end(); I != E; ++I) {
Gabor Greif96f1d8e2010-07-22 13:36:47 +0000208 Instruction *II = dyn_cast<Instruction>(*I);
Bill Wendling201f5f02010-03-29 23:37:07 +0000209 if (!II || II->getParent()->getParent() != F) continue;
210
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);
Bill Wendling201f5f02010-03-29 23:37:07 +0000219 } 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);
223 }
224 }
225
226 return Changed;
227}
228
Bill Wendling49ad7312010-10-29 07:46:01 +0000229/// 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.
Bill Wendling2ad4aca2010-03-26 23:41:30 +0000234bool DwarfEHPrepare::HandleURoRInvokes() {
235 if (!EHCatchAllValue) {
236 EHCatchAllValue =
Bill Wendling23295cc2010-07-26 22:36:52 +0000237 F->getParent()->getNamedGlobal("llvm.eh.catch.all.value");
Bill Wendling2ad4aca2010-03-26 23:41:30 +0000238 if (!EHCatchAllValue) return false;
239 }
240
Bill Wendlingbfbd8532010-03-27 01:19:12 +0000241 if (!SelectorIntrinsic) {
242 SelectorIntrinsic =
243 Intrinsic::getDeclaration(F->getParent(), Intrinsic::eh_selector);
244 if (!SelectorIntrinsic) return false;
245 }
246
Bill Wendlingd9e3b2b2010-06-30 22:49:53 +0000247 SmallPtrSet<IntrinsicInst*, 32> Sels;
248 SmallPtrSet<IntrinsicInst*, 32> CatchAllSels;
249 FindAllCleanupSelectors(Sels, CatchAllSels);
250
Bill Wendling2ad4aca2010-03-26 23:41:30 +0000251 if (!URoR) {
252 URoR = F->getParent()->getFunction("_Unwind_Resume_or_Rethrow");
Bill Wendling49ad7312010-10-29 07:46:01 +0000253 if (!URoR) {
254 URoR = F->getParent()->getFunction("_Unwind_SjLj_Resume");
255 if (!URoR) return CleanupSelectors(CatchAllSels);
256 }
Bill Wendling2ad4aca2010-03-26 23:41:30 +0000257 }
258
Bill Wendlingbfde6442010-03-29 23:02:46 +0000259 SmallPtrSet<InvokeInst*, 32> URoRInvokes;
Bill Wendlingbfde6442010-03-29 23:02:46 +0000260 FindAllURoRInvokes(URoRInvokes);
Bill Wendling2ad4aca2010-03-26 23:41:30 +0000261
Bill Wendling2ad4aca2010-03-26 23:41:30 +0000262 SmallPtrSet<IntrinsicInst*, 32> SelsToConvert;
263
Bill Wendlingbfde6442010-03-29 23:02:46 +0000264 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();
Dan Gohmance0fe5d2010-07-26 17:38:15 +0000270 if (DT->dominates(SelBB, URoRBB)) {
Bill Wendlingbfde6442010-03-29 23:02:46 +0000271 SelsToConvert.insert(*SI);
272 break;
Bill Wendling2ad4aca2010-03-26 23:41:30 +0000273 }
274 }
275 }
276
Bill Wendlingbfde6442010-03-29 23:02:46 +0000277 bool Changed = false;
278
Bill Wendling201f5f02010-03-29 23:37:07 +0000279 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);
Bill Wendlingd9e3b2b2010-06-30 22:49:53 +0000285 if (!ExceptionValueIntrinsic)
286 return CleanupSelectors(CatchAllSels);
Bill Wendling201f5f02010-03-29 23:37:07 +0000287 }
288
289 for (Value::use_iterator
290 I = ExceptionValueIntrinsic->use_begin(),
291 E = ExceptionValueIntrinsic->use_end(); I != E; ++I) {
Gabor Greif96f1d8e2010-07-22 13:36:47 +0000292 IntrinsicInst *EHPtr = dyn_cast<IntrinsicInst>(*I);
Bill Wendling201f5f02010-03-29 23:37:07 +0000293 if (!EHPtr || EHPtr->getParent()->getParent() != F) continue;
294
Bill Wendling201f5f02010-03-29 23:37:07 +0000295 bool URoRInvoke = false;
296 SmallPtrSet<IntrinsicInst*, 8> SelCalls;
297 Changed |= FindSelectorAndURoR(EHPtr, URoRInvoke, SelCalls);
298
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
Bill Wendling94366112010-06-12 02:34:29 +0000304 SI = SelCalls.begin(), SE = SelCalls.end(); SI != SE; ++SI)
Bill Wendlingefbf3062010-06-24 18:49:10 +0000305 if (!HasCatchAllInSelector(*SI))
Bill Wendling94366112010-06-12 02:34:29 +0000306 SelsToConvert.insert(*SI);
Bill Wendling201f5f02010-03-29 23:37:07 +0000307 }
308 }
309 }
310
Bill Wendling2ad4aca2010-03-26 23:41:30 +0000311 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;
315
316 for (SmallPtrSet<IntrinsicInst*, 8>::iterator
317 SI = SelsToConvert.begin(), SE = SelsToConvert.end();
318 SI != SE; ++SI) {
319 IntrinsicInst *II = *SI;
Bill Wendling2ad4aca2010-03-26 23:41:30 +0000320
321 // Use the exception object pointer and the personality function
322 // from the original selector.
Gabor Greif2bf4b3b2010-06-25 11:25:30 +0000323 CallSite CS(II);
324 IntrinsicInst::op_iterator I = CS.arg_begin();
Gabor Greif2bf4b3b2010-06-25 11:25:30 +0000325 IntrinsicInst::op_iterator E = CS.arg_end();
326 IntrinsicInst::op_iterator B = prior(E);
327
328 // Exclude last argument if it is an integer.
329 if (isa<ConstantInt>(B)) E = B;
Bill Wendling94366112010-06-12 02:34:29 +0000330
Gabor Greif32621ad2010-06-28 16:40:52 +0000331 // Add exception object pointer (front).
332 // Add personality function (next).
333 // Add in any filter IDs (rest).
334 SmallVector<Value*, 8> Args(I, E);
Bill Wendling94366112010-06-12 02:34:29 +0000335
Bill Wendling2ad4aca2010-03-26 23:41:30 +0000336 Args.push_back(EHCatchAllValue->getInitializer()); // Catch-all indicator.
337
338 CallInst *NewSelector =
339 CallInst::Create(SelectorIntrinsic, Args.begin(), Args.end(),
340 "eh.sel.catch.all", II);
341
342 NewSelector->setTailCall(II->isTailCall());
343 NewSelector->setAttributes(II->getAttributes());
344 NewSelector->setCallingConv(II->getCallingConv());
345
346 II->replaceAllUsesWith(NewSelector);
347 II->eraseFromParent();
348 }
349 }
350
Bill Wendlingd9e3b2b2010-06-30 22:49:53 +0000351 Changed |= CleanupSelectors(CatchAllSels);
Bill Wendling2ad4aca2010-03-26 23:41:30 +0000352 return Changed;
353}
354
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000355/// NormalizeLandingPads - Normalize and discover landing pads, noting them
356/// in the LandingPads set. A landing pad is normal if the only CFG edges
Eric Christopherec26bf72009-09-15 21:56:46 +0000357/// 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.
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000360/// Abnormal landing pads are fixed up by redirecting all unwind edges to
361/// a new basic block which falls through to the original.
362bool DwarfEHPrepare::NormalizeLandingPads() {
363 bool Changed = false;
364
Dan Gohman55e59c12010-04-19 19:05:59 +0000365 const MCAsmInfo *MAI = TM->getMCAsmInfo();
Jim Grosbach8d77cc82010-01-20 23:03:55 +0000366 bool usingSjLjEH = MAI->getExceptionHandlingType() == ExceptionHandling::SjLj;
367
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000368 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;
376
377 // Check that only invoke unwind edges end at the landing pad.
378 bool OnlyUnwoundTo = true;
Jim Grosbach8d77cc82010-01-20 23:03:55 +0000379 bool SwitchOK = usingSjLjEH;
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000380 for (pred_iterator PI = pred_begin(LPad), PE = pred_end(LPad);
381 PI != PE; ++PI) {
382 TerminatorInst *PT = (*PI)->getTerminator();
Jim Grosbach8d77cc82010-01-20 23:03:55 +0000383 // 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;
390 }
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000391 if (!isa<InvokeInst>(PT) || LPad == PT->getSuccessor(0)) {
392 OnlyUnwoundTo = false;
393 break;
394 }
395 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000396
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000397 if (OnlyUnwoundTo) {
398 // Only unwind edges lead to the landing pad. Remember the landing pad.
399 LandingPads.insert(LPad);
400 continue;
401 }
402
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.
405
406 // Create the new basic block.
Bill Wendling8bedf972009-10-29 00:37:35 +0000407 BasicBlock *NewBB = BasicBlock::Create(F->getContext(),
Owen Anderson1d0be152009-08-13 21:58:54 +0000408 LPad->getName() + "_unwind_edge");
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000409
410 // Insert it into the function right before the original landing pad.
411 LPad->getParent()->getBasicBlockList().insert(LPad, NewBB);
412
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);
419 }
420
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);
426
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;
434 }
435 }
436
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);
445
446 // Now use this new PHI as the common incoming value for NewBB in PN.
447 InVal = NewPN;
448 }
449
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);
457 }
458
459 // Add a fallthrough from NewBB to the original landing pad.
460 BranchInst::Create(LPad, NewBB);
461
Duncan Sands22efc182010-08-31 09:05:06 +0000462 // Now update DominatorTree analysis information.
463 DT->splitBlock(NewBB);
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000464
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;
471 }
472
473 return Changed;
474}
475
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.
480bool DwarfEHPrepare::LowerUnwinds() {
Bill Wendling43488712009-09-14 20:52:37 +0000481 SmallVector<TerminatorInst*, 16> UnwindInsts;
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000482
483 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
484 TerminatorInst *TI = I->getTerminator();
Bill Wendling43488712009-09-14 20:52:37 +0000485 if (isa<UnwindInst>(TI))
486 UnwindInsts.push_back(TI);
487 }
488
489 if (UnwindInsts.empty()) return false;
490
491 // Find the rewind function if we didn't already.
492 if (!RewindFunction) {
Bill Wendling8bedf972009-10-29 00:37:35 +0000493 LLVMContext &Ctx = UnwindInsts[0]->getContext();
Bill Wendling43488712009-09-14 20:52:37 +0000494 std::vector<const Type*>
Bill Wendling8bedf972009-10-29 00:37:35 +0000495 Params(1, Type::getInt8PtrTy(Ctx));
496 FunctionType *FTy = FunctionType::get(Type::getVoidTy(Ctx),
Bill Wendling43488712009-09-14 20:52:37 +0000497 Params, false);
498 const char *RewindName = TLI->getLibcallName(RTLIB::UNWIND_RESUME);
499 RewindFunction = F->getParent()->getOrInsertFunction(RewindName, FTy);
500 }
501
Bill Wendling8bedf972009-10-29 00:37:35 +0000502 bool Changed = false;
503
Bill Wendling43488712009-09-14 20:52:37 +0000504 for (SmallVectorImpl<TerminatorInst*>::iterator
505 I = UnwindInsts.begin(), E = UnwindInsts.end(); I != E; ++I) {
506 TerminatorInst *TI = *I;
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000507
508 // Replace the unwind instruction with a call to _Unwind_Resume (or the
509 // appropriate target equivalent) followed by an UnreachableInst.
510
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000511 // Create the call...
Eric Christopher82f149d2009-09-04 01:14:14 +0000512 CallInst *CI = CallInst::Create(RewindFunction,
Duncan Sands850fcd42010-09-03 08:31:48 +0000513 CreateExceptionValueCall(TI->getParent()),
Bill Wendling43488712009-09-14 20:52:37 +0000514 "", TI);
Eric Christopher82f149d2009-09-04 01:14:14 +0000515 CI->setCallingConv(TLI->getLibcallCallingConv(RTLIB::UNWIND_RESUME));
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000516 // ...followed by an UnreachableInst.
Bill Wendling8bedf972009-10-29 00:37:35 +0000517 new UnreachableInst(TI->getContext(), TI);
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000518
519 // Nuke the unwind instruction.
520 TI->eraseFromParent();
521 ++NumUnwindsLowered;
522 Changed = true;
523 }
524
525 return Changed;
526}
527
528/// MoveExceptionValueCalls - Ensure that eh.exception is only ever called from
Duncan Sands850fcd42010-09-03 08:31:48 +0000529/// 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).
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000534bool 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.
Bill Wendling8bedf972009-10-29 00:37:35 +0000537 if (!ExceptionValueIntrinsic &&
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000538 !F->getParent()->getFunction(Intrinsic::getName(Intrinsic::eh_exception)))
539 return false;
540
541 bool Changed = false;
542
Duncan Sands850fcd42010-09-03 08:31:48 +0000543 // 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();
Eric Christopheradc581f2010-09-01 17:29:10 +0000546 LI != LE; ++LI) {
Duncan Sands850fcd42010-09-03 08:31:48 +0000547 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);
556
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);
561 }
562 EI->eraseFromParent();
563 ++NumExceptionValuesMoved;
564 Changed = true;
565 }
Duncan Sandsfb4e8ab2010-09-01 14:07:47 +0000566 }
567
Duncan Sands850fcd42010-09-03 08:31:48 +0000568 // 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;
573
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;
582
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;
589 }
590
591 if (FoundCallOutsideLandingPad)
592 break;
593 }
594
595 // If all calls to eh.exception are in landing pads then we are done.
596 if (!FoundCallOutsideLandingPad)
597 return Changed;
598
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));
604
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;
611
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;
620 }
621 }
622
623 return true;
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000624}
625
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000626/// 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).
629Instruction *DwarfEHPrepare::CreateExceptionValueCall(BasicBlock *BB) {
Dale Johannesen7249ef02010-04-02 21:49:27 +0000630 Instruction *Start = BB->getFirstNonPHIOrDbg();
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000631 // 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;
636
637 // Find the eh.exception intrinsic if we didn't already.
Bill Wendling8bedf972009-10-29 00:37:35 +0000638 if (!ExceptionValueIntrinsic)
639 ExceptionValueIntrinsic = Intrinsic::getDeclaration(F->getParent(),
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000640 Intrinsic::eh_exception);
641
642 // Create the call.
Bill Wendling8bedf972009-10-29 00:37:35 +0000643 return CallInst::Create(ExceptionValueIntrinsic, "eh.value.call", Start);
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000644}
645
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000646bool DwarfEHPrepare::runOnFunction(Function &Fn) {
647 bool Changed = false;
648
649 // Initialize internal state.
Duncan Sands22efc182010-08-31 09:05:06 +0000650 DT = &getAnalysis<DominatorTree>();
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000651 F = &Fn;
652
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();
656
657 // Turn unwind instructions into libcalls.
658 Changed |= LowerUnwinds();
659
Bill Wendling8bedf972009-10-29 00:37:35 +0000660 // TODO: Move eh.selector calls to landing pads and combine them.
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000661
662 // Move eh.exception calls to landing pads.
663 Changed |= MoveExceptionValueCalls();
664
Bill Wendling2ad4aca2010-03-26 23:41:30 +0000665 Changed |= HandleURoRInvokes();
666
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000667 LandingPads.clear();
668
669 return Changed;
670}