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