Minor cleanups
[oota-llvm.git] / lib / Transforms / IPO / LowerSetJmp.cpp
1 //===- LowerSetJmp.cpp - Code pertaining to lowering set/long jumps -------===//
2 //
3 //  This file implements the lowering of setjmp and longjmp to use the
4 //  LLVM invoke and unwind instructions as necessary.
5 //
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.
10 //
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.
19 //
20 //===----------------------------------------------------------------------===//
21
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 //===----------------------------------------------------------------------===//
28
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"
41
42 namespace {
43   Statistic<> LongJmpsTransformed("lowersetjmp",
44                                   "Number of longjmps transformed");
45   Statistic<> SetJmpsTransformed("lowersetjmp",
46                                  "Number of setjmps transformed");
47
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
51   // time.
52
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
63
64     typedef std::pair<SwitchInst*, CallInst*> SwitchValuePair;
65
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;
70
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;
75
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
78     // be rethrown.
79     std::map<const Function*, BasicBlock*>      RethrowBBMap;
80
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;
84
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;
90
91     // A map of which setjmps we've seen so far in a function.
92     std::map<const Function*, unsigned>         SetJmpIDMap;
93
94     AllocaInst*     GetSetJmpMap(Function* Func);
95     BasicBlock*     GetRethrowBB(Function* Func);
96     SwitchValuePair GetSJSwitch(Function* Func, BasicBlock* Rethrow);
97
98     void TransformLongJmpCall(CallInst* Inst);
99     void TransformSetJmpCall(CallInst* Inst);
100
101     bool IsTransformableFunction(const std::string& Name);
102   public:
103     void visitCallInst(CallInst& CI);
104     void visitInvokeInst(InvokeInst& II);
105     void visitReturnInst(ReturnInst& RI);
106     void visitUnwindInst(UnwindInst& UI);
107
108     bool run(Module& M);
109     bool doInitialization(Module& M);
110   };
111
112   RegisterOpt<LowerSetJmp> X("lowersetjmp", "Lower Set Jump");
113 } // end anonymous namespace
114
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)
119 {
120   bool Changed = false;
121
122   // These are what the functions are called.
123   Function* SetJmp = M.getNamedFunction("llvm.setjmp");
124   Function* LongJmp = M.getNamedFunction("llvm.longjmp");
125
126   // This program doesn't have longjmp and setjmp calls.
127   if ((!LongJmp || LongJmp->use_empty()) &&
128         (!SetJmp || SetJmp->use_empty())) return false;
129
130   // Initialize some values and functions we'll need to transform the
131   // setjmp/longjmp functions.
132   doInitialization(M);
133
134   if (SetJmp) {
135     std::set<BasicBlock*> BBSet;
136     
137     for (Value::use_iterator B = SetJmp->use_begin(), E = SetJmp->use_end();
138          B != E; ++B) {
139       BasicBlock* BB = cast<Instruction>(*B)->getParent();
140       DFSBlocks.insert(df_begin(BB), df_end(BB));
141     }
142
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()));
147       Changed = true;
148     }
149   }
150
151   if (LongJmp)
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()));
156       Changed = true;
157     }
158
159   // Now go through the affected functions and convert calls and invokes
160   // to new 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; ) {
166         visit(*IB++);
167         if (IB != BB->end() && IB->getParent() != BB)
168           break;  // The next instruction got moved to a different block!
169       }
170   }
171
172   DFSBlocks.clear();
173   SJMap.clear();
174   RethrowBBMap.clear();
175   PrelimBBMap.clear();
176   SwitchValMap.clear();
177   SetJmpIDMap.clear();
178
179   return Changed;
180 }
181
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.
185 //
186 // This function is always successful, unless it isn't.
187 bool LowerSetJmp::doInitialization(Module& M)
188 {
189   const Type *SBPTy = PointerType::get(Type::SByteTy);
190   const Type *SBPPTy = PointerType::get(SBPTy);
191
192   // N.B. See llvm/runtime/GCCLibraries/libexception/SJLJ-Exception.h for
193   // a description of the following library functions.
194
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);
201
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,
205                                      Type::UIntTy, 0);
206
207   // void __llvm_sjljeh_throw_longjmp(int*, int)
208   ThrowLongJmp = M.getOrInsertFunction("__llvm_sjljeh_throw_longjmp",
209                                        Type::VoidTy, SBPTy, Type::IntTy, 0);
210
211   // unsigned __llvm_sjljeh_try_catching_longjmp_exception(void **)
212   TryCatchLJ =
213     M.getOrInsertFunction("__llvm_sjljeh_try_catching_longjmp_exception",
214                           Type::UIntTy, SBPPTy, 0);
215
216   // bool __llvm_sjljeh_is_longjmp_exception()
217   IsLJException = M.getOrInsertFunction("__llvm_sjljeh_is_longjmp_exception",
218                                         Type::BoolTy, 0);
219
220   // int __llvm_sjljeh_get_longjmp_value()
221   GetLJValue = M.getOrInsertFunction("__llvm_sjljeh_get_longjmp_value",
222                                      Type::IntTy, 0);
223   return true;
224 }
225
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
230 // exceptions).
231 bool LowerSetJmp::IsTransformableFunction(const std::string& Name)
232 {
233   std::string SJLJEh("__llvm_sjljeh");
234
235   if (Name.size() > SJLJEh.size())
236     return std::string(Name.begin(), Name.begin() + SJLJEh.size()) != SJLJEh;
237
238   return true;
239 }
240
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)
245 {
246   const Type* SBPTy = PointerType::get(Type::SByteTy);
247
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),
254                "", Inst);
255
256   SwitchValuePair& SVP = SwitchValMap[Inst->getParent()->getParent()];
257
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.
261   if (SVP.first)
262     new BranchInst(SVP.first->getParent(), Inst);
263   else
264     new UnwindInst(Inst);
265
266   // Remove all insts after the branch/unwind inst.
267   Inst->getParent()->getInstList().erase(Inst,
268                                        Inst->getParent()->getInstList().end());
269
270   ++LongJmpsTransformed;
271 }
272
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)
278 {
279   if (SJMap[Func]) return SJMap[Func];
280
281   // Insert the setjmp map initialization before the first instruction in
282   // the function.
283   Instruction* Inst = Func->getEntryBlock().begin();
284   assert(Inst && "Couldn't find even ONE instruction in entry block!");
285
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;
291 }
292
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)
297 {
298   if (RethrowBBMap[Func]) return RethrowBBMap[Func];
299
300   // The basic block we're going to jump to if we need to rethrow the
301   // exception.
302   BasicBlock* Rethrow = new BasicBlock("RethrowExcept", Func);
303   BasicBlock::InstListType& RethrowBlkIL = Rethrow->getInstList();
304
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;
310 }
311
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,
315                                                       BasicBlock* Rethrow)
316 {
317   if (SwitchValMap[Func].first) return SwitchValMap[Func];
318
319   BasicBlock* LongJmpPre = new BasicBlock("LongJmpBlkPre", Func);
320   BasicBlock::InstListType& LongJmpPreIL = LongJmpPre->getInstList();
321
322   // Keep track of the preliminary basic block for some of the other
323   // transformations.
324   PrelimBBMap[Func] = LongJmpPre;
325
326   // Grab the exception.
327   CallInst* Cond = new
328     CallInst(IsLJException, std::vector<Value*>(), "IsLJExcept");
329   LongJmpPreIL.push_back(Cond);
330
331   // The "decision basic block" gets the number associated with the
332   // setjmp call returning to switch on and the value returned by
333   // longjmp.
334   BasicBlock* DecisionBB = new BasicBlock("LJDecisionBB", Func);
335   BasicBlock::InstListType& DecisionBBIL = DecisionBB->getInstList();
336
337   LongJmpPreIL.push_back(new BranchInst(DecisionBB, Rethrow, Cond));
338
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);
345
346   SwitchInst* SI = new SwitchInst(SJNum, Rethrow);
347   DecisionBBIL.push_back(SI);
348   return SwitchValMap[Func] = SwitchValuePair(SI, LJVal);
349 }
350
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)
356 {
357   BasicBlock* ABlock = Inst->getParent();
358   Function* Func = ABlock->getParent();
359
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),
367                "", Inst);
368
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!!");
373
374   SetJmpContBlock->setName("SetJmpContBlock");
375
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),
379                                    SetJmpContBlock);
380
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);
384
385   // Coming from a call to setjmp, the return is 0.
386   PHI->addIncoming(ConstantInt::getNullValue(Type::IntTy), ABlock);
387
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),
391                      SetJmpContBlock);
392
393   // Value coming from the handling of the exception.
394   PHI->addIncoming(SVP.second, SVP.second->getParent());
395
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);
400
401   ++SetJmpsTransformed;
402 }
403
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
407 // exception or not.
408 void LowerSetJmp::visitCallInst(CallInst& CI)
409 {
410   if (CI.getCalledFunction())
411     if (!IsTransformableFunction(CI.getCalledFunction()->getName()) ||
412         CI.getCalledFunction()->isIntrinsic()) return;
413
414   BasicBlock* OldBB = CI.getParent();
415
416   // If not reachable from a setjmp call, don't transform.
417   if (!DFSBlocks.count(OldBB)) return;
418
419   BasicBlock* NewBB = OldBB->splitBasicBlock(CI);
420   assert(NewBB && "Couldn't split BB of \"call\" instruction!!");
421   NewBB->setName("Call2Invoke");
422
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);
427
428   // Construct the new "invoke" instruction.
429   TerminatorInst* Term = OldBB->getTerminator();
430   std::vector<Value*> Params(CI.op_begin() + 1, CI.op_end());
431   InvokeInst* II = new
432     InvokeInst(CI.getCalledValue(), NewBB, PrelimBBMap[Func],
433                Params, CI.getName(), Term); 
434
435   // Replace the old call inst with the invoke inst and remove the call.
436   CI.replaceAllUsesWith(II);
437   CI.getParent()->getInstList().erase(&CI);
438
439   // The old terminator is useless now that we have the invoke inst.
440   Term->getParent()->getInstList().erase(Term);
441 }
442
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)
448 {
449   if (II.getCalledFunction())
450     if (!IsTransformableFunction(II.getCalledFunction()->getName()) ||
451         II.getCalledFunction()->isIntrinsic()) return;
452
453   BasicBlock* BB = II.getParent();
454
455   // If not reachable from a setjmp call, don't transform.
456   if (!DFSBlocks.count(BB)) return;
457
458   BasicBlock* NormalBB = II.getNormalDest();
459   BasicBlock* ExceptBB = II.getExceptionalDest();
460
461   Function* Func = BB->getParent();
462   BasicBlock* NewExceptBB = new BasicBlock("InvokeExcept", Func);
463   BasicBlock::InstListType& InstList = NewExceptBB->getInstList();
464
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);
470
471   BranchInst* BR = new BranchInst(PrelimBBMap[Func], ExceptBB, IsLJExcept);
472   InstList.push_back(BR);
473
474   II.setExceptionalDest(NewExceptBB);
475 }
476
477 // visitReturnInst - We want to destroy the setjmp map upon exit from the
478 // function.
479 void LowerSetJmp::visitReturnInst(ReturnInst& RI)
480 {
481   Function* Func = RI.getParent()->getParent();
482   new CallInst(DestroySJMap, make_vector<Value*>(GetSetJmpMap(Func), 0),
483                "", &RI);
484 }
485
486 // visitUnwindInst - We want to destroy the setjmp map upon exit from the
487 // function.
488 void LowerSetJmp::visitUnwindInst(UnwindInst& UI)
489 {
490   Function* Func = UI.getParent()->getParent();
491   new CallInst(DestroySJMap, make_vector<Value*>(GetSetJmpMap(Func), 0),
492                "", &UI);
493 }
494
495 Pass* createLowerSetJmpPass()
496 {
497   return new LowerSetJmp();
498 }