Remove VISIBILITY_HIDDEN from class/struct found inside anonymous namespaces.
[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/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"
34 using namespace llvm;
35
36 STATISTIC(NumInvokes, "Number of invokes replaced");
37 STATISTIC(NumUnwinds, "Number of unwinds replaced");
38 STATISTIC(NumSpilled, "Number of registers live across unwind edges");
39
40 namespace {
41   class 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 *SelectorFn;
54     Constant *ExceptionFn;
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
78 char SjLjEHPass::ID = 0;
79
80 // Public Interface To the SjLjEHPass pass.
81 FunctionPass *llvm::createSjLjEHPass(const TargetLowering *TLI) {
82   return new SjLjEHPass(TLI);
83 }
84 // doInitialization - Set up decalarations and types needed to process
85 // exceptions.
86 bool 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   PersonalityFn = 0;
121
122   return true;
123 }
124
125 /// markInvokeCallSite - Insert code to mark the call_site for this invoke
126 void SjLjEHPass::markInvokeCallSite(InvokeInst *II, unsigned InvokeNo,
127                                     Value *CallSite,
128                                     SwitchInst *CatchSwitch) {
129   ConstantInt *CallSiteNoC= ConstantInt::get(Type::getInt32Ty(II->getContext()),
130                                             InvokeNo);
131   // The runtime comes back to the dispatcher with the call_site - 1 in
132   // the context. Odd, but there it is.
133   ConstantInt *SwitchValC = ConstantInt::get(Type::getInt32Ty(II->getContext()),
134                                             InvokeNo - 1);
135
136   // If the unwind edge has phi nodes, split the edge.
137   if (isa<PHINode>(II->getUnwindDest()->begin())) {
138     SplitCriticalEdge(II, 1, this);
139
140     // If there are any phi nodes left, they must have a single predecessor.
141     while (PHINode *PN = dyn_cast<PHINode>(II->getUnwindDest()->begin())) {
142       PN->replaceAllUsesWith(PN->getIncomingValue(0));
143       PN->eraseFromParent();
144     }
145   }
146
147   // Insert a store of the invoke num before the invoke and store zero into the
148   // location afterward.
149   new StoreInst(CallSiteNoC, CallSite, true, II);  // volatile
150
151   // Add a switch case to our unwind block.
152   CatchSwitch->addCase(SwitchValC, II->getUnwindDest());
153   // We still want this to look like an invoke so we emit the LSDA properly
154   // FIXME: ??? Or will this cause strangeness with mis-matched IDs like
155   //  when it was in the front end?
156 }
157
158 /// MarkBlocksLiveIn - Insert BB and all of its predescessors into LiveBBs until
159 /// we reach blocks we've already seen.
160 static 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.
171 void SjLjEHPass::
172 splitLiveRangesLiveAcrossInvokes(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
269 bool 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
386
387
388     // The entry block changes to have the eh.sjlj.setjmp, with a conditional
389     // branch to a dispatch block for non-zero returns. If we return normally,
390     // we're not handling an exception and just register the function context
391     // and continue.
392
393     // Create the dispatch block.  The dispatch block is basically a big switch
394     // statement that goes to all of the invoke landing pads.
395     BasicBlock *DispatchBlock =
396             BasicBlock::Create(F.getContext(), "eh.sjlj.setjmp.catch", &F);
397
398     // Insert a load in the Catch block, and a switch on its value.  By default,
399     // we go to a block that just does an unwind (which is the correct action
400     // for a standard call).
401     BasicBlock *UnwindBlock = BasicBlock::Create(F.getContext(), "unwindbb", &F);
402     Unwinds.push_back(new UnwindInst(F.getContext(), UnwindBlock));
403
404     Value *DispatchLoad = new LoadInst(CallSite, "invoke.num", true,
405                                        DispatchBlock);
406     SwitchInst *DispatchSwitch =
407       SwitchInst::Create(DispatchLoad, UnwindBlock, Invokes.size(), DispatchBlock);
408     // Split the entry block to insert the conditional branch for the setjmp.
409     BasicBlock *ContBlock = EntryBB->splitBasicBlock(EntryBB->getTerminator(),
410                                                      "eh.sjlj.setjmp.cont");
411
412     // Populate the Function Context
413     //   1. LSDA address
414     //   2. Personality function address
415     //   3. jmpbuf (save FP and call eh.sjlj.setjmp)
416
417     // LSDA address
418     Idxs[0] = Zero;
419     Idxs[1] = ConstantInt::get(Int32Ty, 4);
420     Value *LSDAFieldPtr =
421       GetElementPtrInst::Create(FunctionContext, Idxs, Idxs+2,
422                                 "lsda_gep",
423                                 EntryBB->getTerminator());
424     Value *LSDA = CallInst::Create(LSDAAddrFn, "lsda_addr",
425                                    EntryBB->getTerminator());
426     new StoreInst(LSDA, LSDAFieldPtr, true, EntryBB->getTerminator());
427
428     Idxs[1] = ConstantInt::get(Int32Ty, 3);
429     Value *PersonalityFieldPtr =
430       GetElementPtrInst::Create(FunctionContext, Idxs, Idxs+2,
431                                 "lsda_gep",
432                                 EntryBB->getTerminator());
433     new StoreInst(PersonalityFn, PersonalityFieldPtr, true,
434                   EntryBB->getTerminator());
435
436     //   Save the frame pointer.
437     Idxs[1] = ConstantInt::get(Int32Ty, 5);
438     Value *FieldPtr
439       = GetElementPtrInst::Create(FunctionContext, Idxs, Idxs+2,
440                                   "jbuf_gep",
441                                   EntryBB->getTerminator());
442     Idxs[1] = ConstantInt::get(Int32Ty, 0);
443     Value *ElemPtr =
444       GetElementPtrInst::Create(FieldPtr, Idxs, Idxs+2, "jbuf_fp_gep",
445                                 EntryBB->getTerminator());
446
447     Value *Val = CallInst::Create(FrameAddrFn,
448                                   ConstantInt::get(Int32Ty, 0),
449                                   "fp",
450                                   EntryBB->getTerminator());
451     new StoreInst(Val, ElemPtr, true, EntryBB->getTerminator());
452     // Call the setjmp instrinsic. It fills in the rest of the jmpbuf
453     Value *SetjmpArg =
454       CastInst::Create(Instruction::BitCast, FieldPtr,
455                        Type::getInt8PtrTy(F.getContext()), "",
456                        EntryBB->getTerminator());
457     Value *DispatchVal = CallInst::Create(BuiltinSetjmpFn, SetjmpArg,
458                                           "dispatch",
459                                           EntryBB->getTerminator());
460     // check the return value of the setjmp. non-zero goes to dispatcher
461     Value *IsNormal = new ICmpInst(EntryBB->getTerminator(),
462                                    ICmpInst::ICMP_EQ, DispatchVal, Zero,
463                                    "notunwind");
464     // Nuke the uncond branch.
465     EntryBB->getTerminator()->eraseFromParent();
466
467     // Put in a new condbranch in its place.
468     BranchInst::Create(ContBlock, DispatchBlock, IsNormal, EntryBB);
469
470     // Register the function context and make sure it's known to not throw
471     CallInst *Register =
472       CallInst::Create(RegisterFn, FunctionContext, "",
473                        ContBlock->getTerminator());
474     Register->setDoesNotThrow();
475
476     // At this point, we are all set up, update the invoke instructions
477     // to mark their call_site values, and fill in the dispatch switch
478     // accordingly.
479     for (unsigned i = 0, e = Invokes.size(); i != e; ++i)
480       markInvokeCallSite(Invokes[i], i+1, CallSite, DispatchSwitch);
481
482     // The front end has likely added calls to _Unwind_Resume. We need
483     // to find those calls and mark the call_site as -1 immediately prior.
484     // resume is a noreturn function, so any block that has a call to it
485     // should end in an 'unreachable' instruction with the call immediately
486     // prior. That's how we'll search.
487     // ??? There's got to be a better way. this is fugly.
488     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
489       if ((dyn_cast<UnreachableInst>(BB->getTerminator()))) {
490         BasicBlock::iterator I = BB->getTerminator();
491         // Check the previous instruction and see if it's a resume call
492         if (I == BB->begin()) continue;
493         if (CallInst *CI = dyn_cast<CallInst>(--I)) {
494           if (CI->getCalledFunction() == ResumeFn) {
495             Value *NegativeOne = Constant::getAllOnesValue(Int32Ty);
496             new StoreInst(NegativeOne, CallSite, true, I);  // volatile
497           }
498         }
499       }
500
501     // Replace all unwinds with a branch to the unwind handler.
502     // ??? Should this ever happen with sjlj exceptions?
503     for (unsigned i = 0, e = Unwinds.size(); i != e; ++i) {
504       BranchInst::Create(UnwindBlock, Unwinds[i]);
505       Unwinds[i]->eraseFromParent();
506     }
507
508     // Finally, for any returns from this function, if this function contains an
509     // invoke, add a call to unregister the function context.
510     for (unsigned i = 0, e = Returns.size(); i != e; ++i)
511       CallInst::Create(UnregisterFn, FunctionContext, "", Returns[i]);
512   }
513
514   return true;
515 }
516
517 bool SjLjEHPass::runOnFunction(Function &F) {
518   bool Res = insertSjLjEHSupport(F);
519   return Res;
520 }