LLVM API Documentation

SjLjEHPrepare.cpp
Go to the documentation of this file.
00001 //===- SjLjEHPrepare.cpp - Eliminate Invoke & Unwind instructions ---------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This transformation is designed for use by code generators which use SjLj
00011 // based exception handling.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #include "llvm/CodeGen/Passes.h"
00016 #include "llvm/ADT/DenseMap.h"
00017 #include "llvm/ADT/SetVector.h"
00018 #include "llvm/ADT/SmallPtrSet.h"
00019 #include "llvm/ADT/SmallVector.h"
00020 #include "llvm/ADT/Statistic.h"
00021 #include "llvm/IR/Constants.h"
00022 #include "llvm/IR/DataLayout.h"
00023 #include "llvm/IR/DerivedTypes.h"
00024 #include "llvm/IR/IRBuilder.h"
00025 #include "llvm/IR/Instructions.h"
00026 #include "llvm/IR/Intrinsics.h"
00027 #include "llvm/IR/LLVMContext.h"
00028 #include "llvm/IR/Module.h"
00029 #include "llvm/Pass.h"
00030 #include "llvm/Support/CommandLine.h"
00031 #include "llvm/Support/Debug.h"
00032 #include "llvm/Support/raw_ostream.h"
00033 #include "llvm/Target/TargetLowering.h"
00034 #include "llvm/Target/TargetSubtargetInfo.h"
00035 #include "llvm/Transforms/Scalar.h"
00036 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
00037 #include "llvm/Transforms/Utils/Local.h"
00038 #include <set>
00039 using namespace llvm;
00040 
00041 #define DEBUG_TYPE "sjljehprepare"
00042 
00043 STATISTIC(NumInvokes, "Number of invokes replaced");
00044 STATISTIC(NumSpilled, "Number of registers live across unwind edges");
00045 
00046 namespace {
00047 class SjLjEHPrepare : public FunctionPass {
00048   const TargetMachine *TM;
00049   Type *FunctionContextTy;
00050   Constant *RegisterFn;
00051   Constant *UnregisterFn;
00052   Constant *BuiltinSetjmpFn;
00053   Constant *FrameAddrFn;
00054   Constant *StackAddrFn;
00055   Constant *StackRestoreFn;
00056   Constant *LSDAAddrFn;
00057   Value *PersonalityFn;
00058   Constant *CallSiteFn;
00059   Constant *FuncCtxFn;
00060   AllocaInst *FuncCtx;
00061 
00062 public:
00063   static char ID; // Pass identification, replacement for typeid
00064   explicit SjLjEHPrepare(const TargetMachine *TM) : FunctionPass(ID), TM(TM) {}
00065   bool doInitialization(Module &M) override;
00066   bool runOnFunction(Function &F) override;
00067 
00068   void getAnalysisUsage(AnalysisUsage &AU) const override {}
00069   const char *getPassName() const override {
00070     return "SJLJ Exception Handling preparation";
00071   }
00072 
00073 private:
00074   bool setupEntryBlockAndCallSites(Function &F);
00075   void substituteLPadValues(LandingPadInst *LPI, Value *ExnVal, Value *SelVal);
00076   Value *setupFunctionContext(Function &F, ArrayRef<LandingPadInst *> LPads);
00077   void lowerIncomingArguments(Function &F);
00078   void lowerAcrossUnwindEdges(Function &F, ArrayRef<InvokeInst *> Invokes);
00079   void insertCallSiteStore(Instruction *I, int Number);
00080 };
00081 } // end anonymous namespace
00082 
00083 char SjLjEHPrepare::ID = 0;
00084 
00085 // Public Interface To the SjLjEHPrepare pass.
00086 FunctionPass *llvm::createSjLjEHPreparePass(const TargetMachine *TM) {
00087   return new SjLjEHPrepare(TM);
00088 }
00089 // doInitialization - Set up decalarations and types needed to process
00090 // exceptions.
00091 bool SjLjEHPrepare::doInitialization(Module &M) {
00092   // Build the function context structure.
00093   // builtin_setjmp uses a five word jbuf
00094   Type *VoidPtrTy = Type::getInt8PtrTy(M.getContext());
00095   Type *Int32Ty = Type::getInt32Ty(M.getContext());
00096   FunctionContextTy = StructType::get(VoidPtrTy,                  // __prev
00097                                       Int32Ty,                    // call_site
00098                                       ArrayType::get(Int32Ty, 4), // __data
00099                                       VoidPtrTy, // __personality
00100                                       VoidPtrTy, // __lsda
00101                                       ArrayType::get(VoidPtrTy, 5), // __jbuf
00102                                       NULL);
00103   RegisterFn = M.getOrInsertFunction(
00104       "_Unwind_SjLj_Register", Type::getVoidTy(M.getContext()),
00105       PointerType::getUnqual(FunctionContextTy), (Type *)nullptr);
00106   UnregisterFn = M.getOrInsertFunction(
00107       "_Unwind_SjLj_Unregister", Type::getVoidTy(M.getContext()),
00108       PointerType::getUnqual(FunctionContextTy), (Type *)nullptr);
00109   FrameAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::frameaddress);
00110   StackAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::stacksave);
00111   StackRestoreFn = Intrinsic::getDeclaration(&M, Intrinsic::stackrestore);
00112   BuiltinSetjmpFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_setjmp);
00113   LSDAAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_lsda);
00114   CallSiteFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_callsite);
00115   FuncCtxFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_functioncontext);
00116   PersonalityFn = nullptr;
00117 
00118   return true;
00119 }
00120 
00121 /// insertCallSiteStore - Insert a store of the call-site value to the
00122 /// function context
00123 void SjLjEHPrepare::insertCallSiteStore(Instruction *I, int Number) {
00124   IRBuilder<> Builder(I);
00125 
00126   // Get a reference to the call_site field.
00127   Type *Int32Ty = Type::getInt32Ty(I->getContext());
00128   Value *Zero = ConstantInt::get(Int32Ty, 0);
00129   Value *One = ConstantInt::get(Int32Ty, 1);
00130   Value *Idxs[2] = { Zero, One };
00131   Value *CallSite = Builder.CreateGEP(FuncCtx, Idxs, "call_site");
00132 
00133   // Insert a store of the call-site number
00134   ConstantInt *CallSiteNoC =
00135       ConstantInt::get(Type::getInt32Ty(I->getContext()), Number);
00136   Builder.CreateStore(CallSiteNoC, CallSite, true /*volatile*/);
00137 }
00138 
00139 /// MarkBlocksLiveIn - Insert BB and all of its predescessors into LiveBBs until
00140 /// we reach blocks we've already seen.
00141 static void MarkBlocksLiveIn(BasicBlock *BB,
00142                              SmallPtrSetImpl<BasicBlock *> &LiveBBs) {
00143   if (!LiveBBs.insert(BB))
00144     return; // already been here.
00145 
00146   for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
00147     MarkBlocksLiveIn(*PI, LiveBBs);
00148 }
00149 
00150 /// substituteLPadValues - Substitute the values returned by the landingpad
00151 /// instruction with those returned by the personality function.
00152 void SjLjEHPrepare::substituteLPadValues(LandingPadInst *LPI, Value *ExnVal,
00153                                          Value *SelVal) {
00154   SmallVector<Value *, 8> UseWorkList(LPI->user_begin(), LPI->user_end());
00155   while (!UseWorkList.empty()) {
00156     Value *Val = UseWorkList.pop_back_val();
00157     ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(Val);
00158     if (!EVI)
00159       continue;
00160     if (EVI->getNumIndices() != 1)
00161       continue;
00162     if (*EVI->idx_begin() == 0)
00163       EVI->replaceAllUsesWith(ExnVal);
00164     else if (*EVI->idx_begin() == 1)
00165       EVI->replaceAllUsesWith(SelVal);
00166     if (EVI->getNumUses() == 0)
00167       EVI->eraseFromParent();
00168   }
00169 
00170   if (LPI->getNumUses() == 0)
00171     return;
00172 
00173   // There are still some uses of LPI. Construct an aggregate with the exception
00174   // values and replace the LPI with that aggregate.
00175   Type *LPadType = LPI->getType();
00176   Value *LPadVal = UndefValue::get(LPadType);
00177   IRBuilder<> Builder(
00178       std::next(BasicBlock::iterator(cast<Instruction>(SelVal))));
00179   LPadVal = Builder.CreateInsertValue(LPadVal, ExnVal, 0, "lpad.val");
00180   LPadVal = Builder.CreateInsertValue(LPadVal, SelVal, 1, "lpad.val");
00181 
00182   LPI->replaceAllUsesWith(LPadVal);
00183 }
00184 
00185 /// setupFunctionContext - Allocate the function context on the stack and fill
00186 /// it with all of the data that we know at this point.
00187 Value *SjLjEHPrepare::setupFunctionContext(Function &F,
00188                                            ArrayRef<LandingPadInst *> LPads) {
00189   BasicBlock *EntryBB = F.begin();
00190 
00191   // Create an alloca for the incoming jump buffer ptr and the new jump buffer
00192   // that needs to be restored on all exits from the function. This is an alloca
00193   // because the value needs to be added to the global context list.
00194   const TargetLowering *TLI = TM->getSubtargetImpl()->getTargetLowering();
00195   unsigned Align =
00196       TLI->getDataLayout()->getPrefTypeAlignment(FunctionContextTy);
00197   FuncCtx = new AllocaInst(FunctionContextTy, nullptr, Align, "fn_context",
00198                            EntryBB->begin());
00199 
00200   // Fill in the function context structure.
00201   for (unsigned I = 0, E = LPads.size(); I != E; ++I) {
00202     LandingPadInst *LPI = LPads[I];
00203     IRBuilder<> Builder(LPI->getParent()->getFirstInsertionPt());
00204 
00205     // Reference the __data field.
00206     Value *FCData = Builder.CreateConstGEP2_32(FuncCtx, 0, 2, "__data");
00207 
00208     // The exception values come back in context->__data[0].
00209     Value *ExceptionAddr =
00210         Builder.CreateConstGEP2_32(FCData, 0, 0, "exception_gep");
00211     Value *ExnVal = Builder.CreateLoad(ExceptionAddr, true, "exn_val");
00212     ExnVal = Builder.CreateIntToPtr(ExnVal, Builder.getInt8PtrTy());
00213 
00214     Value *SelectorAddr =
00215         Builder.CreateConstGEP2_32(FCData, 0, 1, "exn_selector_gep");
00216     Value *SelVal = Builder.CreateLoad(SelectorAddr, true, "exn_selector_val");
00217 
00218     substituteLPadValues(LPI, ExnVal, SelVal);
00219   }
00220 
00221   // Personality function
00222   IRBuilder<> Builder(EntryBB->getTerminator());
00223   if (!PersonalityFn)
00224     PersonalityFn = LPads[0]->getPersonalityFn();
00225   Value *PersonalityFieldPtr =
00226       Builder.CreateConstGEP2_32(FuncCtx, 0, 3, "pers_fn_gep");
00227   Builder.CreateStore(
00228       Builder.CreateBitCast(PersonalityFn, Builder.getInt8PtrTy()),
00229       PersonalityFieldPtr, /*isVolatile=*/true);
00230 
00231   // LSDA address
00232   Value *LSDA = Builder.CreateCall(LSDAAddrFn, "lsda_addr");
00233   Value *LSDAFieldPtr = Builder.CreateConstGEP2_32(FuncCtx, 0, 4, "lsda_gep");
00234   Builder.CreateStore(LSDA, LSDAFieldPtr, /*isVolatile=*/true);
00235 
00236   return FuncCtx;
00237 }
00238 
00239 /// lowerIncomingArguments - To avoid having to handle incoming arguments
00240 /// specially, we lower each arg to a copy instruction in the entry block. This
00241 /// ensures that the argument value itself cannot be live out of the entry
00242 /// block.
00243 void SjLjEHPrepare::lowerIncomingArguments(Function &F) {
00244   BasicBlock::iterator AfterAllocaInsPt = F.begin()->begin();
00245   while (isa<AllocaInst>(AfterAllocaInsPt) &&
00246          isa<ConstantInt>(cast<AllocaInst>(AfterAllocaInsPt)->getArraySize()))
00247     ++AfterAllocaInsPt;
00248 
00249   for (Function::arg_iterator AI = F.arg_begin(), AE = F.arg_end(); AI != AE;
00250        ++AI) {
00251     Type *Ty = AI->getType();
00252 
00253     // Use 'select i8 true, %arg, undef' to simulate a 'no-op' instruction.
00254     Value *TrueValue = ConstantInt::getTrue(F.getContext());
00255     Value *UndefValue = UndefValue::get(Ty);
00256     Instruction *SI = SelectInst::Create(TrueValue, AI, UndefValue,
00257                                          AI->getName() + ".tmp",
00258                                          AfterAllocaInsPt);
00259     AI->replaceAllUsesWith(SI);
00260 
00261     // Reset the operand, because it  was clobbered by the RAUW above.
00262     SI->setOperand(1, AI);
00263   }
00264 }
00265 
00266 /// lowerAcrossUnwindEdges - Find all variables which are alive across an unwind
00267 /// edge and spill them.
00268 void SjLjEHPrepare::lowerAcrossUnwindEdges(Function &F,
00269                                            ArrayRef<InvokeInst *> Invokes) {
00270   // Finally, scan the code looking for instructions with bad live ranges.
00271   for (Function::iterator BB = F.begin(), BBE = F.end(); BB != BBE; ++BB) {
00272     for (BasicBlock::iterator II = BB->begin(), IIE = BB->end(); II != IIE;
00273          ++II) {
00274       // Ignore obvious cases we don't have to handle. In particular, most
00275       // instructions either have no uses or only have a single use inside the
00276       // current block. Ignore them quickly.
00277       Instruction *Inst = II;
00278       if (Inst->use_empty())
00279         continue;
00280       if (Inst->hasOneUse() &&
00281           cast<Instruction>(Inst->user_back())->getParent() == BB &&
00282           !isa<PHINode>(Inst->user_back()))
00283         continue;
00284 
00285       // If this is an alloca in the entry block, it's not a real register
00286       // value.
00287       if (AllocaInst *AI = dyn_cast<AllocaInst>(Inst))
00288         if (isa<ConstantInt>(AI->getArraySize()) && BB == F.begin())
00289           continue;
00290 
00291       // Avoid iterator invalidation by copying users to a temporary vector.
00292       SmallVector<Instruction *, 16> Users;
00293       for (User *U : Inst->users()) {
00294         Instruction *UI = cast<Instruction>(U);
00295         if (UI->getParent() != BB || isa<PHINode>(UI))
00296           Users.push_back(UI);
00297       }
00298 
00299       // Find all of the blocks that this value is live in.
00300       SmallPtrSet<BasicBlock *, 64> LiveBBs;
00301       LiveBBs.insert(Inst->getParent());
00302       while (!Users.empty()) {
00303         Instruction *U = Users.back();
00304         Users.pop_back();
00305 
00306         if (!isa<PHINode>(U)) {
00307           MarkBlocksLiveIn(U->getParent(), LiveBBs);
00308         } else {
00309           // Uses for a PHI node occur in their predecessor block.
00310           PHINode *PN = cast<PHINode>(U);
00311           for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
00312             if (PN->getIncomingValue(i) == Inst)
00313               MarkBlocksLiveIn(PN->getIncomingBlock(i), LiveBBs);
00314         }
00315       }
00316 
00317       // Now that we know all of the blocks that this thing is live in, see if
00318       // it includes any of the unwind locations.
00319       bool NeedsSpill = false;
00320       for (unsigned i = 0, e = Invokes.size(); i != e; ++i) {
00321         BasicBlock *UnwindBlock = Invokes[i]->getUnwindDest();
00322         if (UnwindBlock != BB && LiveBBs.count(UnwindBlock)) {
00323           DEBUG(dbgs() << "SJLJ Spill: " << *Inst << " around "
00324                        << UnwindBlock->getName() << "\n");
00325           NeedsSpill = true;
00326           break;
00327         }
00328       }
00329 
00330       // If we decided we need a spill, do it.
00331       // FIXME: Spilling this way is overkill, as it forces all uses of
00332       // the value to be reloaded from the stack slot, even those that aren't
00333       // in the unwind blocks. We should be more selective.
00334       if (NeedsSpill) {
00335         DemoteRegToStack(*Inst, true);
00336         ++NumSpilled;
00337       }
00338     }
00339   }
00340 
00341   // Go through the landing pads and remove any PHIs there.
00342   for (unsigned i = 0, e = Invokes.size(); i != e; ++i) {
00343     BasicBlock *UnwindBlock = Invokes[i]->getUnwindDest();
00344     LandingPadInst *LPI = UnwindBlock->getLandingPadInst();
00345 
00346     // Place PHIs into a set to avoid invalidating the iterator.
00347     SmallPtrSet<PHINode *, 8> PHIsToDemote;
00348     for (BasicBlock::iterator PN = UnwindBlock->begin(); isa<PHINode>(PN); ++PN)
00349       PHIsToDemote.insert(cast<PHINode>(PN));
00350     if (PHIsToDemote.empty())
00351       continue;
00352 
00353     // Demote the PHIs to the stack.
00354     for (PHINode *PN : PHIsToDemote)
00355       DemotePHIToStack(PN);
00356 
00357     // Move the landingpad instruction back to the top of the landing pad block.
00358     LPI->moveBefore(UnwindBlock->begin());
00359   }
00360 }
00361 
00362 /// setupEntryBlockAndCallSites - Setup the entry block by creating and filling
00363 /// the function context and marking the call sites with the appropriate
00364 /// values. These values are used by the DWARF EH emitter.
00365 bool SjLjEHPrepare::setupEntryBlockAndCallSites(Function &F) {
00366   SmallVector<ReturnInst *, 16> Returns;
00367   SmallVector<InvokeInst *, 16> Invokes;
00368   SmallSetVector<LandingPadInst *, 16> LPads;
00369 
00370   // Look through the terminators of the basic blocks to find invokes.
00371   for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
00372     if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
00373       if (Function *Callee = II->getCalledFunction())
00374         if (Callee->isIntrinsic() &&
00375             Callee->getIntrinsicID() == Intrinsic::donothing) {
00376           // Remove the NOP invoke.
00377           BranchInst::Create(II->getNormalDest(), II);
00378           II->eraseFromParent();
00379           continue;
00380         }
00381 
00382       Invokes.push_back(II);
00383       LPads.insert(II->getUnwindDest()->getLandingPadInst());
00384     } else if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
00385       Returns.push_back(RI);
00386     }
00387 
00388   if (Invokes.empty())
00389     return false;
00390 
00391   NumInvokes += Invokes.size();
00392 
00393   lowerIncomingArguments(F);
00394   lowerAcrossUnwindEdges(F, Invokes);
00395 
00396   Value *FuncCtx =
00397       setupFunctionContext(F, makeArrayRef(LPads.begin(), LPads.end()));
00398   BasicBlock *EntryBB = F.begin();
00399   IRBuilder<> Builder(EntryBB->getTerminator());
00400 
00401   // Get a reference to the jump buffer.
00402   Value *JBufPtr = Builder.CreateConstGEP2_32(FuncCtx, 0, 5, "jbuf_gep");
00403 
00404   // Save the frame pointer.
00405   Value *FramePtr = Builder.CreateConstGEP2_32(JBufPtr, 0, 0, "jbuf_fp_gep");
00406 
00407   Value *Val = Builder.CreateCall(FrameAddrFn, Builder.getInt32(0), "fp");
00408   Builder.CreateStore(Val, FramePtr, /*isVolatile=*/true);
00409 
00410   // Save the stack pointer.
00411   Value *StackPtr = Builder.CreateConstGEP2_32(JBufPtr, 0, 2, "jbuf_sp_gep");
00412 
00413   Val = Builder.CreateCall(StackAddrFn, "sp");
00414   Builder.CreateStore(Val, StackPtr, /*isVolatile=*/true);
00415 
00416   // Call the setjmp instrinsic. It fills in the rest of the jmpbuf.
00417   Value *SetjmpArg = Builder.CreateBitCast(JBufPtr, Builder.getInt8PtrTy());
00418   Builder.CreateCall(BuiltinSetjmpFn, SetjmpArg);
00419 
00420   // Store a pointer to the function context so that the back-end will know
00421   // where to look for it.
00422   Value *FuncCtxArg = Builder.CreateBitCast(FuncCtx, Builder.getInt8PtrTy());
00423   Builder.CreateCall(FuncCtxFn, FuncCtxArg);
00424 
00425   // At this point, we are all set up, update the invoke instructions to mark
00426   // their call_site values.
00427   for (unsigned I = 0, E = Invokes.size(); I != E; ++I) {
00428     insertCallSiteStore(Invokes[I], I + 1);
00429 
00430     ConstantInt *CallSiteNum =
00431         ConstantInt::get(Type::getInt32Ty(F.getContext()), I + 1);
00432 
00433     // Record the call site value for the back end so it stays associated with
00434     // the invoke.
00435     CallInst::Create(CallSiteFn, CallSiteNum, "", Invokes[I]);
00436   }
00437 
00438   // Mark call instructions that aren't nounwind as no-action (call_site ==
00439   // -1). Skip the entry block, as prior to then, no function context has been
00440   // created for this function and any unexpected exceptions thrown will go
00441   // directly to the caller's context, which is what we want anyway, so no need
00442   // to do anything here.
00443   for (Function::iterator BB = F.begin(), E = F.end(); ++BB != E;)
00444     for (BasicBlock::iterator I = BB->begin(), end = BB->end(); I != end; ++I)
00445       if (CallInst *CI = dyn_cast<CallInst>(I)) {
00446         if (!CI->doesNotThrow())
00447           insertCallSiteStore(CI, -1);
00448       } else if (ResumeInst *RI = dyn_cast<ResumeInst>(I)) {
00449         insertCallSiteStore(RI, -1);
00450       }
00451 
00452   // Register the function context and make sure it's known to not throw
00453   CallInst *Register =
00454       CallInst::Create(RegisterFn, FuncCtx, "", EntryBB->getTerminator());
00455   Register->setDoesNotThrow();
00456 
00457   // Following any allocas not in the entry block, update the saved SP in the
00458   // jmpbuf to the new value.
00459   for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
00460     if (BB == F.begin())
00461       continue;
00462     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
00463       if (CallInst *CI = dyn_cast<CallInst>(I)) {
00464         if (CI->getCalledFunction() != StackRestoreFn)
00465           continue;
00466       } else if (!isa<AllocaInst>(I)) {
00467         continue;
00468       }
00469       Instruction *StackAddr = CallInst::Create(StackAddrFn, "sp");
00470       StackAddr->insertAfter(I);
00471       Instruction *StoreStackAddr = new StoreInst(StackAddr, StackPtr, true);
00472       StoreStackAddr->insertAfter(StackAddr);
00473     }
00474   }
00475 
00476   // Finally, for any returns from this function, if this function contains an
00477   // invoke, add a call to unregister the function context.
00478   for (unsigned I = 0, E = Returns.size(); I != E; ++I)
00479     CallInst::Create(UnregisterFn, FuncCtx, "", Returns[I]);
00480 
00481   return true;
00482 }
00483 
00484 bool SjLjEHPrepare::runOnFunction(Function &F) {
00485   bool Res = setupEntryBlockAndCallSites(F);
00486   return Res;
00487 }