blob: 1a9513751d73b6d64c6b558b02cdb6dca2a72bf0 [file] [log] [blame]
Chris Lattner8bce9882002-11-19 22:04:49 +00001//===- CloneFunction.cpp - Clone a function into another function ---------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner8bce9882002-11-19 22:04:49 +00009//
10// This file implements the CloneFunctionInto interface, which is used as the
11// low-level function cloner. This is used by the CloneFunction and function
12// inliner to do the dirty work of copying the body of a function around.
13//
14//===----------------------------------------------------------------------===//
Chris Lattner16bfdb52002-03-29 19:03:54 +000015
Chris Lattner16667512002-11-19 20:59:41 +000016#include "llvm/Transforms/Utils/Cloning.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000017#include "llvm/ADT/SmallVector.h"
18#include "llvm/Analysis/ConstantFolding.h"
19#include "llvm/Analysis/InstructionSimplify.h"
Chandler Carruth1305dc32014-03-04 11:45:46 +000020#include "llvm/IR/CFG.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000021#include "llvm/IR/Constants.h"
Chandler Carruth9a4c9e52014-03-06 00:46:21 +000022#include "llvm/IR/DebugInfo.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000023#include "llvm/IR/DerivedTypes.h"
24#include "llvm/IR/Function.h"
25#include "llvm/IR/GlobalVariable.h"
26#include "llvm/IR/Instructions.h"
27#include "llvm/IR/IntrinsicInst.h"
28#include "llvm/IR/LLVMContext.h"
29#include "llvm/IR/Metadata.h"
Alon Mishne07d949f2014-03-12 14:42:51 +000030#include "llvm/IR/Module.h"
Chandler Carruth772c88b2012-03-28 08:38:27 +000031#include "llvm/Transforms/Utils/BasicBlockUtils.h"
32#include "llvm/Transforms/Utils/Local.h"
Dan Gohmana2095032010-08-24 18:50:07 +000033#include "llvm/Transforms/Utils/ValueMapper.h"
Chris Lattner1bfc7ab2007-02-03 00:08:31 +000034#include <map>
Gerolf Hoflehnerc46e9b02014-04-26 02:03:17 +000035#include <set>
Chris Lattnerdf3c3422004-01-09 06:12:26 +000036using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000037
Chris Lattnere9f42322003-04-18 03:50:09 +000038// CloneBasicBlock - See comments in Cloning.h
Chris Lattnerdf3c3422004-01-09 06:12:26 +000039BasicBlock *llvm::CloneBasicBlock(const BasicBlock *BB,
Devang Pateld8dedee2010-06-24 00:00:42 +000040 ValueToValueMapTy &VMap,
Benjamin Kramer1266d462010-01-27 19:58:47 +000041 const Twine &NameSuffix, Function *F,
Chris Lattneredad1282006-01-13 18:39:17 +000042 ClonedCodeInfo *CodeInfo) {
Owen Anderson55f1c092009-08-13 21:58:54 +000043 BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), "", F);
Chris Lattnere9f42322003-04-18 03:50:09 +000044 if (BB->hasName()) NewBB->setName(BB->getName()+NameSuffix);
45
Chris Lattneredad1282006-01-13 18:39:17 +000046 bool hasCalls = false, hasDynamicAllocas = false, hasStaticAllocas = false;
47
48 // Loop over all instructions, and copy them over.
Chris Lattnere9f42322003-04-18 03:50:09 +000049 for (BasicBlock::const_iterator II = BB->begin(), IE = BB->end();
50 II != IE; ++II) {
Nick Lewycky42fb7452009-09-27 07:38:41 +000051 Instruction *NewInst = II->clone();
Chris Lattnere9f42322003-04-18 03:50:09 +000052 if (II->hasName())
53 NewInst->setName(II->getName()+NameSuffix);
54 NewBB->getInstList().push_back(NewInst);
Devang Patelb8f11de2010-06-23 23:55:51 +000055 VMap[II] = NewInst; // Add instruction map to value.
Chris Lattneredad1282006-01-13 18:39:17 +000056
Dale Johannesen900aaa32009-03-10 22:20:02 +000057 hasCalls |= (isa<CallInst>(II) && !isa<DbgInfoIntrinsic>(II));
Chris Lattneredad1282006-01-13 18:39:17 +000058 if (const AllocaInst *AI = dyn_cast<AllocaInst>(II)) {
59 if (isa<ConstantInt>(AI->getArraySize()))
60 hasStaticAllocas = true;
61 else
62 hasDynamicAllocas = true;
63 }
64 }
65
66 if (CodeInfo) {
67 CodeInfo->ContainsCalls |= hasCalls;
Chris Lattneredad1282006-01-13 18:39:17 +000068 CodeInfo->ContainsDynamicAllocas |= hasDynamicAllocas;
69 CodeInfo->ContainsDynamicAllocas |= hasStaticAllocas &&
Dan Gohmandcb291f2007-03-22 16:38:57 +000070 BB != &BB->getParent()->getEntryBlock();
Chris Lattnere9f42322003-04-18 03:50:09 +000071 }
72 return NewBB;
73}
74
Chris Lattner16bfdb52002-03-29 19:03:54 +000075// Clone OldFunc into NewFunc, transforming the old arguments into references to
Dan Gohmanca26f792010-08-26 15:41:53 +000076// VMap values.
Chris Lattner16bfdb52002-03-29 19:03:54 +000077//
Chris Lattnerdf3c3422004-01-09 06:12:26 +000078void llvm::CloneFunctionInto(Function *NewFunc, const Function *OldFunc,
Devang Pateld8dedee2010-06-24 00:00:42 +000079 ValueToValueMapTy &VMap,
Dan Gohmanca26f792010-08-26 15:41:53 +000080 bool ModuleLevelChanges,
Chris Lattnerd84dbb32009-08-27 04:02:30 +000081 SmallVectorImpl<ReturnInst*> &Returns,
Mon P Wang5d44a432011-12-23 02:18:32 +000082 const char *NameSuffix, ClonedCodeInfo *CodeInfo,
James Molloyf6f121e2013-05-28 15:17:05 +000083 ValueMapTypeRemapper *TypeMapper,
84 ValueMaterializer *Materializer) {
Chris Lattnerb1120052002-11-19 21:54:07 +000085 assert(NameSuffix && "NameSuffix cannot be null!");
Misha Brukmanb1c93172005-04-21 23:48:37 +000086
Chris Lattnerc3626182002-11-19 22:54:01 +000087#ifndef NDEBUG
Chris Lattneredad1282006-01-13 18:39:17 +000088 for (Function::const_arg_iterator I = OldFunc->arg_begin(),
89 E = OldFunc->arg_end(); I != E; ++I)
Devang Patelb8f11de2010-06-23 23:55:51 +000090 assert(VMap.count(I) && "No mapping from source argument specified!");
Chris Lattnerc3626182002-11-19 22:54:01 +000091#endif
Chris Lattner16bfdb52002-03-29 19:03:54 +000092
Reid Kleckner23798a92014-03-26 22:26:35 +000093 // Copy all attributes other than those stored in the AttributeSet. We need
94 // to remap the parameter indices of the AttributeSet.
95 AttributeSet NewAttrs = NewFunc->getAttributes();
96 NewFunc->copyAttributesFrom(OldFunc);
97 NewFunc->setAttributes(NewAttrs);
98
Joey Gouly81259292013-04-10 10:37:38 +000099 AttributeSet OldAttrs = OldFunc->getAttributes();
100 // Clone any argument attributes that are present in the VMap.
Reid Kleckner23798a92014-03-26 22:26:35 +0000101 for (const Argument &OldArg : OldFunc->args())
102 if (Argument *NewArg = dyn_cast<Argument>(VMap[&OldArg])) {
Joey Gouly81259292013-04-10 10:37:38 +0000103 AttributeSet attrs =
Reid Kleckner23798a92014-03-26 22:26:35 +0000104 OldAttrs.getParamAttributes(OldArg.getArgNo() + 1);
Joey Gouly81259292013-04-10 10:37:38 +0000105 if (attrs.getNumSlots() > 0)
Reid Kleckner23798a92014-03-26 22:26:35 +0000106 NewArg->addAttr(attrs);
Joey Gouly81259292013-04-10 10:37:38 +0000107 }
Andrew Lenharth5aa1cc42008-10-07 18:08:38 +0000108
Reid Kleckner23798a92014-03-26 22:26:35 +0000109 NewFunc->setAttributes(
110 NewFunc->getAttributes()
111 .addAttributes(NewFunc->getContext(), AttributeSet::ReturnIndex,
112 OldAttrs.getRetAttributes())
113 .addAttributes(NewFunc->getContext(), AttributeSet::FunctionIndex,
114 OldAttrs.getFnAttributes()));
Anton Korobeynikovd38b3fb2008-03-23 16:03:00 +0000115
Chris Lattner16bfdb52002-03-29 19:03:54 +0000116 // Loop over all of the basic blocks in the function, cloning them as
Chris Lattnerb1120052002-11-19 21:54:07 +0000117 // appropriate. Note that we save BE this way in order to handle cloning of
118 // recursive functions into themselves.
Chris Lattner16bfdb52002-03-29 19:03:54 +0000119 //
120 for (Function::const_iterator BI = OldFunc->begin(), BE = OldFunc->end();
121 BI != BE; ++BI) {
Chris Lattnerfda72b12002-06-25 16:12:52 +0000122 const BasicBlock &BB = *BI;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000123
Chris Lattnere9f42322003-04-18 03:50:09 +0000124 // Create a new basic block and copy instructions into it!
Chris Lattner43f8d162011-01-08 08:15:20 +0000125 BasicBlock *CBB = CloneBasicBlock(&BB, VMap, NameSuffix, NewFunc, CodeInfo);
Chris Lattner16bfdb52002-03-29 19:03:54 +0000126
Eli Friedman688db1d2011-10-21 20:45:19 +0000127 // Add basic block mapping.
128 VMap[&BB] = CBB;
129
130 // It is only legal to clone a function if a block address within that
131 // function is never referenced outside of the function. Given that, we
132 // want to map block addresses from the old function to block addresses in
133 // the clone. (This is different from the generic ValueMapper
134 // implementation, which generates an invalid blockaddress when
135 // cloning a function.)
136 if (BB.hasAddressTaken()) {
137 Constant *OldBBAddr = BlockAddress::get(const_cast<Function*>(OldFunc),
138 const_cast<BasicBlock*>(&BB));
139 VMap[OldBBAddr] = BlockAddress::get(NewFunc, CBB);
140 }
141
142 // Note return instructions for the caller.
Chris Lattnerb1120052002-11-19 21:54:07 +0000143 if (ReturnInst *RI = dyn_cast<ReturnInst>(CBB->getTerminator()))
144 Returns.push_back(RI);
Chris Lattner16bfdb52002-03-29 19:03:54 +0000145 }
146
Misha Brukmanb1c93172005-04-21 23:48:37 +0000147 // Loop over all of the instructions in the function, fixing up operand
Devang Patelb8f11de2010-06-23 23:55:51 +0000148 // references as we go. This uses VMap to do all the hard work.
Devang Patelb8f11de2010-06-23 23:55:51 +0000149 for (Function::iterator BB = cast<BasicBlock>(VMap[OldFunc->begin()]),
Nick Lewycky4d43d3c2008-04-25 16:53:59 +0000150 BE = NewFunc->end(); BB != BE; ++BB)
Chris Lattner16bfdb52002-03-29 19:03:54 +0000151 // Loop over all instructions, fixing each one as we find it...
Chris Lattner39ad6f22004-02-04 21:44:26 +0000152 for (BasicBlock::iterator II = BB->begin(); II != BB->end(); ++II)
Chris Lattner43f8d162011-01-08 08:15:20 +0000153 RemapInstruction(II, VMap,
Mon P Wang5d44a432011-12-23 02:18:32 +0000154 ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges,
James Molloyf6f121e2013-05-28 15:17:05 +0000155 TypeMapper, Materializer);
Chris Lattner16bfdb52002-03-29 19:03:54 +0000156}
Chris Lattnerfb311d22002-11-19 23:12:22 +0000157
Alon Mishne07d949f2014-03-12 14:42:51 +0000158// Find the MDNode which corresponds to the DISubprogram data that described F.
159static MDNode* FindSubprogram(const Function *F, DebugInfoFinder &Finder) {
Alon Mishnead312152014-03-18 09:41:07 +0000160 for (DISubprogram Subprogram : Finder.subprograms()) {
Alon Mishne07d949f2014-03-12 14:42:51 +0000161 if (Subprogram.describes(F)) return Subprogram;
162 }
Craig Topperf40110f2014-04-25 05:29:35 +0000163 return nullptr;
Alon Mishne07d949f2014-03-12 14:42:51 +0000164}
165
166// Add an operand to an existing MDNode. The new operand will be added at the
167// back of the operand list.
168static void AddOperand(MDNode *Node, Value *Operand) {
169 SmallVector<Value*, 16> Operands;
170 for (unsigned i = 0; i < Node->getNumOperands(); i++) {
171 Operands.push_back(Node->getOperand(i));
172 }
173 Operands.push_back(Operand);
174 MDNode *NewNode = MDNode::get(Node->getContext(), Operands);
175 Node->replaceAllUsesWith(NewNode);
176}
177
178// Clone the module-level debug info associated with OldFunc. The cloned data
179// will point to NewFunc instead.
180static void CloneDebugInfoMetadata(Function *NewFunc, const Function *OldFunc,
181 ValueToValueMapTy &VMap) {
182 DebugInfoFinder Finder;
183 Finder.processModule(*OldFunc->getParent());
184
185 const MDNode *OldSubprogramMDNode = FindSubprogram(OldFunc, Finder);
186 if (!OldSubprogramMDNode) return;
187
188 // Ensure that OldFunc appears in the map.
189 // (if it's already there it must point to NewFunc anyway)
190 VMap[OldFunc] = NewFunc;
191 DISubprogram NewSubprogram(MapValue(OldSubprogramMDNode, VMap));
192
Alon Mishnead312152014-03-18 09:41:07 +0000193 for (DICompileUnit CU : Finder.compile_units()) {
Alon Mishne07d949f2014-03-12 14:42:51 +0000194 DIArray Subprograms(CU.getSubprograms());
195
196 // If the compile unit's function list contains the old function, it should
197 // also contain the new one.
198 for (unsigned i = 0; i < Subprograms.getNumElements(); i++) {
199 if ((MDNode*)Subprograms.getElement(i) == OldSubprogramMDNode) {
200 AddOperand(Subprograms, NewSubprogram);
201 }
202 }
203 }
204}
205
Chris Lattnerfb311d22002-11-19 23:12:22 +0000206/// CloneFunction - Return a copy of the specified function, but without
207/// embedding the function into another module. Also, any references specified
Devang Patelb8f11de2010-06-23 23:55:51 +0000208/// in the VMap are changed to refer to their mapped value instead of the
209/// original one. If any of the arguments to the function are in the VMap,
210/// the arguments are deleted from the resultant function. The VMap is
Chris Lattnerfb311d22002-11-19 23:12:22 +0000211/// updated to include mappings from all of the instructions and basicblocks in
212/// the function from their old to new values.
213///
Chris Lattner43f8d162011-01-08 08:15:20 +0000214Function *llvm::CloneFunction(const Function *F, ValueToValueMapTy &VMap,
Dan Gohmanca26f792010-08-26 15:41:53 +0000215 bool ModuleLevelChanges,
Chris Lattneredad1282006-01-13 18:39:17 +0000216 ClonedCodeInfo *CodeInfo) {
Jay Foadb804a2b2011-07-12 14:06:48 +0000217 std::vector<Type*> ArgTypes;
Chris Lattnerfb311d22002-11-19 23:12:22 +0000218
219 // The user might be deleting arguments to the function by specifying them in
Devang Patelb8f11de2010-06-23 23:55:51 +0000220 // the VMap. If so, we need to not add the arguments to the arg ty vector
Chris Lattnerfb311d22002-11-19 23:12:22 +0000221 //
Chris Lattneredad1282006-01-13 18:39:17 +0000222 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
223 I != E; ++I)
Devang Patelb8f11de2010-06-23 23:55:51 +0000224 if (VMap.count(I) == 0) // Haven't mapped the argument to anything yet?
Chris Lattnerfb311d22002-11-19 23:12:22 +0000225 ArgTypes.push_back(I->getType());
226
227 // Create a new function type...
Owen Anderson4056ca92009-07-29 22:17:13 +0000228 FunctionType *FTy = FunctionType::get(F->getFunctionType()->getReturnType(),
Chris Lattnerfb311d22002-11-19 23:12:22 +0000229 ArgTypes, F->getFunctionType()->isVarArg());
230
231 // Create the new function...
Gabor Greife9ecc682008-04-06 20:25:17 +0000232 Function *NewF = Function::Create(FTy, F->getLinkage(), F->getName());
Misha Brukmanb1c93172005-04-21 23:48:37 +0000233
Chris Lattnerfb311d22002-11-19 23:12:22 +0000234 // Loop over the arguments, copying the names of the mapped arguments over...
Chris Lattner531f9e92005-03-15 04:54:21 +0000235 Function::arg_iterator DestI = NewF->arg_begin();
Chris Lattneredad1282006-01-13 18:39:17 +0000236 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
237 I != E; ++I)
Devang Patelb8f11de2010-06-23 23:55:51 +0000238 if (VMap.count(I) == 0) { // Is this argument preserved?
Chris Lattnerfb311d22002-11-19 23:12:22 +0000239 DestI->setName(I->getName()); // Copy the name over...
Devang Patelb8f11de2010-06-23 23:55:51 +0000240 VMap[I] = DestI++; // Add mapping to VMap
Chris Lattnerfb311d22002-11-19 23:12:22 +0000241 }
242
Alon Mishne07d949f2014-03-12 14:42:51 +0000243 if (ModuleLevelChanges)
244 CloneDebugInfoMetadata(NewF, F, VMap);
245
Chris Lattnerd84dbb32009-08-27 04:02:30 +0000246 SmallVector<ReturnInst*, 8> Returns; // Ignore returns cloned.
Dan Gohmanca26f792010-08-26 15:41:53 +0000247 CloneFunctionInto(NewF, F, VMap, ModuleLevelChanges, Returns, "", CodeInfo);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000248 return NewF;
Chris Lattnerfb311d22002-11-19 23:12:22 +0000249}
Brian Gaeke960707c2003-11-11 22:41:34 +0000250
Chris Lattner3df13f42006-05-27 01:22:24 +0000251
252
253namespace {
254 /// PruningFunctionCloner - This class is a private class used to implement
255 /// the CloneAndPruneFunctionInto method.
Nick Lewycky02d5f772009-10-25 06:33:48 +0000256 struct PruningFunctionCloner {
Chris Lattner3df13f42006-05-27 01:22:24 +0000257 Function *NewFunc;
258 const Function *OldFunc;
Devang Pateld8dedee2010-06-24 00:00:42 +0000259 ValueToValueMapTy &VMap;
Dan Gohmanca26f792010-08-26 15:41:53 +0000260 bool ModuleLevelChanges;
Chris Lattner3df13f42006-05-27 01:22:24 +0000261 const char *NameSuffix;
262 ClonedCodeInfo *CodeInfo;
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000263 const DataLayout *DL;
Chris Lattner3df13f42006-05-27 01:22:24 +0000264 public:
265 PruningFunctionCloner(Function *newFunc, const Function *oldFunc,
Devang Pateld8dedee2010-06-24 00:00:42 +0000266 ValueToValueMapTy &valueMap,
Dan Gohmanca26f792010-08-26 15:41:53 +0000267 bool moduleLevelChanges,
Chris Lattner3df13f42006-05-27 01:22:24 +0000268 const char *nameSuffix,
Chris Lattnerad84a732007-01-30 23:22:39 +0000269 ClonedCodeInfo *codeInfo,
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000270 const DataLayout *DL)
Dan Gohmanca26f792010-08-26 15:41:53 +0000271 : NewFunc(newFunc), OldFunc(oldFunc),
272 VMap(valueMap), ModuleLevelChanges(moduleLevelChanges),
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000273 NameSuffix(nameSuffix), CodeInfo(codeInfo), DL(DL) {
Chris Lattner3df13f42006-05-27 01:22:24 +0000274 }
275
Gerolf Hoflehnerc46e9b02014-04-26 02:03:17 +0000276 /// CloneBlock - The specified block is found to be reachable, so clone it
277 /// into newBB.
Chris Lattner4bd8cda2007-03-02 03:11:20 +0000278 void CloneBlock(const BasicBlock *BB,
Gerolf Hoflehnerc46e9b02014-04-26 02:03:17 +0000279 BasicBlock *NewBB,
280 std::vector<const BasicBlock *> &ToClone,
281 std::set<const BasicBlock *> &OrigBBs);
Chris Lattner3df13f42006-05-27 01:22:24 +0000282 };
283}
284
Gerolf Hoflehnerc46e9b02014-04-26 02:03:17 +0000285/// CloneBlock - The specified block is found to be reachable, so clone it
286/// into newBB.
Chris Lattner4bd8cda2007-03-02 03:11:20 +0000287void PruningFunctionCloner::CloneBlock(const BasicBlock *BB,
Gerolf Hoflehnerc46e9b02014-04-26 02:03:17 +0000288 BasicBlock *NewBB,
289 std::vector<const BasicBlock *> &ToClone,
290 std::set<const BasicBlock *> &OrigBBs) {
Chris Lattner3df13f42006-05-27 01:22:24 +0000291
Gerolf Hoflehnerc46e9b02014-04-26 02:03:17 +0000292 // Remove BB from list of blocks to clone.
293 // When it was not in the list, it has been cloned already, so
294 // don't clone again.
295 if (!OrigBBs.erase(BB)) return;
Chris Lattner3df13f42006-05-27 01:22:24 +0000296
Gerolf Hoflehnerc46e9b02014-04-26 02:03:17 +0000297 // Nope, clone it now.
Eli Friedman688db1d2011-10-21 20:45:19 +0000298
Chris Lattner3df13f42006-05-27 01:22:24 +0000299 bool hasCalls = false, hasDynamicAllocas = false, hasStaticAllocas = false;
300
301 // Loop over all instructions, and copy them over, DCE'ing as we go. This
302 // loop doesn't include the terminator.
Chris Lattnercc340c02006-06-01 19:19:23 +0000303 for (BasicBlock::const_iterator II = BB->begin(), IE = --BB->end();
Chris Lattner3df13f42006-05-27 01:22:24 +0000304 II != IE; ++II) {
Chandler Carruth21211992012-03-25 04:03:40 +0000305 Instruction *NewInst = II->clone();
306
307 // Eagerly remap operands to the newly cloned instruction, except for PHI
308 // nodes for which we defer processing until we update the CFG.
309 if (!isa<PHINode>(NewInst)) {
310 RemapInstruction(NewInst, VMap,
311 ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges);
312
313 // If we can simplify this instruction to some other value, simply add
314 // a mapping to that value rather than inserting a new instruction into
315 // the basic block.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000316 if (Value *V = SimplifyInstruction(NewInst, DL)) {
Chandler Carruth21211992012-03-25 04:03:40 +0000317 // On the off-chance that this simplifies to an instruction in the old
318 // function, map it back into the new function.
319 if (Value *MappedV = VMap.lookup(V))
320 V = MappedV;
321
322 VMap[II] = V;
323 delete NewInst;
324 continue;
325 }
Chris Lattner3df13f42006-05-27 01:22:24 +0000326 }
Devang Patel4bed3562009-02-10 07:48:18 +0000327
Chris Lattner3df13f42006-05-27 01:22:24 +0000328 if (II->hasName())
329 NewInst->setName(II->getName()+NameSuffix);
Devang Patelb8f11de2010-06-23 23:55:51 +0000330 VMap[II] = NewInst; // Add instruction map to value.
Chandler Carruth21211992012-03-25 04:03:40 +0000331 NewBB->getInstList().push_back(NewInst);
Dale Johannesen900aaa32009-03-10 22:20:02 +0000332 hasCalls |= (isa<CallInst>(II) && !isa<DbgInfoIntrinsic>(II));
Chris Lattner3df13f42006-05-27 01:22:24 +0000333 if (const AllocaInst *AI = dyn_cast<AllocaInst>(II)) {
334 if (isa<ConstantInt>(AI->getArraySize()))
335 hasStaticAllocas = true;
336 else
337 hasDynamicAllocas = true;
338 }
339 }
340
Chris Lattnercc340c02006-06-01 19:19:23 +0000341 // Finally, clone over the terminator.
342 const TerminatorInst *OldTI = BB->getTerminator();
343 bool TerminatorDone = false;
344 if (const BranchInst *BI = dyn_cast<BranchInst>(OldTI)) {
345 if (BI->isConditional()) {
346 // If the condition was a known constant in the callee...
Zhou Sheng75b871f2007-01-11 12:24:14 +0000347 ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition());
348 // Or is a known constant in the caller...
Craig Topperf40110f2014-04-25 05:29:35 +0000349 if (!Cond) {
Rafael Espindolac2240ad2010-10-13 02:08:17 +0000350 Value *V = VMap[BI->getCondition()];
351 Cond = dyn_cast_or_null<ConstantInt>(V);
352 }
Zhou Sheng75b871f2007-01-11 12:24:14 +0000353
354 // Constant fold to uncond branch!
355 if (Cond) {
Reid Spencercddc9df2007-01-12 04:24:46 +0000356 BasicBlock *Dest = BI->getSuccessor(!Cond->getZExtValue());
Devang Patelb8f11de2010-06-23 23:55:51 +0000357 VMap[OldTI] = BranchInst::Create(Dest, NewBB);
Chris Lattner4bd8cda2007-03-02 03:11:20 +0000358 ToClone.push_back(Dest);
Chris Lattnercc340c02006-06-01 19:19:23 +0000359 TerminatorDone = true;
360 }
361 }
362 } else if (const SwitchInst *SI = dyn_cast<SwitchInst>(OldTI)) {
363 // If switching on a value known constant in the caller.
364 ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition());
Craig Topperf40110f2014-04-25 05:29:35 +0000365 if (!Cond) { // Or known constant after constant prop in the callee...
Rafael Espindolac2240ad2010-10-13 02:08:17 +0000366 Value *V = VMap[SI->getCondition()];
367 Cond = dyn_cast_or_null<ConstantInt>(V);
368 }
Chris Lattnercc340c02006-06-01 19:19:23 +0000369 if (Cond) { // Constant fold to uncond branch!
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +0000370 SwitchInst::ConstCaseIt Case = SI->findCaseValue(Cond);
371 BasicBlock *Dest = const_cast<BasicBlock*>(Case.getCaseSuccessor());
Devang Patelb8f11de2010-06-23 23:55:51 +0000372 VMap[OldTI] = BranchInst::Create(Dest, NewBB);
Chris Lattner4bd8cda2007-03-02 03:11:20 +0000373 ToClone.push_back(Dest);
Chris Lattnercc340c02006-06-01 19:19:23 +0000374 TerminatorDone = true;
375 }
376 }
377
378 if (!TerminatorDone) {
Nick Lewycky42fb7452009-09-27 07:38:41 +0000379 Instruction *NewInst = OldTI->clone();
Chris Lattnercc340c02006-06-01 19:19:23 +0000380 if (OldTI->hasName())
381 NewInst->setName(OldTI->getName()+NameSuffix);
382 NewBB->getInstList().push_back(NewInst);
Devang Patelb8f11de2010-06-23 23:55:51 +0000383 VMap[OldTI] = NewInst; // Add instruction map to value.
Chris Lattnercc340c02006-06-01 19:19:23 +0000384
385 // Recursively clone any reachable successor blocks.
386 const TerminatorInst *TI = BB->getTerminator();
387 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
Chris Lattner4bd8cda2007-03-02 03:11:20 +0000388 ToClone.push_back(TI->getSuccessor(i));
Chris Lattnercc340c02006-06-01 19:19:23 +0000389 }
390
Chris Lattner3df13f42006-05-27 01:22:24 +0000391 if (CodeInfo) {
392 CodeInfo->ContainsCalls |= hasCalls;
Chris Lattner3df13f42006-05-27 01:22:24 +0000393 CodeInfo->ContainsDynamicAllocas |= hasDynamicAllocas;
394 CodeInfo->ContainsDynamicAllocas |= hasStaticAllocas &&
395 BB != &BB->getParent()->front();
396 }
Chris Lattner3df13f42006-05-27 01:22:24 +0000397}
398
Chris Lattner3df13f42006-05-27 01:22:24 +0000399/// CloneAndPruneFunctionInto - This works exactly like CloneFunctionInto,
400/// except that it does some simple constant prop and DCE on the fly. The
401/// effect of this is to copy significantly less code in cases where (for
402/// example) a function call with constant arguments is inlined, and those
403/// constant arguments cause a significant amount of code in the callee to be
Duncan Sandsad0ea2d2007-11-27 13:23:08 +0000404/// dead. Since this doesn't produce an exact copy of the input, it can't be
Chris Lattner3df13f42006-05-27 01:22:24 +0000405/// used for things like CloneFunction or CloneModule.
406void llvm::CloneAndPruneFunctionInto(Function *NewFunc, const Function *OldFunc,
Devang Pateld8dedee2010-06-24 00:00:42 +0000407 ValueToValueMapTy &VMap,
Dan Gohmanca26f792010-08-26 15:41:53 +0000408 bool ModuleLevelChanges,
Chris Lattnerd84dbb32009-08-27 04:02:30 +0000409 SmallVectorImpl<ReturnInst*> &Returns,
Chris Lattner3df13f42006-05-27 01:22:24 +0000410 const char *NameSuffix,
Chris Lattnerad84a732007-01-30 23:22:39 +0000411 ClonedCodeInfo *CodeInfo,
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000412 const DataLayout *DL,
Devang Patelf6eeaeb2009-11-10 23:06:00 +0000413 Instruction *TheCall) {
Chris Lattner3df13f42006-05-27 01:22:24 +0000414 assert(NameSuffix && "NameSuffix cannot be null!");
Gerolf Hoflehnerc46e9b02014-04-26 02:03:17 +0000415
Chris Lattner3df13f42006-05-27 01:22:24 +0000416#ifndef NDEBUG
Jeff Cohen7d6f3db2006-11-05 19:31:28 +0000417 for (Function::const_arg_iterator II = OldFunc->arg_begin(),
418 E = OldFunc->arg_end(); II != E; ++II)
Devang Patelb8f11de2010-06-23 23:55:51 +0000419 assert(VMap.count(II) && "No mapping from source argument specified!");
Chris Lattner3df13f42006-05-27 01:22:24 +0000420#endif
Duncan Sandsdd7daee2008-05-26 19:58:59 +0000421
Dan Gohmanca26f792010-08-26 15:41:53 +0000422 PruningFunctionCloner PFC(NewFunc, OldFunc, VMap, ModuleLevelChanges,
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000423 NameSuffix, CodeInfo, DL);
Chris Lattner3df13f42006-05-27 01:22:24 +0000424
Gerolf Hoflehnerc46e9b02014-04-26 02:03:17 +0000425 // Since all BB address references need to be known before block-by-block
426 // processing, we need to create all reachable blocks before processing
427 // them for instruction cloning and pruning. Some of these blocks may
428 // be removed due to later pruning.
Chris Lattner4bd8cda2007-03-02 03:11:20 +0000429 std::vector<const BasicBlock*> CloneWorklist;
Gerolf Hoflehnerc46e9b02014-04-26 02:03:17 +0000430 //
431 // OrigBBs consists of all blocks reachable from the entry
432 // block.
433 // This list will be pruned down by the CloneFunction() currently
434 // (March 2014) due to two optimizations:
435 // First, when a conditional branch target is known at compile-time,
436 // only the actual branch destination block needs to be cloned.
437 // Second, when a switch statement target is known at compile-time,
438 // only the actual case statement needs to be cloned.
439 std::set<const BasicBlock*> OrigBBs;
440
Chris Lattner4bd8cda2007-03-02 03:11:20 +0000441 CloneWorklist.push_back(&OldFunc->getEntryBlock());
442 while (!CloneWorklist.empty()) {
443 const BasicBlock *BB = CloneWorklist.back();
444 CloneWorklist.pop_back();
Gerolf Hoflehnerc46e9b02014-04-26 02:03:17 +0000445
446 // Don't revisit blocks.
447 if (VMap.count(BB))
448 continue;
449
450 BasicBlock *NewBB = BasicBlock::Create(BB->getContext());
451 if (BB->hasName()) NewBB->setName(BB->getName()+NameSuffix);
452
453 // It is only legal to clone a function if a block address within that
454 // function is never referenced outside of the function. Given that, we
455 // want to map block addresses from the old function to block addresses in
456 // the clone. (This is different from the generic ValueMapper
457 // implementation, which generates an invalid blockaddress when
458 // cloning a function.)
459 //
460 // Note that we don't need to fix the mapping for unreachable blocks;
461 // the default mapping there is safe.
462 if (BB->hasAddressTaken()) {
463 Constant *OldBBAddr = BlockAddress::get(const_cast<Function*>(OldFunc),
464 const_cast<BasicBlock*>(BB));
465 VMap[OldBBAddr] = BlockAddress::get(NewFunc, NewBB);
466 }
467
468 OrigBBs.insert(BB);
469 VMap[BB] = NewBB;
470 // Iterate over all possible successors and add them to the CloneWorklist.
471 const TerminatorInst *Term = BB->getTerminator();
472 for (unsigned i = 0, e = Term->getNumSuccessors(); i != e; ++i) {
473 BasicBlock *Succ = Term->getSuccessor(i);
474 CloneWorklist.push_back(Succ);
475 }
Chris Lattner4bd8cda2007-03-02 03:11:20 +0000476 }
Gerolf Hoflehnerc46e9b02014-04-26 02:03:17 +0000477
478 // Now, fill only the reachable blocks with the cloned contents
479 // of the originals.
480 assert(CloneWorklist.empty() && "Dirty worklist before re-use\n");
481 CloneWorklist.push_back(&OldFunc->getEntryBlock());
482 while (!CloneWorklist.empty()) {
483 const BasicBlock *BB = CloneWorklist.back();
484 CloneWorklist.pop_back();
485 PFC.CloneBlock(BB, cast<BasicBlock>(VMap[BB]), CloneWorklist,
486 OrigBBs);
487 }
488
489 // Removed BB's that were created that turned out to be prunable.
490 // Actual cloning may have found pruning opportunities since
491 // branch or switch statement target may have been known at compile-time.
492 // Alternatively we could write a routine CloneFunction and add a) a
493 // parameter to actually do the cloning and b) a return parameter that
494 // gives a list of blocks that need to be cloned also. Then we could
495 // call CloneFunction when we collect the blocks to call, but suppress
496 // cloning. And actually *do* the cloning in the while loop above. Also
497 // the cleanup here would become redundant, and so would be the OrigBBs.
498 for (std::set<const BasicBlock *>::iterator Oi = OrigBBs.begin(),
499 Oe = OrigBBs.end(); Oi != Oe; ++Oi) {
500 const BasicBlock *Orig = *Oi;
501 BasicBlock *NewBB = cast<BasicBlock>(VMap[Orig]);
502 delete NewBB;
503 VMap[Orig] = 0;
504 }
505
Chris Lattner3df13f42006-05-27 01:22:24 +0000506 // Loop over all of the basic blocks in the old function. If the block was
507 // reachable, we have cloned it and the old block is now in the value map:
508 // insert it into the new function in the right order. If not, ignore it.
509 //
Chris Lattnercc340c02006-06-01 19:19:23 +0000510 // Defer PHI resolution until rest of function is resolved.
Chris Lattnerd84dbb32009-08-27 04:02:30 +0000511 SmallVector<const PHINode*, 16> PHIToResolve;
Chris Lattner3df13f42006-05-27 01:22:24 +0000512 for (Function::const_iterator BI = OldFunc->begin(), BE = OldFunc->end();
513 BI != BE; ++BI) {
Rafael Espindolac2240ad2010-10-13 02:08:17 +0000514 Value *V = VMap[BI];
515 BasicBlock *NewBB = cast_or_null<BasicBlock>(V);
Craig Topperf40110f2014-04-25 05:29:35 +0000516 if (!NewBB) continue; // Dead block.
Chris Lattnercc340c02006-06-01 19:19:23 +0000517
Chris Lattner3df13f42006-05-27 01:22:24 +0000518 // Add the new block to the new function.
519 NewFunc->getBasicBlockList().push_back(NewBB);
Devang Patelf6eeaeb2009-11-10 23:06:00 +0000520
Chris Lattner3df13f42006-05-27 01:22:24 +0000521 // Handle PHI nodes specially, as we have to remove references to dead
522 // blocks.
Chandler Carruth21211992012-03-25 04:03:40 +0000523 for (BasicBlock::const_iterator I = BI->begin(), E = BI->end(); I != E; ++I)
524 if (const PHINode *PN = dyn_cast<PHINode>(I))
525 PHIToResolve.push_back(PN);
526 else
527 break;
528
529 // Finally, remap the terminator instructions, as those can't be remapped
530 // until all BBs are mapped.
531 RemapInstruction(NewBB->getTerminator(), VMap,
532 ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges);
Chris Lattner3df13f42006-05-27 01:22:24 +0000533 }
Chris Lattnercc340c02006-06-01 19:19:23 +0000534
535 // Defer PHI resolution until rest of function is resolved, PHI resolution
536 // requires the CFG to be up-to-date.
537 for (unsigned phino = 0, e = PHIToResolve.size(); phino != e; ) {
538 const PHINode *OPN = PHIToResolve[phino];
Chris Lattnercc340c02006-06-01 19:19:23 +0000539 unsigned NumPreds = OPN->getNumIncomingValues();
Chris Lattnercc340c02006-06-01 19:19:23 +0000540 const BasicBlock *OldBB = OPN->getParent();
Devang Patelb8f11de2010-06-23 23:55:51 +0000541 BasicBlock *NewBB = cast<BasicBlock>(VMap[OldBB]);
Chris Lattnercc340c02006-06-01 19:19:23 +0000542
543 // Map operands for blocks that are live and remove operands for blocks
544 // that are dead.
545 for (; phino != PHIToResolve.size() &&
546 PHIToResolve[phino]->getParent() == OldBB; ++phino) {
547 OPN = PHIToResolve[phino];
Devang Patelb8f11de2010-06-23 23:55:51 +0000548 PHINode *PN = cast<PHINode>(VMap[OPN]);
Chris Lattnercc340c02006-06-01 19:19:23 +0000549 for (unsigned pred = 0, e = NumPreds; pred != e; ++pred) {
Rafael Espindolac2240ad2010-10-13 02:08:17 +0000550 Value *V = VMap[PN->getIncomingBlock(pred)];
Chris Lattner43f8d162011-01-08 08:15:20 +0000551 if (BasicBlock *MappedBlock = cast_or_null<BasicBlock>(V)) {
Owen Andersone70b6372009-07-05 22:41:43 +0000552 Value *InVal = MapValue(PN->getIncomingValue(pred),
Chris Lattner43f8d162011-01-08 08:15:20 +0000553 VMap,
554 ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges);
Chris Lattnercc340c02006-06-01 19:19:23 +0000555 assert(InVal && "Unknown input value?");
556 PN->setIncomingValue(pred, InVal);
557 PN->setIncomingBlock(pred, MappedBlock);
558 } else {
559 PN->removeIncomingValue(pred, false);
560 --pred, --e; // Revisit the next entry.
561 }
562 }
563 }
564
565 // The loop above has removed PHI entries for those blocks that are dead
566 // and has updated others. However, if a block is live (i.e. copied over)
567 // but its terminator has been changed to not go to this block, then our
568 // phi nodes will have invalid entries. Update the PHI nodes in this
569 // case.
570 PHINode *PN = cast<PHINode>(NewBB->begin());
571 NumPreds = std::distance(pred_begin(NewBB), pred_end(NewBB));
572 if (NumPreds != PN->getNumIncomingValues()) {
573 assert(NumPreds < PN->getNumIncomingValues());
574 // Count how many times each predecessor comes to this block.
575 std::map<BasicBlock*, unsigned> PredCount;
576 for (pred_iterator PI = pred_begin(NewBB), E = pred_end(NewBB);
577 PI != E; ++PI)
578 --PredCount[*PI];
579
580 // Figure out how many entries to remove from each PHI.
581 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
582 ++PredCount[PN->getIncomingBlock(i)];
583
584 // At this point, the excess predecessor entries are positive in the
585 // map. Loop over all of the PHIs and remove excess predecessor
586 // entries.
587 BasicBlock::iterator I = NewBB->begin();
588 for (; (PN = dyn_cast<PHINode>(I)); ++I) {
589 for (std::map<BasicBlock*, unsigned>::iterator PCI =PredCount.begin(),
590 E = PredCount.end(); PCI != E; ++PCI) {
591 BasicBlock *Pred = PCI->first;
592 for (unsigned NumToRemove = PCI->second; NumToRemove; --NumToRemove)
593 PN->removeIncomingValue(Pred, false);
594 }
595 }
596 }
597
598 // If the loops above have made these phi nodes have 0 or 1 operand,
599 // replace them with undef or the input value. We must do this for
600 // correctness, because 0-operand phis are not valid.
601 PN = cast<PHINode>(NewBB->begin());
602 if (PN->getNumIncomingValues() == 0) {
603 BasicBlock::iterator I = NewBB->begin();
604 BasicBlock::const_iterator OldI = OldBB->begin();
605 while ((PN = dyn_cast<PHINode>(I++))) {
Owen Andersonb292b8c2009-07-30 23:03:37 +0000606 Value *NV = UndefValue::get(PN->getType());
Chris Lattnercc340c02006-06-01 19:19:23 +0000607 PN->replaceAllUsesWith(NV);
Devang Patelb8f11de2010-06-23 23:55:51 +0000608 assert(VMap[OldI] == PN && "VMap mismatch");
609 VMap[OldI] = NV;
Chris Lattnercc340c02006-06-01 19:19:23 +0000610 PN->eraseFromParent();
611 ++OldI;
612 }
Chris Lattnercc340c02006-06-01 19:19:23 +0000613 }
614 }
Chandler Carruthef82cf52012-03-25 10:34:54 +0000615
616 // Make a second pass over the PHINodes now that all of them have been
617 // remapped into the new function, simplifying the PHINode and performing any
618 // recursive simplifications exposed. This will transparently update the
Chandler Carruth772c88b2012-03-28 08:38:27 +0000619 // WeakVH in the VMap. Notably, we rely on that so that if we coalesce
Chandler Carruthef82cf52012-03-25 10:34:54 +0000620 // two PHINodes, the iteration over the old PHIs remains valid, and the
621 // mapping will just map us to the new node (which may not even be a PHI
622 // node).
623 for (unsigned Idx = 0, Size = PHIToResolve.size(); Idx != Size; ++Idx)
624 if (PHINode *PN = dyn_cast<PHINode>(VMap[PHIToResolve[Idx]]))
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000625 recursivelySimplifyInstruction(PN, DL);
Chandler Carruthef82cf52012-03-25 10:34:54 +0000626
Chris Lattner237ccf22006-09-13 21:27:00 +0000627 // Now that the inlined function body has been fully constructed, go through
628 // and zap unconditional fall-through branches. This happen all the time when
629 // specializing code: code specialization turns conditional branches into
630 // uncond branches, and this code folds them.
Chandler Carruth772c88b2012-03-28 08:38:27 +0000631 Function::iterator Begin = cast<BasicBlock>(VMap[&OldFunc->getEntryBlock()]);
632 Function::iterator I = Begin;
Chris Lattner237ccf22006-09-13 21:27:00 +0000633 while (I != NewFunc->end()) {
Chandler Carruth772c88b2012-03-28 08:38:27 +0000634 // Check if this block has become dead during inlining or other
635 // simplifications. Note that the first block will appear dead, as it has
636 // not yet been wired up properly.
637 if (I != Begin && (pred_begin(I) == pred_end(I) ||
638 I->getSinglePredecessor() == I)) {
639 BasicBlock *DeadBB = I++;
640 DeleteDeadBlock(DeadBB);
641 continue;
642 }
643
644 // We need to simplify conditional branches and switches with a constant
645 // operand. We try to prune these out when cloning, but if the
646 // simplification required looking through PHI nodes, those are only
647 // available after forming the full basic block. That may leave some here,
648 // and we still want to prune the dead code as early as possible.
649 ConstantFoldTerminator(I);
650
Chris Lattner237ccf22006-09-13 21:27:00 +0000651 BranchInst *BI = dyn_cast<BranchInst>(I->getTerminator());
652 if (!BI || BI->isConditional()) { ++I; continue; }
653
654 BasicBlock *Dest = BI->getSuccessor(0);
Chandler Carruthef82cf52012-03-25 10:34:54 +0000655 if (!Dest->getSinglePredecessor()) {
Chris Lattnerce494222007-02-01 18:48:38 +0000656 ++I; continue;
657 }
Chandler Carruthef82cf52012-03-25 10:34:54 +0000658
659 // We shouldn't be able to get single-entry PHI nodes here, as instsimplify
660 // above should have zapped all of them..
661 assert(!isa<PHINode>(Dest->begin()));
662
Chris Lattner237ccf22006-09-13 21:27:00 +0000663 // We know all single-entry PHI nodes in the inlined function have been
664 // removed, so we just need to splice the blocks.
665 BI->eraseFromParent();
666
Eric Christopher96513122011-06-23 06:24:52 +0000667 // Make all PHI nodes that referred to Dest now refer to I as their source.
668 Dest->replaceAllUsesWith(I);
669
Jay Foad61ea0e42011-06-23 09:09:15 +0000670 // Move all the instructions in the succ to the pred.
671 I->getInstList().splice(I->end(), Dest->getInstList());
672
Chris Lattner237ccf22006-09-13 21:27:00 +0000673 // Remove the dest block.
674 Dest->eraseFromParent();
675
676 // Do not increment I, iteratively merge all things this block branches to.
677 }
Chandler Carruth49da9332012-04-06 17:21:31 +0000678
679 // Make a final pass over the basic blocks from theh old function to gather
680 // any return instructions which survived folding. We have to do this here
681 // because we can iteratively remove and merge returns above.
682 for (Function::iterator I = cast<BasicBlock>(VMap[&OldFunc->getEntryBlock()]),
683 E = NewFunc->end();
684 I != E; ++I)
685 if (ReturnInst *RI = dyn_cast<ReturnInst>(I->getTerminator()))
686 Returns.push_back(RI);
Chris Lattner3df13f42006-05-27 01:22:24 +0000687}