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