SjLjEHPrepare.cpp revision ca752c9020a1b1cf151142bd9e0cbca9af12d807
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/Debug.h"
31#include "llvm/Support/raw_ostream.h"
32#include "llvm/Target/TargetLowering.h"
33using namespace llvm;
34
35STATISTIC(NumInvokes, "Number of invokes replaced");
36STATISTIC(NumUnwinds, "Number of unwinds replaced");
37STATISTIC(NumSpilled, "Number of registers live across unwind edges");
38
39namespace {
40  class SjLjEHPass : public FunctionPass {
41
42    const TargetLowering *TLI;
43
44    const Type *FunctionContextTy;
45    Constant *RegisterFn;
46    Constant *UnregisterFn;
47    Constant *ResumeFn;
48    Constant *BuiltinSetjmpFn;
49    Constant *FrameAddrFn;
50    Constant *LSDAAddrFn;
51    Value *PersonalityFn;
52    Constant *SelectorFn;
53    Constant *ExceptionFn;
54    Constant *CallSiteFn;
55
56    Value *CallSite;
57  public:
58    static char ID; // Pass identification, replacement for typeid
59    explicit SjLjEHPass(const TargetLowering *tli = NULL)
60      : FunctionPass(&ID), TLI(tli) { }
61    bool doInitialization(Module &M);
62    bool runOnFunction(Function &F);
63
64    virtual void getAnalysisUsage(AnalysisUsage &AU) const { }
65    const char *getPassName() const {
66      return "SJLJ Exception Handling preparation";
67    }
68
69  private:
70    void markInvokeCallSite(InvokeInst *II, unsigned InvokeNo,
71                            Value *CallSite,
72                            SwitchInst *CatchSwitch);
73    void splitLiveRangesLiveAcrossInvokes(SmallVector<InvokeInst*,16> &Invokes);
74    bool insertSjLjEHSupport(Function &F);
75  };
76} // end anonymous namespace
77
78char SjLjEHPass::ID = 0;
79
80// Public Interface To the SjLjEHPass pass.
81FunctionPass *llvm::createSjLjEHPass(const TargetLowering *TLI) {
82  return new SjLjEHPass(TLI);
83}
84// doInitialization - Set up decalarations and types needed to process
85// exceptions.
86bool SjLjEHPass::doInitialization(Module &M) {
87  // Build the function context structure.
88  // builtin_setjmp uses a five word jbuf
89  const Type *VoidPtrTy =
90          Type::getInt8PtrTy(M.getContext());
91  const Type *Int32Ty = Type::getInt32Ty(M.getContext());
92  FunctionContextTy =
93    StructType::get(M.getContext(),
94                    VoidPtrTy,                        // __prev
95                    Int32Ty,                          // call_site
96                    ArrayType::get(Int32Ty, 4),       // __data
97                    VoidPtrTy,                        // __personality
98                    VoidPtrTy,                        // __lsda
99                    ArrayType::get(VoidPtrTy, 5),     // __jbuf
100                    NULL);
101  RegisterFn = M.getOrInsertFunction("_Unwind_SjLj_Register",
102                                     Type::getVoidTy(M.getContext()),
103                                     PointerType::getUnqual(FunctionContextTy),
104                                     (Type *)0);
105  UnregisterFn =
106    M.getOrInsertFunction("_Unwind_SjLj_Unregister",
107                          Type::getVoidTy(M.getContext()),
108                          PointerType::getUnqual(FunctionContextTy),
109                          (Type *)0);
110  ResumeFn =
111    M.getOrInsertFunction("_Unwind_SjLj_Resume",
112                          Type::getVoidTy(M.getContext()),
113                          VoidPtrTy,
114                          (Type *)0);
115  FrameAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::frameaddress);
116  BuiltinSetjmpFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_setjmp);
117  LSDAAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_lsda);
118  SelectorFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_selector);
119  ExceptionFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_exception);
120  CallSiteFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_callsite);
121  PersonalityFn = 0;
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
149  new StoreInst(CallSiteNoC, CallSite, true, II);  // volatile
150  CallInst::Create(CallSiteFn, CallSiteNoC, "", II);
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  // so we don't transform the invoke into a call here.
156}
157
158/// MarkBlocksLiveIn - Insert BB and all of its predescessors into LiveBBs until
159/// we reach blocks we've already seen.
160static void MarkBlocksLiveIn(BasicBlock *BB, std::set<BasicBlock*> &LiveBBs) {
161  if (!LiveBBs.insert(BB).second) return; // already been here.
162
163  for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
164    MarkBlocksLiveIn(*PI, LiveBBs);
165}
166
167/// splitLiveRangesAcrossInvokes - Each value that is live across an unwind edge
168/// we spill into a stack location, guaranteeing that there is nothing live
169/// across the unwind edge.  This process also splits all critical edges
170/// coming out of invoke's.
171void SjLjEHPass::
172splitLiveRangesLiveAcrossInvokes(SmallVector<InvokeInst*,16> &Invokes) {
173  // First step, split all critical edges from invoke instructions.
174  for (unsigned i = 0, e = Invokes.size(); i != e; ++i) {
175    InvokeInst *II = Invokes[i];
176    SplitCriticalEdge(II, 0, this);
177    SplitCriticalEdge(II, 1, this);
178    assert(!isa<PHINode>(II->getNormalDest()) &&
179           !isa<PHINode>(II->getUnwindDest()) &&
180           "critical edge splitting left single entry phi nodes?");
181  }
182
183  Function *F = Invokes.back()->getParent()->getParent();
184
185  // To avoid having to handle incoming arguments specially, we lower each arg
186  // to a copy instruction in the entry block.  This ensures that the argument
187  // value itself cannot be live across the entry block.
188  BasicBlock::iterator AfterAllocaInsertPt = F->begin()->begin();
189  while (isa<AllocaInst>(AfterAllocaInsertPt) &&
190        isa<ConstantInt>(cast<AllocaInst>(AfterAllocaInsertPt)->getArraySize()))
191    ++AfterAllocaInsertPt;
192  for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
193       AI != E; ++AI) {
194    // This is always a no-op cast because we're casting AI to AI->getType() so
195    // src and destination types are identical. BitCast is the only possibility.
196    CastInst *NC = new BitCastInst(
197      AI, AI->getType(), AI->getName()+".tmp", AfterAllocaInsertPt);
198    AI->replaceAllUsesWith(NC);
199    // Normally its is forbidden to replace a CastInst's operand because it
200    // could cause the opcode to reflect an illegal conversion. However, we're
201    // replacing it here with the same value it was constructed with to simply
202    // make NC its user.
203    NC->setOperand(0, AI);
204  }
205
206  // Finally, scan the code looking for instructions with bad live ranges.
207  for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
208    for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E; ++II) {
209      // Ignore obvious cases we don't have to handle.  In particular, most
210      // instructions either have no uses or only have a single use inside the
211      // current block.  Ignore them quickly.
212      Instruction *Inst = II;
213      if (Inst->use_empty()) continue;
214      if (Inst->hasOneUse() &&
215          cast<Instruction>(Inst->use_back())->getParent() == BB &&
216          !isa<PHINode>(Inst->use_back())) continue;
217
218      // If this is an alloca in the entry block, it's not a real register
219      // value.
220      if (AllocaInst *AI = dyn_cast<AllocaInst>(Inst))
221        if (isa<ConstantInt>(AI->getArraySize()) && BB == F->begin())
222          continue;
223
224      // Avoid iterator invalidation by copying users to a temporary vector.
225      SmallVector<Instruction*,16> Users;
226      for (Value::use_iterator UI = Inst->use_begin(), E = Inst->use_end();
227           UI != E; ++UI) {
228        Instruction *User = cast<Instruction>(*UI);
229        if (User->getParent() != BB || isa<PHINode>(User))
230          Users.push_back(User);
231      }
232
233      // Find all of the blocks that this value is live in.
234      std::set<BasicBlock*> LiveBBs;
235      LiveBBs.insert(Inst->getParent());
236      while (!Users.empty()) {
237        Instruction *U = Users.back();
238        Users.pop_back();
239
240        if (!isa<PHINode>(U)) {
241          MarkBlocksLiveIn(U->getParent(), LiveBBs);
242        } else {
243          // Uses for a PHI node occur in their predecessor block.
244          PHINode *PN = cast<PHINode>(U);
245          for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
246            if (PN->getIncomingValue(i) == Inst)
247              MarkBlocksLiveIn(PN->getIncomingBlock(i), LiveBBs);
248        }
249      }
250
251      // Now that we know all of the blocks that this thing is live in, see if
252      // it includes any of the unwind locations.
253      bool NeedsSpill = false;
254      for (unsigned i = 0, e = Invokes.size(); i != e; ++i) {
255        BasicBlock *UnwindBlock = Invokes[i]->getUnwindDest();
256        if (UnwindBlock != BB && LiveBBs.count(UnwindBlock)) {
257          NeedsSpill = true;
258        }
259      }
260
261      // If we decided we need a spill, do it.
262      if (NeedsSpill) {
263        ++NumSpilled;
264        DemoteRegToStack(*Inst, true);
265      }
266    }
267}
268
269bool SjLjEHPass::insertSjLjEHSupport(Function &F) {
270  SmallVector<ReturnInst*,16> Returns;
271  SmallVector<UnwindInst*,16> Unwinds;
272  SmallVector<InvokeInst*,16> Invokes;
273
274  // Look through the terminators of the basic blocks to find invokes, returns
275  // and unwinds
276  for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
277    if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
278      // Remember all return instructions in case we insert an invoke into this
279      // function.
280      Returns.push_back(RI);
281    } else if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
282      Invokes.push_back(II);
283    } else if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->getTerminator())) {
284      Unwinds.push_back(UI);
285    }
286  // If we don't have any invokes or unwinds, there's nothing to do.
287  if (Unwinds.empty() && Invokes.empty()) return false;
288
289  // Find the eh.selector.*  and eh.exception calls. We'll use the first
290  // eh.selector to determine the right personality function to use. For
291  // SJLJ, we always use the same personality for the whole function,
292  // not on a per-selector basis.
293  // FIXME: That's a bit ugly. Better way?
294  SmallVector<CallInst*,16> EH_Selectors;
295  SmallVector<CallInst*,16> EH_Exceptions;
296  for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
297    for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
298      if (CallInst *CI = dyn_cast<CallInst>(I)) {
299        if (CI->getCalledFunction() == SelectorFn) {
300          if (!PersonalityFn) PersonalityFn = CI->getOperand(2);
301          EH_Selectors.push_back(CI);
302        } else if (CI->getCalledFunction() == ExceptionFn) {
303          EH_Exceptions.push_back(CI);
304        }
305      }
306    }
307  }
308  // If we don't have any eh.selector calls, we can't determine the personality
309  // function. Without a personality function, we can't process exceptions.
310  if (!PersonalityFn) return false;
311
312  NumInvokes += Invokes.size();
313  NumUnwinds += Unwinds.size();
314
315  if (!Invokes.empty()) {
316    // We have invokes, so we need to add register/unregister calls to get
317    // this function onto the global unwind stack.
318    //
319    // First thing we need to do is scan the whole function for values that are
320    // live across unwind edges.  Each value that is live across an unwind edge
321    // we spill into a stack location, guaranteeing that there is nothing live
322    // across the unwind edge.  This process also splits all critical edges
323    // coming out of invoke's.
324    splitLiveRangesLiveAcrossInvokes(Invokes);
325
326    BasicBlock *EntryBB = F.begin();
327    // Create an alloca for the incoming jump buffer ptr and the new jump buffer
328    // that needs to be restored on all exits from the function.  This is an
329    // alloca because the value needs to be added to the global context list.
330    unsigned Align = 4; // FIXME: Should be a TLI check?
331    AllocaInst *FunctionContext =
332      new AllocaInst(FunctionContextTy, 0, Align,
333                     "fcn_context", F.begin()->begin());
334
335    Value *Idxs[2];
336    const Type *Int32Ty = Type::getInt32Ty(F.getContext());
337    Value *Zero = ConstantInt::get(Int32Ty, 0);
338    // We need to also keep around a reference to the call_site field
339    Idxs[0] = Zero;
340    Idxs[1] = ConstantInt::get(Int32Ty, 1);
341    CallSite = GetElementPtrInst::Create(FunctionContext, Idxs, Idxs+2,
342                                         "call_site",
343                                         EntryBB->getTerminator());
344
345    // The exception selector comes back in context->data[1]
346    Idxs[1] = ConstantInt::get(Int32Ty, 2);
347    Value *FCData = GetElementPtrInst::Create(FunctionContext, Idxs, Idxs+2,
348                                              "fc_data",
349                                              EntryBB->getTerminator());
350    Idxs[1] = ConstantInt::get(Int32Ty, 1);
351    Value *SelectorAddr = GetElementPtrInst::Create(FCData, Idxs, Idxs+2,
352                                                    "exc_selector_gep",
353                                                    EntryBB->getTerminator());
354    // The exception value comes back in context->data[0]
355    Idxs[1] = Zero;
356    Value *ExceptionAddr = GetElementPtrInst::Create(FCData, Idxs, Idxs+2,
357                                                     "exception_gep",
358                                                     EntryBB->getTerminator());
359
360    // The result of the eh.selector call will be replaced with a
361    // a reference to the selector value returned in the function
362    // context. We leave the selector itself so the EH analysis later
363    // can use it.
364    for (int i = 0, e = EH_Selectors.size(); i < e; ++i) {
365      CallInst *I = EH_Selectors[i];
366      Value *SelectorVal = new LoadInst(SelectorAddr, "select_val", true, I);
367      I->replaceAllUsesWith(SelectorVal);
368    }
369    // eh.exception calls are replaced with references to the proper
370    // location in the context. Unlike eh.selector, the eh.exception
371    // calls are removed entirely.
372    for (int i = 0, e = EH_Exceptions.size(); i < e; ++i) {
373      CallInst *I = EH_Exceptions[i];
374      // Possible for there to be duplicates, so check to make sure
375      // the instruction hasn't already been removed.
376      if (!I->getParent()) continue;
377      Value *Val = new LoadInst(ExceptionAddr, "exception", true, I);
378      const Type *Ty = Type::getInt8PtrTy(F.getContext());
379      Val = CastInst::Create(Instruction::IntToPtr, Val, Ty, "", I);
380
381      I->replaceAllUsesWith(Val);
382      I->eraseFromParent();
383    }
384
385    // The entry block changes to have the eh.sjlj.setjmp, with a conditional
386    // branch to a dispatch block for non-zero returns. If we return normally,
387    // we're not handling an exception and just register the function context
388    // and continue.
389
390    // Create the dispatch block.  The dispatch block is basically a big switch
391    // statement that goes to all of the invoke landing pads.
392    BasicBlock *DispatchBlock =
393            BasicBlock::Create(F.getContext(), "eh.sjlj.setjmp.catch", &F);
394
395    // Insert a load in the Catch block, and a switch on its value.  By default,
396    // we go to a block that just does an unwind (which is the correct action
397    // for a standard call).
398    BasicBlock *UnwindBlock =
399      BasicBlock::Create(F.getContext(), "unwindbb", &F);
400    Unwinds.push_back(new UnwindInst(F.getContext(), UnwindBlock));
401
402    Value *DispatchLoad = new LoadInst(CallSite, "invoke.num", true,
403                                       DispatchBlock);
404    SwitchInst *DispatchSwitch =
405      SwitchInst::Create(DispatchLoad, UnwindBlock, Invokes.size(),
406                         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::getInt8PtrTy(F.getContext()), "",
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