Fix bug: SimplifyCFG/2003-08-17-BranchFoldOrdering.ll
[oota-llvm.git] / lib / Transforms / Utils / InlineFunction.cpp
1 //===- InlineFunction.cpp - Code to perform function inlining -------------===//
2 //
3 // This file implements inlining of a function into a call site, resolving
4 // parameters and the return value as appropriate.
5 //
6 // FIXME: This pass should transform alloca instructions in the called function
7 //        into malloc/free pairs!  Or perhaps it should refuse to inline them!
8 //
9 //===----------------------------------------------------------------------===//
10
11 #include "llvm/Transforms/Utils/Cloning.h"
12 #include "llvm/Module.h"
13 #include "llvm/iTerminators.h"
14 #include "llvm/iPHINode.h"
15 #include "llvm/iMemory.h"
16 #include "llvm/iOther.h"
17 #include "llvm/DerivedTypes.h"
18
19 // InlineFunction - This function inlines the called function into the basic
20 // block of the caller.  This returns false if it is not possible to inline this
21 // call.  The program is still in a well defined state if this occurs though.
22 //
23 // Note that this only does one level of inlining.  For example, if the 
24 // instruction 'call B' is inlined, and 'B' calls 'C', then the call to 'C' now 
25 // exists in the instruction stream.  Similiarly this will inline a recursive
26 // function by one level.
27 //
28 bool InlineFunction(CallInst *CI) {
29   assert(isa<CallInst>(CI) && "InlineFunction only works on CallInst nodes");
30   assert(CI->getParent() && "Instruction not embedded in basic block!");
31   assert(CI->getParent()->getParent() && "Instruction not in function!");
32
33   const Function *CalledFunc = CI->getCalledFunction();
34   if (CalledFunc == 0 ||          // Can't inline external function or indirect
35       CalledFunc->isExternal() || // call, or call to a vararg function!
36       CalledFunc->getFunctionType()->isVarArg()) return false;
37
38   BasicBlock *OrigBB = CI->getParent();
39   Function *Caller = OrigBB->getParent();
40
41   // Call splitBasicBlock - The original basic block now ends at the instruction
42   // immediately before the call.  The original basic block now ends with an
43   // unconditional branch to NewBB, and NewBB starts with the call instruction.
44   //
45   BasicBlock *NewBB = OrigBB->splitBasicBlock(CI);
46   NewBB->setName(OrigBB->getName()+".split");
47
48   // Remove (unlink) the CallInst from the start of the new basic block.  
49   NewBB->getInstList().remove(CI);
50
51   // If we have a return value generated by this call, convert it into a PHI 
52   // node that gets values from each of the old RET instructions in the original
53   // function.
54   //
55   PHINode *PHI = 0;
56   if (!CI->use_empty()) {
57     // The PHI node should go at the front of the new basic block to merge all 
58     // possible incoming values.
59     //
60     PHI = new PHINode(CalledFunc->getReturnType(), CI->getName(),
61                       NewBB->begin());
62
63     // Anything that used the result of the function call should now use the PHI
64     // node as their operand.
65     //
66     CI->replaceAllUsesWith(PHI);
67   }
68
69   // Get an iterator to the last basic block in the function, which will have
70   // the new function inlined after it.
71   //
72   Function::iterator LastBlock = &Caller->back();
73
74   // Calculate the vector of arguments to pass into the function cloner...
75   std::map<const Value*, Value*> ValueMap;
76   assert((unsigned)std::distance(CalledFunc->abegin(), CalledFunc->aend()) == 
77          CI->getNumOperands()-1 && "No varargs calls can be inlined yet!");
78
79   unsigned i = 1;
80   for (Function::const_aiterator I = CalledFunc->abegin(), E=CalledFunc->aend();
81        I != E; ++I, ++i)
82     ValueMap[I] = CI->getOperand(i);
83
84   // Since we are now done with the CallInst, we can delete it.
85   delete CI;
86
87   // Make a vector to capture the return instructions in the cloned function...
88   std::vector<ReturnInst*> Returns;
89
90   // Populate the value map with all of the globals in the program.
91   Module &M = *Caller->getParent();
92   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
93     ValueMap[I] = I;
94   for (Module::giterator I = M.gbegin(), E = M.gend(); I != E; ++I)
95     ValueMap[I] = I;
96
97   // Do all of the hard part of cloning the callee into the caller...
98   CloneFunctionInto(Caller, CalledFunc, ValueMap, Returns, ".i");
99
100   // Loop over all of the return instructions, turning them into unconditional
101   // branches to the merge point now...
102   for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
103     ReturnInst *RI = Returns[i];
104     BasicBlock *BB = RI->getParent();
105
106     // Add a branch to the merge point where the PHI node would live...
107     new BranchInst(NewBB, RI);
108
109     if (PHI) {   // The PHI node should include this value!
110       assert(RI->getReturnValue() && "Ret should have value!");
111       assert(RI->getReturnValue()->getType() == PHI->getType() && 
112              "Ret value not consistent in function!");
113       PHI->addIncoming(RI->getReturnValue(), BB);
114     }
115
116     // Delete the return instruction now
117     BB->getInstList().erase(RI);
118   }
119
120   // Check to see if the PHI node only has one argument.  This is a common
121   // case resulting from there only being a single return instruction in the
122   // function call.  Because this is so common, eliminate the PHI node.
123   //
124   if (PHI && PHI->getNumIncomingValues() == 1) {
125     PHI->replaceAllUsesWith(PHI->getIncomingValue(0));
126     PHI->getParent()->getInstList().erase(PHI);
127   }
128
129   // Change the branch that used to go to NewBB to branch to the first basic 
130   // block of the inlined function.
131   //
132   TerminatorInst *Br = OrigBB->getTerminator();
133   assert(Br && Br->getOpcode() == Instruction::Br && 
134          "splitBasicBlock broken!");
135   Br->setOperand(0, ++LastBlock);
136
137   // If there are any alloca instructions in the block that used to be the entry
138   // block for the callee, move them to the entry block of the caller.  First
139   // calculate which instruction they should be inserted before.  We insert the
140   // instructions at the end of the current alloca list.
141   //
142   BasicBlock::iterator InsertPoint = Caller->begin()->begin();
143   while (isa<AllocaInst>(InsertPoint)) ++InsertPoint;
144
145   for (BasicBlock::iterator I = LastBlock->begin(), E = LastBlock->end();
146        I != E; )
147     if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) {
148       ++I;  // Move to the next instruction
149       LastBlock->getInstList().remove(AI);
150       Caller->front().getInstList().insert(InsertPoint, AI);
151       
152     } else {
153       ++I;
154     }
155
156   // Now that the function is correct, make it a little bit nicer.  In
157   // particular, move the basic blocks inserted from the end of the function
158   // into the space made by splitting the source basic block.
159   //
160   Caller->getBasicBlockList().splice(NewBB, Caller->getBasicBlockList(), 
161                                      LastBlock, Caller->end());
162
163   return true;
164 }