blob: 03604b0a170ff658b181246cbfb93eae538c4b08 [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");
John McCalld7c10862011-05-28 07:45:59 +000033STATISTIC(NumResumesLowered, "Number of eh.resume calls lowered");
Bill Wendling8bedf972009-10-29 00:37:35 +000034STATISTIC(NumExceptionValuesMoved, "Number of eh.exception calls moved");
Duncan Sandsb0f1e172009-05-22 20:36:31 +000035
36namespace {
Nick Lewycky6726b6d2009-10-25 06:33:48 +000037 class DwarfEHPrepare : public FunctionPass {
Dan Gohman55e59c12010-04-19 19:05:59 +000038 const TargetMachine *TM;
Duncan Sandsb0f1e172009-05-22 20:36:31 +000039 const TargetLowering *TLI;
Duncan Sandsb0f1e172009-05-22 20:36:31 +000040
41 // The eh.exception intrinsic.
Bill Wendling8bedf972009-10-29 00:37:35 +000042 Function *ExceptionValueIntrinsic;
Duncan Sandsb0f1e172009-05-22 20:36:31 +000043
Bill Wendling2ad4aca2010-03-26 23:41:30 +000044 // The eh.selector intrinsic.
45 Function *SelectorIntrinsic;
46
Bill Wendling49ad7312010-10-29 07:46:01 +000047 // _Unwind_Resume_or_Rethrow or _Unwind_SjLj_Resume call.
Bill Wendling2ad4aca2010-03-26 23:41:30 +000048 Constant *URoR;
49
50 // The EH language-specific catch-all type.
51 GlobalVariable *EHCatchAllValue;
52
Duncan Sandsb0f1e172009-05-22 20:36:31 +000053 // _Unwind_Resume or the target equivalent.
54 Constant *RewindFunction;
55
Duncan Sands22efc182010-08-31 09:05:06 +000056 // We both use and preserve dominator info.
Duncan Sandsb0f1e172009-05-22 20:36:31 +000057 DominatorTree *DT;
Duncan Sandsb0f1e172009-05-22 20:36:31 +000058
59 // The function we are running on.
60 Function *F;
61
62 // The landing pads for this function.
63 typedef SmallPtrSet<BasicBlock*, 8> BBSet;
64 BBSet LandingPads;
65
Duncan Sandsb0f1e172009-05-22 20:36:31 +000066 bool NormalizeLandingPads();
John McCalld7c10862011-05-28 07:45:59 +000067 bool LowerUnwindsAndResumes();
Duncan Sandsb0f1e172009-05-22 20:36:31 +000068 bool MoveExceptionValueCalls();
Duncan Sandsb0f1e172009-05-22 20:36:31 +000069
70 Instruction *CreateExceptionValueCall(BasicBlock *BB);
Duncan Sandsb0f1e172009-05-22 20:36:31 +000071
Bill Wendlingbfbd8532010-03-27 01:19:12 +000072 /// CleanupSelectors - Any remaining eh.selector intrinsic calls which still
Bill Wendling23295cc2010-07-26 22:36:52 +000073 /// use the "llvm.eh.catch.all.value" call need to convert to using its
Bill Wendlingbfbd8532010-03-27 01:19:12 +000074 /// initializer instead.
Bill Wendlingd9e3b2b2010-06-30 22:49:53 +000075 bool CleanupSelectors(SmallPtrSet<IntrinsicInst*, 32> &Sels);
Bill Wendlingbfbd8532010-03-27 01:19:12 +000076
Bill Wendlingefbf3062010-06-24 18:49:10 +000077 bool HasCatchAllInSelector(IntrinsicInst *);
Bill Wendling94366112010-06-12 02:34:29 +000078
Bill Wendlingbfde6442010-03-29 23:02:46 +000079 /// FindAllCleanupSelectors - Find all eh.selector calls that are clean-ups.
Bill Wendlingd9e3b2b2010-06-30 22:49:53 +000080 void FindAllCleanupSelectors(SmallPtrSet<IntrinsicInst*, 32> &Sels,
81 SmallPtrSet<IntrinsicInst*, 32> &CatchAllSels);
Bill Wendlingbfde6442010-03-29 23:02:46 +000082
83 /// FindAllURoRInvokes - Find all URoR invokes in the function.
84 void FindAllURoRInvokes(SmallPtrSet<InvokeInst*, 32> &URoRInvokes);
85
Bill Wendling49ad7312010-10-29 07:46:01 +000086 /// HandleURoRInvokes - Handle invokes of "_Unwind_Resume_or_Rethrow" or
87 /// "_Unwind_SjLj_Resume" calls. The "unwind" part of these invokes jump to
88 /// a landing pad within the current function. This is a candidate to merge
89 /// the selector associated with the URoR invoke with the one from the
90 /// URoR's landing pad.
Bill Wendling2ad4aca2010-03-26 23:41:30 +000091 bool HandleURoRInvokes();
92
Bill Wendling201f5f02010-03-29 23:37:07 +000093 /// 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,
Bill Wendling28cc1aa2011-03-15 01:03:17 +000097 SmallPtrSet<IntrinsicInst*, 8> &SelCalls,
98 SmallPtrSet<PHINode*, 32> &SeenPHIs);
Bill Wendling201f5f02010-03-29 23:37:07 +000099
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000100 public:
101 static char ID; // Pass identification, replacement for typeid.
Duncan Sands22efc182010-08-31 09:05:06 +0000102 DwarfEHPrepare(const TargetMachine *tm) :
Owen Anderson90c579d2010-08-06 18:33:48 +0000103 FunctionPass(ID), TM(tm), TLI(TM->getTargetLowering()),
Bill Wendling2ad4aca2010-03-26 23:41:30 +0000104 ExceptionValueIntrinsic(0), SelectorIntrinsic(0),
Owen Anderson081c34b2010-10-19 17:21:58 +0000105 URoR(0), EHCatchAllValue(0), RewindFunction(0) {
106 initializeDominatorTreePass(*PassRegistry::getPassRegistry());
107 }
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000108
109 virtual bool runOnFunction(Function &Fn);
110
Duncan Sands850fcd42010-09-03 08:31:48 +0000111 // getAnalysisUsage - We need the dominator tree for handling URoR.
Bill Wendling8bedf972009-10-29 00:37:35 +0000112 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Duncan Sands22efc182010-08-31 09:05:06 +0000113 AU.addRequired<DominatorTree>();
Bill Wendling8bedf972009-10-29 00:37:35 +0000114 AU.addPreserved<DominatorTree>();
Bill Wendling8bedf972009-10-29 00:37:35 +0000115 }
116
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000117 const char *getPassName() const {
118 return "Exception handling preparation";
119 }
120
121 };
122} // end anonymous namespace
123
124char DwarfEHPrepare::ID = 0;
125
Duncan Sands22efc182010-08-31 09:05:06 +0000126FunctionPass *llvm::createDwarfEHPass(const TargetMachine *tm) {
127 return new DwarfEHPrepare(tm);
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000128}
129
Bill Wendlingefbf3062010-06-24 18:49:10 +0000130/// HasCatchAllInSelector - Return true if the intrinsic instruction has a
131/// catch-all.
132bool DwarfEHPrepare::HasCatchAllInSelector(IntrinsicInst *II) {
133 if (!EHCatchAllValue) return false;
Bill Wendling94366112010-06-12 02:34:29 +0000134
Gabor Greif2bf4b3b2010-06-25 11:25:30 +0000135 unsigned ArgIdx = II->getNumArgOperands() - 1;
136 GlobalVariable *GV = dyn_cast<GlobalVariable>(II->getArgOperand(ArgIdx));
Bill Wendlingefbf3062010-06-24 18:49:10 +0000137 return GV == EHCatchAllValue;
Bill Wendling94366112010-06-12 02:34:29 +0000138}
139
Bill Wendlingbfde6442010-03-29 23:02:46 +0000140/// FindAllCleanupSelectors - Find all eh.selector calls that are clean-ups.
141void DwarfEHPrepare::
Bill Wendlingd9e3b2b2010-06-30 22:49:53 +0000142FindAllCleanupSelectors(SmallPtrSet<IntrinsicInst*, 32> &Sels,
143 SmallPtrSet<IntrinsicInst*, 32> &CatchAllSels) {
Bill Wendling2ad4aca2010-03-26 23:41:30 +0000144 for (Value::use_iterator
Bill Wendlingbfde6442010-03-29 23:02:46 +0000145 I = SelectorIntrinsic->use_begin(),
146 E = SelectorIntrinsic->use_end(); I != E; ++I) {
Gabor Greif96f1d8e2010-07-22 13:36:47 +0000147 IntrinsicInst *II = cast<IntrinsicInst>(*I);
Bill Wendling2ad4aca2010-03-26 23:41:30 +0000148
Bill Wendling94366112010-06-12 02:34:29 +0000149 if (II->getParent()->getParent() != F)
150 continue;
Bill Wendlingbfde6442010-03-29 23:02:46 +0000151
Bill Wendlingefbf3062010-06-24 18:49:10 +0000152 if (!HasCatchAllInSelector(II))
Bill Wendling94366112010-06-12 02:34:29 +0000153 Sels.insert(II);
Bill Wendlingd9e3b2b2010-06-30 22:49:53 +0000154 else
155 CatchAllSels.insert(II);
Bill Wendlingbfde6442010-03-29 23:02:46 +0000156 }
157}
158
159/// FindAllURoRInvokes - Find all URoR invokes in the function.
160void DwarfEHPrepare::
161FindAllURoRInvokes(SmallPtrSet<InvokeInst*, 32> &URoRInvokes) {
162 for (Value::use_iterator
163 I = URoR->use_begin(),
164 E = URoR->use_end(); I != E; ++I) {
Gabor Greif96f1d8e2010-07-22 13:36:47 +0000165 if (InvokeInst *II = dyn_cast<InvokeInst>(*I))
Bill Wendlingbfde6442010-03-29 23:02:46 +0000166 URoRInvokes.insert(II);
167 }
Bill Wendling2ad4aca2010-03-26 23:41:30 +0000168}
169
Bill Wendlingbfbd8532010-03-27 01:19:12 +0000170/// CleanupSelectors - Any remaining eh.selector intrinsic calls which still use
Bill Wendling23295cc2010-07-26 22:36:52 +0000171/// the "llvm.eh.catch.all.value" call need to convert to using its
Bill Wendlingbfbd8532010-03-27 01:19:12 +0000172/// initializer instead.
Bill Wendlingd9e3b2b2010-06-30 22:49:53 +0000173bool DwarfEHPrepare::CleanupSelectors(SmallPtrSet<IntrinsicInst*, 32> &Sels) {
Bill Wendlingbfde6442010-03-29 23:02:46 +0000174 if (!EHCatchAllValue) return false;
175
176 if (!SelectorIntrinsic) {
177 SelectorIntrinsic =
178 Intrinsic::getDeclaration(F->getParent(), Intrinsic::eh_selector);
179 if (!SelectorIntrinsic) return false;
180 }
181
Bill Wendling43de15f2010-03-27 01:22:38 +0000182 bool Changed = false;
Bill Wendlingd9e3b2b2010-06-30 22:49:53 +0000183 for (SmallPtrSet<IntrinsicInst*, 32>::iterator
184 I = Sels.begin(), E = Sels.end(); I != E; ++I) {
185 IntrinsicInst *Sel = *I;
Bill Wendlingbfbd8532010-03-27 01:19:12 +0000186
Bill Wendling23295cc2010-07-26 22:36:52 +0000187 // Index of the "llvm.eh.catch.all.value" variable.
Gabor Greif9d677682010-06-29 13:03:46 +0000188 unsigned OpIdx = Sel->getNumArgOperands() - 1;
189 GlobalVariable *GV = dyn_cast<GlobalVariable>(Sel->getArgOperand(OpIdx));
Bill Wendlingbfbd8532010-03-27 01:19:12 +0000190 if (GV != EHCatchAllValue) continue;
Gabor Greif9d677682010-06-29 13:03:46 +0000191 Sel->setArgOperand(OpIdx, EHCatchAllValue->getInitializer());
Bill Wendling43de15f2010-03-27 01:22:38 +0000192 Changed = true;
Bill Wendlingbfbd8532010-03-27 01:19:12 +0000193 }
Bill Wendling43de15f2010-03-27 01:22:38 +0000194
195 return Changed;
Bill Wendlingbfbd8532010-03-27 01:19:12 +0000196}
197
Bill Wendling201f5f02010-03-29 23:37:07 +0000198/// FindSelectorAndURoR - Find the eh.selector call associated with the
199/// eh.exception call. And indicate if there is a URoR "invoke" associated with
200/// the eh.exception call. This recursively looks past instructions which don't
201/// change the EH pointer value, like casts or PHI nodes.
202bool
203DwarfEHPrepare::FindSelectorAndURoR(Instruction *Inst, bool &URoRInvoke,
Bill Wendling28cc1aa2011-03-15 01:03:17 +0000204 SmallPtrSet<IntrinsicInst*, 8> &SelCalls,
205 SmallPtrSet<PHINode*, 32> &SeenPHIs) {
Bill Wendling201f5f02010-03-29 23:37:07 +0000206 bool Changed = false;
207
Bill Wendling201f5f02010-03-29 23:37:07 +0000208 for (Value::use_iterator
209 I = Inst->use_begin(), E = Inst->use_end(); I != E; ++I) {
Gabor Greif96f1d8e2010-07-22 13:36:47 +0000210 Instruction *II = dyn_cast<Instruction>(*I);
Bill Wendling201f5f02010-03-29 23:37:07 +0000211 if (!II || II->getParent()->getParent() != F) continue;
212
213 if (IntrinsicInst *Sel = dyn_cast<IntrinsicInst>(II)) {
214 if (Sel->getIntrinsicID() == Intrinsic::eh_selector)
215 SelCalls.insert(Sel);
216 } else if (InvokeInst *Invoke = dyn_cast<InvokeInst>(II)) {
217 if (Invoke->getCalledFunction() == URoR)
218 URoRInvoke = true;
219 } else if (CastInst *CI = dyn_cast<CastInst>(II)) {
Bill Wendling28cc1aa2011-03-15 01:03:17 +0000220 Changed |= FindSelectorAndURoR(CI, URoRInvoke, SelCalls, SeenPHIs);
Bill Wendling201f5f02010-03-29 23:37:07 +0000221 } else if (PHINode *PN = dyn_cast<PHINode>(II)) {
222 if (SeenPHIs.insert(PN))
223 // Don't process a PHI node more than once.
Bill Wendling28cc1aa2011-03-15 01:03:17 +0000224 Changed |= FindSelectorAndURoR(PN, URoRInvoke, SelCalls, SeenPHIs);
Bill Wendling201f5f02010-03-29 23:37:07 +0000225 }
226 }
227
228 return Changed;
229}
230
Bill Wendling49ad7312010-10-29 07:46:01 +0000231/// HandleURoRInvokes - Handle invokes of "_Unwind_Resume_or_Rethrow" or
232/// "_Unwind_SjLj_Resume" calls. The "unwind" part of these invokes jump to a
233/// landing pad within the current function. This is a candidate to merge the
234/// selector associated with the URoR invoke with the one from the URoR's
235/// landing pad.
Bill Wendling2ad4aca2010-03-26 23:41:30 +0000236bool DwarfEHPrepare::HandleURoRInvokes() {
237 if (!EHCatchAllValue) {
238 EHCatchAllValue =
Bill Wendling23295cc2010-07-26 22:36:52 +0000239 F->getParent()->getNamedGlobal("llvm.eh.catch.all.value");
Bill Wendling2ad4aca2010-03-26 23:41:30 +0000240 if (!EHCatchAllValue) return false;
241 }
242
Bill Wendlingbfbd8532010-03-27 01:19:12 +0000243 if (!SelectorIntrinsic) {
244 SelectorIntrinsic =
245 Intrinsic::getDeclaration(F->getParent(), Intrinsic::eh_selector);
246 if (!SelectorIntrinsic) return false;
247 }
248
Bill Wendlingd9e3b2b2010-06-30 22:49:53 +0000249 SmallPtrSet<IntrinsicInst*, 32> Sels;
250 SmallPtrSet<IntrinsicInst*, 32> CatchAllSels;
251 FindAllCleanupSelectors(Sels, CatchAllSels);
252
Bill Wendling2ad4aca2010-03-26 23:41:30 +0000253 if (!URoR) {
254 URoR = F->getParent()->getFunction("_Unwind_Resume_or_Rethrow");
Bill Wendlingedac4922011-06-01 01:49:35 +0000255 if (!URoR) return CleanupSelectors(CatchAllSels);
Bill Wendling2ad4aca2010-03-26 23:41:30 +0000256 }
257
Bill Wendlingbfde6442010-03-29 23:02:46 +0000258 SmallPtrSet<InvokeInst*, 32> URoRInvokes;
Bill Wendlingbfde6442010-03-29 23:02:46 +0000259 FindAllURoRInvokes(URoRInvokes);
Bill Wendling2ad4aca2010-03-26 23:41:30 +0000260
Bill Wendling2ad4aca2010-03-26 23:41:30 +0000261 SmallPtrSet<IntrinsicInst*, 32> SelsToConvert;
262
Bill Wendlingbfde6442010-03-29 23:02:46 +0000263 for (SmallPtrSet<IntrinsicInst*, 32>::iterator
264 SI = Sels.begin(), SE = Sels.end(); SI != SE; ++SI) {
265 const BasicBlock *SelBB = (*SI)->getParent();
266 for (SmallPtrSet<InvokeInst*, 32>::iterator
267 UI = URoRInvokes.begin(), UE = URoRInvokes.end(); UI != UE; ++UI) {
268 const BasicBlock *URoRBB = (*UI)->getParent();
Dan Gohmance0fe5d2010-07-26 17:38:15 +0000269 if (DT->dominates(SelBB, URoRBB)) {
Bill Wendlingbfde6442010-03-29 23:02:46 +0000270 SelsToConvert.insert(*SI);
271 break;
Bill Wendling2ad4aca2010-03-26 23:41:30 +0000272 }
273 }
274 }
275
Bill Wendlingbfde6442010-03-29 23:02:46 +0000276 bool Changed = false;
277
Bill Wendling201f5f02010-03-29 23:37:07 +0000278 if (Sels.size() != SelsToConvert.size()) {
279 // If we haven't been able to convert all of the clean-up selectors, then
280 // loop through the slow way to see if they still need to be converted.
281 if (!ExceptionValueIntrinsic) {
282 ExceptionValueIntrinsic =
283 Intrinsic::getDeclaration(F->getParent(), Intrinsic::eh_exception);
Bill Wendlingd9e3b2b2010-06-30 22:49:53 +0000284 if (!ExceptionValueIntrinsic)
285 return CleanupSelectors(CatchAllSels);
Bill Wendling201f5f02010-03-29 23:37:07 +0000286 }
287
288 for (Value::use_iterator
289 I = ExceptionValueIntrinsic->use_begin(),
290 E = ExceptionValueIntrinsic->use_end(); I != E; ++I) {
Gabor Greif96f1d8e2010-07-22 13:36:47 +0000291 IntrinsicInst *EHPtr = dyn_cast<IntrinsicInst>(*I);
Bill Wendling201f5f02010-03-29 23:37:07 +0000292 if (!EHPtr || EHPtr->getParent()->getParent() != F) continue;
293
Bill Wendling201f5f02010-03-29 23:37:07 +0000294 bool URoRInvoke = false;
295 SmallPtrSet<IntrinsicInst*, 8> SelCalls;
Bill Wendling28cc1aa2011-03-15 01:03:17 +0000296 SmallPtrSet<PHINode*, 32> SeenPHIs;
297 Changed |= FindSelectorAndURoR(EHPtr, URoRInvoke, SelCalls, SeenPHIs);
Bill Wendling201f5f02010-03-29 23:37:07 +0000298
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 =
Jay Foada3efbb12011-07-15 08:37:34 +0000339 CallInst::Create(SelectorIntrinsic, Args, "eh.sel.catch.all", II);
Bill Wendling2ad4aca2010-03-26 23:41:30 +0000340
341 NewSelector->setTailCall(II->isTailCall());
342 NewSelector->setAttributes(II->getAttributes());
343 NewSelector->setCallingConv(II->getCallingConv());
344
345 II->replaceAllUsesWith(NewSelector);
346 II->eraseFromParent();
347 }
348 }
349
Bill Wendlingd9e3b2b2010-06-30 22:49:53 +0000350 Changed |= CleanupSelectors(CatchAllSels);
Bill Wendling2ad4aca2010-03-26 23:41:30 +0000351 return Changed;
352}
353
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000354/// NormalizeLandingPads - Normalize and discover landing pads, noting them
355/// in the LandingPads set. A landing pad is normal if the only CFG edges
Eric Christopherec26bf72009-09-15 21:56:46 +0000356/// that end at it are unwind edges from invoke instructions. If we inlined
357/// through an invoke we could have a normal branch from the previous
358/// unwind block through to the landing pad for the original invoke.
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000359/// Abnormal landing pads are fixed up by redirecting all unwind edges to
360/// a new basic block which falls through to the original.
361bool DwarfEHPrepare::NormalizeLandingPads() {
362 bool Changed = false;
363
Dan Gohman55e59c12010-04-19 19:05:59 +0000364 const MCAsmInfo *MAI = TM->getMCAsmInfo();
Jim Grosbach8d77cc82010-01-20 23:03:55 +0000365 bool usingSjLjEH = MAI->getExceptionHandlingType() == ExceptionHandling::SjLj;
366
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000367 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
368 TerminatorInst *TI = I->getTerminator();
369 if (!isa<InvokeInst>(TI))
370 continue;
371 BasicBlock *LPad = TI->getSuccessor(1);
372 // Skip landing pads that have already been normalized.
373 if (LandingPads.count(LPad))
374 continue;
375
376 // Check that only invoke unwind edges end at the landing pad.
377 bool OnlyUnwoundTo = true;
Jim Grosbach8d77cc82010-01-20 23:03:55 +0000378 bool SwitchOK = usingSjLjEH;
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000379 for (pred_iterator PI = pred_begin(LPad), PE = pred_end(LPad);
380 PI != PE; ++PI) {
381 TerminatorInst *PT = (*PI)->getTerminator();
Jim Grosbach8d77cc82010-01-20 23:03:55 +0000382 // The SjLj dispatch block uses a switch instruction. This is effectively
383 // an unwind edge, so we can disregard it here. There will only ever
384 // be one dispatch, however, so if there are multiple switches, one
385 // of them truly is a normal edge, not an unwind edge.
386 if (SwitchOK && isa<SwitchInst>(PT)) {
387 SwitchOK = false;
388 continue;
389 }
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000390 if (!isa<InvokeInst>(PT) || LPad == PT->getSuccessor(0)) {
391 OnlyUnwoundTo = false;
392 break;
393 }
394 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000395
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000396 if (OnlyUnwoundTo) {
397 // Only unwind edges lead to the landing pad. Remember the landing pad.
398 LandingPads.insert(LPad);
399 continue;
400 }
401
402 // At least one normal edge ends at the landing pad. Redirect the unwind
403 // edges to a new basic block which falls through into this one.
404
405 // Create the new basic block.
Bill Wendling8bedf972009-10-29 00:37:35 +0000406 BasicBlock *NewBB = BasicBlock::Create(F->getContext(),
Owen Anderson1d0be152009-08-13 21:58:54 +0000407 LPad->getName() + "_unwind_edge");
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000408
409 // Insert it into the function right before the original landing pad.
410 LPad->getParent()->getBasicBlockList().insert(LPad, NewBB);
411
412 // Redirect unwind edges from the original landing pad to NewBB.
413 for (pred_iterator PI = pred_begin(LPad), PE = pred_end(LPad); PI != PE; ) {
414 TerminatorInst *PT = (*PI++)->getTerminator();
415 if (isa<InvokeInst>(PT) && PT->getSuccessor(1) == LPad)
416 // Unwind to the new block.
417 PT->setSuccessor(1, NewBB);
418 }
419
420 // If there are any PHI nodes in LPad, we need to update them so that they
421 // merge incoming values from NewBB instead.
422 for (BasicBlock::iterator II = LPad->begin(); isa<PHINode>(II); ++II) {
423 PHINode *PN = cast<PHINode>(II);
424 pred_iterator PB = pred_begin(NewBB), PE = pred_end(NewBB);
425
426 // Check to see if all of the values coming in via unwind edges are the
427 // same. If so, we don't need to create a new PHI node.
428 Value *InVal = PN->getIncomingValueForBlock(*PB);
429 for (pred_iterator PI = PB; PI != PE; ++PI) {
430 if (PI != PB && InVal != PN->getIncomingValueForBlock(*PI)) {
431 InVal = 0;
432 break;
433 }
434 }
435
436 if (InVal == 0) {
437 // Different unwind edges have different values. Create a new PHI node
438 // in NewBB.
Jay Foad3ecfc862011-03-30 11:28:46 +0000439 PHINode *NewPN = PHINode::Create(PN->getType(),
440 PN->getNumIncomingValues(),
441 PN->getName()+".unwind", NewBB);
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000442 // 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.
John McCalld7c10862011-05-28 07:45:59 +0000480bool DwarfEHPrepare::LowerUnwindsAndResumes() {
481 SmallVector<Instruction*, 16> ResumeInsts;
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000482
John McCalld7c10862011-05-28 07:45:59 +0000483 for (Function::iterator fi = F->begin(), fe = F->end(); fi != fe; ++fi) {
484 for (BasicBlock::iterator bi = fi->begin(), be = fi->end(); bi != be; ++bi){
485 if (isa<UnwindInst>(bi))
486 ResumeInsts.push_back(bi);
487 else if (CallInst *call = dyn_cast<CallInst>(bi))
488 if (Function *fn = dyn_cast<Function>(call->getCalledValue()))
489 if (fn->getName() == "llvm.eh.resume")
490 ResumeInsts.push_back(bi);
491 }
Bill Wendling43488712009-09-14 20:52:37 +0000492 }
493
John McCalld7c10862011-05-28 07:45:59 +0000494 if (ResumeInsts.empty()) return false;
Bill Wendling43488712009-09-14 20:52:37 +0000495
496 // Find the rewind function if we didn't already.
497 if (!RewindFunction) {
John McCalld7c10862011-05-28 07:45:59 +0000498 LLVMContext &Ctx = ResumeInsts[0]->getContext();
Bill Wendling8bedf972009-10-29 00:37:35 +0000499 FunctionType *FTy = FunctionType::get(Type::getVoidTy(Ctx),
Jay Foad5fdd6c82011-07-12 14:06:48 +0000500 Type::getInt8PtrTy(Ctx), false);
Bill Wendling43488712009-09-14 20:52:37 +0000501 const char *RewindName = TLI->getLibcallName(RTLIB::UNWIND_RESUME);
502 RewindFunction = F->getParent()->getOrInsertFunction(RewindName, FTy);
503 }
504
Bill Wendling8bedf972009-10-29 00:37:35 +0000505 bool Changed = false;
506
John McCalld7c10862011-05-28 07:45:59 +0000507 for (SmallVectorImpl<Instruction*>::iterator
508 I = ResumeInsts.begin(), E = ResumeInsts.end(); I != E; ++I) {
509 Instruction *RI = *I;
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000510
John McCalld7c10862011-05-28 07:45:59 +0000511 // Replace the resuming instruction with a call to _Unwind_Resume (or the
512 // appropriate target equivalent).
513
514 llvm::Value *ExnValue;
515 if (isa<UnwindInst>(RI))
516 ExnValue = CreateExceptionValueCall(RI->getParent());
517 else
518 ExnValue = cast<CallInst>(RI)->getArgOperand(0);
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000519
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000520 // Create the call...
John McCalld7c10862011-05-28 07:45:59 +0000521 CallInst *CI = CallInst::Create(RewindFunction, ExnValue, "", RI);
Eric Christopher82f149d2009-09-04 01:14:14 +0000522 CI->setCallingConv(TLI->getLibcallCallingConv(RTLIB::UNWIND_RESUME));
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000523
John McCalld7c10862011-05-28 07:45:59 +0000524 // ...followed by an UnreachableInst, if it was an unwind.
525 // Calls to llvm.eh.resume are typically already followed by this.
526 if (isa<UnwindInst>(RI))
527 new UnreachableInst(RI->getContext(), RI);
528
John McCalld7c10862011-05-28 07:45:59 +0000529 if (isa<UnwindInst>(RI))
530 ++NumUnwindsLowered;
531 else
532 ++NumResumesLowered;
Benjamin Kramer33858012011-05-28 11:48:37 +0000533
534 // Nuke the resume instruction.
535 RI->eraseFromParent();
536
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000537 Changed = true;
538 }
539
540 return Changed;
541}
542
543/// MoveExceptionValueCalls - Ensure that eh.exception is only ever called from
Duncan Sands850fcd42010-09-03 08:31:48 +0000544/// landing pads by replacing calls outside of landing pads with direct use of
545/// a register holding the appropriate value; this requires adding calls inside
546/// all landing pads to initialize the register. Also, move eh.exception calls
547/// inside landing pads to the start of the landing pad (optional, but may make
548/// things simpler for later passes).
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000549bool DwarfEHPrepare::MoveExceptionValueCalls() {
550 // If the eh.exception intrinsic is not declared in the module then there is
551 // nothing to do. Speed up compilation by checking for this common case.
Bill Wendling8bedf972009-10-29 00:37:35 +0000552 if (!ExceptionValueIntrinsic &&
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000553 !F->getParent()->getFunction(Intrinsic::getName(Intrinsic::eh_exception)))
554 return false;
555
556 bool Changed = false;
557
Duncan Sands850fcd42010-09-03 08:31:48 +0000558 // Move calls to eh.exception that are inside a landing pad to the start of
559 // the landing pad.
560 for (BBSet::const_iterator LI = LandingPads.begin(), LE = LandingPads.end();
Eric Christopheradc581f2010-09-01 17:29:10 +0000561 LI != LE; ++LI) {
Duncan Sands850fcd42010-09-03 08:31:48 +0000562 BasicBlock *LP = *LI;
563 for (BasicBlock::iterator II = LP->getFirstNonPHIOrDbg(), IE = LP->end();
564 II != IE;)
565 if (EHExceptionInst *EI = dyn_cast<EHExceptionInst>(II++)) {
566 // Found a call to eh.exception.
567 if (!EI->use_empty()) {
568 // If there is already a call to eh.exception at the start of the
569 // landing pad, then get hold of it; otherwise create such a call.
570 Value *CallAtStart = CreateExceptionValueCall(LP);
571
572 // If the call was at the start of a landing pad then leave it alone.
573 if (EI == CallAtStart)
574 continue;
575 EI->replaceAllUsesWith(CallAtStart);
576 }
577 EI->eraseFromParent();
578 ++NumExceptionValuesMoved;
579 Changed = true;
580 }
Duncan Sandsfb4e8ab2010-09-01 14:07:47 +0000581 }
582
Duncan Sands850fcd42010-09-03 08:31:48 +0000583 // Look for calls to eh.exception that are not in a landing pad. If one is
584 // found, then a register that holds the exception value will be created in
585 // each landing pad, and the SSAUpdater will be used to compute the values
586 // returned by eh.exception calls outside of landing pads.
587 SSAUpdater SSA;
588
589 // Remember where we found the eh.exception call, to avoid rescanning earlier
590 // basic blocks which we already know contain no eh.exception calls.
591 bool FoundCallOutsideLandingPad = false;
592 Function::iterator BB = F->begin();
593 for (Function::iterator BE = F->end(); BB != BE; ++BB) {
594 // Skip over landing pads.
595 if (LandingPads.count(BB))
596 continue;
597
598 for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end();
599 II != IE; ++II)
600 if (isa<EHExceptionInst>(II)) {
601 SSA.Initialize(II->getType(), II->getName());
602 FoundCallOutsideLandingPad = true;
603 break;
604 }
605
606 if (FoundCallOutsideLandingPad)
607 break;
608 }
609
610 // If all calls to eh.exception are in landing pads then we are done.
611 if (!FoundCallOutsideLandingPad)
612 return Changed;
613
614 // Add a call to eh.exception at the start of each landing pad, and tell the
615 // SSAUpdater that this is the value produced by the landing pad.
616 for (BBSet::iterator LI = LandingPads.begin(), LE = LandingPads.end();
617 LI != LE; ++LI)
618 SSA.AddAvailableValue(*LI, CreateExceptionValueCall(*LI));
619
620 // Now turn all calls to eh.exception that are not in a landing pad into a use
621 // of the appropriate register.
622 for (Function::iterator BE = F->end(); BB != BE; ++BB) {
623 // Skip over landing pads.
624 if (LandingPads.count(BB))
625 continue;
626
627 for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end();
628 II != IE;)
629 if (EHExceptionInst *EI = dyn_cast<EHExceptionInst>(II++)) {
630 // Found a call to eh.exception, replace it with the value from any
631 // upstream landing pad(s).
632 EI->replaceAllUsesWith(SSA.GetValueAtEndOfBlock(BB));
633 EI->eraseFromParent();
634 ++NumExceptionValuesMoved;
635 }
636 }
637
638 return true;
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000639}
640
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000641/// CreateExceptionValueCall - Insert a call to the eh.exception intrinsic at
642/// the start of the basic block (unless there already is one, in which case
643/// the existing call is returned).
644Instruction *DwarfEHPrepare::CreateExceptionValueCall(BasicBlock *BB) {
Dale Johannesen7249ef02010-04-02 21:49:27 +0000645 Instruction *Start = BB->getFirstNonPHIOrDbg();
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000646 // Is this a call to eh.exception?
647 if (IntrinsicInst *CI = dyn_cast<IntrinsicInst>(Start))
648 if (CI->getIntrinsicID() == Intrinsic::eh_exception)
649 // Reuse the existing call.
650 return Start;
651
652 // Find the eh.exception intrinsic if we didn't already.
Bill Wendling8bedf972009-10-29 00:37:35 +0000653 if (!ExceptionValueIntrinsic)
654 ExceptionValueIntrinsic = Intrinsic::getDeclaration(F->getParent(),
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000655 Intrinsic::eh_exception);
656
657 // Create the call.
Bill Wendling8bedf972009-10-29 00:37:35 +0000658 return CallInst::Create(ExceptionValueIntrinsic, "eh.value.call", Start);
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000659}
660
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000661bool DwarfEHPrepare::runOnFunction(Function &Fn) {
662 bool Changed = false;
663
664 // Initialize internal state.
Duncan Sands22efc182010-08-31 09:05:06 +0000665 DT = &getAnalysis<DominatorTree>();
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000666 F = &Fn;
667
668 // Ensure that only unwind edges end at landing pads (a landing pad is a
669 // basic block where an invoke unwind edge ends).
670 Changed |= NormalizeLandingPads();
671
John McCalld7c10862011-05-28 07:45:59 +0000672 // Turn unwind instructions and eh.resume calls into libcalls.
673 Changed |= LowerUnwindsAndResumes();
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000674
Bill Wendling8bedf972009-10-29 00:37:35 +0000675 // TODO: Move eh.selector calls to landing pads and combine them.
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000676
677 // Move eh.exception calls to landing pads.
678 Changed |= MoveExceptionValueCalls();
679
Bill Wendling2ad4aca2010-03-26 23:41:30 +0000680 Changed |= HandleURoRInvokes();
681
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000682 LandingPads.clear();
683
684 return Changed;
685}