LLVM API Documentation

Main Page | Namespace List | Class Hierarchy | Alphabetical List | Class List | Directories | File List | Namespace Members | Class Members | File Members | Related Pages

LowerInvoke.cpp

Go to the documentation of this file.
00001 //===- LowerInvoke.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 do not yet
00011 // support stack unwinding.  This pass supports two models of exception handling
00012 // lowering, the 'cheap' support and the 'expensive' support.
00013 //
00014 // 'Cheap' exception handling support gives the program the ability to execute
00015 // any program which does not "throw an exception", by turning 'invoke'
00016 // instructions into calls and by turning 'unwind' instructions into calls to
00017 // abort().  If the program does dynamically use the unwind instruction, the
00018 // program will print a message then abort.
00019 //
00020 // 'Expensive' exception handling support gives the full exception handling
00021 // support to the program at the cost of making the 'invoke' instruction
00022 // really expensive.  It basically inserts setjmp/longjmp calls to emulate the
00023 // exception handling as necessary.
00024 //
00025 // Because the 'expensive' support slows down programs a lot, and EH is only
00026 // used for a subset of the programs, it must be specifically enabled by an
00027 // option.
00028 //
00029 // Note that after this pass runs the CFG is not entirely accurate (exceptional
00030 // control flow edges are not correct anymore) so only very simple things should
00031 // be done after the lowerinvoke pass has run (like generation of native code).
00032 // This should not be used as a general purpose "my LLVM-to-LLVM pass doesn't
00033 // support the invoke instruction yet" lowering pass.
00034 //
00035 //===----------------------------------------------------------------------===//
00036 
00037 #define DEBUG_TYPE "lowerinvoke"
00038 #include "llvm/Transforms/Scalar.h"
00039 #include "llvm/Constants.h"
00040 #include "llvm/DerivedTypes.h"
00041 #include "llvm/Instructions.h"
00042 #include "llvm/Intrinsics.h"
00043 #include "llvm/Module.h"
00044 #include "llvm/Pass.h"
00045 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
00046 #include "llvm/Transforms/Utils/Local.h"
00047 #include "llvm/ADT/Statistic.h"
00048 #include "llvm/Support/CommandLine.h"
00049 #include "llvm/Support/Compiler.h"
00050 #include "llvm/Target/TargetLowering.h"
00051 #include <csetjmp>
00052 #include <set>
00053 using namespace llvm;
00054 
00055 STATISTIC(NumInvokes, "Number of invokes replaced");
00056 STATISTIC(NumUnwinds, "Number of unwinds replaced");
00057 STATISTIC(NumSpilled, "Number of registers live across unwind edges");
00058 
00059 static cl::opt<bool> ExpensiveEHSupport("enable-correct-eh-support",
00060  cl::desc("Make the -lowerinvoke pass insert expensive, but correct, EH code"));
00061 
00062 namespace {
00063   class VISIBILITY_HIDDEN LowerInvoke : public FunctionPass {
00064     // Used for both models.
00065     Constant *WriteFn;
00066     Constant *AbortFn;
00067     Value *AbortMessage;
00068     unsigned AbortMessageLength;
00069 
00070     // Used for expensive EH support.
00071     const Type *JBLinkTy;
00072     GlobalVariable *JBListHead;
00073     Constant *SetJmpFn, *LongJmpFn;
00074     
00075     // We peek in TLI to grab the target's jmp_buf size and alignment
00076     const TargetLowering *TLI;
00077     
00078   public:
00079     static char ID; // Pass identification, replacement for typeid
00080     explicit LowerInvoke(const TargetLowering *tli = NULL)
00081       : FunctionPass(&ID), TLI(tli) { }
00082     bool doInitialization(Module &M);
00083     bool runOnFunction(Function &F);
00084  
00085     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
00086       // This is a cluster of orthogonal Transforms
00087       AU.addPreservedID(PromoteMemoryToRegisterID);
00088       AU.addPreservedID(LowerSwitchID);
00089       AU.addPreservedID(LowerAllocationsID);
00090     }
00091        
00092   private:
00093     void createAbortMessage(Module *M);
00094     void writeAbortMessage(Instruction *IB);
00095     bool insertCheapEHSupport(Function &F);
00096     void splitLiveRangesLiveAcrossInvokes(std::vector<InvokeInst*> &Invokes);
00097     void rewriteExpensiveInvoke(InvokeInst *II, unsigned InvokeNo,
00098                                 AllocaInst *InvokeNum, SwitchInst *CatchSwitch);
00099     bool insertExpensiveEHSupport(Function &F);
00100   };
00101 }
00102 
00103 char LowerInvoke::ID = 0;
00104 static RegisterPass<LowerInvoke>
00105 X("lowerinvoke", "Lower invoke and unwind, for unwindless code generators");
00106 
00107 const PassInfo *const llvm::LowerInvokePassID = &X;
00108 
00109 // Public Interface To the LowerInvoke pass.
00110 FunctionPass *llvm::createLowerInvokePass(const TargetLowering *TLI) { 
00111   return new LowerInvoke(TLI); 
00112 }
00113 
00114 // doInitialization - Make sure that there is a prototype for abort in the
00115 // current module.
00116 bool LowerInvoke::doInitialization(Module &M) {
00117   const Type *VoidPtrTy = PointerType::getUnqual(Type::Int8Ty);
00118   AbortMessage = 0;
00119   if (ExpensiveEHSupport) {
00120     // Insert a type for the linked list of jump buffers.
00121     unsigned JBSize = TLI ? TLI->getJumpBufSize() : 0;
00122     JBSize = JBSize ? JBSize : 200;
00123     const Type *JmpBufTy = ArrayType::get(VoidPtrTy, JBSize);
00124 
00125     { // The type is recursive, so use a type holder.
00126       std::vector<const Type*> Elements;
00127       Elements.push_back(JmpBufTy);
00128       OpaqueType *OT = OpaqueType::get();
00129       Elements.push_back(PointerType::getUnqual(OT));
00130       PATypeHolder JBLType(StructType::get(Elements));
00131       OT->refineAbstractTypeTo(JBLType.get());  // Complete the cycle.
00132       JBLinkTy = JBLType.get();
00133       M.addTypeName("llvm.sjljeh.jmpbufty", JBLinkTy);
00134     }
00135 
00136     const Type *PtrJBList = PointerType::getUnqual(JBLinkTy);
00137 
00138     // Now that we've done that, insert the jmpbuf list head global, unless it
00139     // already exists.
00140     if (!(JBListHead = M.getGlobalVariable("llvm.sjljeh.jblist", PtrJBList))) {
00141       JBListHead = new GlobalVariable(PtrJBList, false,
00142                                       GlobalValue::LinkOnceLinkage,
00143                                       Constant::getNullValue(PtrJBList),
00144                                       "llvm.sjljeh.jblist", &M);
00145     }
00146 
00147 // VisualStudio defines setjmp as _setjmp via #include <csetjmp> / <setjmp.h>, 
00148 // so it looks like Intrinsic::_setjmp
00149 #if defined(_MSC_VER) && defined(setjmp)
00150 #define setjmp_undefined_for_visual_studio
00151 #undef setjmp
00152 #endif
00153 
00154     SetJmpFn = Intrinsic::getDeclaration(&M, Intrinsic::setjmp);
00155 
00156 #if defined(_MSC_VER) && defined(setjmp_undefined_for_visual_studio)
00157 // let's return it to _setjmp state in case anyone ever needs it after this 
00158 // point under VisualStudio
00159 #define setjmp _setjmp 
00160 #endif
00161 
00162     LongJmpFn = Intrinsic::getDeclaration(&M, Intrinsic::longjmp);
00163   }
00164 
00165   // We need the 'write' and 'abort' functions for both models.
00166   AbortFn = M.getOrInsertFunction("abort", Type::VoidTy, (Type *)0);
00167 #if 0 // "write" is Unix-specific.. code is going away soon anyway.
00168   WriteFn = M.getOrInsertFunction("write", Type::VoidTy, Type::Int32Ty,
00169                                   VoidPtrTy, Type::Int32Ty, (Type *)0);
00170 #else
00171   WriteFn = 0;
00172 #endif
00173   return true;
00174 }
00175 
00176 void LowerInvoke::createAbortMessage(Module *M) {
00177   if (ExpensiveEHSupport) {
00178     // The abort message for expensive EH support tells the user that the
00179     // program 'unwound' without an 'invoke' instruction.
00180     Constant *Msg =
00181       ConstantArray::get("ERROR: Exception thrown, but not caught!\n");
00182     AbortMessageLength = Msg->getNumOperands()-1;  // don't include \0
00183 
00184     GlobalVariable *MsgGV = new GlobalVariable(Msg->getType(), true,
00185                                                GlobalValue::InternalLinkage,
00186                                                Msg, "abortmsg", M);
00187     std::vector<Constant*> GEPIdx(2, Constant::getNullValue(Type::Int32Ty));
00188     AbortMessage = ConstantExpr::getGetElementPtr(MsgGV, &GEPIdx[0], 2);
00189   } else {
00190     // The abort message for cheap EH support tells the user that EH is not
00191     // enabled.
00192     Constant *Msg =
00193       ConstantArray::get("Exception handler needed, but not enabled.  Recompile"
00194                          " program with -enable-correct-eh-support.\n");
00195     AbortMessageLength = Msg->getNumOperands()-1;  // don't include \0
00196 
00197     GlobalVariable *MsgGV = new GlobalVariable(Msg->getType(), true,
00198                                                GlobalValue::InternalLinkage,
00199                                                Msg, "abortmsg", M);
00200     std::vector<Constant*> GEPIdx(2, Constant::getNullValue(Type::Int32Ty));
00201     AbortMessage = ConstantExpr::getGetElementPtr(MsgGV, &GEPIdx[0], 2);
00202   }
00203 }
00204 
00205 
00206 void LowerInvoke::writeAbortMessage(Instruction *IB) {
00207 #if 0
00208   if (AbortMessage == 0)
00209     createAbortMessage(IB->getParent()->getParent()->getParent());
00210 
00211   // These are the arguments we WANT...
00212   Value* Args[3];
00213   Args[0] = ConstantInt::get(Type::Int32Ty, 2);
00214   Args[1] = AbortMessage;
00215   Args[2] = ConstantInt::get(Type::Int32Ty, AbortMessageLength);
00216   (new CallInst(WriteFn, Args, 3, "", IB))->setTailCall();
00217 #endif
00218 }
00219 
00220 bool LowerInvoke::insertCheapEHSupport(Function &F) {
00221   bool Changed = false;
00222   for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
00223     if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
00224       std::vector<Value*> CallArgs(II->op_begin()+3, II->op_end());
00225       // Insert a normal call instruction...
00226       CallInst *NewCall = CallInst::Create(II->getCalledValue(),
00227                                            CallArgs.begin(), CallArgs.end(), "",II);
00228       NewCall->takeName(II);
00229       NewCall->setCallingConv(II->getCallingConv());
00230       NewCall->setParamAttrs(II->getParamAttrs());
00231       II->replaceAllUsesWith(NewCall);
00232 
00233       // Insert an unconditional branch to the normal destination.
00234       BranchInst::Create(II->getNormalDest(), II);
00235 
00236       // Remove any PHI node entries from the exception destination.
00237       II->getUnwindDest()->removePredecessor(BB);
00238 
00239       // Remove the invoke instruction now.
00240       BB->getInstList().erase(II);
00241 
00242       ++NumInvokes; Changed = true;
00243     } else if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->getTerminator())) {
00244       // Insert a new call to write(2, AbortMessage, AbortMessageLength);
00245       writeAbortMessage(UI);
00246 
00247       // Insert a call to abort()
00248       CallInst::Create(AbortFn, "", UI)->setTailCall();
00249 
00250       // Insert a return instruction.  This really should be a "barrier", as it
00251       // is unreachable.
00252       ReturnInst::Create(F.getReturnType() == Type::VoidTy ? 0 :
00253                          Constant::getNullValue(F.getReturnType()), UI);
00254 
00255       // Remove the unwind instruction now.
00256       BB->getInstList().erase(UI);
00257 
00258       ++NumUnwinds; Changed = true;
00259     }
00260   return Changed;
00261 }
00262 
00263 /// rewriteExpensiveInvoke - Insert code and hack the function to replace the
00264 /// specified invoke instruction with a call.
00265 void LowerInvoke::rewriteExpensiveInvoke(InvokeInst *II, unsigned InvokeNo,
00266                                          AllocaInst *InvokeNum,
00267                                          SwitchInst *CatchSwitch) {
00268   ConstantInt *InvokeNoC = ConstantInt::get(Type::Int32Ty, InvokeNo);
00269 
00270   // If the unwind edge has phi nodes, split the edge.
00271   if (isa<PHINode>(II->getUnwindDest()->begin())) {
00272     SplitCriticalEdge(II, 1, this);
00273    
00274     // If there are any phi nodes left, they must have a single predecessor.
00275     while (PHINode *PN = dyn_cast<PHINode>(II->getUnwindDest()->begin())) {
00276       PN->replaceAllUsesWith(PN->getIncomingValue(0));
00277       PN->eraseFromParent();
00278     }
00279   }
00280   
00281   // Insert a store of the invoke num before the invoke and store zero into the
00282   // location afterward.
00283   new StoreInst(InvokeNoC, InvokeNum, true, II);  // volatile
00284   
00285   BasicBlock::iterator NI = II->getNormalDest()->getFirstNonPHI();
00286   // nonvolatile.
00287   new StoreInst(Constant::getNullValue(Type::Int32Ty), InvokeNum, false, NI);
00288   
00289   // Add a switch case to our unwind block.
00290   CatchSwitch->addCase(InvokeNoC, II->getUnwindDest());
00291   
00292   // Insert a normal call instruction.
00293   std::vector<Value*> CallArgs(II->op_begin()+3, II->op_end());
00294   CallInst *NewCall = CallInst::Create(II->getCalledValue(),
00295                                        CallArgs.begin(), CallArgs.end(), "",
00296                                        II);
00297   NewCall->takeName(II);
00298   NewCall->setCallingConv(II->getCallingConv());
00299   NewCall->setParamAttrs(II->getParamAttrs());
00300   II->replaceAllUsesWith(NewCall);
00301   
00302   // Replace the invoke with an uncond branch.
00303   BranchInst::Create(II->getNormalDest(), NewCall->getParent());
00304   II->eraseFromParent();
00305 }
00306 
00307 /// MarkBlocksLiveIn - Insert BB and all of its predescessors into LiveBBs until
00308 /// we reach blocks we've already seen.
00309 static void MarkBlocksLiveIn(BasicBlock *BB, std::set<BasicBlock*> &LiveBBs) {
00310   if (!LiveBBs.insert(BB).second) return; // already been here.
00311   
00312   for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
00313     MarkBlocksLiveIn(*PI, LiveBBs);  
00314 }
00315 
00316 // First thing we need to do is scan the whole function for values that are
00317 // live across unwind edges.  Each value that is live across an unwind edge
00318 // we spill into a stack location, guaranteeing that there is nothing live
00319 // across the unwind edge.  This process also splits all critical edges
00320 // coming out of invoke's.
00321 void LowerInvoke::
00322 splitLiveRangesLiveAcrossInvokes(std::vector<InvokeInst*> &Invokes) {
00323   // First step, split all critical edges from invoke instructions.
00324   for (unsigned i = 0, e = Invokes.size(); i != e; ++i) {
00325     InvokeInst *II = Invokes[i];
00326     SplitCriticalEdge(II, 0, this);
00327     SplitCriticalEdge(II, 1, this);
00328     assert(!isa<PHINode>(II->getNormalDest()) &&
00329            !isa<PHINode>(II->getUnwindDest()) &&
00330            "critical edge splitting left single entry phi nodes?");
00331   }
00332 
00333   Function *F = Invokes.back()->getParent()->getParent();
00334   
00335   // To avoid having to handle incoming arguments specially, we lower each arg
00336   // to a copy instruction in the entry block.  This ensures that the argument
00337   // value itself cannot be live across the entry block.
00338   BasicBlock::iterator AfterAllocaInsertPt = F->begin()->begin();
00339   while (isa<AllocaInst>(AfterAllocaInsertPt) &&
00340         isa<ConstantInt>(cast<AllocaInst>(AfterAllocaInsertPt)->getArraySize()))
00341     ++AfterAllocaInsertPt;
00342   for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
00343        AI != E; ++AI) {
00344     // This is always a no-op cast because we're casting AI to AI->getType() so
00345     // src and destination types are identical. BitCast is the only possibility.
00346     CastInst *NC = new BitCastInst(
00347       AI, AI->getType(), AI->getName()+".tmp", AfterAllocaInsertPt);
00348     AI->replaceAllUsesWith(NC);
00349     // Normally its is forbidden to replace a CastInst's operand because it
00350     // could cause the opcode to reflect an illegal conversion. However, we're
00351     // replacing it here with the same value it was constructed with to simply
00352     // make NC its user.
00353     NC->setOperand(0, AI); 
00354   }
00355   
00356   // Finally, scan the code looking for instructions with bad live ranges.
00357   for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
00358     for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E; ++II) {
00359       // Ignore obvious cases we don't have to handle.  In particular, most
00360       // instructions either have no uses or only have a single use inside the
00361       // current block.  Ignore them quickly.
00362       Instruction *Inst = II;
00363       if (Inst->use_empty()) continue;
00364       if (Inst->hasOneUse() &&
00365           cast<Instruction>(Inst->use_back())->getParent() == BB &&
00366           !isa<PHINode>(Inst->use_back())) continue;
00367       
00368       // If this is an alloca in the entry block, it's not a real register
00369       // value.
00370       if (AllocaInst *AI = dyn_cast<AllocaInst>(Inst))
00371         if (isa<ConstantInt>(AI->getArraySize()) && BB == F->begin())
00372           continue;
00373       
00374       // Avoid iterator invalidation by copying users to a temporary vector.
00375       std::vector<Instruction*> Users;
00376       for (Value::use_iterator UI = Inst->use_begin(), E = Inst->use_end();
00377            UI != E; ++UI) {
00378         Instruction *User = cast<Instruction>(*UI);
00379         if (User->getParent() != BB || isa<PHINode>(User))
00380           Users.push_back(User);
00381       }
00382 
00383       // Scan all of the uses and see if the live range is live across an unwind
00384       // edge.  If we find a use live across an invoke edge, create an alloca
00385       // and spill the value.
00386       std::set<InvokeInst*> InvokesWithStoreInserted;
00387 
00388       // Find all of the blocks that this value is live in.
00389       std::set<BasicBlock*> LiveBBs;
00390       LiveBBs.insert(Inst->getParent());
00391       while (!Users.empty()) {
00392         Instruction *U = Users.back();
00393         Users.pop_back();
00394         
00395         if (!isa<PHINode>(U)) {
00396           MarkBlocksLiveIn(U->getParent(), LiveBBs);
00397         } else {
00398           // Uses for a PHI node occur in their predecessor block.
00399           PHINode *PN = cast<PHINode>(U);
00400           for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
00401             if (PN->getIncomingValue(i) == Inst)
00402               MarkBlocksLiveIn(PN->getIncomingBlock(i), LiveBBs);
00403         }
00404       }
00405       
00406       // Now that we know all of the blocks that this thing is live in, see if
00407       // it includes any of the unwind locations.
00408       bool NeedsSpill = false;
00409       for (unsigned i = 0, e = Invokes.size(); i != e; ++i) {
00410         BasicBlock *UnwindBlock = Invokes[i]->getUnwindDest();
00411         if (UnwindBlock != BB && LiveBBs.count(UnwindBlock)) {
00412           NeedsSpill = true;
00413         }
00414       }
00415 
00416       // If we decided we need a spill, do it.
00417       if (NeedsSpill) {
00418         ++NumSpilled;
00419         DemoteRegToStack(*Inst, true);
00420       }
00421     }
00422 }
00423 
00424 bool LowerInvoke::insertExpensiveEHSupport(Function &F) {
00425   std::vector<ReturnInst*> Returns;
00426   std::vector<UnwindInst*> Unwinds;
00427   std::vector<InvokeInst*> Invokes;
00428 
00429   for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
00430     if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
00431       // Remember all return instructions in case we insert an invoke into this
00432       // function.
00433       Returns.push_back(RI);
00434     } else if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
00435       Invokes.push_back(II);
00436     } else if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->getTerminator())) {
00437       Unwinds.push_back(UI);
00438     }
00439 
00440   if (Unwinds.empty() && Invokes.empty()) return false;
00441 
00442   NumInvokes += Invokes.size();
00443   NumUnwinds += Unwinds.size();
00444   
00445   // TODO: This is not an optimal way to do this.  In particular, this always
00446   // inserts setjmp calls into the entries of functions with invoke instructions
00447   // even though there are possibly paths through the function that do not
00448   // execute any invokes.  In particular, for functions with early exits, e.g.
00449   // the 'addMove' method in hexxagon, it would be nice to not have to do the
00450   // setjmp stuff on the early exit path.  This requires a bit of dataflow, but
00451   // would not be too hard to do.
00452 
00453   // If we have an invoke instruction, insert a setjmp that dominates all
00454   // invokes.  After the setjmp, use a cond branch that goes to the original
00455   // code path on zero, and to a designated 'catch' block of nonzero.
00456   Value *OldJmpBufPtr = 0;
00457   if (!Invokes.empty()) {
00458     // First thing we need to do is scan the whole function for values that are
00459     // live across unwind edges.  Each value that is live across an unwind edge
00460     // we spill into a stack location, guaranteeing that there is nothing live
00461     // across the unwind edge.  This process also splits all critical edges
00462     // coming out of invoke's.
00463     splitLiveRangesLiveAcrossInvokes(Invokes);    
00464     
00465     BasicBlock *EntryBB = F.begin();
00466     
00467     // Create an alloca for the incoming jump buffer ptr and the new jump buffer
00468     // that needs to be restored on all exits from the function.  This is an
00469     // alloca because the value needs to be live across invokes.
00470     unsigned Align = TLI ? TLI->getJumpBufAlignment() : 0;
00471     AllocaInst *JmpBuf = 
00472       new AllocaInst(JBLinkTy, 0, Align, "jblink", F.begin()->begin());
00473     
00474     std::vector<Value*> Idx;
00475     Idx.push_back(Constant::getNullValue(Type::Int32Ty));
00476     Idx.push_back(ConstantInt::get(Type::Int32Ty, 1));
00477     OldJmpBufPtr = GetElementPtrInst::Create(JmpBuf, Idx.begin(), Idx.end(),
00478                                              "OldBuf", EntryBB->getTerminator());
00479 
00480     // Copy the JBListHead to the alloca.
00481     Value *OldBuf = new LoadInst(JBListHead, "oldjmpbufptr", true,
00482                                  EntryBB->getTerminator());
00483     new StoreInst(OldBuf, OldJmpBufPtr, true, EntryBB->getTerminator());
00484     
00485     // Add the new jumpbuf to the list.
00486     new StoreInst(JmpBuf, JBListHead, true, EntryBB->getTerminator());
00487 
00488     // Create the catch block.  The catch block is basically a big switch
00489     // statement that goes to all of the invoke catch blocks.
00490     BasicBlock *CatchBB = BasicBlock::Create("setjmp.catch", &F);
00491     
00492     // Create an alloca which keeps track of which invoke is currently
00493     // executing.  For normal calls it contains zero.
00494     AllocaInst *InvokeNum = new AllocaInst(Type::Int32Ty, 0, "invokenum",
00495                                            EntryBB->begin());
00496     new StoreInst(ConstantInt::get(Type::Int32Ty, 0), InvokeNum, true,
00497                   EntryBB->getTerminator());
00498     
00499     // Insert a load in the Catch block, and a switch on its value.  By default,
00500     // we go to a block that just does an unwind (which is the correct action
00501     // for a standard call).
00502     BasicBlock *UnwindBB = BasicBlock::Create("unwindbb", &F);
00503     Unwinds.push_back(new UnwindInst(UnwindBB));
00504     
00505     Value *CatchLoad = new LoadInst(InvokeNum, "invoke.num", true, CatchBB);
00506     SwitchInst *CatchSwitch =
00507       SwitchInst::Create(CatchLoad, UnwindBB, Invokes.size(), CatchBB);
00508 
00509     // Now that things are set up, insert the setjmp call itself.
00510     
00511     // Split the entry block to insert the conditional branch for the setjmp.
00512     BasicBlock *ContBlock = EntryBB->splitBasicBlock(EntryBB->getTerminator(),
00513                                                      "setjmp.cont");
00514 
00515     Idx[1] = ConstantInt::get(Type::Int32Ty, 0);
00516     Value *JmpBufPtr = GetElementPtrInst::Create(JmpBuf, Idx.begin(), Idx.end(),
00517                                                  "TheJmpBuf",
00518                                                  EntryBB->getTerminator());
00519     JmpBufPtr = new BitCastInst(JmpBufPtr, PointerType::getUnqual(Type::Int8Ty),
00520                                 "tmp", EntryBB->getTerminator());
00521     Value *SJRet = CallInst::Create(SetJmpFn, JmpBufPtr, "sjret",
00522                                     EntryBB->getTerminator());
00523 
00524     // Compare the return value to zero.
00525     Value *IsNormal = new ICmpInst(ICmpInst::ICMP_EQ, SJRet, 
00526                                    Constant::getNullValue(SJRet->getType()),
00527       "notunwind", EntryBB->getTerminator());
00528     // Nuke the uncond branch.
00529     EntryBB->getTerminator()->eraseFromParent();
00530     
00531     // Put in a new condbranch in its place.
00532     BranchInst::Create(ContBlock, CatchBB, IsNormal, EntryBB);
00533 
00534     // At this point, we are all set up, rewrite each invoke instruction.
00535     for (unsigned i = 0, e = Invokes.size(); i != e; ++i)
00536       rewriteExpensiveInvoke(Invokes[i], i+1, InvokeNum, CatchSwitch);
00537   }
00538 
00539   // We know that there is at least one unwind.
00540   
00541   // Create three new blocks, the block to load the jmpbuf ptr and compare
00542   // against null, the block to do the longjmp, and the error block for if it
00543   // is null.  Add them at the end of the function because they are not hot.
00544   BasicBlock *UnwindHandler = BasicBlock::Create("dounwind", &F);
00545   BasicBlock *UnwindBlock = BasicBlock::Create("unwind", &F);
00546   BasicBlock *TermBlock = BasicBlock::Create("unwinderror", &F);
00547 
00548   // If this function contains an invoke, restore the old jumpbuf ptr.
00549   Value *BufPtr;
00550   if (OldJmpBufPtr) {
00551     // Before the return, insert a copy from the saved value to the new value.
00552     BufPtr = new LoadInst(OldJmpBufPtr, "oldjmpbufptr", UnwindHandler);
00553     new StoreInst(BufPtr, JBListHead, UnwindHandler);
00554   } else {
00555     BufPtr = new LoadInst(JBListHead, "ehlist", UnwindHandler);
00556   }
00557   
00558   // Load the JBList, if it's null, then there was no catch!
00559   Value *NotNull = new ICmpInst(ICmpInst::ICMP_NE, BufPtr, 
00560                                 Constant::getNullValue(BufPtr->getType()),
00561     "notnull", UnwindHandler);
00562   BranchInst::Create(UnwindBlock, TermBlock, NotNull, UnwindHandler);
00563   
00564   // Create the block to do the longjmp.
00565   // Get a pointer to the jmpbuf and longjmp.
00566   std::vector<Value*> Idx;
00567   Idx.push_back(Constant::getNullValue(Type::Int32Ty));
00568   Idx.push_back(ConstantInt::get(Type::Int32Ty, 0));
00569   Idx[0] = GetElementPtrInst::Create(BufPtr, Idx.begin(), Idx.end(), "JmpBuf",
00570                                      UnwindBlock);
00571   Idx[0] = new BitCastInst(Idx[0], PointerType::getUnqual(Type::Int8Ty),
00572                            "tmp", UnwindBlock);
00573   Idx[1] = ConstantInt::get(Type::Int32Ty, 1);
00574   CallInst::Create(LongJmpFn, Idx.begin(), Idx.end(), "", UnwindBlock);
00575   new UnreachableInst(UnwindBlock);
00576   
00577   // Set up the term block ("throw without a catch").
00578   new UnreachableInst(TermBlock);
00579 
00580   // Insert a new call to write(2, AbortMessage, AbortMessageLength);
00581   writeAbortMessage(TermBlock->getTerminator());
00582   
00583   // Insert a call to abort()
00584   CallInst::Create(AbortFn, "",
00585                    TermBlock->getTerminator())->setTailCall();
00586     
00587   
00588   // Replace all unwinds with a branch to the unwind handler.
00589   for (unsigned i = 0, e = Unwinds.size(); i != e; ++i) {
00590     BranchInst::Create(UnwindHandler, Unwinds[i]);
00591     Unwinds[i]->eraseFromParent();    
00592   } 
00593   
00594   // Finally, for any returns from this function, if this function contains an
00595   // invoke, restore the old jmpbuf pointer to its input value.
00596   if (OldJmpBufPtr) {
00597     for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
00598       ReturnInst *R = Returns[i];
00599       
00600       // Before the return, insert a copy from the saved value to the new value.
00601       Value *OldBuf = new LoadInst(OldJmpBufPtr, "oldjmpbufptr", true, R);
00602       new StoreInst(OldBuf, JBListHead, true, R);
00603     }
00604   }
00605   
00606   return true;
00607 }
00608 
00609 bool LowerInvoke::runOnFunction(Function &F) {
00610   if (ExpensiveEHSupport)
00611     return insertExpensiveEHSupport(F);
00612   else
00613     return insertCheapEHSupport(F);
00614 }



This web site is hosted by the Computer Science Department at the University of Illinois at Urbana-Champaign.