LowerInvoke.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629
  1. //===- LowerInvoke.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 do not yet
  11. // support stack unwinding. This pass supports two models of exception handling
  12. // lowering, the 'cheap' support and the 'expensive' support.
  13. //
  14. // 'Cheap' exception handling support gives the program the ability to execute
  15. // any program which does not "throw an exception", by turning 'invoke'
  16. // instructions into calls and by turning 'unwind' instructions into calls to
  17. // abort(). If the program does dynamically use the unwind instruction, the
  18. // program will print a message then abort.
  19. //
  20. // 'Expensive' exception handling support gives the full exception handling
  21. // support to the program at the cost of making the 'invoke' instruction
  22. // really expensive. It basically inserts setjmp/longjmp calls to emulate the
  23. // exception handling as necessary.
  24. //
  25. // Because the 'expensive' support slows down programs a lot, and EH is only
  26. // used for a subset of the programs, it must be specifically enabled by an
  27. // option.
  28. //
  29. // Note that after this pass runs the CFG is not entirely accurate (exceptional
  30. // control flow edges are not correct anymore) so only very simple things should
  31. // be done after the lowerinvoke pass has run (like generation of native code).
  32. // This should not be used as a general purpose "my LLVM-to-LLVM pass doesn't
  33. // support the invoke instruction yet" lowering pass.
  34. //
  35. //===----------------------------------------------------------------------===//
  36. #define DEBUG_TYPE "lowerinvoke"
  37. #include "llvm/Transforms/Scalar.h"
  38. #include "llvm/Constants.h"
  39. #include "llvm/DerivedTypes.h"
  40. #include "llvm/Instructions.h"
  41. #include "llvm/Intrinsics.h"
  42. #include "llvm/LLVMContext.h"
  43. #include "llvm/Module.h"
  44. #include "llvm/Pass.h"
  45. #include "llvm/Transforms/Utils/BasicBlockUtils.h"
  46. #include "llvm/Transforms/Utils/Local.h"
  47. #include "llvm/ADT/Statistic.h"
  48. #include "llvm/Support/CommandLine.h"
  49. #include "llvm/Target/TargetLowering.h"
  50. #include <csetjmp>
  51. #include <set>
  52. using namespace llvm;
  53. STATISTIC(NumInvokes, "Number of invokes replaced");
  54. STATISTIC(NumUnwinds, "Number of unwinds replaced");
  55. STATISTIC(NumSpilled, "Number of registers live across unwind edges");
  56. static cl::opt<bool> ExpensiveEHSupport("enable-correct-eh-support",
  57. cl::desc("Make the -lowerinvoke pass insert expensive, but correct, EH code"));
  58. namespace {
  59. class LowerInvoke : public FunctionPass {
  60. // Used for both models.
  61. Constant *WriteFn;
  62. Constant *AbortFn;
  63. Value *AbortMessage;
  64. unsigned AbortMessageLength;
  65. // Used for expensive EH support.
  66. const Type *JBLinkTy;
  67. GlobalVariable *JBListHead;
  68. Constant *SetJmpFn, *LongJmpFn;
  69. // We peek in TLI to grab the target's jmp_buf size and alignment
  70. const TargetLowering *TLI;
  71. public:
  72. static char ID; // Pass identification, replacement for typeid
  73. explicit LowerInvoke(const TargetLowering *tli = NULL)
  74. : FunctionPass(&ID), TLI(tli) { }
  75. bool doInitialization(Module &M);
  76. bool runOnFunction(Function &F);
  77. virtual void getAnalysisUsage(AnalysisUsage &AU) const {
  78. // This is a cluster of orthogonal Transforms
  79. AU.addPreservedID(PromoteMemoryToRegisterID);
  80. AU.addPreservedID(LowerSwitchID);
  81. }
  82. private:
  83. void createAbortMessage(Module *M);
  84. void writeAbortMessage(Instruction *IB);
  85. bool insertCheapEHSupport(Function &F);
  86. void splitLiveRangesLiveAcrossInvokes(std::vector<InvokeInst*> &Invokes);
  87. void rewriteExpensiveInvoke(InvokeInst *II, unsigned InvokeNo,
  88. AllocaInst *InvokeNum, SwitchInst *CatchSwitch);
  89. bool insertExpensiveEHSupport(Function &F);
  90. };
  91. }
  92. char LowerInvoke::ID = 0;
  93. static RegisterPass<LowerInvoke>
  94. X("lowerinvoke", "Lower invoke and unwind, for unwindless code generators");
  95. const PassInfo *const llvm::LowerInvokePassID = &X;
  96. // Public Interface To the LowerInvoke pass.
  97. FunctionPass *llvm::createLowerInvokePass(const TargetLowering *TLI) {
  98. return new LowerInvoke(TLI);
  99. }
  100. // doInitialization - Make sure that there is a prototype for abort in the
  101. // current module.
  102. bool LowerInvoke::doInitialization(Module &M) {
  103. const Type *VoidPtrTy =
  104. Type::getInt8PtrTy(M.getContext());
  105. AbortMessage = 0;
  106. if (ExpensiveEHSupport) {
  107. // Insert a type for the linked list of jump buffers.
  108. unsigned JBSize = TLI ? TLI->getJumpBufSize() : 0;
  109. JBSize = JBSize ? JBSize : 200;
  110. const Type *JmpBufTy = ArrayType::get(VoidPtrTy, JBSize);
  111. { // The type is recursive, so use a type holder.
  112. std::vector<const Type*> Elements;
  113. Elements.push_back(JmpBufTy);
  114. OpaqueType *OT = OpaqueType::get(M.getContext());
  115. Elements.push_back(PointerType::getUnqual(OT));
  116. PATypeHolder JBLType(StructType::get(M.getContext(), Elements));
  117. OT->refineAbstractTypeTo(JBLType.get()); // Complete the cycle.
  118. JBLinkTy = JBLType.get();
  119. M.addTypeName("llvm.sjljeh.jmpbufty", JBLinkTy);
  120. }
  121. const Type *PtrJBList = PointerType::getUnqual(JBLinkTy);
  122. // Now that we've done that, insert the jmpbuf list head global, unless it
  123. // already exists.
  124. if (!(JBListHead = M.getGlobalVariable("llvm.sjljeh.jblist", PtrJBList))) {
  125. JBListHead = new GlobalVariable(M, PtrJBList, false,
  126. GlobalValue::LinkOnceAnyLinkage,
  127. Constant::getNullValue(PtrJBList),
  128. "llvm.sjljeh.jblist");
  129. }
  130. // VisualStudio defines setjmp as _setjmp via #include <csetjmp> / <setjmp.h>,
  131. // so it looks like Intrinsic::_setjmp
  132. #if defined(_MSC_VER) && defined(setjmp)
  133. #define setjmp_undefined_for_visual_studio
  134. #undef setjmp
  135. #endif
  136. SetJmpFn = Intrinsic::getDeclaration(&M, Intrinsic::setjmp);
  137. #if defined(_MSC_VER) && defined(setjmp_undefined_for_visual_studio)
  138. // let's return it to _setjmp state in case anyone ever needs it after this
  139. // point under VisualStudio
  140. #define setjmp _setjmp
  141. #endif
  142. LongJmpFn = Intrinsic::getDeclaration(&M, Intrinsic::longjmp);
  143. }
  144. // We need the 'write' and 'abort' functions for both models.
  145. AbortFn = M.getOrInsertFunction("abort", Type::getVoidTy(M.getContext()),
  146. (Type *)0);
  147. #if 0 // "write" is Unix-specific.. code is going away soon anyway.
  148. WriteFn = M.getOrInsertFunction("write", Type::VoidTy, Type::Int32Ty,
  149. VoidPtrTy, Type::Int32Ty, (Type *)0);
  150. #else
  151. WriteFn = 0;
  152. #endif
  153. return true;
  154. }
  155. void LowerInvoke::createAbortMessage(Module *M) {
  156. if (ExpensiveEHSupport) {
  157. // The abort message for expensive EH support tells the user that the
  158. // program 'unwound' without an 'invoke' instruction.
  159. Constant *Msg =
  160. ConstantArray::get(M->getContext(),
  161. "ERROR: Exception thrown, but not caught!\n");
  162. AbortMessageLength = Msg->getNumOperands()-1; // don't include \0
  163. GlobalVariable *MsgGV = new GlobalVariable(*M, Msg->getType(), true,
  164. GlobalValue::InternalLinkage,
  165. Msg, "abortmsg");
  166. std::vector<Constant*> GEPIdx(2,
  167. Constant::getNullValue(Type::getInt32Ty(M->getContext())));
  168. AbortMessage = ConstantExpr::getGetElementPtr(MsgGV, &GEPIdx[0], 2);
  169. } else {
  170. // The abort message for cheap EH support tells the user that EH is not
  171. // enabled.
  172. Constant *Msg =
  173. ConstantArray::get(M->getContext(),
  174. "Exception handler needed, but not enabled."
  175. "Recompile program with -enable-correct-eh-support.\n");
  176. AbortMessageLength = Msg->getNumOperands()-1; // don't include \0
  177. GlobalVariable *MsgGV = new GlobalVariable(*M, Msg->getType(), true,
  178. GlobalValue::InternalLinkage,
  179. Msg, "abortmsg");
  180. std::vector<Constant*> GEPIdx(2, Constant::getNullValue(
  181. Type::getInt32Ty(M->getContext())));
  182. AbortMessage = ConstantExpr::getGetElementPtr(MsgGV, &GEPIdx[0], 2);
  183. }
  184. }
  185. void LowerInvoke::writeAbortMessage(Instruction *IB) {
  186. #if 0
  187. if (AbortMessage == 0)
  188. createAbortMessage(IB->getParent()->getParent()->getParent());
  189. // These are the arguments we WANT...
  190. Value* Args[3];
  191. Args[0] = ConstantInt::get(Type::Int32Ty, 2);
  192. Args[1] = AbortMessage;
  193. Args[2] = ConstantInt::get(Type::Int32Ty, AbortMessageLength);
  194. (new CallInst(WriteFn, Args, 3, "", IB))->setTailCall();
  195. #endif
  196. }
  197. bool LowerInvoke::insertCheapEHSupport(Function &F) {
  198. bool Changed = false;
  199. for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
  200. if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
  201. std::vector<Value*> CallArgs(II->op_begin(), II->op_end() - 3);
  202. // Insert a normal call instruction...
  203. CallInst *NewCall = CallInst::Create(II->getCalledValue(),
  204. CallArgs.begin(), CallArgs.end(), "",II);
  205. NewCall->takeName(II);
  206. NewCall->setCallingConv(II->getCallingConv());
  207. NewCall->setAttributes(II->getAttributes());
  208. II->replaceAllUsesWith(NewCall);
  209. // Insert an unconditional branch to the normal destination.
  210. BranchInst::Create(II->getNormalDest(), II);
  211. // Remove any PHI node entries from the exception destination.
  212. II->getUnwindDest()->removePredecessor(BB);
  213. // Remove the invoke instruction now.
  214. BB->getInstList().erase(II);
  215. ++NumInvokes; Changed = true;
  216. } else if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->getTerminator())) {
  217. // Insert a new call to write(2, AbortMessage, AbortMessageLength);
  218. writeAbortMessage(UI);
  219. // Insert a call to abort()
  220. CallInst::Create(AbortFn, "", UI)->setTailCall();
  221. // Insert a return instruction. This really should be a "barrier", as it
  222. // is unreachable.
  223. ReturnInst::Create(F.getContext(),
  224. F.getReturnType()->isVoidTy() ?
  225. 0 : Constant::getNullValue(F.getReturnType()), UI);
  226. // Remove the unwind instruction now.
  227. BB->getInstList().erase(UI);
  228. ++NumUnwinds; Changed = true;
  229. }
  230. return Changed;
  231. }
  232. /// rewriteExpensiveInvoke - Insert code and hack the function to replace the
  233. /// specified invoke instruction with a call.
  234. void LowerInvoke::rewriteExpensiveInvoke(InvokeInst *II, unsigned InvokeNo,
  235. AllocaInst *InvokeNum,
  236. SwitchInst *CatchSwitch) {
  237. ConstantInt *InvokeNoC = ConstantInt::get(Type::getInt32Ty(II->getContext()),
  238. InvokeNo);
  239. // If the unwind edge has phi nodes, split the edge.
  240. if (isa<PHINode>(II->getUnwindDest()->begin())) {
  241. SplitCriticalEdge(II, 1, this);
  242. // If there are any phi nodes left, they must have a single predecessor.
  243. while (PHINode *PN = dyn_cast<PHINode>(II->getUnwindDest()->begin())) {
  244. PN->replaceAllUsesWith(PN->getIncomingValue(0));
  245. PN->eraseFromParent();
  246. }
  247. }
  248. // Insert a store of the invoke num before the invoke and store zero into the
  249. // location afterward.
  250. new StoreInst(InvokeNoC, InvokeNum, true, II); // volatile
  251. BasicBlock::iterator NI = II->getNormalDest()->getFirstNonPHI();
  252. // nonvolatile.
  253. new StoreInst(Constant::getNullValue(Type::getInt32Ty(II->getContext())),
  254. InvokeNum, false, NI);
  255. // Add a switch case to our unwind block.
  256. CatchSwitch->addCase(InvokeNoC, II->getUnwindDest());
  257. // Insert a normal call instruction.
  258. std::vector<Value*> CallArgs(II->op_begin(), II->op_end() - 3);
  259. CallInst *NewCall = CallInst::Create(II->getCalledValue(),
  260. CallArgs.begin(), CallArgs.end(), "",
  261. II);
  262. NewCall->takeName(II);
  263. NewCall->setCallingConv(II->getCallingConv());
  264. NewCall->setAttributes(II->getAttributes());
  265. II->replaceAllUsesWith(NewCall);
  266. // Replace the invoke with an uncond branch.
  267. BranchInst::Create(II->getNormalDest(), NewCall->getParent());
  268. II->eraseFromParent();
  269. }
  270. /// MarkBlocksLiveIn - Insert BB and all of its predescessors into LiveBBs until
  271. /// we reach blocks we've already seen.
  272. static void MarkBlocksLiveIn(BasicBlock *BB, std::set<BasicBlock*> &LiveBBs) {
  273. if (!LiveBBs.insert(BB).second) return; // already been here.
  274. for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
  275. MarkBlocksLiveIn(*PI, LiveBBs);
  276. }
  277. // First thing we need to do is scan the whole function for values that are
  278. // live across unwind edges. Each value that is live across an unwind edge
  279. // we spill into a stack location, guaranteeing that there is nothing live
  280. // across the unwind edge. This process also splits all critical edges
  281. // coming out of invoke's.
  282. void LowerInvoke::
  283. splitLiveRangesLiveAcrossInvokes(std::vector<InvokeInst*> &Invokes) {
  284. // First step, split all critical edges from invoke instructions.
  285. for (unsigned i = 0, e = Invokes.size(); i != e; ++i) {
  286. InvokeInst *II = Invokes[i];
  287. SplitCriticalEdge(II, 0, this);
  288. SplitCriticalEdge(II, 1, this);
  289. assert(!isa<PHINode>(II->getNormalDest()) &&
  290. !isa<PHINode>(II->getUnwindDest()) &&
  291. "critical edge splitting left single entry phi nodes?");
  292. }
  293. Function *F = Invokes.back()->getParent()->getParent();
  294. // To avoid having to handle incoming arguments specially, we lower each arg
  295. // to a copy instruction in the entry block. This ensures that the argument
  296. // value itself cannot be live across the entry block.
  297. BasicBlock::iterator AfterAllocaInsertPt = F->begin()->begin();
  298. while (isa<AllocaInst>(AfterAllocaInsertPt) &&
  299. isa<ConstantInt>(cast<AllocaInst>(AfterAllocaInsertPt)->getArraySize()))
  300. ++AfterAllocaInsertPt;
  301. for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
  302. AI != E; ++AI) {
  303. // This is always a no-op cast because we're casting AI to AI->getType() so
  304. // src and destination types are identical. BitCast is the only possibility.
  305. CastInst *NC = new BitCastInst(
  306. AI, AI->getType(), AI->getName()+".tmp", AfterAllocaInsertPt);
  307. AI->replaceAllUsesWith(NC);
  308. // Normally its is forbidden to replace a CastInst's operand because it
  309. // could cause the opcode to reflect an illegal conversion. However, we're
  310. // replacing it here with the same value it was constructed with to simply
  311. // make NC its user.
  312. NC->setOperand(0, AI);
  313. }
  314. // Finally, scan the code looking for instructions with bad live ranges.
  315. for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
  316. for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E; ++II) {
  317. // Ignore obvious cases we don't have to handle. In particular, most
  318. // instructions either have no uses or only have a single use inside the
  319. // current block. Ignore them quickly.
  320. Instruction *Inst = II;
  321. if (Inst->use_empty()) continue;
  322. if (Inst->hasOneUse() &&
  323. cast<Instruction>(Inst->use_back())->getParent() == BB &&
  324. !isa<PHINode>(Inst->use_back())) continue;
  325. // If this is an alloca in the entry block, it's not a real register
  326. // value.
  327. if (AllocaInst *AI = dyn_cast<AllocaInst>(Inst))
  328. if (isa<ConstantInt>(AI->getArraySize()) && BB == F->begin())
  329. continue;
  330. // Avoid iterator invalidation by copying users to a temporary vector.
  331. std::vector<Instruction*> Users;
  332. for (Value::use_iterator UI = Inst->use_begin(), E = Inst->use_end();
  333. UI != E; ++UI) {
  334. Instruction *User = cast<Instruction>(*UI);
  335. if (User->getParent() != BB || isa<PHINode>(User))
  336. Users.push_back(User);
  337. }
  338. // Scan all of the uses and see if the live range is live across an unwind
  339. // edge. If we find a use live across an invoke edge, create an alloca
  340. // and spill the value.
  341. std::set<InvokeInst*> InvokesWithStoreInserted;
  342. // Find all of the blocks that this value is live in.
  343. std::set<BasicBlock*> LiveBBs;
  344. LiveBBs.insert(Inst->getParent());
  345. while (!Users.empty()) {
  346. Instruction *U = Users.back();
  347. Users.pop_back();
  348. if (!isa<PHINode>(U)) {
  349. MarkBlocksLiveIn(U->getParent(), LiveBBs);
  350. } else {
  351. // Uses for a PHI node occur in their predecessor block.
  352. PHINode *PN = cast<PHINode>(U);
  353. for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
  354. if (PN->getIncomingValue(i) == Inst)
  355. MarkBlocksLiveIn(PN->getIncomingBlock(i), LiveBBs);
  356. }
  357. }
  358. // Now that we know all of the blocks that this thing is live in, see if
  359. // it includes any of the unwind locations.
  360. bool NeedsSpill = false;
  361. for (unsigned i = 0, e = Invokes.size(); i != e; ++i) {
  362. BasicBlock *UnwindBlock = Invokes[i]->getUnwindDest();
  363. if (UnwindBlock != BB && LiveBBs.count(UnwindBlock)) {
  364. NeedsSpill = true;
  365. }
  366. }
  367. // If we decided we need a spill, do it.
  368. if (NeedsSpill) {
  369. ++NumSpilled;
  370. DemoteRegToStack(*Inst, true);
  371. }
  372. }
  373. }
  374. bool LowerInvoke::insertExpensiveEHSupport(Function &F) {
  375. std::vector<ReturnInst*> Returns;
  376. std::vector<UnwindInst*> Unwinds;
  377. std::vector<InvokeInst*> Invokes;
  378. for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
  379. if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
  380. // Remember all return instructions in case we insert an invoke into this
  381. // function.
  382. Returns.push_back(RI);
  383. } else if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
  384. Invokes.push_back(II);
  385. } else if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->getTerminator())) {
  386. Unwinds.push_back(UI);
  387. }
  388. if (Unwinds.empty() && Invokes.empty()) return false;
  389. NumInvokes += Invokes.size();
  390. NumUnwinds += Unwinds.size();
  391. // TODO: This is not an optimal way to do this. In particular, this always
  392. // inserts setjmp calls into the entries of functions with invoke instructions
  393. // even though there are possibly paths through the function that do not
  394. // execute any invokes. In particular, for functions with early exits, e.g.
  395. // the 'addMove' method in hexxagon, it would be nice to not have to do the
  396. // setjmp stuff on the early exit path. This requires a bit of dataflow, but
  397. // would not be too hard to do.
  398. // If we have an invoke instruction, insert a setjmp that dominates all
  399. // invokes. After the setjmp, use a cond branch that goes to the original
  400. // code path on zero, and to a designated 'catch' block of nonzero.
  401. Value *OldJmpBufPtr = 0;
  402. if (!Invokes.empty()) {
  403. // First thing we need to do is scan the whole function for values that are
  404. // live across unwind edges. Each value that is live across an unwind edge
  405. // we spill into a stack location, guaranteeing that there is nothing live
  406. // across the unwind edge. This process also splits all critical edges
  407. // coming out of invoke's.
  408. splitLiveRangesLiveAcrossInvokes(Invokes);
  409. BasicBlock *EntryBB = F.begin();
  410. // Create an alloca for the incoming jump buffer ptr and the new jump buffer
  411. // that needs to be restored on all exits from the function. This is an
  412. // alloca because the value needs to be live across invokes.
  413. unsigned Align = TLI ? TLI->getJumpBufAlignment() : 0;
  414. AllocaInst *JmpBuf =
  415. new AllocaInst(JBLinkTy, 0, Align,
  416. "jblink", F.begin()->begin());
  417. std::vector<Value*> Idx;
  418. Idx.push_back(Constant::getNullValue(Type::getInt32Ty(F.getContext())));
  419. Idx.push_back(ConstantInt::get(Type::getInt32Ty(F.getContext()), 1));
  420. OldJmpBufPtr = GetElementPtrInst::Create(JmpBuf, Idx.begin(), Idx.end(),
  421. "OldBuf",
  422. EntryBB->getTerminator());
  423. // Copy the JBListHead to the alloca.
  424. Value *OldBuf = new LoadInst(JBListHead, "oldjmpbufptr", true,
  425. EntryBB->getTerminator());
  426. new StoreInst(OldBuf, OldJmpBufPtr, true, EntryBB->getTerminator());
  427. // Add the new jumpbuf to the list.
  428. new StoreInst(JmpBuf, JBListHead, true, EntryBB->getTerminator());
  429. // Create the catch block. The catch block is basically a big switch
  430. // statement that goes to all of the invoke catch blocks.
  431. BasicBlock *CatchBB =
  432. BasicBlock::Create(F.getContext(), "setjmp.catch", &F);
  433. // Create an alloca which keeps track of which invoke is currently
  434. // executing. For normal calls it contains zero.
  435. AllocaInst *InvokeNum = new AllocaInst(Type::getInt32Ty(F.getContext()), 0,
  436. "invokenum",EntryBB->begin());
  437. new StoreInst(ConstantInt::get(Type::getInt32Ty(F.getContext()), 0),
  438. InvokeNum, true, EntryBB->getTerminator());
  439. // Insert a load in the Catch block, and a switch on its value. By default,
  440. // we go to a block that just does an unwind (which is the correct action
  441. // for a standard call).
  442. BasicBlock *UnwindBB = BasicBlock::Create(F.getContext(), "unwindbb", &F);
  443. Unwinds.push_back(new UnwindInst(F.getContext(), UnwindBB));
  444. Value *CatchLoad = new LoadInst(InvokeNum, "invoke.num", true, CatchBB);
  445. SwitchInst *CatchSwitch =
  446. SwitchInst::Create(CatchLoad, UnwindBB, Invokes.size(), CatchBB);
  447. // Now that things are set up, insert the setjmp call itself.
  448. // Split the entry block to insert the conditional branch for the setjmp.
  449. BasicBlock *ContBlock = EntryBB->splitBasicBlock(EntryBB->getTerminator(),
  450. "setjmp.cont");
  451. Idx[1] = ConstantInt::get(Type::getInt32Ty(F.getContext()), 0);
  452. Value *JmpBufPtr = GetElementPtrInst::Create(JmpBuf, Idx.begin(), Idx.end(),
  453. "TheJmpBuf",
  454. EntryBB->getTerminator());
  455. JmpBufPtr = new BitCastInst(JmpBufPtr,
  456. Type::getInt8PtrTy(F.getContext()),
  457. "tmp", EntryBB->getTerminator());
  458. Value *SJRet = CallInst::Create(SetJmpFn, JmpBufPtr, "sjret",
  459. EntryBB->getTerminator());
  460. // Compare the return value to zero.
  461. Value *IsNormal = new ICmpInst(EntryBB->getTerminator(),
  462. ICmpInst::ICMP_EQ, SJRet,
  463. Constant::getNullValue(SJRet->getType()),
  464. "notunwind");
  465. // Nuke the uncond branch.
  466. EntryBB->getTerminator()->eraseFromParent();
  467. // Put in a new condbranch in its place.
  468. BranchInst::Create(ContBlock, CatchBB, IsNormal, EntryBB);
  469. // At this point, we are all set up, rewrite each invoke instruction.
  470. for (unsigned i = 0, e = Invokes.size(); i != e; ++i)
  471. rewriteExpensiveInvoke(Invokes[i], i+1, InvokeNum, CatchSwitch);
  472. }
  473. // We know that there is at least one unwind.
  474. // Create three new blocks, the block to load the jmpbuf ptr and compare
  475. // against null, the block to do the longjmp, and the error block for if it
  476. // is null. Add them at the end of the function because they are not hot.
  477. BasicBlock *UnwindHandler = BasicBlock::Create(F.getContext(),
  478. "dounwind", &F);
  479. BasicBlock *UnwindBlock = BasicBlock::Create(F.getContext(), "unwind", &F);
  480. BasicBlock *TermBlock = BasicBlock::Create(F.getContext(), "unwinderror", &F);
  481. // If this function contains an invoke, restore the old jumpbuf ptr.
  482. Value *BufPtr;
  483. if (OldJmpBufPtr) {
  484. // Before the return, insert a copy from the saved value to the new value.
  485. BufPtr = new LoadInst(OldJmpBufPtr, "oldjmpbufptr", UnwindHandler);
  486. new StoreInst(BufPtr, JBListHead, UnwindHandler);
  487. } else {
  488. BufPtr = new LoadInst(JBListHead, "ehlist", UnwindHandler);
  489. }
  490. // Load the JBList, if it's null, then there was no catch!
  491. Value *NotNull = new ICmpInst(*UnwindHandler, ICmpInst::ICMP_NE, BufPtr,
  492. Constant::getNullValue(BufPtr->getType()),
  493. "notnull");
  494. BranchInst::Create(UnwindBlock, TermBlock, NotNull, UnwindHandler);
  495. // Create the block to do the longjmp.
  496. // Get a pointer to the jmpbuf and longjmp.
  497. std::vector<Value*> Idx;
  498. Idx.push_back(Constant::getNullValue(Type::getInt32Ty(F.getContext())));
  499. Idx.push_back(ConstantInt::get(Type::getInt32Ty(F.getContext()), 0));
  500. Idx[0] = GetElementPtrInst::Create(BufPtr, Idx.begin(), Idx.end(), "JmpBuf",
  501. UnwindBlock);
  502. Idx[0] = new BitCastInst(Idx[0],
  503. Type::getInt8PtrTy(F.getContext()),
  504. "tmp", UnwindBlock);
  505. Idx[1] = ConstantInt::get(Type::getInt32Ty(F.getContext()), 1);
  506. CallInst::Create(LongJmpFn, Idx.begin(), Idx.end(), "", UnwindBlock);
  507. new UnreachableInst(F.getContext(), UnwindBlock);
  508. // Set up the term block ("throw without a catch").
  509. new UnreachableInst(F.getContext(), TermBlock);
  510. // Insert a new call to write(2, AbortMessage, AbortMessageLength);
  511. writeAbortMessage(TermBlock->getTerminator());
  512. // Insert a call to abort()
  513. CallInst::Create(AbortFn, "",
  514. TermBlock->getTerminator())->setTailCall();
  515. // Replace all unwinds with a branch to the unwind handler.
  516. for (unsigned i = 0, e = Unwinds.size(); i != e; ++i) {
  517. BranchInst::Create(UnwindHandler, Unwinds[i]);
  518. Unwinds[i]->eraseFromParent();
  519. }
  520. // Finally, for any returns from this function, if this function contains an
  521. // invoke, restore the old jmpbuf pointer to its input value.
  522. if (OldJmpBufPtr) {
  523. for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
  524. ReturnInst *R = Returns[i];
  525. // Before the return, insert a copy from the saved value to the new value.
  526. Value *OldBuf = new LoadInst(OldJmpBufPtr, "oldjmpbufptr", true, R);
  527. new StoreInst(OldBuf, JBListHead, true, R);
  528. }
  529. }
  530. return true;
  531. }
  532. bool LowerInvoke::runOnFunction(Function &F) {
  533. if (ExpensiveEHSupport)
  534. return insertExpensiveEHSupport(F);
  535. else
  536. return insertCheapEHSupport(F);
  537. }