llvm.org GIT mirror llvm / 9bb9615
Remove LowerInvoke's obsolete "-enable-correct-eh-support" option This option caused LowerInvoke to generate code using SJLJ-based exception handling, but there is no code left that interprets the jmp_buf stack that the resulting code maintained (llvm.sjljeh.jblist). This option has been obsolete for a while, and replaced by SjLjEHPrepare. This leaves the default behaviour of LowerInvoke, which is to convert invokes to calls. Differential Revision: http://llvm-reviews.chandlerc.com/D3136 git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@204388 91177308-0d34-0410-b5e6-96231b3b80d8 Mark Seaborn 5 years ago
11 changed file(s) with 19 addition(s) and 645 deletion(s). Raw diff Collapse all Expand all
111111 optimizations allow the code generator to make use of some instructions which
112112 would otherwise not be usable (such as ``fsin`` on X86).
113113
114 .. option:: --enable-correct-eh-support
115
116 Instruct the **lowerinvoke** pass to insert code for correct exception
117 handling support. This is expensive and is by default omitted for efficiency.
118
119114 .. option:: --stats
120115
121116 Print statistics recorded by code-generation passes.
186186 **-disable-spill-fusing**
187187
188188 Disable fusing of spill code into instructions.
189
190
191
192 **-enable-correct-eh-support**
193
194 Make the -lowerinvoke pass insert expensive, but correct, EH code.
195189
196190
197191
892892 any libraries which may not be available in bitcode form); it simply lowers
893893 every atomic intrinsic.
894894
895 ``-lowerinvoke``: Lower invoke and unwind, for unwindless code generators
896 -------------------------------------------------------------------------
895 ``-lowerinvoke``: Lower invokes to calls, for unwindless code generators
896 ------------------------------------------------------------------------
897897
898898 This transformation is designed for use by code generators which do not yet
899 support stack unwinding. This pass supports two models of exception handling
900 lowering, the "cheap" support and the "expensive" support.
901
902 "Cheap" exception handling support gives the program the ability to execute any
903 program which does not "throw an exception", by turning "``invoke``"
904 instructions into calls and by turning "``unwind``" instructions into calls to
905 ``abort()``. If the program does dynamically use the "``unwind``" instruction,
906 the program will print a message then abort.
907
908 "Expensive" exception handling support gives the full exception handling
909 support to the program at the cost of making the "``invoke``" instruction
910 really expensive. It basically inserts ``setjmp``/``longjmp`` calls to emulate
911 the exception handling as necessary.
912
913 Because the "expensive" support slows down programs a lot, and EH is only used
914 for a subset of the programs, it must be specifically enabled by the
915 ``-enable-correct-eh-support`` option.
916
917 Note that after this pass runs the CFG is not entirely accurate (exceptional
918 control flow edges are not correct anymore) so only very simple things should
919 be done after the ``lowerinvoke`` pass has run (like generation of native
920 code). This should not be used as a general purpose "my LLVM-to-LLVM pass
921 doesn't support the ``invoke`` instruction yet" lowering pass.
899 support stack unwinding. This pass converts ``invoke`` instructions to
900 ``call`` instructions, so that any exception-handling ``landingpad`` blocks
901 become dead code (which can be removed by running the ``-simplifycfg`` pass
902 afterwards).
922903
923904 ``-lowerswitch``: Lower ``SwitchInst``\ s to branches
924905 -----------------------------------------------------
261261
262262 //===----------------------------------------------------------------------===//
263263 //
264 // LowerInvoke - This pass converts invoke and unwind instructions to use sjlj
265 // exception handling mechanisms. Note that after this pass runs the CFG is not
266 // entirely accurate (exceptional control flow edges are not correct anymore) so
267 // only very simple things should be done after the lowerinvoke pass has run
268 // (like generation of native code). This should *NOT* be used as a general
269 // purpose "my LLVM-to-LLVM pass doesn't support the invoke instruction yet"
270 // lowering pass.
271 //
272 FunctionPass *createLowerInvokePass(const TargetMachine *TM = 0,
273 bool useExpensiveEHSupport = false);
264 // LowerInvoke - This pass removes invoke instructions, converting them to call
265 // instructions.
266 //
267 FunctionPass *createLowerInvokePass();
274268 extern char &LowerInvokePassID;
275269
276270 //===----------------------------------------------------------------------===//
422422 addPass(createDwarfEHPass(TM));
423423 break;
424424 case ExceptionHandling::None:
425 addPass(createLowerInvokePass(TM));
425 addPass(createLowerInvokePass());
426426
427427 // The lower invoke pass may create unreachable code. Remove it.
428428 addPass(createUnreachableBlockEliminationPass());
None //===- LowerInvoke.cpp - Eliminate Invoke & Unwind instructions -----------===//
0 //===- LowerInvoke.cpp - Eliminate Invoke instructions --------------------===//
11 //
22 // The LLVM Compiler Infrastructure
33 //
77 //===----------------------------------------------------------------------===//
88 //
99 // This transformation is designed for use by code generators which do not yet
10 // support stack unwinding. This pass supports two models of exception handling
11 // lowering, the 'cheap' support and the 'expensive' support.
12 //
13 // 'Cheap' exception handling support gives the program the ability to execute
14 // any program which does not "throw an exception", by turning 'invoke'
15 // instructions into calls and by turning 'unwind' instructions into calls to
16 // abort(). If the program does dynamically use the unwind instruction, the
17 // program will print a message then abort.
18 //
19 // 'Expensive' exception handling support gives the full exception handling
20 // support to the program at the cost of making the 'invoke' instruction
21 // really expensive. It basically inserts setjmp/longjmp calls to emulate the
22 // exception handling as necessary.
23 //
24 // Because the 'expensive' support slows down programs a lot, and EH is only
25 // used for a subset of the programs, it must be specifically enabled by an
26 // option.
27 //
28 // Note that after this pass runs the CFG is not entirely accurate (exceptional
29 // control flow edges are not correct anymore) so only very simple things should
30 // be done after the lowerinvoke pass has run (like generation of native code).
31 // This should not be used as a general purpose "my LLVM-to-LLVM pass doesn't
32 // support the invoke instruction yet" lowering pass.
10 // support stack unwinding. This pass converts 'invoke' instructions to 'call'
11 // instructions, so that any exception-handling 'landingpad' blocks become dead
12 // code (which can be removed by running the '-simplifycfg' pass afterwards).
3313 //
3414 //===----------------------------------------------------------------------===//
3515
3717 #include "llvm/Transforms/Scalar.h"
3818 #include "llvm/ADT/SmallVector.h"
3919 #include "llvm/ADT/Statistic.h"
40 #include "llvm/IR/Constants.h"
41 #include "llvm/IR/DerivedTypes.h"
4220 #include "llvm/IR/Instructions.h"
43 #include "llvm/IR/Intrinsics.h"
4421 #include "llvm/IR/LLVMContext.h"
4522 #include "llvm/IR/Module.h"
4623 #include "llvm/Pass.h"
4724 #include "llvm/Support/CommandLine.h"
48 #include "llvm/Target/TargetLowering.h"
49 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
50 #include "llvm/Transforms/Utils/Local.h"
51 #include
52 #include
5325 using namespace llvm;
5426
5527 STATISTIC(NumInvokes, "Number of invokes replaced");
56 STATISTIC(NumSpilled, "Number of registers live across unwind edges");
57
58 static cl::opt ExpensiveEHSupport("enable-correct-eh-support",
59 cl::desc("Make the -lowerinvoke pass insert expensive, but correct, EH code"));
6028
6129 namespace {
6230 class LowerInvoke : public FunctionPass {
63 const TargetMachine *TM;
64
65 // Used for both models.
66 Constant *AbortFn;
67
68 // Used for expensive EH support.
69 StructType *JBLinkTy;
70 GlobalVariable *JBListHead;
71 Constant *SetJmpFn, *LongJmpFn, *StackSaveFn, *StackRestoreFn;
72 bool useExpensiveEHSupport;
73
7431 public:
7532 static char ID; // Pass identification, replacement for typeid
76 explicit LowerInvoke(const TargetMachine *TM = 0,
77 bool useExpensiveEHSupport = ExpensiveEHSupport)
78 : FunctionPass(ID), TM(TM),
79 useExpensiveEHSupport(useExpensiveEHSupport) {
33 explicit LowerInvoke() : FunctionPass(ID) {
8034 initializeLowerInvokePass(*PassRegistry::getPassRegistry());
8135 }
82 bool doInitialization(Module &M) override;
8336 bool runOnFunction(Function &F) override;
84
85 void getAnalysisUsage(AnalysisUsage &AU) const override {
86 // This is a cluster of orthogonal Transforms
87 AU.addPreserved("mem2reg");
88 AU.addPreservedID(LowerSwitchID);
89 }
90
91 private:
92 bool insertCheapEHSupport(Function &F);
93 void splitLiveRangesLiveAcrossInvokes(SmallVectorImpl&Invokes);
94 void rewriteExpensiveInvoke(InvokeInst *II, unsigned InvokeNo,
95 AllocaInst *InvokeNum, AllocaInst *StackPtr,
96 SwitchInst *CatchSwitch);
97 bool insertExpensiveEHSupport(Function &F);
9837 };
9938 }
10039
10645 char &llvm::LowerInvokePassID = LowerInvoke::ID;
10746
10847 // Public Interface To the LowerInvoke pass.
109 FunctionPass *llvm::createLowerInvokePass(const TargetMachine *TM,
110 bool useExpensiveEHSupport) {
111 return new LowerInvoke(TM, useExpensiveEHSupport || ExpensiveEHSupport);
48 FunctionPass *llvm::createLowerInvokePass() {
49 return new LowerInvoke();
11250 }
11351
114 // doInitialization - Make sure that there is a prototype for abort in the
115 // current module.
116 bool LowerInvoke::doInitialization(Module &M) {
117 Type *VoidPtrTy = Type::getInt8PtrTy(M.getContext());
118 if (useExpensiveEHSupport) {
119 // Insert a type for the linked list of jump buffers.
120 const TargetLowering *TLI = TM ? TM->getTargetLowering() : 0;
121 unsigned JBSize = TLI ? TLI->getJumpBufSize() : 0;
122 JBSize = JBSize ? JBSize : 200;
123 Type *JmpBufTy = ArrayType::get(VoidPtrTy, JBSize);
124
125 JBLinkTy = StructType::create(M.getContext(), "llvm.sjljeh.jmpbufty");
126 Type *Elts[] = { JmpBufTy, PointerType::getUnqual(JBLinkTy) };
127 JBLinkTy->setBody(Elts);
128
129 Type *PtrJBList = PointerType::getUnqual(JBLinkTy);
130
131 // Now that we've done that, insert the jmpbuf list head global, unless it
132 // already exists.
133 if (!(JBListHead = M.getGlobalVariable("llvm.sjljeh.jblist", PtrJBList))) {
134 JBListHead = new GlobalVariable(M, PtrJBList, false,
135 GlobalValue::LinkOnceAnyLinkage,
136 Constant::getNullValue(PtrJBList),
137 "llvm.sjljeh.jblist");
138 }
139
140 // VisualStudio defines setjmp as _setjmp
141 #if defined(_MSC_VER) && defined(setjmp) && \
142 !defined(setjmp_undefined_for_msvc)
143 # pragma push_macro("setjmp")
144 # undef setjmp
145 # define setjmp_undefined_for_msvc
146 #endif
147
148 SetJmpFn = Intrinsic::getDeclaration(&M, Intrinsic::setjmp);
149
150 #if defined(_MSC_VER) && defined(setjmp_undefined_for_msvc)
151 // let's return it to _setjmp state
152 # pragma pop_macro("setjmp")
153 # undef setjmp_undefined_for_msvc
154 #endif
155
156 LongJmpFn = Intrinsic::getDeclaration(&M, Intrinsic::longjmp);
157 StackSaveFn = Intrinsic::getDeclaration(&M, Intrinsic::stacksave);
158 StackRestoreFn = Intrinsic::getDeclaration(&M, Intrinsic::stackrestore);
159 }
160
161 // We need the 'write' and 'abort' functions for both models.
162 AbortFn = M.getOrInsertFunction("abort", Type::getVoidTy(M.getContext()),
163 (Type *)0);
164 return true;
165 }
166
167 bool LowerInvoke::insertCheapEHSupport(Function &F) {
52 bool LowerInvoke::runOnFunction(Function &F) {
16853 bool Changed = false;
16954 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
17055 if (InvokeInst *II = dyn_cast(BB->getTerminator())) {
19176 }
19277 return Changed;
19378 }
194
195 /// rewriteExpensiveInvoke - Insert code and hack the function to replace the
196 /// specified invoke instruction with a call.
197 void LowerInvoke::rewriteExpensiveInvoke(InvokeInst *II, unsigned InvokeNo,
198 AllocaInst *InvokeNum,
199 AllocaInst *StackPtr,
200 SwitchInst *CatchSwitch) {
201 ConstantInt *InvokeNoC = ConstantInt::get(Type::getInt32Ty(II->getContext()),
202 InvokeNo);
203
204 // If the unwind edge has phi nodes, split the edge.
205 if (isa(II->getUnwindDest()->begin())) {
206 SplitCriticalEdge(II, 1, this);
207
208 // If there are any phi nodes left, they must have a single predecessor.
209 while (PHINode *PN = dyn_cast(II->getUnwindDest()->begin())) {
210 PN->replaceAllUsesWith(PN->getIncomingValue(0));
211 PN->eraseFromParent();
212 }
213 }
214
215 // Insert a store of the invoke num before the invoke and store zero into the
216 // location afterward.
217 new StoreInst(InvokeNoC, InvokeNum, true, II); // volatile
218
219 // Insert a store of the stack ptr before the invoke, so we can restore it
220 // later in the exception case.
221 CallInst* StackSaveRet = CallInst::Create(StackSaveFn, "ssret", II);
222 new StoreInst(StackSaveRet, StackPtr, true, II); // volatile
223
224 BasicBlock::iterator NI = II->getNormalDest()->getFirstInsertionPt();
225 // nonvolatile.
226 new StoreInst(Constant::getNullValue(Type::getInt32Ty(II->getContext())),
227 InvokeNum, false, NI);
228
229 Instruction* StackPtrLoad =
230 new LoadInst(StackPtr, "stackptr.restore", true,
231 II->getUnwindDest()->getFirstInsertionPt());
232 CallInst::Create(StackRestoreFn, StackPtrLoad, "")->insertAfter(StackPtrLoad);
233
234 // Add a switch case to our unwind block.
235 CatchSwitch->addCase(InvokeNoC, II->getUnwindDest());
236
237 // Insert a normal call instruction.
238 SmallVector CallArgs(II->op_begin(), II->op_end() - 3);
239 CallInst *NewCall = CallInst::Create(II->getCalledValue(),
240 CallArgs, "", II);
241 NewCall->takeName(II);
242 NewCall->setCallingConv(II->getCallingConv());
243 NewCall->setAttributes(II->getAttributes());
244 NewCall->setDebugLoc(II->getDebugLoc());
245 II->replaceAllUsesWith(NewCall);
246
247 // Replace the invoke with an uncond branch.
248 BranchInst::Create(II->getNormalDest(), NewCall->getParent());
249 II->eraseFromParent();
250 }
251
252 /// MarkBlocksLiveIn - Insert BB and all of its predescessors into LiveBBs until
253 /// we reach blocks we've already seen.
254 static void MarkBlocksLiveIn(BasicBlock *BB, std::set &LiveBBs) {
255 if (!LiveBBs.insert(BB).second) return; // already been here.
256
257 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
258 MarkBlocksLiveIn(*PI, LiveBBs);
259 }
260
261 // First thing we need to do is scan the whole function for values that are
262 // live across unwind edges. Each value that is live across an unwind edge
263 // we spill into a stack location, guaranteeing that there is nothing live
264 // across the unwind edge. This process also splits all critical edges
265 // coming out of invoke's.
266 void LowerInvoke::
267 splitLiveRangesLiveAcrossInvokes(SmallVectorImpl &Invokes) {
268 // First step, split all critical edges from invoke instructions.
269 for (unsigned i = 0, e = Invokes.size(); i != e; ++i) {
270 InvokeInst *II = Invokes[i];
271 SplitCriticalEdge(II, 0, this);
272 SplitCriticalEdge(II, 1, this);
273 assert(!isa(II->getNormalDest()) &&
274 !isa(II->getUnwindDest()) &&
275 "critical edge splitting left single entry phi nodes?");
276 }
277
278 Function *F = Invokes.back()->getParent()->getParent();
279
280 // To avoid having to handle incoming arguments specially, we lower each arg
281 // to a copy instruction in the entry block. This ensures that the argument
282 // value itself cannot be live across the entry block.
283 BasicBlock::iterator AfterAllocaInsertPt = F->begin()->begin();
284 while (isa(AfterAllocaInsertPt) &&
285 isa(cast(AfterAllocaInsertPt)->getArraySize()))
286 ++AfterAllocaInsertPt;
287 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
288 AI != E; ++AI) {
289 Type *Ty = AI->getType();
290 // Aggregate types can't be cast, but are legal argument types, so we have
291 // to handle them differently. We use an extract/insert pair as a
292 // lightweight method to achieve the same goal.
293 if (isa(Ty) || isa(Ty) || isa(Ty)) {
294 Instruction *EI = ExtractValueInst::Create(AI, 0, "",AfterAllocaInsertPt);
295 Instruction *NI = InsertValueInst::Create(AI, EI, 0);
296 NI->insertAfter(EI);
297 AI->replaceAllUsesWith(NI);
298 // Set the operand of the instructions back to the AllocaInst.
299 EI->setOperand(0, AI);
300 NI->setOperand(0, AI);
301 } else {
302 // This is always a no-op cast because we're casting AI to AI->getType()
303 // so src and destination types are identical. BitCast is the only
304 // possibility.
305 CastInst *NC = new BitCastInst(
306 AI, AI->getType(), AI->getName()+".tmp", AfterAllocaInsertPt);
307 AI->replaceAllUsesWith(NC);
308 // Set the operand of the cast instruction back to the AllocaInst.
309 // Normally it's forbidden to replace a CastInst's operand because it
310 // could cause the opcode to reflect an illegal conversion. However,
311 // we're replacing it here with the same value it was constructed with.
312 // We do this because the above replaceAllUsesWith() clobbered the
313 // operand, but we want this one to remain.
314 NC->setOperand(0, AI);
315 }
316 }
317
318 // Finally, scan the code looking for instructions with bad live ranges.
319 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
320 for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E; ++II) {
321 // Ignore obvious cases we don't have to handle. In particular, most
322 // instructions either have no uses or only have a single use inside the
323 // current block. Ignore them quickly.
324 Instruction *Inst = II;
325 if (Inst->use_empty()) continue;
326 if (Inst->hasOneUse() &&
327 cast(Inst->user_back())->getParent() == BB &&
328 !isa(Inst->user_back())) continue;
329
330 // If this is an alloca in the entry block, it's not a real register
331 // value.
332 if (AllocaInst *AI = dyn_cast(Inst))
333 if (isa(AI->getArraySize()) && BB == F->begin())
334 continue;
335
336 // Avoid iterator invalidation by copying users to a temporary vector.
337 SmallVector Users;
338 for (User *U : Inst->users()) {
339 Instruction *UI = cast(U);
340 if (UI->getParent() != BB || isa(UI))
341 Users.push_back(UI);
342 }
343
344 // Scan all of the uses and see if the live range is live across an unwind
345 // edge. If we find a use live across an invoke edge, create an alloca
346 // and spill the value.
347
348 // Find all of the blocks that this value is live in.
349 std::set LiveBBs;
350 LiveBBs.insert(Inst->getParent());
351 while (!Users.empty()) {
352 Instruction *U = Users.back();
353 Users.pop_back();
354
355 if (!isa(U)) {
356 MarkBlocksLiveIn(U->getParent(), LiveBBs);
357 } else {
358 // Uses for a PHI node occur in their predecessor block.
359 PHINode *PN = cast(U);
360 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
361 if (PN->getIncomingValue(i) == Inst)
362 MarkBlocksLiveIn(PN->getIncomingBlock(i), LiveBBs);
363 }
364 }
365
366 // Now that we know all of the blocks that this thing is live in, see if
367 // it includes any of the unwind locations.
368 bool NeedsSpill = false;
369 for (unsigned i = 0, e = Invokes.size(); i != e; ++i) {
370 BasicBlock *UnwindBlock = Invokes[i]->getUnwindDest();
371 if (UnwindBlock != BB && LiveBBs.count(UnwindBlock)) {
372 NeedsSpill = true;
373 }
374 }
375
376 // If we decided we need a spill, do it.
377 if (NeedsSpill) {
378 ++NumSpilled;
379 DemoteRegToStack(*Inst, true);
380 }
381 }
382 }
383
384 bool LowerInvoke::insertExpensiveEHSupport(Function &F) {
385 SmallVector Returns;
386 SmallVector Invokes;
387 UnreachableInst* UnreachablePlaceholder = 0;
388
389 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
390 if (ReturnInst *RI = dyn_cast(BB->getTerminator())) {
391 // Remember all return instructions in case we insert an invoke into this
392 // function.
393 Returns.push_back(RI);
394 } else if (InvokeInst *II = dyn_cast(BB->getTerminator())) {
395 Invokes.push_back(II);
396 }
397
398 if (Invokes.empty()) return false;
399
400 NumInvokes += Invokes.size();
401
402 // TODO: This is not an optimal way to do this. In particular, this always
403 // inserts setjmp calls into the entries of functions with invoke instructions
404 // even though there are possibly paths through the function that do not
405 // execute any invokes. In particular, for functions with early exits, e.g.
406 // the 'addMove' method in hexxagon, it would be nice to not have to do the
407 // setjmp stuff on the early exit path. This requires a bit of dataflow, but
408 // would not be too hard to do.
409
410 // If we have an invoke instruction, insert a setjmp that dominates all
411 // invokes. After the setjmp, use a cond branch that goes to the original
412 // code path on zero, and to a designated 'catch' block of nonzero.
413 Value *OldJmpBufPtr = 0;
414 if (!Invokes.empty()) {
415 // First thing we need to do is scan the whole function for values that are
416 // live across unwind edges. Each value that is live across an unwind edge
417 // we spill into a stack location, guaranteeing that there is nothing live
418 // across the unwind edge. This process also splits all critical edges
419 // coming out of invoke's.
420 splitLiveRangesLiveAcrossInvokes(Invokes);
421
422 BasicBlock *EntryBB = F.begin();
423
424 // Create an alloca for the incoming jump buffer ptr and the new jump buffer
425 // that needs to be restored on all exits from the function. This is an
426 // alloca because the value needs to be live across invokes.
427 const TargetLowering *TLI = TM ? TM->getTargetLowering() : 0;
428 unsigned Align = TLI ? TLI->getJumpBufAlignment() : 0;
429 AllocaInst *JmpBuf =
430 new AllocaInst(JBLinkTy, 0, Align,
431 "jblink", F.begin()->begin());
432
433 Value *Idx[] = { Constant::getNullValue(Type::getInt32Ty(F.getContext())),
434 ConstantInt::get(Type::getInt32Ty(F.getContext()), 1) };
435 OldJmpBufPtr = GetElementPtrInst::Create(JmpBuf, Idx, "OldBuf",
436 EntryBB->getTerminator());
437
438 // Copy the JBListHead to the alloca.
439 Value *OldBuf = new LoadInst(JBListHead, "oldjmpbufptr", true,
440 EntryBB->getTerminator());
441 new StoreInst(OldBuf, OldJmpBufPtr, true, EntryBB->getTerminator());
442
443 // Add the new jumpbuf to the list.
444 new StoreInst(JmpBuf, JBListHead, true, EntryBB->getTerminator());
445
446 // Create the catch block. The catch block is basically a big switch
447 // statement that goes to all of the invoke catch blocks.
448 BasicBlock *CatchBB =
449 BasicBlock::Create(F.getContext(), "setjmp.catch", &F);
450
451 // Create an alloca which keeps track of the stack pointer before every
452 // invoke, this allows us to properly restore the stack pointer after
453 // long jumping.
454 AllocaInst *StackPtr = new AllocaInst(Type::getInt8PtrTy(F.getContext()), 0,
455 "stackptr", EntryBB->begin());
456
457 // Create an alloca which keeps track of which invoke is currently
458 // executing. For normal calls it contains zero.
459 AllocaInst *InvokeNum = new AllocaInst(Type::getInt32Ty(F.getContext()), 0,
460 "invokenum",EntryBB->begin());
461 new StoreInst(ConstantInt::get(Type::getInt32Ty(F.getContext()), 0),
462 InvokeNum, true, EntryBB->getTerminator());
463
464 // Insert a load in the Catch block, and a switch on its value. By default,
465 // we go to a block that just does an unwind (which is the correct action
466 // for a standard call). We insert an unreachable instruction here and
467 // modify the block to jump to the correct unwinding pad later.
468 BasicBlock *UnwindBB = BasicBlock::Create(F.getContext(), "unwindbb", &F);
469 UnreachablePlaceholder = new UnreachableInst(F.getContext(), UnwindBB);
470
471 Value *CatchLoad = new LoadInst(InvokeNum, "invoke.num", true, CatchBB);
472 SwitchInst *CatchSwitch =
473 SwitchInst::Create(CatchLoad, UnwindBB, Invokes.size(), CatchBB);
474
475 // Now that things are set up, insert the setjmp call itself.
476
477 // Split the entry block to insert the conditional branch for the setjmp.
478 BasicBlock *ContBlock = EntryBB->splitBasicBlock(EntryBB->getTerminator(),
479 "setjmp.cont");
480
481 Idx[1] = ConstantInt::get(Type::getInt32Ty(F.getContext()), 0);
482 Value *JmpBufPtr = GetElementPtrInst::Create(JmpBuf, Idx, "TheJmpBuf",
483 EntryBB->getTerminator());
484 JmpBufPtr = new BitCastInst(JmpBufPtr,
485 Type::getInt8PtrTy(F.getContext()),
486 "tmp", EntryBB->getTerminator());
487 Value *SJRet = CallInst::Create(SetJmpFn, JmpBufPtr, "sjret",
488 EntryBB->getTerminator());
489
490 // Compare the return value to zero.
491 Value *IsNormal = new ICmpInst(EntryBB->getTerminator(),
492 ICmpInst::ICMP_EQ, SJRet,
493 Constant::getNullValue(SJRet->getType()),
494 "notunwind");
495 // Nuke the uncond branch.
496 EntryBB->getTerminator()->eraseFromParent();
497
498 // Put in a new condbranch in its place.
499 BranchInst::Create(ContBlock, CatchBB, IsNormal, EntryBB);
500
501 // At this point, we are all set up, rewrite each invoke instruction.
502 for (unsigned i = 0, e = Invokes.size(); i != e; ++i)
503 rewriteExpensiveInvoke(Invokes[i], i+1, InvokeNum, StackPtr, CatchSwitch);
504 }
505
506 // We know that there is at least one unwind.
507
508 // Create three new blocks, the block to load the jmpbuf ptr and compare
509 // against null, the block to do the longjmp, and the error block for if it
510 // is null. Add them at the end of the function because they are not hot.
511 BasicBlock *UnwindHandler = BasicBlock::Create(F.getContext(),
512 "dounwind", &F);
513 BasicBlock *UnwindBlock = BasicBlock::Create(F.getContext(), "unwind", &F);
514 BasicBlock *TermBlock = BasicBlock::Create(F.getContext(), "unwinderror", &F);
515
516 // If this function contains an invoke, restore the old jumpbuf ptr.
517 Value *BufPtr;
518 if (OldJmpBufPtr) {
519 // Before the return, insert a copy from the saved value to the new value.
520 BufPtr = new LoadInst(OldJmpBufPtr, "oldjmpbufptr", UnwindHandler);
521 new StoreInst(BufPtr, JBListHead, UnwindHandler);
522 } else {
523 BufPtr = new LoadInst(JBListHead, "ehlist", UnwindHandler);
524 }
525
526 // Load the JBList, if it's null, then there was no catch!
527 Value *NotNull = new ICmpInst(*UnwindHandler, ICmpInst::ICMP_NE, BufPtr,
528 Constant::getNullValue(BufPtr->getType()),
529 "notnull");
530 BranchInst::Create(UnwindBlock, TermBlock, NotNull, UnwindHandler);
531
532 // Create the block to do the longjmp.
533 // Get a pointer to the jmpbuf and longjmp.
534 Value *Idx[] = { Constant::getNullValue(Type::getInt32Ty(F.getContext())),
535 ConstantInt::get(Type::getInt32Ty(F.getContext()), 0) };
536 Idx[0] = GetElementPtrInst::Create(BufPtr, Idx, "JmpBuf", UnwindBlock);
537 Idx[0] = new BitCastInst(Idx[0],
538 Type::getInt8PtrTy(F.getContext()),
539 "tmp", UnwindBlock);
540 Idx[1] = ConstantInt::get(Type::getInt32Ty(F.getContext()), 1);
541 CallInst::Create(LongJmpFn, Idx, "", UnwindBlock);
542 new UnreachableInst(F.getContext(), UnwindBlock);
543
544 // Set up the term block ("throw without a catch").
545 new UnreachableInst(F.getContext(), TermBlock);
546
547 // Insert a call to abort()
548 CallInst::Create(AbortFn, "",
549 TermBlock->getTerminator())->setTailCall();
550
551 // Replace the inserted unreachable with a branch to the unwind handler.
552 if (UnreachablePlaceholder) {
553 BranchInst::Create(UnwindHandler, UnreachablePlaceholder);
554 UnreachablePlaceholder->eraseFromParent();
555 }
556
557 // Finally, for any returns from this function, if this function contains an
558 // invoke, restore the old jmpbuf pointer to its input value.
559 if (OldJmpBufPtr) {
560 for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
561 ReturnInst *R = Returns[i];
562
563 // Before the return, insert a copy from the saved value to the new value.
564 Value *OldBuf = new LoadInst(OldJmpBufPtr, "oldjmpbufptr", true, R);
565 new StoreInst(OldBuf, JBListHead, true, R);
566 }
567 }
568
569 return true;
570 }
571
572 bool LowerInvoke::runOnFunction(Function &F) {
573 if (useExpensiveEHSupport)
574 return insertExpensiveEHSupport(F);
575 else
576 return insertCheapEHSupport(F);
577 }
+0
-15
test/Transforms/LowerInvoke/2004-02-29-PHICrash.ll less more
None ; RUN: opt < %s -lowerinvoke -enable-correct-eh-support -disable-output
1
2 define void @_ZNKSt11__use_cacheISt16__numpunct_cacheIcEEclERKSt6locale() {
3 entry:
4 br i1 false, label %then, label %UnifiedReturnBlock
5 then: ; preds = %entry
6 invoke void @_Znwj( )
7 to label %UnifiedReturnBlock unwind label %UnifiedReturnBlock
8 UnifiedReturnBlock: ; preds = %then, %then, %entry
9 %UnifiedRetVal = phi i32* [ null, %entry ], [ null, %then ], [ null, %then ] ; [#uses=0]
10 ret void
11 }
12
13 declare void @_Znwj()
14
+0
-17
test/Transforms/LowerInvoke/2005-08-03-InvokeWithPHI.ll less more
None ; RUN: opt < %s -lowerinvoke -enable-correct-eh-support -disable-output
1
2 declare void @ll_listnext__listiterPtr()
3
4 define void @WorkTask.fn() {
5 block0:
6 invoke void @ll_listnext__listiterPtr( )
7 to label %block9 unwind label %block8_exception_handling
8 block8_exception_handling: ; preds = %block0
9 ret void
10 block9: ; preds = %block0
11 %w_2690 = phi { i32, i32 }* [ null, %block0 ] ; <{ i32, i32 }*> [#uses=1]
12 %tmp.129 = getelementptr { i32, i32 }* %w_2690, i32 0, i32 1 ; [#uses=1]
13 %v2769 = load i32* %tmp.129 ; [#uses=0]
14 ret void
15 }
16
+0
-15
test/Transforms/LowerInvoke/2005-08-03-InvokeWithPHIUse.ll less more
None ; RUN: opt < %s -lowerinvoke -enable-correct-eh-support -disable-output
1
2 declare fastcc i32 @ll_listnext__listiterPtr()
3
4 define fastcc i32 @WorkTask.fn() {
5 block0:
6 %v2679 = invoke fastcc i32 @ll_listnext__listiterPtr( )
7 to label %block9 unwind label %block8_exception_handling ; [#uses=1]
8 block8_exception_handling: ; preds = %block0
9 ret i32 0
10 block9: ; preds = %block0
11 %i_2689 = phi i32 [ %v2679, %block0 ] ; [#uses=1]
12 ret i32 %i_2689
13 }
14
+0
-14
test/Transforms/LowerInvoke/2008-02-14-CritEdgePhiCrash.ll less more
None ; RUN: opt < %s -lowerinvoke -enable-correct-eh-support -disable-output
1 ; PR2029
2 define i32 @main(i32 %argc, i8** %argv) {
3 bb470:
4 invoke i32 @main(i32 0, i8** null) to label %invcont474 unwind label
5 %lpad902
6
7 invcont474: ; preds = %bb470
8 ret i32 0
9
10 lpad902: ; preds = %bb470
11 %tmp471.lcssa = phi i8* [ null, %bb470 ] ;
12 ret i32 0
13 }
+0
-30
test/Transforms/LowerInvoke/basictest.ll less more
None ; RUN: opt < %s -lowerinvoke -disable-output -enable-correct-eh-support
1
2
3 define i32 @foo() {
4 invoke i32 @foo( )
5 to label %Ok unwind label %Crap ; :1 [#uses=0]
6 Ok: ; preds = %0
7 invoke i32 @foo( )
8 to label %Ok2 unwind label %Crap ; :2 [#uses=0]
9 Ok2: ; preds = %Ok
10 ret i32 2
11 Crap: ; preds = %Ok, %0
12 ret i32 1
13 }
14
15 define i32 @bar(i32 %blah) {
16 br label %doit
17 doit: ; preds = %0
18 ;; Value live across an unwind edge.
19 %B2 = add i32 %blah, 1 ; [#uses=1]
20 invoke i32 @foo( )
21 to label %Ok unwind label %Crap ; :1 [#uses=0]
22 Ok: ; preds = %doit
23 invoke i32 @foo( )
24 to label %Ok2 unwind label %Crap ; :2 [#uses=0]
25 Ok2: ; preds = %Ok
26 ret i32 2
27 Crap: ; preds = %Ok, %doit
28 ret i32 %B2
29 }