-bool InlineFunction(CallInst *CI) {
- assert(isa<CallInst>(CI) && "InlineFunction only works on CallInst nodes");
- assert(CI->getParent() && "Instruction not embedded in basic block!");
- assert(CI->getParent()->getParent() && "Instruction not in function!");
-
- const Function *CalledFunc = CI->getCalledFunction();
- if (CalledFunc == 0 || // Can't inline external function or indirect call!
- CalledFunc->isExternal()) return false;
-
- //cerr << "Inlining " << CalledFunc->getName() << " into "
- // << CurrentMeth->getName() << "\n";
-
- BasicBlock *OrigBB = CI->getParent();
-
- // Call splitBasicBlock - The original basic block now ends at the instruction
- // immediately before the call. The original basic block now ends with an
- // unconditional branch to NewBB, and NewBB starts with the call instruction.
- //
- BasicBlock *NewBB = OrigBB->splitBasicBlock(CI);
- NewBB->setName("InlinedFunctionReturnNode");
-
- // Remove (unlink) the CallInst from the start of the new basic block.
- NewBB->getInstList().remove(CI);
-
- // If we have a return value generated by this call, convert it into a PHI
- // node that gets values from each of the old RET instructions in the original
- // function.
- //
- PHINode *PHI = 0;
- if (!CI->use_empty()) {
- // The PHI node should go at the front of the new basic block to merge all
- // possible incoming values.
- //
- PHI = new PHINode(CalledFunc->getReturnType(), CI->getName(),
- NewBB->begin());
-
- // Anything that used the result of the function call should now use the PHI
- // node as their operand.
- //
- CI->replaceAllUsesWith(PHI);
- }
-
- // Get a pointer to the last basic block in the function, which will have the
- // new function inlined after it.
- //
- Function::iterator LastBlock = &OrigBB->getParent()->back();
-
- // Calculate the vector of arguments to pass into the function cloner...
- std::map<const Value*, Value*> ValueMap;
- assert((unsigned)std::distance(CalledFunc->abegin(), CalledFunc->aend()) ==
- CI->getNumOperands()-1 && "No varargs calls can be inlined yet!");
-
- unsigned i = 1;
- for (Function::const_aiterator I = CalledFunc->abegin(), E=CalledFunc->aend();
- I != E; ++I, ++i)
- ValueMap[I] = CI->getOperand(i);
-
- // Since we are now done with the CallInst, we can delete it.
- delete CI;
-
- // Make a vector to capture the return instructions in the cloned function...
- std::vector<ReturnInst*> Returns;
-
- // Populate the value map with all of the globals in the program.
- Module &M = *OrigBB->getParent()->getParent();
- for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
- ValueMap[I] = I;
- for (Module::giterator I = M.gbegin(), E = M.gend(); I != E; ++I)
- ValueMap[I] = I;
-
- // Do all of the hard part of cloning the callee into the caller...
- CloneFunctionInto(OrigBB->getParent(), CalledFunc, ValueMap, Returns, ".i");