1 //===- LowerSetJmp.cpp - Code pertaining to lowering set/long jumps -------===//
3 // This file implements the lowering of setjmp and longjmp to use the
4 // LLVM invoke and unwind instructions as necessary.
6 // Lowering of longjmp is fairly trivial. We replace the call with a
7 // call to the LLVM library function "__llvm_sjljeh_throw_longjmp()".
8 // This unwinds the stack for us calling all of the destructors for
9 // objects allocated on the stack.
11 // At a setjmp call, the basic block is split and the setjmp removed.
12 // The calls in a function that have a setjmp are converted to invoke
13 // where the except part checks to see if it's a longjmp exception and,
14 // if so, if it's handled in the function. If it is, then it gets the
15 // value returned by the longjmp and goes to where the basic block was
16 // split. Invoke instructions are handled in a similar fashion with the
17 // original except block being executed if it isn't a longjmp except
18 // that is handled by that function.
20 //===----------------------------------------------------------------------===//
22 //===----------------------------------------------------------------------===//
23 // FIXME: This pass doesn't deal with PHI statements just yet. That is,
24 // we expect this to occur before SSAification is done. This would seem
25 // to make sense, but in general, it might be a good idea to make this
26 // pass invokable via the "opt" command at will.
27 //===----------------------------------------------------------------------===//
29 #include "llvm/Constants.h"
30 #include "llvm/DerivedTypes.h"
31 #include "llvm/Instructions.h"
32 #include "llvm/Intrinsics.h"
33 #include "llvm/Module.h"
34 #include "llvm/Pass.h"
35 #include "llvm/Support/CFG.h"
36 #include "llvm/Support/InstVisitor.h"
37 #include "Support/DepthFirstIterator.h"
38 #include "Support/Statistic.h"
39 #include "Support/StringExtras.h"
40 #include "Support/VectorExtras.h"
43 Statistic<> LongJmpsTransformed("lowersetjmp",
44 "Number of longjmps transformed");
45 Statistic<> SetJmpsTransformed("lowersetjmp",
46 "Number of setjmps transformed");
48 //===--------------------------------------------------------------------===//
49 // LowerSetJmp pass implementation. This is subclassed from the "Pass"
50 // class because it works on a module as a whole, not a function at a
53 class LowerSetJmp : public Pass,
54 public InstVisitor<LowerSetJmp> {
55 // LLVM library functions...
56 Function* InitSJMap; // __llvm_sjljeh_init_setjmpmap
57 Function* DestroySJMap; // __llvm_sjljeh_destroy_setjmpmap
58 Function* AddSJToMap; // __llvm_sjljeh_add_setjmp_to_map
59 Function* ThrowLongJmp; // __llvm_sjljeh_throw_longjmp
60 Function* TryCatchLJ; // __llvm_sjljeh_try_catching_longjmp_exception
61 Function* IsLJException; // __llvm_sjljeh_is_longjmp_exception
62 Function* GetLJValue; // __llvm_sjljeh_get_longjmp_value
64 typedef std::pair<SwitchInst*, CallInst*> SwitchValuePair;
66 // Keep track of those basic blocks reachable via a depth-first search of
67 // the CFG from a setjmp call. We only need to transform those "call" and
68 // "invoke" instructions that are reachable from the setjmp call site.
69 std::set<BasicBlock*> DFSBlocks;
71 // The setjmp map is going to hold information about which setjmps
72 // were called (each setjmp gets its own number) and with which
73 // buffer it was called.
74 std::map<Function*, AllocaInst*> SJMap;
76 // The rethrow basic block map holds the basic block to branch to if
77 // the exception isn't handled in the current function and needs to
79 std::map<const Function*, BasicBlock*> RethrowBBMap;
81 // The preliminary basic block map holds a basic block that grabs the
82 // exception and determines if it's handled by the current function.
83 std::map<const Function*, BasicBlock*> PrelimBBMap;
85 // The switch/value map holds a switch inst/call inst pair. The
86 // switch inst controls which handler (if any) gets called and the
87 // value is the value returned to that handler by the call to
88 // __llvm_sjljeh_get_longjmp_value.
89 std::map<const Function*, SwitchValuePair> SwitchValMap;
91 // A map of which setjmps we've seen so far in a function.
92 std::map<const Function*, unsigned> SetJmpIDMap;
94 AllocaInst* GetSetJmpMap(Function* Func);
95 BasicBlock* GetRethrowBB(Function* Func);
96 SwitchValuePair GetSJSwitch(Function* Func, BasicBlock* Rethrow);
98 void TransformLongJmpCall(CallInst* Inst);
99 void TransformSetJmpCall(CallInst* Inst);
101 bool IsTransformableFunction(const std::string& Name);
103 void visitCallInst(CallInst& CI);
104 void visitInvokeInst(InvokeInst& II);
105 void visitReturnInst(ReturnInst& RI);
106 void visitUnwindInst(UnwindInst& UI);
109 bool doInitialization(Module& M);
112 RegisterOpt<LowerSetJmp> X("lowersetjmp", "Lower Set Jump");
113 } // end anonymous namespace
115 // run - Run the transformation on the program. We grab the function
116 // prototypes for longjmp and setjmp. If they are used in the program,
117 // then we can go directly to the places they're at and transform them.
118 bool LowerSetJmp::run(Module& M)
120 bool Changed = false;
122 // These are what the functions are called.
123 Function* SetJmp = M.getNamedFunction("llvm.setjmp");
124 Function* LongJmp = M.getNamedFunction("llvm.longjmp");
126 // This program doesn't have longjmp and setjmp calls.
127 if ((!LongJmp || LongJmp->use_empty()) &&
128 (!SetJmp || SetJmp->use_empty())) return false;
130 // Initialize some values and functions we'll need to transform the
131 // setjmp/longjmp functions.
135 std::set<BasicBlock*> BBSet;
137 for (Value::use_iterator B = SetJmp->use_begin(), E = SetJmp->use_end();
139 BasicBlock* BB = cast<Instruction>(*B)->getParent();
140 DFSBlocks.insert(df_begin(BB), df_end(BB));
143 while (!SetJmp->use_empty()) {
144 assert(isa<CallInst>(SetJmp->use_back()) &&
145 "User of setjmp intrinsic not a call?");
146 TransformSetJmpCall(cast<CallInst>(SetJmp->use_back()));
152 while (!LongJmp->use_empty()) {
153 assert(isa<CallInst>(LongJmp->use_back()) &&
154 "User of longjmp intrinsic not a call?");
155 TransformLongJmpCall(cast<CallInst>(LongJmp->use_back()));
159 // Now go through the affected functions and convert calls and invokes
161 for (std::map<Function*, AllocaInst*>::iterator
162 B = SJMap.begin(), E = SJMap.end(); B != E; ++B) {
163 Function* F = B->first;
164 for (Function::iterator BB = F->begin(), BE = F->end(); BB != BE; ++BB)
165 for (BasicBlock::iterator IB = BB->begin(), IE = BB->end(); IB != IE; ) {
167 if (IB != BB->end() && IB->getParent() != BB)
168 break; // The next instruction got moved to a different block!
174 RethrowBBMap.clear();
176 SwitchValMap.clear();
182 // doInitialization - For the lower long/setjmp pass, this ensures that a
183 // module contains a declaration for the intrisic functions we are going
184 // to call to convert longjmp and setjmp calls.
186 // This function is always successful, unless it isn't.
187 bool LowerSetJmp::doInitialization(Module& M)
189 const Type *SBPTy = PointerType::get(Type::SByteTy);
190 const Type *SBPPTy = PointerType::get(SBPTy);
192 // N.B. See llvm/runtime/GCCLibraries/libexception/SJLJ-Exception.h for
193 // a description of the following library functions.
195 // void __llvm_sjljeh_init_setjmpmap(void**)
196 InitSJMap = M.getOrInsertFunction("__llvm_sjljeh_init_setjmpmap",
197 Type::VoidTy, SBPPTy, 0);
198 // void __llvm_sjljeh_destroy_setjmpmap(void**)
199 DestroySJMap = M.getOrInsertFunction("__llvm_sjljeh_destroy_setjmpmap",
200 Type::VoidTy, SBPPTy, 0);
202 // void __llvm_sjljeh_add_setjmp_to_map(void**, void*, unsigned)
203 AddSJToMap = M.getOrInsertFunction("__llvm_sjljeh_add_setjmp_to_map",
204 Type::VoidTy, SBPPTy, SBPTy,
207 // void __llvm_sjljeh_throw_longjmp(int*, int)
208 ThrowLongJmp = M.getOrInsertFunction("__llvm_sjljeh_throw_longjmp",
209 Type::VoidTy, SBPTy, Type::IntTy, 0);
211 // unsigned __llvm_sjljeh_try_catching_longjmp_exception(void **)
213 M.getOrInsertFunction("__llvm_sjljeh_try_catching_longjmp_exception",
214 Type::UIntTy, SBPPTy, 0);
216 // bool __llvm_sjljeh_is_longjmp_exception()
217 IsLJException = M.getOrInsertFunction("__llvm_sjljeh_is_longjmp_exception",
220 // int __llvm_sjljeh_get_longjmp_value()
221 GetLJValue = M.getOrInsertFunction("__llvm_sjljeh_get_longjmp_value",
226 // IsTransformableFunction - Return true if the function name isn't one
227 // of the ones we don't want transformed. Currently, don't transform any
228 // "llvm.{setjmp,longjmp}" functions and none of the setjmp/longjmp error
229 // handling functions (beginning with __llvm_sjljeh_...they don't throw
231 bool LowerSetJmp::IsTransformableFunction(const std::string& Name)
233 std::string SJLJEh("__llvm_sjljeh");
235 if (Name.size() > SJLJEh.size())
236 return std::string(Name.begin(), Name.begin() + SJLJEh.size()) != SJLJEh;
241 // TransformLongJmpCall - Transform a longjmp call into a call to the
242 // internal __llvm_sjljeh_throw_longjmp function. It then takes care of
243 // throwing the exception for us.
244 void LowerSetJmp::TransformLongJmpCall(CallInst* Inst)
246 const Type* SBPTy = PointerType::get(Type::SByteTy);
248 // Create the call to "__llvm_sjljeh_throw_longjmp". This takes the
249 // same parameters as "longjmp", except that the buffer is cast to a
250 // char*. It returns "void", so it doesn't need to replace any of
251 // Inst's uses and doesn't get a name.
252 CastInst* CI = new CastInst(Inst->getOperand(1), SBPTy, "LJBuf", Inst);
253 new CallInst(ThrowLongJmp, make_vector<Value*>(CI, Inst->getOperand(2), 0),
256 SwitchValuePair& SVP = SwitchValMap[Inst->getParent()->getParent()];
258 // If the function has a setjmp call in it (they are transformed first)
259 // we should branch to the basic block that determines if this longjmp
260 // is applicable here. Otherwise, issue an unwind.
262 new BranchInst(SVP.first->getParent(), Inst);
264 new UnwindInst(Inst);
266 // Remove all insts after the branch/unwind inst.
267 Inst->getParent()->getInstList().erase(Inst,
268 Inst->getParent()->getInstList().end());
270 ++LongJmpsTransformed;
273 // GetSetJmpMap - Retrieve (create and initialize, if necessary) the
274 // setjmp map. This map is going to hold information about which setjmps
275 // were called (each setjmp gets its own number) and with which buffer it
276 // was called. There can be only one!
277 AllocaInst* LowerSetJmp::GetSetJmpMap(Function* Func)
279 if (SJMap[Func]) return SJMap[Func];
281 // Insert the setjmp map initialization before the first instruction in
283 Instruction* Inst = Func->getEntryBlock().begin();
284 assert(Inst && "Couldn't find even ONE instruction in entry block!");
286 // Fill in the alloca and call to initialize the SJ map.
287 const Type *SBPTy = PointerType::get(Type::SByteTy);
288 AllocaInst* Map = new AllocaInst(SBPTy, 0, "SJMap", Inst);
289 new CallInst(InitSJMap, make_vector<Value*>(Map, 0), "", Inst);
290 return SJMap[Func] = Map;
293 // GetRethrowBB - Only one rethrow basic block is needed per function.
294 // If this is a longjmp exception but not handled in this block, this BB
295 // performs the rethrow.
296 BasicBlock* LowerSetJmp::GetRethrowBB(Function* Func)
298 if (RethrowBBMap[Func]) return RethrowBBMap[Func];
300 // The basic block we're going to jump to if we need to rethrow the
302 BasicBlock* Rethrow = new BasicBlock("RethrowExcept", Func);
303 BasicBlock::InstListType& RethrowBlkIL = Rethrow->getInstList();
305 // Fill in the "Rethrow" BB with a call to rethrow the exception. This
306 // is the last instruction in the BB since at this point the runtime
307 // should exit this function and go to the next function.
308 RethrowBlkIL.push_back(new UnwindInst());
309 return RethrowBBMap[Func] = Rethrow;
312 // GetSJSwitch - Return the switch statement that controls which handler
313 // (if any) gets called and the value returned to that handler.
314 LowerSetJmp::SwitchValuePair LowerSetJmp::GetSJSwitch(Function* Func,
317 if (SwitchValMap[Func].first) return SwitchValMap[Func];
319 BasicBlock* LongJmpPre = new BasicBlock("LongJmpBlkPre", Func);
320 BasicBlock::InstListType& LongJmpPreIL = LongJmpPre->getInstList();
322 // Keep track of the preliminary basic block for some of the other
324 PrelimBBMap[Func] = LongJmpPre;
326 // Grab the exception.
328 CallInst(IsLJException, std::vector<Value*>(), "IsLJExcept");
329 LongJmpPreIL.push_back(Cond);
331 // The "decision basic block" gets the number associated with the
332 // setjmp call returning to switch on and the value returned by
334 BasicBlock* DecisionBB = new BasicBlock("LJDecisionBB", Func);
335 BasicBlock::InstListType& DecisionBBIL = DecisionBB->getInstList();
337 LongJmpPreIL.push_back(new BranchInst(DecisionBB, Rethrow, Cond));
339 // Fill in the "decision" basic block.
340 CallInst* LJVal = new CallInst(GetLJValue, std::vector<Value*>(), "LJVal");
341 DecisionBBIL.push_back(LJVal);
342 CallInst* SJNum = new
343 CallInst(TryCatchLJ, make_vector<Value*>(GetSetJmpMap(Func), 0), "SJNum");
344 DecisionBBIL.push_back(SJNum);
346 SwitchInst* SI = new SwitchInst(SJNum, Rethrow);
347 DecisionBBIL.push_back(SI);
348 return SwitchValMap[Func] = SwitchValuePair(SI, LJVal);
351 // TransformSetJmpCall - The setjmp call is a bit trickier to transform.
352 // We're going to convert all setjmp calls to nops. Then all "call" and
353 // "invoke" instructions in the function are converted to "invoke" where
354 // the "except" branch is used when returning from a longjmp call.
355 void LowerSetJmp::TransformSetJmpCall(CallInst* Inst)
357 BasicBlock* ABlock = Inst->getParent();
358 Function* Func = ABlock->getParent();
360 // Add this setjmp to the setjmp map.
361 const Type* SBPTy = PointerType::get(Type::SByteTy);
362 CastInst* BufPtr = new CastInst(Inst->getOperand(1), SBPTy, "SBJmpBuf", Inst);
363 new CallInst(AddSJToMap,
364 make_vector<Value*>(GetSetJmpMap(Func), BufPtr,
365 ConstantUInt::get(Type::UIntTy,
366 SetJmpIDMap[Func]++), 0),
369 // Change the setjmp call into a branch statement. We'll remove the
370 // setjmp call in a little bit. No worries.
371 BasicBlock* SetJmpContBlock = ABlock->splitBasicBlock(Inst);
372 assert(SetJmpContBlock && "Couldn't split setjmp BB!!");
374 SetJmpContBlock->setName("SetJmpContBlock");
376 // Reposition the split BB in the BB list to make things tidier.
377 Func->getBasicBlockList().remove(SetJmpContBlock);
378 Func->getBasicBlockList().insert(++Function::iterator(ABlock),
381 // This PHI node will be in the new block created from the
382 // splitBasicBlock call.
383 PHINode* PHI = new PHINode(Type::IntTy, "SetJmpReturn", Inst);
385 // Coming from a call to setjmp, the return is 0.
386 PHI->addIncoming(ConstantInt::getNullValue(Type::IntTy), ABlock);
388 // Add the case for this setjmp's number...
389 SwitchValuePair SVP = GetSJSwitch(Func, GetRethrowBB(Func));
390 SVP.first->addCase(ConstantUInt::get(Type::UIntTy, SetJmpIDMap[Func] - 1),
393 // Value coming from the handling of the exception.
394 PHI->addIncoming(SVP.second, SVP.second->getParent());
396 // Replace all uses of this instruction with the PHI node created by
397 // the eradication of setjmp.
398 Inst->replaceAllUsesWith(PHI);
399 Inst->getParent()->getInstList().erase(Inst);
401 ++SetJmpsTransformed;
404 // visitCallInst - This converts all LLVM call instructions into invoke
405 // instructions. The except part of the invoke goes to the "LongJmpBlkPre"
406 // that grabs the exception and proceeds to determine if it's a longjmp
408 void LowerSetJmp::visitCallInst(CallInst& CI)
410 if (CI.getCalledFunction())
411 if (!IsTransformableFunction(CI.getCalledFunction()->getName()) ||
412 CI.getCalledFunction()->isIntrinsic()) return;
414 BasicBlock* OldBB = CI.getParent();
416 // If not reachable from a setjmp call, don't transform.
417 if (!DFSBlocks.count(OldBB)) return;
419 BasicBlock* NewBB = OldBB->splitBasicBlock(CI);
420 assert(NewBB && "Couldn't split BB of \"call\" instruction!!");
421 NewBB->setName("Call2Invoke");
423 // Reposition the split BB in the BB list to make things tidier.
424 Function* Func = OldBB->getParent();
425 Func->getBasicBlockList().remove(NewBB);
426 Func->getBasicBlockList().insert(++Function::iterator(OldBB), NewBB);
428 // Construct the new "invoke" instruction.
429 TerminatorInst* Term = OldBB->getTerminator();
430 std::vector<Value*> Params(CI.op_begin() + 1, CI.op_end());
432 InvokeInst(CI.getCalledValue(), NewBB, PrelimBBMap[Func],
433 Params, CI.getName(), Term);
435 // Replace the old call inst with the invoke inst and remove the call.
436 CI.replaceAllUsesWith(II);
437 CI.getParent()->getInstList().erase(&CI);
439 // The old terminator is useless now that we have the invoke inst.
440 Term->getParent()->getInstList().erase(Term);
443 // visitInvokeInst - Converting the "invoke" instruction is fairly
444 // straight-forward. The old exception part is replaced by a query asking
445 // if this is a longjmp exception. If it is, then it goes to the longjmp
446 // exception blocks. Otherwise, control is passed the old exception.
447 void LowerSetJmp::visitInvokeInst(InvokeInst& II)
449 if (II.getCalledFunction())
450 if (!IsTransformableFunction(II.getCalledFunction()->getName()) ||
451 II.getCalledFunction()->isIntrinsic()) return;
453 BasicBlock* BB = II.getParent();
455 // If not reachable from a setjmp call, don't transform.
456 if (!DFSBlocks.count(BB)) return;
458 BasicBlock* NormalBB = II.getNormalDest();
459 BasicBlock* ExceptBB = II.getExceptionalDest();
461 Function* Func = BB->getParent();
462 BasicBlock* NewExceptBB = new BasicBlock("InvokeExcept", Func);
463 BasicBlock::InstListType& InstList = NewExceptBB->getInstList();
465 // If this is a longjmp exception, then branch to the preliminary BB of
466 // the longjmp exception handling. Otherwise, go to the old exception.
467 CallInst* IsLJExcept = new
468 CallInst(IsLJException, std::vector<Value*>(), "IsLJExcept");
469 InstList.push_back(IsLJExcept);
471 BranchInst* BR = new BranchInst(PrelimBBMap[Func], ExceptBB, IsLJExcept);
472 InstList.push_back(BR);
474 II.setExceptionalDest(NewExceptBB);
477 // visitReturnInst - We want to destroy the setjmp map upon exit from the
479 void LowerSetJmp::visitReturnInst(ReturnInst& RI)
481 Function* Func = RI.getParent()->getParent();
482 new CallInst(DestroySJMap, make_vector<Value*>(GetSetJmpMap(Func), 0),
486 // visitUnwindInst - We want to destroy the setjmp map upon exit from the
488 void LowerSetJmp::visitUnwindInst(UnwindInst& UI)
490 Function* Func = UI.getParent()->getParent();
491 new CallInst(DestroySJMap, make_vector<Value*>(GetSetJmpMap(Func), 0),
495 Pass* createLowerSetJmpPass()
497 return new LowerSetJmp();