1 //===- InlineFunction.cpp - Code to perform function inlining -------------===// 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 inlining of a function into a call site, resolving 11 // parameters and the return value as appropriate. 12 // 13 // FIXME: This pass should transform alloca instructions in the called function 14 // into alloca/dealloca pairs! Or perhaps it should refuse to inline them! 15 // 16 //===----------------------------------------------------------------------===// 17 18 #include "llvm/Transforms/Utils/Cloning.h" 19 #include "llvm/Constants.h" 20 #include "llvm/DerivedTypes.h" 21 #include "llvm/Module.h" 22 #include "llvm/Instructions.h" 23 #include "llvm/Intrinsics.h" 24 #include "llvm/Support/CallSite.h" 25 using namespace llvm; 26 27 bool llvm::InlineFunction(CallInst *CI) { return InlineFunction(CallSite(CI)); } 28 bool llvm::InlineFunction(InvokeInst *II) {return InlineFunction(CallSite(II));} 29 30 // InlineFunction - This function inlines the called function into the basic 31 // block of the caller. This returns false if it is not possible to inline this 32 // call. The program is still in a well defined state if this occurs though. 33 // 34 // Note that this only does one level of inlining. For example, if the 35 // instruction 'call B' is inlined, and 'B' calls 'C', then the call to 'C' now 36 // exists in the instruction stream. Similiarly this will inline a recursive 37 // function by one level. 38 // 39 bool llvm::InlineFunction(CallSite CS) { 40 Instruction *TheCall = CS.getInstruction(); 41 assert(TheCall->getParent() && TheCall->getParent()->getParent() && 42 "Instruction not in function!"); 43 44 const Function *CalledFunc = CS.getCalledFunction(); 45 if (CalledFunc == 0 || // Can't inline external function or indirect 46 CalledFunc->isExternal() || // call, or call to a vararg function! 47 CalledFunc->getFunctionType()->isVarArg()) return false; 48 49 50 // If the call to the callee is a non-tail call, we must clear the 'tail' 51 // flags on any calls that we inline. 52 bool MustClearTailCallFlags = 53 isa<CallInst>(TheCall) && !cast<CallInst>(TheCall)->isTailCall(); 54 55 BasicBlock *OrigBB = TheCall->getParent(); 56 Function *Caller = OrigBB->getParent(); 57 58 // Get an iterator to the last basic block in the function, which will have 59 // the new function inlined after it. 60 // 61 Function::iterator LastBlock = &Caller->back(); 62 63 // Make sure to capture all of the return instructions from the cloned 64 // function. 65 std::vector<ReturnInst*> Returns; 66 { // Scope to destroy ValueMap after cloning. 67 // Calculate the vector of arguments to pass into the function cloner... 68 std::map<const Value*, Value*> ValueMap; 69 assert(std::distance(CalledFunc->arg_begin(), CalledFunc->arg_end()) == 70 std::distance(CS.arg_begin(), CS.arg_end()) && 71 "No varargs calls can be inlined!"); 72 73 CallSite::arg_iterator AI = CS.arg_begin(); 74 for (Function::const_arg_iterator I = CalledFunc->arg_begin(), 75 E = CalledFunc->arg_end(); I != E; ++I, ++AI) 76 ValueMap[I] = *AI; 77 78 // Clone the entire body of the callee into the caller. 79 CloneFunctionInto(Caller, CalledFunc, ValueMap, Returns, ".i"); 80 } 81 82 // Remember the first block that is newly cloned over. 83 Function::iterator FirstNewBlock = LastBlock; ++FirstNewBlock; 84 85 // If there are any alloca instructions in the block that used to be the entry 86 // block for the callee, move them to the entry block of the caller. First 87 // calculate which instruction they should be inserted before. We insert the 88 // instructions at the end of the current alloca list. 89 // 90 if (isa<AllocaInst>(FirstNewBlock->begin())) { 91 BasicBlock::iterator InsertPoint = Caller->begin()->begin(); 92 for (BasicBlock::iterator I = FirstNewBlock->begin(), 93 E = FirstNewBlock->end(); I != E; ) 94 if (AllocaInst *AI = dyn_cast<AllocaInst>(I++)) 95 if (isa<Constant>(AI->getArraySize())) { 96 // Scan for the block of allocas that we can move over. 97 while (isa<AllocaInst>(I) && 98 isa<Constant>(cast<AllocaInst>(I)->getArraySize())) 99 ++I; 100 101 // Transfer all of the allocas over in a block. Using splice means 102 // that they instructions aren't removed from the symbol table, then 103 // reinserted. 104 Caller->front().getInstList().splice(InsertPoint, 105 FirstNewBlock->getInstList(), 106 AI, I); 107 } 108 } 109 110 // If we are inlining tail call instruction through an invoke or 111 if (MustClearTailCallFlags) { 112 for (Function::iterator BB = FirstNewBlock, E = Caller->end(); 113 BB != E; ++BB) 114 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) 115 if (CallInst *CI = dyn_cast<CallInst>(I)) 116 CI->setTailCall(false); 117 } 118 119 // If we are inlining for an invoke instruction, we must make sure to rewrite 120 // any inlined 'unwind' instructions into branches to the invoke exception 121 // destination, and call instructions into invoke instructions. 122 if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall)) { 123 BasicBlock *InvokeDest = II->getUnwindDest(); 124 std::vector<Value*> InvokeDestPHIValues; 125 126 // If there are PHI nodes in the exceptional destination block, we need to 127 // keep track of which values came into them from this invoke, then remove 128 // the entry for this block. 129 for (BasicBlock::iterator I = InvokeDest->begin(); isa<PHINode>(I); ++I) { 130 PHINode *PN = cast<PHINode>(I); 131 // Save the value to use for this edge... 132 InvokeDestPHIValues.push_back(PN->getIncomingValueForBlock(OrigBB)); 133 } 134 135 for (Function::iterator BB = FirstNewBlock, E = Caller->end(); 136 BB != E; ++BB) { 137 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) { 138 // We only need to check for function calls: inlined invoke instructions 139 // require no special handling... 140 if (CallInst *CI = dyn_cast<CallInst>(I)) { 141 // Convert this function call into an invoke instruction... if it's 142 // not an intrinsic function call (which are known to not unwind). 143 if (CI->getCalledFunction() && 144 CI->getCalledFunction()->getIntrinsicID()) { 145 ++I; 146 } else { 147 // First, split the basic block... 148 BasicBlock *Split = BB->splitBasicBlock(CI, CI->getName()+".noexc"); 149 150 // Next, create the new invoke instruction, inserting it at the end 151 // of the old basic block. 152 InvokeInst *II = 153 new InvokeInst(CI->getCalledValue(), Split, InvokeDest, 154 std::vector<Value*>(CI->op_begin()+1, CI->op_end()), 155 CI->getName(), BB->getTerminator()); 156 II->setCallingConv(CI->getCallingConv()); 157 158 // Make sure that anything using the call now uses the invoke! 159 CI->replaceAllUsesWith(II); 160 161 // Delete the unconditional branch inserted by splitBasicBlock 162 BB->getInstList().pop_back(); 163 Split->getInstList().pop_front(); // Delete the original call 164 165 // Update any PHI nodes in the exceptional block to indicate that 166 // there is now a new entry in them. 167 unsigned i = 0; 168 for (BasicBlock::iterator I = InvokeDest->begin(); 169 isa<PHINode>(I); ++I, ++i) { 170 PHINode *PN = cast<PHINode>(I); 171 PN->addIncoming(InvokeDestPHIValues[i], BB); 172 } 173 174 // This basic block is now complete, start scanning the next one. 175 break; 176 } 177 } else { 178 ++I; 179 } 180 } 181 182 if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->getTerminator())) { 183 // An UnwindInst requires special handling when it gets inlined into an 184 // invoke site. Once this happens, we know that the unwind would cause 185 // a control transfer to the invoke exception destination, so we can 186 // transform it into a direct branch to the exception destination. 187 new BranchInst(InvokeDest, UI); 188 189 // Delete the unwind instruction! 190 UI->getParent()->getInstList().pop_back(); 191 192 // Update any PHI nodes in the exceptional block to indicate that 193 // there is now a new entry in them. 194 unsigned i = 0; 195 for (BasicBlock::iterator I = InvokeDest->begin(); 196 isa<PHINode>(I); ++I, ++i) { 197 PHINode *PN = cast<PHINode>(I); 198 PN->addIncoming(InvokeDestPHIValues[i], BB); 199 } 200 } 201 } 202 203 // Now that everything is happy, we have one final detail. The PHI nodes in 204 // the exception destination block still have entries due to the original 205 // invoke instruction. Eliminate these entries (which might even delete the 206 // PHI node) now. 207 InvokeDest->removePredecessor(II->getParent()); 208 } 209 210 // If we cloned in _exactly one_ basic block, and if that block ends in a 211 // return instruction, we splice the body of the inlined callee directly into 212 // the calling basic block. 213 if (Returns.size() == 1 && std::distance(FirstNewBlock, Caller->end()) == 1) { 214 // Move all of the instructions right before the call. 215 OrigBB->getInstList().splice(TheCall, FirstNewBlock->getInstList(), 216 FirstNewBlock->begin(), FirstNewBlock->end()); 217 // Remove the cloned basic block. 218 Caller->getBasicBlockList().pop_back(); 219 220 // If the call site was an invoke instruction, add a branch to the normal 221 // destination. 222 if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall)) 223 new BranchInst(II->getNormalDest(), TheCall); 224 225 // If the return instruction returned a value, replace uses of the call with 226 // uses of the returned value. 227 if (!TheCall->use_empty()) 228 TheCall->replaceAllUsesWith(Returns[0]->getReturnValue()); 229 230 // Since we are now done with the Call/Invoke, we can delete it. 231 TheCall->getParent()->getInstList().erase(TheCall); 232 233 // Since we are now done with the return instruction, delete it also. 234 Returns[0]->getParent()->getInstList().erase(Returns[0]); 235 236 // We are now done with the inlining. 237 return true; 238 } 239 240 // Otherwise, we have the normal case, of more than one block to inline or 241 // multiple return sites. 242 243 // We want to clone the entire callee function into the hole between the 244 // "starter" and "ender" blocks. How we accomplish this depends on whether 245 // this is an invoke instruction or a call instruction. 246 BasicBlock *AfterCallBB; 247 if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall)) { 248 249 // Add an unconditional branch to make this look like the CallInst case... 250 BranchInst *NewBr = new BranchInst(II->getNormalDest(), TheCall); 251 252 // Split the basic block. This guarantees that no PHI nodes will have to be 253 // updated due to new incoming edges, and make the invoke case more 254 // symmetric to the call case. 255 AfterCallBB = OrigBB->splitBasicBlock(NewBr, 256 CalledFunc->getName()+".exit"); 257 258 } else { // It's a call 259 // If this is a call instruction, we need to split the basic block that 260 // the call lives in. 261 // 262 AfterCallBB = OrigBB->splitBasicBlock(TheCall, 263 CalledFunc->getName()+".exit"); 264 } 265 266 // Change the branch that used to go to AfterCallBB to branch to the first 267 // basic block of the inlined function. 268 // 269 TerminatorInst *Br = OrigBB->getTerminator(); 270 assert(Br && Br->getOpcode() == Instruction::Br && 271 "splitBasicBlock broken!"); 272 Br->setOperand(0, FirstNewBlock); 273 274 275 // Now that the function is correct, make it a little bit nicer. In 276 // particular, move the basic blocks inserted from the end of the function 277 // into the space made by splitting the source basic block. 278 // 279 Caller->getBasicBlockList().splice(AfterCallBB, Caller->getBasicBlockList(), 280 FirstNewBlock, Caller->end()); 281 282 // Handle all of the return instructions that we just cloned in, and eliminate 283 // any users of the original call/invoke instruction. 284 if (Returns.size() > 1) { 285 // The PHI node should go at the front of the new basic block to merge all 286 // possible incoming values. 287 // 288 PHINode *PHI = 0; 289 if (!TheCall->use_empty()) { 290 PHI = new PHINode(CalledFunc->getReturnType(), 291 TheCall->getName(), AfterCallBB->begin()); 292 293 // Anything that used the result of the function call should now use the 294 // PHI node as their operand. 295 // 296 TheCall->replaceAllUsesWith(PHI); 297 } 298 299 // Loop over all of the return instructions, turning them into unconditional 300 // branches to the merge point now, and adding entries to the PHI node as 301 // appropriate. 302 for (unsigned i = 0, e = Returns.size(); i != e; ++i) { 303 ReturnInst *RI = Returns[i]; 304 305 if (PHI) { 306 assert(RI->getReturnValue() && "Ret should have value!"); 307 assert(RI->getReturnValue()->getType() == PHI->getType() && 308 "Ret value not consistent in function!"); 309 PHI->addIncoming(RI->getReturnValue(), RI->getParent()); 310 } 311 312 // Add a branch to the merge point where the PHI node lives if it exists. 313 new BranchInst(AfterCallBB, RI); 314 315 // Delete the return instruction now 316 RI->getParent()->getInstList().erase(RI); 317 } 318 319 } else if (!Returns.empty()) { 320 // Otherwise, if there is exactly one return value, just replace anything 321 // using the return value of the call with the computed value. 322 if (!TheCall->use_empty()) 323 TheCall->replaceAllUsesWith(Returns[0]->getReturnValue()); 324 325 // Splice the code from the return block into the block that it will return 326 // to, which contains the code that was after the call. 327 BasicBlock *ReturnBB = Returns[0]->getParent(); 328 AfterCallBB->getInstList().splice(AfterCallBB->begin(), 329 ReturnBB->getInstList()); 330 331 // Update PHI nodes that use the ReturnBB to use the AfterCallBB. 332 ReturnBB->replaceAllUsesWith(AfterCallBB); 333 334 // Delete the return instruction now and empty ReturnBB now. 335 Returns[0]->eraseFromParent(); 336 ReturnBB->eraseFromParent(); 337 } else if (!TheCall->use_empty()) { 338 // No returns, but something is using the return value of the call. Just 339 // nuke the result. 340 TheCall->replaceAllUsesWith(UndefValue::get(TheCall->getType())); 341 } 342 343 // Since we are now done with the Call/Invoke, we can delete it. 344 TheCall->eraseFromParent(); 345 346 // We should always be able to fold the entry block of the function into the 347 // single predecessor of the block... 348 assert(cast<BranchInst>(Br)->isUnconditional() && "splitBasicBlock broken!"); 349 BasicBlock *CalleeEntry = cast<BranchInst>(Br)->getSuccessor(0); 350 351 // Splice the code entry block into calling block, right before the 352 // unconditional branch. 353 OrigBB->getInstList().splice(Br, CalleeEntry->getInstList()); 354 CalleeEntry->replaceAllUsesWith(OrigBB); // Update PHI nodes 355 356 // Remove the unconditional branch. 357 OrigBB->getInstList().erase(Br); 358 359 // Now we can remove the CalleeEntry block, which is now empty. 360 Caller->getBasicBlockList().erase(CalleeEntry); 361 return true; 362 } 363