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