Have the SjLjEHPrepare pass do some more heavy lifting.
[oota-llvm.git] / lib / CodeGen / SjLjEHPrepare.cpp
1 //===- SjLjEHPass.cpp - Eliminate Invoke & Unwind instructions -----------===//
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 transformation is designed for use by code generators which use SjLj
11 // based exception handling.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "sjljehprepare"
16 #include "llvm/Transforms/Scalar.h"
17 #include "llvm/Constants.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/Instructions.h"
20 #include "llvm/Intrinsics.h"
21 #include "llvm/LLVMContext.h"
22 #include "llvm/Module.h"
23 #include "llvm/Pass.h"
24 #include "llvm/CodeGen/Passes.h"
25 #include "llvm/Target/TargetData.h"
26 #include "llvm/Target/TargetLowering.h"
27 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
28 #include "llvm/Transforms/Utils/Local.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/IRBuilder.h"
32 #include "llvm/ADT/DenseMap.h"
33 #include "llvm/ADT/SmallVector.h"
34 #include "llvm/ADT/Statistic.h"
35 #include <set>
36 using namespace llvm;
37
38 static cl::opt<bool> DisableOldSjLjEH("disable-old-sjlj-eh", cl::Hidden,
39     cl::desc("Disable the old SjLj EH preparation pass"));
40
41 STATISTIC(NumInvokes, "Number of invokes replaced");
42 STATISTIC(NumUnwinds, "Number of unwinds replaced");
43 STATISTIC(NumSpilled, "Number of registers live across unwind edges");
44
45 namespace {
46   class SjLjEHPass : public FunctionPass {
47     const TargetLowering *TLI;
48     Type *FunctionContextTy;
49     Constant *RegisterFn;
50     Constant *UnregisterFn;
51     Constant *BuiltinSetjmpFn;
52     Constant *FrameAddrFn;
53     Constant *StackAddrFn;
54     Constant *StackRestoreFn;
55     Constant *LSDAAddrFn;
56     Value *PersonalityFn;
57     Constant *SelectorFn;
58     Constant *ExceptionFn;
59     Constant *CallSiteFn;
60     Constant *DispatchSetupFn;
61     Constant *FuncCtxFn;
62     Value *CallSite;
63     DenseMap<InvokeInst*, BasicBlock*> LPadSuccMap;
64   public:
65     static char ID; // Pass identification, replacement for typeid
66     explicit SjLjEHPass(const TargetLowering *tli = NULL)
67       : FunctionPass(ID), TLI(tli) { }
68     bool doInitialization(Module &M);
69     bool runOnFunction(Function &F);
70
71     virtual void getAnalysisUsage(AnalysisUsage &AU) const {}
72     const char *getPassName() const {
73       return "SJLJ Exception Handling preparation";
74     }
75
76   private:
77     bool setupEntryBlockAndCallSites(Function &F);
78     std::pair<Value*, Value*>
79     setupFunctionContext(Function &F, ArrayRef<LandingPadInst*> LPads);
80
81     void insertCallSiteStore(Instruction *I, int Number, Value *CallSite);
82     void markInvokeCallSite(InvokeInst *II, int InvokeNo, Value *CallSite,
83                             SwitchInst *CatchSwitch);
84     void splitLiveRangesAcrossInvokes(SmallVector<InvokeInst*,16> &Invokes);
85     void splitLandingPad(InvokeInst *II);
86     bool insertSjLjEHSupport(Function &F);
87   };
88 } // end anonymous namespace
89
90 char SjLjEHPass::ID = 0;
91
92 // Public Interface To the SjLjEHPass pass.
93 FunctionPass *llvm::createSjLjEHPass(const TargetLowering *TLI) {
94   return new SjLjEHPass(TLI);
95 }
96 // doInitialization - Set up decalarations and types needed to process
97 // exceptions.
98 bool SjLjEHPass::doInitialization(Module &M) {
99   // Build the function context structure.
100   // builtin_setjmp uses a five word jbuf
101   Type *VoidPtrTy = Type::getInt8PtrTy(M.getContext());
102   Type *Int32Ty = Type::getInt32Ty(M.getContext());
103   FunctionContextTy =
104     StructType::get(VoidPtrTy,                        // __prev
105                     Int32Ty,                          // call_site
106                     ArrayType::get(Int32Ty, 4),       // __data
107                     VoidPtrTy,                        // __personality
108                     VoidPtrTy,                        // __lsda
109                     ArrayType::get(VoidPtrTy, 5),     // __jbuf
110                     NULL);
111   RegisterFn = M.getOrInsertFunction("_Unwind_SjLj_Register",
112                                      Type::getVoidTy(M.getContext()),
113                                      PointerType::getUnqual(FunctionContextTy),
114                                      (Type *)0);
115   UnregisterFn =
116     M.getOrInsertFunction("_Unwind_SjLj_Unregister",
117                           Type::getVoidTy(M.getContext()),
118                           PointerType::getUnqual(FunctionContextTy),
119                           (Type *)0);
120   FrameAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::frameaddress);
121   StackAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::stacksave);
122   StackRestoreFn = Intrinsic::getDeclaration(&M, Intrinsic::stackrestore);
123   BuiltinSetjmpFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_setjmp);
124   LSDAAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_lsda);
125   SelectorFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_selector);
126   ExceptionFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_exception);
127   CallSiteFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_callsite);
128   DispatchSetupFn
129     = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_dispatch_setup);
130   FuncCtxFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_functioncontext);
131   PersonalityFn = 0;
132
133   return true;
134 }
135
136 /// insertCallSiteStore - Insert a store of the call-site value to the
137 /// function context
138 void SjLjEHPass::insertCallSiteStore(Instruction *I, int Number,
139                                      Value *CallSite) {
140   ConstantInt *CallSiteNoC = ConstantInt::get(Type::getInt32Ty(I->getContext()),
141                                               Number);
142   // Insert a store of the call-site number
143   new StoreInst(CallSiteNoC, CallSite, true, I);  // volatile
144 }
145
146 /// splitLandingPad - Split a landing pad. This takes considerable care because
147 /// of PHIs and other nasties. The problem is that the jump table needs to jump
148 /// to the landing pad block. However, the landing pad block can be jumped to
149 /// only by an invoke instruction. So we clone the landingpad instruction into
150 /// its own basic block, have the invoke jump to there. The landingpad
151 /// instruction's basic block's successor is now the target for the jump table.
152 ///
153 /// But because of PHI nodes, we need to create another basic block for the jump
154 /// table to jump to. This is definitely a hack, because the values for the PHI
155 /// nodes may not be defined on the edge from the jump table. But that's okay,
156 /// because the jump table is simply a construct to mimic what is happening in
157 /// the CFG. So the values are mysteriously there, even though there is no value
158 /// for the PHI from the jump table's edge (hence calling this a hack).
159 void SjLjEHPass::splitLandingPad(InvokeInst *II) {
160   SmallVector<BasicBlock*, 2> NewBBs;
161   SplitLandingPadPredecessors(II->getUnwindDest(), II->getParent(),
162                               ".1", ".2", this, NewBBs);
163
164   // Create an empty block so that the jump table has something to jump to
165   // which doesn't have any PHI nodes.
166   BasicBlock *LPad = NewBBs[0];
167   BasicBlock *Succ = *succ_begin(LPad);
168   BasicBlock *JumpTo = BasicBlock::Create(II->getContext(), "jt.land",
169                                           LPad->getParent(), Succ);
170   LPad->getTerminator()->eraseFromParent();
171   BranchInst::Create(JumpTo, LPad);
172   BranchInst::Create(Succ, JumpTo);
173   LPadSuccMap[II] = JumpTo;
174
175   for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
176     PHINode *PN = cast<PHINode>(I);
177     Value *Val = PN->removeIncomingValue(LPad, false);
178     PN->addIncoming(Val, JumpTo);
179   }
180 }
181
182 /// markInvokeCallSite - Insert code to mark the call_site for this invoke
183 void SjLjEHPass::markInvokeCallSite(InvokeInst *II, int InvokeNo,
184                                     Value *CallSite,
185                                     SwitchInst *CatchSwitch) {
186   ConstantInt *CallSiteNoC= ConstantInt::get(Type::getInt32Ty(II->getContext()),
187                                               InvokeNo);
188   // The runtime comes back to the dispatcher with the call_site - 1 in
189   // the context. Odd, but there it is.
190   ConstantInt *SwitchValC = ConstantInt::get(Type::getInt32Ty(II->getContext()),
191                                              InvokeNo - 1);
192
193   // If the unwind edge has phi nodes, split the edge.
194   if (isa<PHINode>(II->getUnwindDest()->begin())) {
195     // FIXME: New EH - This if-condition will be always true in the new scheme.
196     if (II->getUnwindDest()->isLandingPad())
197       splitLandingPad(II);
198     else
199       SplitCriticalEdge(II, 1, this);
200
201     // If there are any phi nodes left, they must have a single predecessor.
202     while (PHINode *PN = dyn_cast<PHINode>(II->getUnwindDest()->begin())) {
203       PN->replaceAllUsesWith(PN->getIncomingValue(0));
204       PN->eraseFromParent();
205     }
206   }
207
208   // Insert the store of the call site value
209   insertCallSiteStore(II, InvokeNo, CallSite);
210
211   // Record the call site value for the back end so it stays associated with
212   // the invoke.
213   CallInst::Create(CallSiteFn, CallSiteNoC, "", II);
214
215   // Add a switch case to our unwind block.
216   if (BasicBlock *SuccBB = LPadSuccMap[II]) {
217     CatchSwitch->addCase(SwitchValC, SuccBB);
218   } else {
219     CatchSwitch->addCase(SwitchValC, II->getUnwindDest());
220   }
221
222   // We still want this to look like an invoke so we emit the LSDA properly,
223   // so we don't transform the invoke into a call here.
224 }
225
226 /// MarkBlocksLiveIn - Insert BB and all of its predescessors into LiveBBs until
227 /// we reach blocks we've already seen.
228 static void MarkBlocksLiveIn(BasicBlock *BB, std::set<BasicBlock*> &LiveBBs) {
229   if (!LiveBBs.insert(BB).second) return; // already been here.
230
231   for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
232     MarkBlocksLiveIn(*PI, LiveBBs);
233 }
234
235 /// splitLiveRangesAcrossInvokes - Each value that is live across an unwind edge
236 /// we spill into a stack location, guaranteeing that there is nothing live
237 /// across the unwind edge.  This process also splits all critical edges
238 /// coming out of invoke's.
239 /// FIXME: Move this function to a common utility file (Local.cpp?) so
240 /// both SjLj and LowerInvoke can use it.
241 void SjLjEHPass::
242 splitLiveRangesAcrossInvokes(SmallVector<InvokeInst*,16> &Invokes) {
243   // First step, split all critical edges from invoke instructions.
244   for (unsigned i = 0, e = Invokes.size(); i != e; ++i) {
245     InvokeInst *II = Invokes[i];
246     SplitCriticalEdge(II, 0, this);
247
248     // FIXME: New EH - This if-condition will be always true in the new scheme.
249     if (II->getUnwindDest()->isLandingPad())
250       splitLandingPad(II);
251     else
252       SplitCriticalEdge(II, 1, this);
253
254     assert(!isa<PHINode>(II->getNormalDest()) &&
255            !isa<PHINode>(II->getUnwindDest()) &&
256            "Critical edge splitting left single entry phi nodes?");
257   }
258
259   Function *F = Invokes.back()->getParent()->getParent();
260
261   // To avoid having to handle incoming arguments specially, we lower each arg
262   // to a copy instruction in the entry block.  This ensures that the argument
263   // value itself cannot be live across the entry block.
264   BasicBlock::iterator AfterAllocaInsertPt = F->begin()->begin();
265   while (isa<AllocaInst>(AfterAllocaInsertPt) &&
266         isa<ConstantInt>(cast<AllocaInst>(AfterAllocaInsertPt)->getArraySize()))
267     ++AfterAllocaInsertPt;
268   for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
269        AI != E; ++AI) {
270     Type *Ty = AI->getType();
271     // Aggregate types can't be cast, but are legal argument types, so we have
272     // to handle them differently. We use an extract/insert pair as a
273     // lightweight method to achieve the same goal.
274     if (isa<StructType>(Ty) || isa<ArrayType>(Ty) || isa<VectorType>(Ty)) {
275       Instruction *EI = ExtractValueInst::Create(AI, 0, "",AfterAllocaInsertPt);
276       Instruction *NI = InsertValueInst::Create(AI, EI, 0);
277       NI->insertAfter(EI);
278       AI->replaceAllUsesWith(NI);
279       // Set the operand of the instructions back to the AllocaInst.
280       EI->setOperand(0, AI);
281       NI->setOperand(0, AI);
282     } else {
283       // This is always a no-op cast because we're casting AI to AI->getType()
284       // so src and destination types are identical. BitCast is the only
285       // possibility.
286       CastInst *NC = new BitCastInst(
287         AI, AI->getType(), AI->getName()+".tmp", AfterAllocaInsertPt);
288       AI->replaceAllUsesWith(NC);
289       // Set the operand of the cast instruction back to the AllocaInst.
290       // Normally it's forbidden to replace a CastInst's operand because it
291       // could cause the opcode to reflect an illegal conversion. However,
292       // we're replacing it here with the same value it was constructed with.
293       // We do this because the above replaceAllUsesWith() clobbered the
294       // operand, but we want this one to remain.
295       NC->setOperand(0, AI);
296     }
297   }
298
299   // Finally, scan the code looking for instructions with bad live ranges.
300   for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
301     for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E; ++II) {
302       // Ignore obvious cases we don't have to handle.  In particular, most
303       // instructions either have no uses or only have a single use inside the
304       // current block.  Ignore them quickly.
305       Instruction *Inst = II;
306       if (Inst->use_empty()) continue;
307       if (Inst->hasOneUse() &&
308           cast<Instruction>(Inst->use_back())->getParent() == BB &&
309           !isa<PHINode>(Inst->use_back())) continue;
310
311       // If this is an alloca in the entry block, it's not a real register
312       // value.
313       if (AllocaInst *AI = dyn_cast<AllocaInst>(Inst))
314         if (isa<ConstantInt>(AI->getArraySize()) && BB == F->begin())
315           continue;
316
317       // Avoid iterator invalidation by copying users to a temporary vector.
318       SmallVector<Instruction*,16> Users;
319       for (Value::use_iterator UI = Inst->use_begin(), E = Inst->use_end();
320            UI != E; ++UI) {
321         Instruction *User = cast<Instruction>(*UI);
322         if (User->getParent() != BB || isa<PHINode>(User))
323           Users.push_back(User);
324       }
325
326       // Find all of the blocks that this value is live in.
327       std::set<BasicBlock*> LiveBBs;
328       LiveBBs.insert(Inst->getParent());
329       while (!Users.empty()) {
330         Instruction *U = Users.back();
331         Users.pop_back();
332
333         if (!isa<PHINode>(U)) {
334           MarkBlocksLiveIn(U->getParent(), LiveBBs);
335         } else {
336           // Uses for a PHI node occur in their predecessor block.
337           PHINode *PN = cast<PHINode>(U);
338           for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
339             if (PN->getIncomingValue(i) == Inst)
340               MarkBlocksLiveIn(PN->getIncomingBlock(i), LiveBBs);
341         }
342       }
343
344       // Now that we know all of the blocks that this thing is live in, see if
345       // it includes any of the unwind locations.
346       bool NeedsSpill = false;
347       for (unsigned i = 0, e = Invokes.size(); i != e; ++i) {
348         BasicBlock *UnwindBlock = Invokes[i]->getUnwindDest();
349         if (UnwindBlock != BB && LiveBBs.count(UnwindBlock)) {
350           NeedsSpill = true;
351         }
352       }
353
354       // If we decided we need a spill, do it.
355       // FIXME: Spilling this way is overkill, as it forces all uses of
356       // the value to be reloaded from the stack slot, even those that aren't
357       // in the unwind blocks. We should be more selective.
358       if (NeedsSpill) {
359         ++NumSpilled;
360         DemoteRegToStack(*Inst, true);
361       }
362     }
363 }
364
365 /// CreateLandingPadLoad - Load the exception handling values and insert them
366 /// into a structure.
367 static Instruction *CreateLandingPadLoad(Function &F, Value *ExnAddr,
368                                          Value *SelAddr,
369                                          BasicBlock::iterator InsertPt) {
370   Value *Exn = new LoadInst(ExnAddr, "exn", false,
371                             InsertPt);
372   Type *Ty = Type::getInt8PtrTy(F.getContext());
373   Exn = CastInst::Create(Instruction::IntToPtr, Exn, Ty, "", InsertPt);
374   Value *Sel = new LoadInst(SelAddr, "sel", false, InsertPt);
375
376   Ty = StructType::get(Exn->getType(), Sel->getType(), NULL);
377   InsertValueInst *LPadVal = InsertValueInst::Create(llvm::UndefValue::get(Ty),
378                                                      Exn, 0,
379                                                      "lpad.val", InsertPt);
380   return InsertValueInst::Create(LPadVal, Sel, 1, "lpad.val", InsertPt);
381 }
382
383 /// ReplaceLandingPadVal - Replace the landingpad instruction's value with a
384 /// load from the stored values (via CreateLandingPadLoad). This looks through
385 /// PHI nodes, and removes them if they are dead.
386 static void ReplaceLandingPadVal(Function &F, Instruction *Inst, Value *ExnAddr,
387                                  Value *SelAddr) {
388   if (Inst->use_empty()) return;
389
390   while (!Inst->use_empty()) {
391     Instruction *I = cast<Instruction>(Inst->use_back());
392
393     if (PHINode *PN = dyn_cast<PHINode>(I)) {
394       ReplaceLandingPadVal(F, PN, ExnAddr, SelAddr);
395       if (PN->use_empty()) PN->eraseFromParent();
396       continue;
397     }
398
399     I->replaceUsesOfWith(Inst, CreateLandingPadLoad(F, ExnAddr, SelAddr, I));
400   }
401 }
402
403 bool SjLjEHPass::insertSjLjEHSupport(Function &F) {
404   SmallVector<ReturnInst*,16> Returns;
405   SmallVector<UnwindInst*,16> Unwinds;
406   SmallVector<InvokeInst*,16> Invokes;
407
408   // Look through the terminators of the basic blocks to find invokes, returns
409   // and unwinds.
410   for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
411     if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
412       // Remember all return instructions in case we insert an invoke into this
413       // function.
414       Returns.push_back(RI);
415     } else if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
416       Invokes.push_back(II);
417     } else if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->getTerminator())) {
418       Unwinds.push_back(UI);
419     }
420   }
421
422   NumInvokes += Invokes.size();
423   NumUnwinds += Unwinds.size();
424
425   // If we don't have any invokes, there's nothing to do.
426   if (Invokes.empty()) return false;
427
428   // Find the eh.selector.*, eh.exception and alloca calls.
429   //
430   // Remember any allocas() that aren't in the entry block, as the
431   // jmpbuf saved SP will need to be updated for them.
432   //
433   // We'll use the first eh.selector to determine the right personality
434   // function to use. For SJLJ, we always use the same personality for the
435   // whole function, not on a per-selector basis.
436   // FIXME: That's a bit ugly. Better way?
437   SmallVector<CallInst*,16> EH_Selectors;
438   SmallVector<CallInst*,16> EH_Exceptions;
439   SmallVector<Instruction*,16> JmpbufUpdatePoints;
440
441   for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
442     // Note: Skip the entry block since there's nothing there that interests
443     // us. eh.selector and eh.exception shouldn't ever be there, and we
444     // want to disregard any allocas that are there.
445     // 
446     // FIXME: This is awkward. The new EH scheme won't need to skip the entry
447     //        block.
448     if (BB == F.begin()) {
449       if (InvokeInst *II = dyn_cast<InvokeInst>(F.begin()->getTerminator())) {
450         // FIXME: This will be always non-NULL in the new EH.
451         if (LandingPadInst *LPI = II->getUnwindDest()->getLandingPadInst())
452           if (!PersonalityFn) PersonalityFn = LPI->getPersonalityFn();
453       }
454
455       continue;
456     }
457
458     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
459       if (CallInst *CI = dyn_cast<CallInst>(I)) {
460         if (CI->getCalledFunction() == SelectorFn) {
461           if (!PersonalityFn) PersonalityFn = CI->getArgOperand(1);
462           EH_Selectors.push_back(CI);
463         } else if (CI->getCalledFunction() == ExceptionFn) {
464           EH_Exceptions.push_back(CI);
465         } else if (CI->getCalledFunction() == StackRestoreFn) {
466           JmpbufUpdatePoints.push_back(CI);
467         }
468       } else if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) {
469         JmpbufUpdatePoints.push_back(AI);
470       } else if (InvokeInst *II = dyn_cast<InvokeInst>(I)) {
471         // FIXME: This will be always non-NULL in the new EH.
472         if (LandingPadInst *LPI = II->getUnwindDest()->getLandingPadInst())
473           if (!PersonalityFn) PersonalityFn = LPI->getPersonalityFn();
474       }
475     }
476   }
477
478   // If we don't have any eh.selector calls, we can't determine the personality
479   // function. Without a personality function, we can't process exceptions.
480   if (!PersonalityFn) return false;
481
482   // We have invokes, so we need to add register/unregister calls to get this
483   // function onto the global unwind stack.
484   //
485   // First thing we need to do is scan the whole function for values that are
486   // live across unwind edges.  Each value that is live across an unwind edge we
487   // spill into a stack location, guaranteeing that there is nothing live across
488   // the unwind edge.  This process also splits all critical edges coming out of
489   // invoke's.
490   splitLiveRangesAcrossInvokes(Invokes);
491
492
493   SmallVector<LandingPadInst*, 16> LandingPads;
494   for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
495     if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator()))
496       // FIXME: This will be always non-NULL in the new EH.
497       if (LandingPadInst *LPI = II->getUnwindDest()->getLandingPadInst())
498         LandingPads.push_back(LPI);
499   }
500
501
502   BasicBlock *EntryBB = F.begin();
503   // Create an alloca for the incoming jump buffer ptr and the new jump buffer
504   // that needs to be restored on all exits from the function.  This is an
505   // alloca because the value needs to be added to the global context list.
506   unsigned Align = 4; // FIXME: Should be a TLI check?
507   AllocaInst *FunctionContext =
508     new AllocaInst(FunctionContextTy, 0, Align,
509                    "fcn_context", F.begin()->begin());
510
511   Value *Idxs[2];
512   Type *Int32Ty = Type::getInt32Ty(F.getContext());
513   Value *Zero = ConstantInt::get(Int32Ty, 0);
514   // We need to also keep around a reference to the call_site field
515   Idxs[0] = Zero;
516   Idxs[1] = ConstantInt::get(Int32Ty, 1);
517   CallSite = GetElementPtrInst::Create(FunctionContext, Idxs, "call_site",
518                                        EntryBB->getTerminator());
519
520   // The exception selector comes back in context->data[1]
521   Idxs[1] = ConstantInt::get(Int32Ty, 2);
522   Value *FCData = GetElementPtrInst::Create(FunctionContext, Idxs, "fc_data",
523                                             EntryBB->getTerminator());
524   Idxs[1] = ConstantInt::get(Int32Ty, 1);
525   Value *SelectorAddr = GetElementPtrInst::Create(FCData, Idxs,
526                                                   "exc_selector_gep",
527                                                   EntryBB->getTerminator());
528   // The exception value comes back in context->data[0]
529   Idxs[1] = Zero;
530   Value *ExceptionAddr = GetElementPtrInst::Create(FCData, Idxs,
531                                                    "exception_gep",
532                                                    EntryBB->getTerminator());
533
534   // The result of the eh.selector call will be replaced with a a reference to
535   // the selector value returned in the function context. We leave the selector
536   // itself so the EH analysis later can use it.
537   for (int i = 0, e = EH_Selectors.size(); i < e; ++i) {
538     CallInst *I = EH_Selectors[i];
539     Value *SelectorVal = new LoadInst(SelectorAddr, "select_val", true, I);
540     I->replaceAllUsesWith(SelectorVal);
541   }
542
543   // eh.exception calls are replaced with references to the proper location in
544   // the context. Unlike eh.selector, the eh.exception calls are removed
545   // entirely.
546   for (int i = 0, e = EH_Exceptions.size(); i < e; ++i) {
547     CallInst *I = EH_Exceptions[i];
548     // Possible for there to be duplicates, so check to make sure the
549     // instruction hasn't already been removed.
550     if (!I->getParent()) continue;
551     Value *Val = new LoadInst(ExceptionAddr, "exception", true, I);
552     Type *Ty = Type::getInt8PtrTy(F.getContext());
553     Val = CastInst::Create(Instruction::IntToPtr, Val, Ty, "", I);
554
555     I->replaceAllUsesWith(Val);
556     I->eraseFromParent();
557   }
558
559   for (unsigned i = 0, e = LandingPads.size(); i != e; ++i)
560     ReplaceLandingPadVal(F, LandingPads[i], ExceptionAddr, SelectorAddr);
561
562   // The entry block changes to have the eh.sjlj.setjmp, with a conditional
563   // branch to a dispatch block for non-zero returns. If we return normally,
564   // we're not handling an exception and just register the function context and
565   // continue.
566
567   // Create the dispatch block.  The dispatch block is basically a big switch
568   // statement that goes to all of the invoke landing pads.
569   BasicBlock *DispatchBlock =
570     BasicBlock::Create(F.getContext(), "eh.sjlj.setjmp.catch", &F);
571
572   // Insert a load of the callsite in the dispatch block, and a switch on its
573   // value. By default, we issue a trap statement.
574   BasicBlock *TrapBlock =
575     BasicBlock::Create(F.getContext(), "trapbb", &F);
576   CallInst::Create(Intrinsic::getDeclaration(F.getParent(), Intrinsic::trap),
577                    "", TrapBlock);
578   new UnreachableInst(F.getContext(), TrapBlock);
579
580   Value *DispatchLoad = new LoadInst(CallSite, "invoke.num", true,
581                                      DispatchBlock);
582   SwitchInst *DispatchSwitch =
583     SwitchInst::Create(DispatchLoad, TrapBlock, Invokes.size(),
584                        DispatchBlock);
585   // Split the entry block to insert the conditional branch for the setjmp.
586   BasicBlock *ContBlock = EntryBB->splitBasicBlock(EntryBB->getTerminator(),
587                                                    "eh.sjlj.setjmp.cont");
588
589   // Populate the Function Context
590   //   1. LSDA address
591   //   2. Personality function address
592   //   3. jmpbuf (save SP, FP and call eh.sjlj.setjmp)
593
594   // LSDA address
595   Idxs[0] = Zero;
596   Idxs[1] = ConstantInt::get(Int32Ty, 4);
597   Value *LSDAFieldPtr =
598     GetElementPtrInst::Create(FunctionContext, Idxs, "lsda_gep",
599                               EntryBB->getTerminator());
600   Value *LSDA = CallInst::Create(LSDAAddrFn, "lsda_addr",
601                                  EntryBB->getTerminator());
602   new StoreInst(LSDA, LSDAFieldPtr, true, EntryBB->getTerminator());
603
604   Idxs[1] = ConstantInt::get(Int32Ty, 3);
605   Value *PersonalityFieldPtr =
606     GetElementPtrInst::Create(FunctionContext, Idxs, "lsda_gep",
607                               EntryBB->getTerminator());
608   new StoreInst(PersonalityFn, PersonalityFieldPtr, true,
609                 EntryBB->getTerminator());
610
611   // Save the frame pointer.
612   Idxs[1] = ConstantInt::get(Int32Ty, 5);
613   Value *JBufPtr
614     = GetElementPtrInst::Create(FunctionContext, Idxs, "jbuf_gep",
615                                 EntryBB->getTerminator());
616   Idxs[1] = ConstantInt::get(Int32Ty, 0);
617   Value *FramePtr =
618     GetElementPtrInst::Create(JBufPtr, Idxs, "jbuf_fp_gep",
619                               EntryBB->getTerminator());
620
621   Value *Val = CallInst::Create(FrameAddrFn,
622                                 ConstantInt::get(Int32Ty, 0),
623                                 "fp",
624                                 EntryBB->getTerminator());
625   new StoreInst(Val, FramePtr, true, EntryBB->getTerminator());
626
627   // Save the stack pointer.
628   Idxs[1] = ConstantInt::get(Int32Ty, 2);
629   Value *StackPtr =
630     GetElementPtrInst::Create(JBufPtr, Idxs, "jbuf_sp_gep",
631                               EntryBB->getTerminator());
632
633   Val = CallInst::Create(StackAddrFn, "sp", EntryBB->getTerminator());
634   new StoreInst(Val, StackPtr, true, EntryBB->getTerminator());
635
636   // Call the setjmp instrinsic. It fills in the rest of the jmpbuf.
637   Value *SetjmpArg =
638     CastInst::Create(Instruction::BitCast, JBufPtr,
639                      Type::getInt8PtrTy(F.getContext()), "",
640                      EntryBB->getTerminator());
641   Value *DispatchVal = CallInst::Create(BuiltinSetjmpFn, SetjmpArg,
642                                         "dispatch",
643                                         EntryBB->getTerminator());
644
645   // Add a call to dispatch_setup after the setjmp call. This is expanded to any
646   // target-specific setup that needs to be done.
647   CallInst::Create(DispatchSetupFn, DispatchVal, "", EntryBB->getTerminator());
648
649   // check the return value of the setjmp. non-zero goes to dispatcher.
650   Value *IsNormal = new ICmpInst(EntryBB->getTerminator(),
651                                  ICmpInst::ICMP_EQ, DispatchVal, Zero,
652                                  "notunwind");
653   // Nuke the uncond branch.
654   EntryBB->getTerminator()->eraseFromParent();
655
656   // Put in a new condbranch in its place.
657   BranchInst::Create(ContBlock, DispatchBlock, IsNormal, EntryBB);
658
659   // Register the function context and make sure it's known to not throw
660   CallInst *Register =
661     CallInst::Create(RegisterFn, FunctionContext, "",
662                      ContBlock->getTerminator());
663   Register->setDoesNotThrow();
664
665   // At this point, we are all set up, update the invoke instructions to mark
666   // their call_site values, and fill in the dispatch switch accordingly.
667   for (unsigned i = 0, e = Invokes.size(); i != e; ++i)
668     markInvokeCallSite(Invokes[i], i+1, CallSite, DispatchSwitch);
669
670   // Mark call instructions that aren't nounwind as no-action (call_site ==
671   // -1). Skip the entry block, as prior to then, no function context has been
672   // created for this function and any unexpected exceptions thrown will go
673   // directly to the caller's context, which is what we want anyway, so no need
674   // to do anything here.
675   for (Function::iterator BB = F.begin(), E = F.end(); ++BB != E;) {
676     for (BasicBlock::iterator I = BB->begin(), end = BB->end(); I != end; ++I)
677       if (CallInst *CI = dyn_cast<CallInst>(I)) {
678         // Ignore calls to the EH builtins (eh.selector, eh.exception)
679         Constant *Callee = CI->getCalledFunction();
680         if (Callee != SelectorFn && Callee != ExceptionFn
681             && !CI->doesNotThrow())
682           insertCallSiteStore(CI, -1, CallSite);
683       } else if (ResumeInst *RI = dyn_cast<ResumeInst>(I)) {
684         insertCallSiteStore(RI, -1, CallSite);
685       }
686   }
687
688   // Replace all unwinds with a branch to the unwind handler.
689   // ??? Should this ever happen with sjlj exceptions?
690   for (unsigned i = 0, e = Unwinds.size(); i != e; ++i) {
691     BranchInst::Create(TrapBlock, Unwinds[i]);
692     Unwinds[i]->eraseFromParent();
693   }
694
695   // Following any allocas not in the entry block, update the saved SP in the
696   // jmpbuf to the new value.
697   for (unsigned i = 0, e = JmpbufUpdatePoints.size(); i != e; ++i) {
698     Instruction *AI = JmpbufUpdatePoints[i];
699     Instruction *StackAddr = CallInst::Create(StackAddrFn, "sp");
700     StackAddr->insertAfter(AI);
701     Instruction *StoreStackAddr = new StoreInst(StackAddr, StackPtr, true);
702     StoreStackAddr->insertAfter(StackAddr);
703   }
704
705   // Finally, for any returns from this function, if this function contains an
706   // invoke, add a call to unregister the function context.
707   for (unsigned i = 0, e = Returns.size(); i != e; ++i)
708     CallInst::Create(UnregisterFn, FunctionContext, "", Returns[i]);
709
710   return true;
711 }
712
713 /// setupFunctionContext - Allocate the function context on the stack and fill
714 /// it with all of the data that we know at this point.
715 std::pair<Value*, Value*> SjLjEHPass::
716 setupFunctionContext(Function &F, ArrayRef<LandingPadInst*> LPads) {
717   BasicBlock *EntryBB = F.begin();
718
719   // Create an alloca for the incoming jump buffer ptr and the new jump buffer
720   // that needs to be restored on all exits from the function. This is an alloca
721   // because the value needs to be added to the global context list.
722   unsigned Align =
723     TLI->getTargetData()->getPrefTypeAlignment(FunctionContextTy);
724   AllocaInst *FuncCtx =
725     new AllocaInst(FunctionContextTy, 0, Align, "fn_context", EntryBB->begin());
726
727   // Fill in the function context structure.
728   Value *Idxs[2];
729   Type *Int32Ty = Type::getInt32Ty(F.getContext());
730   Value *Zero = ConstantInt::get(Int32Ty, 0);
731   Value *One = ConstantInt::get(Int32Ty, 1);
732
733   // Keep around a reference to the call_site field.
734   Idxs[0] = Zero;
735   Idxs[1] = One;
736   CallSite = GetElementPtrInst::Create(FuncCtx, Idxs, "call_site",
737                                        EntryBB->getTerminator());
738
739   // Reference the __data field.
740   Idxs[1] = ConstantInt::get(Int32Ty, 2);
741   Value *FCData = GetElementPtrInst::Create(FuncCtx, Idxs, "__data",
742                                             EntryBB->getTerminator());
743
744   // The exception value comes back in context->__data[0].
745   Idxs[1] = Zero;
746   Value *ExceptionAddr = GetElementPtrInst::Create(FCData, Idxs,
747                                                    "exception_gep",
748                                                    EntryBB->getTerminator());
749
750   // The exception selector comes back in context->__data[1].
751   Idxs[1] = One;
752   Value *SelectorAddr = GetElementPtrInst::Create(FCData, Idxs,
753                                                   "exn_selector_gep",
754                                                   EntryBB->getTerminator());
755
756   for (unsigned I = 0, E = LPads.size(); I != E; ++I) {
757     LandingPadInst *LPI = LPads[I];
758     IRBuilder<> Builder(LPI->getParent()->getFirstInsertionPt());
759
760     Value *ExnVal = Builder.CreateLoad(ExceptionAddr, true, "exn_val");
761     ExnVal = Builder.CreateIntToPtr(ExnVal, Type::getInt8PtrTy(F.getContext()));
762     Value *SelVal = Builder.CreateLoad(SelectorAddr, true, "exn_selector_val");
763
764     Type *LPadType = LPI->getType();
765     Value *LPadVal = UndefValue::get(LPadType);
766     LPadVal = Builder.CreateInsertValue(LPadVal, ExnVal, 0, "lpad.val");
767     LPadVal = Builder.CreateInsertValue(LPadVal, SelVal, 1, "lpad.val");
768
769     LPI->replaceAllUsesWith(LPadVal);
770   }
771
772   // Personality function
773   Idxs[1] = ConstantInt::get(Int32Ty, 3);
774   if (!PersonalityFn)
775     PersonalityFn = LPads[0]->getPersonalityFn();
776   Value *PersonalityFieldPtr =
777     GetElementPtrInst::Create(FuncCtx, Idxs, "pers_fn_gep",
778                               EntryBB->getTerminator());
779   new StoreInst(PersonalityFn, PersonalityFieldPtr, true,
780                 EntryBB->getTerminator());
781
782   // LSDA address
783   Idxs[1] = ConstantInt::get(Int32Ty, 4);
784   Value *LSDAFieldPtr =
785     GetElementPtrInst::Create(FuncCtx, Idxs, "lsda_gep",
786                               EntryBB->getTerminator());
787   Value *LSDA = CallInst::Create(LSDAAddrFn, "lsda_addr",
788                                  EntryBB->getTerminator());
789   new StoreInst(LSDA, LSDAFieldPtr, true, EntryBB->getTerminator());
790
791   // Get a reference to the jump buffer.
792   Idxs[1] = ConstantInt::get(Int32Ty, 5);
793   Value *JBufPtr =
794     GetElementPtrInst::Create(FuncCtx, Idxs, "jbuf_gep",
795                               EntryBB->getTerminator());
796   Idxs[1] = Zero;
797   Value *FramePtr =
798     GetElementPtrInst::Create(JBufPtr, Idxs, "jbuf_fp_gep",
799                               EntryBB->getTerminator());
800
801   // Save the frame pointer.
802   Value *Val = CallInst::Create(FrameAddrFn,
803                                 ConstantInt::get(Int32Ty, 0),
804                                 "fp",
805                                 EntryBB->getTerminator());
806   new StoreInst(Val, FramePtr, true, EntryBB->getTerminator());
807
808   return std::make_pair(FuncCtx, JBufPtr);
809 }
810
811 /// setupEntryBlockAndCallSites - Setup the entry block by creating and filling
812 /// the function context and marking the call sites with the appropriate
813 /// values. These values are used by the DWARF EH emitter.
814 bool SjLjEHPass::setupEntryBlockAndCallSites(Function &F) {
815   SmallVector<ReturnInst*,     16> Returns;
816   SmallVector<InvokeInst*,     16> Invokes;
817   SmallVector<LandingPadInst*, 16> LPads;
818
819   // Look through the terminators of the basic blocks to find invokes.
820   for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
821     if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
822       Invokes.push_back(II);
823       LPads.push_back(II->getUnwindDest()->getLandingPadInst());
824     } else if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
825       Returns.push_back(RI);
826     }
827
828   if (Invokes.empty()) return false;
829
830   std::pair<Value*, Value*> FuncCtx = setupFunctionContext(F, LPads);
831   BasicBlock *EntryBB = F.begin();
832
833   // Save the stack pointer.
834   Type *Int32Ty = Type::getInt32Ty(F.getContext());
835   Value *Idxs[2] = {
836     ConstantInt::get(Int32Ty, 0), ConstantInt::get(Int32Ty, 2)
837   };
838   Value *StackPtr =
839     GetElementPtrInst::Create(FuncCtx.second, Idxs, "jbuf_sp_gep",
840                               EntryBB->getTerminator());
841
842   Value *Val = CallInst::Create(StackAddrFn, "sp", EntryBB->getTerminator());
843   new StoreInst(Val, StackPtr, true, EntryBB->getTerminator());
844
845   // Call the setjmp instrinsic. It fills in the rest of the jmpbuf.
846   Value *SetjmpArg =
847     CastInst::Create(Instruction::BitCast, FuncCtx.second,
848                      Type::getInt8PtrTy(F.getContext()), "",
849                      EntryBB->getTerminator());
850   Value *DispatchVal = CallInst::Create(BuiltinSetjmpFn, SetjmpArg,
851                                         "dispatch",
852                                         EntryBB->getTerminator());
853
854   // Add a call to dispatch_setup after the setjmp call. This is expanded to any
855   // target-specific setup that needs to be done.
856   CallInst::Create(DispatchSetupFn, DispatchVal, "", EntryBB->getTerminator());
857
858   // Store a pointer to the function context so that the back-end will know
859   // where to look for it.
860   Value *FuncCtxArg =
861     CastInst::Create(Instruction::BitCast, FuncCtx.first,
862                      Type::getInt8PtrTy(F.getContext()), "",
863                      EntryBB->getTerminator());
864   CallInst::Create(FuncCtxFn, FuncCtxArg, "", EntryBB->getTerminator());
865
866   // At this point, we are all set up, update the invoke instructions to mark
867   // their call_site values, and fill in the dispatch switch accordingly.
868   for (unsigned I = 0, E = Invokes.size(); I != E; ++I) {
869     insertCallSiteStore(Invokes[I], I + 1, CallSite);
870
871     ConstantInt *CallSiteNum =
872       ConstantInt::get(Type::getInt32Ty(F.getContext()), I + 1);
873
874     // Record the call site value for the back end so it stays associated with
875     // the invoke.
876     CallInst::Create(CallSiteFn, CallSiteNum, "", Invokes[I]);
877   }
878
879   // Mark call instructions that aren't nounwind as no-action (call_site ==
880   // -1). Skip the entry block, as prior to then, no function context has been
881   // created for this function and any unexpected exceptions thrown will go
882   // directly to the caller's context, which is what we want anyway, so no need
883   // to do anything here.
884   for (Function::iterator BB = F.begin(), E = F.end(); ++BB != E;) {
885     for (BasicBlock::iterator I = BB->begin(), end = BB->end(); I != end; ++I)
886       if (CallInst *CI = dyn_cast<CallInst>(I)) {
887         if (!CI->doesNotThrow())
888           insertCallSiteStore(CI, -1, CallSite);
889       } else if (ResumeInst *RI = dyn_cast<ResumeInst>(I)) {
890         insertCallSiteStore(RI, -1, CallSite);
891       }
892   }
893
894   // Register the function context and make sure it's known to not throw
895   CallInst *Register = CallInst::Create(RegisterFn, FuncCtx.first, "",
896                                         EntryBB->getTerminator());
897   Register->setDoesNotThrow();
898
899   // Finally, for any returns from this function, if this function contains an
900   // invoke, add a call to unregister the function context.
901   for (unsigned I = 0, E = Returns.size(); I != E; ++I)
902     CallInst::Create(UnregisterFn, FuncCtx.first, "", Returns[I]);
903
904   return true;
905 }
906
907 bool SjLjEHPass::runOnFunction(Function &F) {
908   bool Res = false;
909   if (!DisableOldSjLjEH)
910     Res = insertSjLjEHSupport(F);
911   else
912     Res = setupEntryBlockAndCallSites(F);
913   return Res;
914 }