SjLjEHPrepare.cpp revision 0a9b7e23d54e15a4fd57dac39e40252db1546245
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/Transforms/Utils/BasicBlockUtils.h"
26#include "llvm/Transforms/Utils/Local.h"
27#include "llvm/ADT/Statistic.h"
28#include "llvm/ADT/SmallVector.h"
29#include "llvm/Support/CommandLine.h"
30#include "llvm/Support/Compiler.h"
31#include "llvm/Support/Debug.h"
32#include "llvm/Support/raw_ostream.h"
33#include "llvm/Target/TargetLowering.h"
34using namespace llvm;
35
36STATISTIC(NumInvokes, "Number of invokes replaced");
37STATISTIC(NumUnwinds, "Number of unwinds replaced");
38STATISTIC(NumSpilled, "Number of registers live across unwind edges");
39
40namespace {
41  class VISIBILITY_HIDDEN SjLjEHPass : public FunctionPass {
42
43    const TargetLowering *TLI;
44
45    const Type *FunctionContextTy;
46    Constant *RegisterFn;
47    Constant *UnregisterFn;
48    Constant *ResumeFn;
49    Constant *BuiltinSetjmpFn;
50    Constant *FrameAddrFn;
51    Constant *LSDAAddrFn;
52    Value *PersonalityFn;
53    Constant *Selector32Fn;
54    Constant *Selector64Fn;
55    Constant *ExceptionFn;
56
57    Value *CallSite;
58  public:
59    static char ID; // Pass identification, replacement for typeid
60    explicit SjLjEHPass(const TargetLowering *tli = NULL)
61      : FunctionPass(&ID), TLI(tli) { }
62    bool doInitialization(Module &M);
63    bool runOnFunction(Function &F);
64
65    virtual void getAnalysisUsage(AnalysisUsage &AU) const { }
66    const char *getPassName() const {
67      return "SJLJ Exception Handling preparation";
68    }
69
70  private:
71    void markInvokeCallSite(InvokeInst *II, unsigned InvokeNo,
72                            Value *CallSite,
73                            SwitchInst *CatchSwitch);
74    void splitLiveRangesLiveAcrossInvokes(SmallVector<InvokeInst*,16> &Invokes);
75    bool insertSjLjEHSupport(Function &F);
76  };
77} // end anonymous namespace
78
79char SjLjEHPass::ID = 0;
80
81// Public Interface To the SjLjEHPass pass.
82FunctionPass *llvm::createSjLjEHPass(const TargetLowering *TLI) {
83  return new SjLjEHPass(TLI);
84}
85// doInitialization - Make sure that there is a prototype for abort in the
86// current module.
87bool SjLjEHPass::doInitialization(Module &M) {
88  // Build the function context structure.
89  // builtin_setjmp uses a five word jbuf
90  const Type *VoidPtrTy =
91          PointerType::getUnqual(Type::getInt8Ty(M.getContext()));
92  const Type *Int32Ty = Type::getInt32Ty(M.getContext());
93  FunctionContextTy =
94    StructType::get(M.getContext(),
95                    VoidPtrTy,                        // __prev
96                    Int32Ty,                          // call_site
97                    ArrayType::get(Int32Ty, 4),       // __data
98                    VoidPtrTy,                        // __personality
99                    VoidPtrTy,                        // __lsda
100                    ArrayType::get(VoidPtrTy, 5),     // __jbuf
101                    NULL);
102  RegisterFn = M.getOrInsertFunction("_Unwind_SjLj_Register",
103                                     Type::getVoidTy(M.getContext()),
104                                     PointerType::getUnqual(FunctionContextTy),
105                                     (Type *)0);
106  UnregisterFn =
107    M.getOrInsertFunction("_Unwind_SjLj_Unregister",
108                          Type::getVoidTy(M.getContext()),
109                          PointerType::getUnqual(FunctionContextTy),
110                          (Type *)0);
111  ResumeFn =
112    M.getOrInsertFunction("_Unwind_SjLj_Resume",
113                          Type::getVoidTy(M.getContext()),
114                          VoidPtrTy,
115                          (Type *)0);
116  FrameAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::frameaddress);
117  BuiltinSetjmpFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_setjmp);
118  LSDAAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_lsda);
119  Selector32Fn = Intrinsic::getDeclaration(&M, Intrinsic::eh_selector_i32);
120  Selector64Fn = Intrinsic::getDeclaration(&M, Intrinsic::eh_selector_i64);
121  ExceptionFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_exception);
122
123  return true;
124}
125
126/// markInvokeCallSite - Insert code to mark the call_site for this invoke
127void SjLjEHPass::markInvokeCallSite(InvokeInst *II, unsigned InvokeNo,
128                                    Value *CallSite,
129                                    SwitchInst *CatchSwitch) {
130  ConstantInt *CallSiteNoC= ConstantInt::get(Type::getInt32Ty(II->getContext()),
131                                            InvokeNo);
132  // The runtime comes back to the dispatcher with the call_site - 1 in
133  // the context. Odd, but there it is.
134  ConstantInt *SwitchValC = ConstantInt::get(Type::getInt32Ty(II->getContext()),
135                                            InvokeNo - 1);
136
137  // If the unwind edge has phi nodes, split the edge.
138  if (isa<PHINode>(II->getUnwindDest()->begin())) {
139    SplitCriticalEdge(II, 1, this);
140
141    // If there are any phi nodes left, they must have a single predecessor.
142    while (PHINode *PN = dyn_cast<PHINode>(II->getUnwindDest()->begin())) {
143      PN->replaceAllUsesWith(PN->getIncomingValue(0));
144      PN->eraseFromParent();
145    }
146  }
147
148  // Insert a store of the invoke num before the invoke and store zero into the
149  // location afterward.
150  new StoreInst(CallSiteNoC, CallSite, true, II);  // volatile
151
152  // Add a switch case to our unwind block.
153  CatchSwitch->addCase(SwitchValC, II->getUnwindDest());
154  // We still want this to look like an invoke so we emit the LSDA properly
155  // FIXME: ??? Or will this cause strangeness with mis-matched IDs like
156  //  when it was in the front end?
157}
158
159/// MarkBlocksLiveIn - Insert BB and all of its predescessors into LiveBBs until
160/// we reach blocks we've already seen.
161static void MarkBlocksLiveIn(BasicBlock *BB, std::set<BasicBlock*> &LiveBBs) {
162  if (!LiveBBs.insert(BB).second) return; // already been here.
163
164  for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
165    MarkBlocksLiveIn(*PI, LiveBBs);
166}
167
168/// splitLiveRangesAcrossInvokes - Each value that is live across an unwind edge
169/// we spill into a stack location, guaranteeing that there is nothing live
170/// across the unwind edge.  This process also splits all critical edges
171/// coming out of invoke's.
172void SjLjEHPass::
173splitLiveRangesLiveAcrossInvokes(SmallVector<InvokeInst*,16> &Invokes) {
174  // First step, split all critical edges from invoke instructions.
175  for (unsigned i = 0, e = Invokes.size(); i != e; ++i) {
176    InvokeInst *II = Invokes[i];
177    SplitCriticalEdge(II, 0, this);
178    SplitCriticalEdge(II, 1, this);
179    assert(!isa<PHINode>(II->getNormalDest()) &&
180           !isa<PHINode>(II->getUnwindDest()) &&
181           "critical edge splitting left single entry phi nodes?");
182  }
183
184  Function *F = Invokes.back()->getParent()->getParent();
185
186  // To avoid having to handle incoming arguments specially, we lower each arg
187  // to a copy instruction in the entry block.  This ensures that the argument
188  // value itself cannot be live across the entry block.
189  BasicBlock::iterator AfterAllocaInsertPt = F->begin()->begin();
190  while (isa<AllocaInst>(AfterAllocaInsertPt) &&
191        isa<ConstantInt>(cast<AllocaInst>(AfterAllocaInsertPt)->getArraySize()))
192    ++AfterAllocaInsertPt;
193  for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
194       AI != E; ++AI) {
195    // This is always a no-op cast because we're casting AI to AI->getType() so
196    // src and destination types are identical. BitCast is the only possibility.
197    CastInst *NC = new BitCastInst(
198      AI, AI->getType(), AI->getName()+".tmp", AfterAllocaInsertPt);
199    AI->replaceAllUsesWith(NC);
200    // Normally its is forbidden to replace a CastInst's operand because it
201    // could cause the opcode to reflect an illegal conversion. However, we're
202    // replacing it here with the same value it was constructed with to simply
203    // make NC its user.
204    NC->setOperand(0, AI);
205  }
206
207  // Finally, scan the code looking for instructions with bad live ranges.
208  for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
209    for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E; ++II) {
210      // Ignore obvious cases we don't have to handle.  In particular, most
211      // instructions either have no uses or only have a single use inside the
212      // current block.  Ignore them quickly.
213      Instruction *Inst = II;
214      if (Inst->use_empty()) continue;
215      if (Inst->hasOneUse() &&
216          cast<Instruction>(Inst->use_back())->getParent() == BB &&
217          !isa<PHINode>(Inst->use_back())) continue;
218
219      // If this is an alloca in the entry block, it's not a real register
220      // value.
221      if (AllocaInst *AI = dyn_cast<AllocaInst>(Inst))
222        if (isa<ConstantInt>(AI->getArraySize()) && BB == F->begin())
223          continue;
224
225      // Avoid iterator invalidation by copying users to a temporary vector.
226      SmallVector<Instruction*,16> Users;
227      for (Value::use_iterator UI = Inst->use_begin(), E = Inst->use_end();
228           UI != E; ++UI) {
229        Instruction *User = cast<Instruction>(*UI);
230        if (User->getParent() != BB || isa<PHINode>(User))
231          Users.push_back(User);
232      }
233
234      // Find all of the blocks that this value is live in.
235      std::set<BasicBlock*> LiveBBs;
236      LiveBBs.insert(Inst->getParent());
237      while (!Users.empty()) {
238        Instruction *U = Users.back();
239        Users.pop_back();
240
241        if (!isa<PHINode>(U)) {
242          MarkBlocksLiveIn(U->getParent(), LiveBBs);
243        } else {
244          // Uses for a PHI node occur in their predecessor block.
245          PHINode *PN = cast<PHINode>(U);
246          for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
247            if (PN->getIncomingValue(i) == Inst)
248              MarkBlocksLiveIn(PN->getIncomingBlock(i), LiveBBs);
249        }
250      }
251
252      // Now that we know all of the blocks that this thing is live in, see if
253      // it includes any of the unwind locations.
254      bool NeedsSpill = false;
255      for (unsigned i = 0, e = Invokes.size(); i != e; ++i) {
256        BasicBlock *UnwindBlock = Invokes[i]->getUnwindDest();
257        if (UnwindBlock != BB && LiveBBs.count(UnwindBlock)) {
258          NeedsSpill = true;
259        }
260      }
261
262      // If we decided we need a spill, do it.
263      if (NeedsSpill) {
264        ++NumSpilled;
265        DemoteRegToStack(*Inst, true);
266      }
267    }
268}
269
270bool SjLjEHPass::insertSjLjEHSupport(Function &F) {
271  SmallVector<ReturnInst*,16> Returns;
272  SmallVector<UnwindInst*,16> Unwinds;
273  SmallVector<InvokeInst*,16> Invokes;
274
275  // Look through the terminators of the basic blocks to find invokes, returns
276  // and unwinds
277  for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
278    if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
279      // Remember all return instructions in case we insert an invoke into this
280      // function.
281      Returns.push_back(RI);
282    } else if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
283      Invokes.push_back(II);
284    } else if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->getTerminator())) {
285      Unwinds.push_back(UI);
286    }
287  // If we don't have any invokes or unwinds, there's nothing to do.
288  if (Unwinds.empty() && Invokes.empty()) return false;
289
290  NumInvokes += Invokes.size();
291  NumUnwinds += Unwinds.size();
292
293
294  if (!Invokes.empty()) {
295    // We have invokes, so we need to add register/unregister calls to get
296    // this function onto the global unwind stack.
297    //
298    // First thing we need to do is scan the whole function for values that are
299    // live across unwind edges.  Each value that is live across an unwind edge
300    // we spill into a stack location, guaranteeing that there is nothing live
301    // across the unwind edge.  This process also splits all critical edges
302    // coming out of invoke's.
303    splitLiveRangesLiveAcrossInvokes(Invokes);
304
305    BasicBlock *EntryBB = F.begin();
306    // Create an alloca for the incoming jump buffer ptr and the new jump buffer
307    // that needs to be restored on all exits from the function.  This is an
308    // alloca because the value needs to be added to the global context list.
309    unsigned Align = 4; // FIXME: Should be a TLI check?
310    AllocaInst *FunctionContext =
311      new AllocaInst(FunctionContextTy, 0, Align,
312                     "fcn_context", F.begin()->begin());
313
314    Value *Idxs[2];
315    const Type *Int32Ty = Type::getInt32Ty(F.getContext());
316    Value *Zero = ConstantInt::get(Int32Ty, 0);
317    // We need to also keep around a reference to the call_site field
318    Idxs[0] = Zero;
319    Idxs[1] = ConstantInt::get(Int32Ty, 1);
320    CallSite = GetElementPtrInst::Create(FunctionContext, Idxs, Idxs+2,
321                                         "call_site",
322                                         EntryBB->getTerminator());
323
324    // The exception selector comes back in context->data[1]
325    Idxs[1] = ConstantInt::get(Int32Ty, 2);
326    Value *FCData = GetElementPtrInst::Create(FunctionContext, Idxs, Idxs+2,
327                                              "fc_data",
328                                              EntryBB->getTerminator());
329    Idxs[1] = ConstantInt::get(Int32Ty, 1);
330    Value *SelectorAddr = GetElementPtrInst::Create(FCData, Idxs, Idxs+2,
331                                                    "exc_selector_gep",
332                                                    EntryBB->getTerminator());
333    // The exception value comes back in context->data[0]
334    Idxs[1] = Zero;
335    Value *ExceptionAddr = GetElementPtrInst::Create(FCData, Idxs, Idxs+2,
336                                                     "exception_gep",
337                                                     EntryBB->getTerminator());
338
339    // Find the eh.selector.*  and eh.exception calls. We'll use the first
340    // ex.selector to determine the right personality function to use. For
341    // SJLJ, we always use the same personality for the whole function,
342    // not on a per-selector basis.
343    // FIXME: That's a bit ugly. Better way?
344    SmallVector<CallInst*,16> EH_Selectors;
345    SmallVector<CallInst*,16> EH_Exceptions;
346    for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
347      for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
348        if (CallInst *CI = dyn_cast<CallInst>(I)) {
349          if (CI->getCalledFunction() == Selector32Fn ||
350              CI->getCalledFunction() == Selector64Fn) {
351            if (!PersonalityFn) PersonalityFn = CI->getOperand(2);
352            EH_Selectors.push_back(CI);
353          } else if (CI->getCalledFunction() == ExceptionFn) {
354            EH_Exceptions.push_back(CI);
355          }
356        }
357      }
358    }
359    // The result of the eh.selector call will be replaced with a
360    // a reference to the selector value returned in the function
361    // context. We leave the selector itself so the EH analysis later
362    // can use it.
363    for (int i = 0, e = EH_Selectors.size(); i < e; ++i) {
364      CallInst *I = EH_Selectors[i];
365      Value *SelectorVal = new LoadInst(SelectorAddr, "select_val", true, I);
366      I->replaceAllUsesWith(SelectorVal);
367    }
368    // eh.exception calls are replaced with references to the proper
369    // location in the context. Unlike eh.selector, the eh.exception
370    // calls are removed entirely.
371    for (int i = 0, e = EH_Exceptions.size(); i < e; ++i) {
372      CallInst *I = EH_Exceptions[i];
373      // Possible for there to be duplicates, so check to make sure
374      // the instruction hasn't already been removed.
375      if (!I->getParent()) continue;
376      Value *Val = new LoadInst(ExceptionAddr, "exception", true, I);
377      Type *Ty = PointerType::getUnqual(Type::getInt8Ty(F.getContext()));
378      Val = CastInst::Create(Instruction::IntToPtr, Val, Ty, "", I);
379
380      I->replaceAllUsesWith(Val);
381      I->eraseFromParent();
382    }
383
384
385
386
387    // The entry block changes to have the eh.sjlj.setjmp, with a conditional
388    // branch to a dispatch block for non-zero returns. If we return normally,
389    // we're not handling an exception and just register the function context
390    // and continue.
391
392    // Create the dispatch block.  The dispatch block is basically a big switch
393    // statement that goes to all of the invoke landing pads.
394    BasicBlock *DispatchBlock =
395            BasicBlock::Create(F.getContext(), "eh.sjlj.setjmp.catch", &F);
396
397    // Insert a load in the Catch block, and a switch on its value.  By default,
398    // we go to a block that just does an unwind (which is the correct action
399    // for a standard call).
400    BasicBlock *UnwindBlock = BasicBlock::Create(F.getContext(), "unwindbb", &F);
401    Unwinds.push_back(new UnwindInst(F.getContext(), UnwindBlock));
402
403    Value *DispatchLoad = new LoadInst(CallSite, "invoke.num", true,
404                                       DispatchBlock);
405    SwitchInst *DispatchSwitch =
406      SwitchInst::Create(DispatchLoad, UnwindBlock, Invokes.size(), DispatchBlock);
407    // Split the entry block to insert the conditional branch for the setjmp.
408    BasicBlock *ContBlock = EntryBB->splitBasicBlock(EntryBB->getTerminator(),
409                                                     "eh.sjlj.setjmp.cont");
410
411    // Populate the Function Context
412    //   1. LSDA address
413    //   2. Personality function address
414    //   3. jmpbuf (save FP and call eh.sjlj.setjmp)
415
416    // LSDA address
417    Idxs[0] = Zero;
418    Idxs[1] = ConstantInt::get(Int32Ty, 4);
419    Value *LSDAFieldPtr =
420      GetElementPtrInst::Create(FunctionContext, Idxs, Idxs+2,
421                                "lsda_gep",
422                                EntryBB->getTerminator());
423    Value *LSDA = CallInst::Create(LSDAAddrFn, "lsda_addr",
424                                   EntryBB->getTerminator());
425    new StoreInst(LSDA, LSDAFieldPtr, true, EntryBB->getTerminator());
426
427    Idxs[1] = ConstantInt::get(Int32Ty, 3);
428    Value *PersonalityFieldPtr =
429      GetElementPtrInst::Create(FunctionContext, Idxs, Idxs+2,
430                                "lsda_gep",
431                                EntryBB->getTerminator());
432    new StoreInst(PersonalityFn, PersonalityFieldPtr, true,
433                  EntryBB->getTerminator());
434
435    //   Save the frame pointer.
436    Idxs[1] = ConstantInt::get(Int32Ty, 5);
437    Value *FieldPtr
438      = GetElementPtrInst::Create(FunctionContext, Idxs, Idxs+2,
439                                  "jbuf_gep",
440                                  EntryBB->getTerminator());
441    Idxs[1] = ConstantInt::get(Int32Ty, 0);
442    Value *ElemPtr =
443      GetElementPtrInst::Create(FieldPtr, Idxs, Idxs+2, "jbuf_fp_gep",
444                                EntryBB->getTerminator());
445
446    Value *Val = CallInst::Create(FrameAddrFn,
447                                  ConstantInt::get(Int32Ty, 0),
448                                  "fp",
449                                  EntryBB->getTerminator());
450    new StoreInst(Val, ElemPtr, true, EntryBB->getTerminator());
451    // Call the setjmp instrinsic. It fills in the rest of the jmpbuf
452    Value *SetjmpArg =
453      CastInst::Create(Instruction::BitCast, FieldPtr,
454                        Type::getInt8Ty(F.getContext())->getPointerTo(), "",
455                        EntryBB->getTerminator());
456    Value *DispatchVal = CallInst::Create(BuiltinSetjmpFn, SetjmpArg,
457                                          "dispatch",
458                                          EntryBB->getTerminator());
459    // check the return value of the setjmp. non-zero goes to dispatcher
460    Value *IsNormal = new ICmpInst(EntryBB->getTerminator(),
461                                   ICmpInst::ICMP_EQ, DispatchVal, Zero,
462                                   "notunwind");
463    // Nuke the uncond branch.
464    EntryBB->getTerminator()->eraseFromParent();
465
466    // Put in a new condbranch in its place.
467    BranchInst::Create(ContBlock, DispatchBlock, IsNormal, EntryBB);
468
469    // Register the function context and make sure it's known to not throw
470    CallInst *Register =
471      CallInst::Create(RegisterFn, FunctionContext, "",
472                       ContBlock->getTerminator());
473    Register->setDoesNotThrow();
474
475    // At this point, we are all set up, update the invoke instructions
476    // to mark their call_site values, and fill in the dispatch switch
477    // accordingly.
478    for (unsigned i = 0, e = Invokes.size(); i != e; ++i)
479      markInvokeCallSite(Invokes[i], i+1, CallSite, DispatchSwitch);
480
481    // The front end has likely added calls to _Unwind_Resume. We need
482    // to find those calls and mark the call_site as -1 immediately prior.
483    // resume is a noreturn function, so any block that has a call to it
484    // should end in an 'unreachable' instruction with the call immediately
485    // prior. That's how we'll search.
486    // ??? There's got to be a better way. this is fugly.
487    for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
488      if ((dyn_cast<UnreachableInst>(BB->getTerminator()))) {
489        BasicBlock::iterator I = BB->getTerminator();
490        // Check the previous instruction and see if it's a resume call
491        if (I == BB->begin()) continue;
492        if (CallInst *CI = dyn_cast<CallInst>(--I)) {
493          if (CI->getCalledFunction() == ResumeFn) {
494            Value *NegativeOne = Constant::getAllOnesValue(Int32Ty);
495            new StoreInst(NegativeOne, CallSite, true, I);  // volatile
496          }
497        }
498      }
499
500    // Replace all unwinds with a branch to the unwind handler.
501    // ??? Should this ever happen with sjlj exceptions?
502    for (unsigned i = 0, e = Unwinds.size(); i != e; ++i) {
503      BranchInst::Create(UnwindBlock, Unwinds[i]);
504      Unwinds[i]->eraseFromParent();
505    }
506
507    // Finally, for any returns from this function, if this function contains an
508    // invoke, add a call to unregister the function context.
509    for (unsigned i = 0, e = Returns.size(); i != e; ++i)
510      CallInst::Create(UnregisterFn, FunctionContext, "", Returns[i]);
511  }
512
513  return true;
514}
515
516bool SjLjEHPass::runOnFunction(Function &F) {
517  bool Res = insertSjLjEHSupport(F);
518  return Res;
519}
520