blob: a199086aedb3d5414b0e176005659a92c40a2753 [file] [log] [blame]
Chris Lattner6c2e2e52002-11-19 22:04:49 +00001//===- CloneFunction.cpp - Clone a function into another function ---------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-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 Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner6c2e2e52002-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 Lattnerfa703a42002-03-29 19:03:54 +000015
Chris Lattner309f1932002-11-19 20:59:41 +000016#include "llvm/Transforms/Utils/Cloning.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000017#include "llvm/ADT/SmallVector.h"
18#include "llvm/Analysis/ConstantFolding.h"
19#include "llvm/Analysis/InstructionSimplify.h"
Stephen Hines36b56882014-04-23 16:57:46 -070020#include "llvm/IR/CFG.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000021#include "llvm/IR/Constants.h"
Stephen Hines36b56882014-04-23 16:57:46 -070022#include "llvm/IR/DebugInfo.h"
Chandler Carruth0b8c9a82013-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"
Stephen Hines36b56882014-04-23 16:57:46 -070030#include "llvm/IR/Module.h"
Chandler Carruthafff3302012-03-28 08:38:27 +000031#include "llvm/Transforms/Utils/BasicBlockUtils.h"
32#include "llvm/Transforms/Utils/Local.h"
Dan Gohman05ea54e2010-08-24 18:50:07 +000033#include "llvm/Transforms/Utils/ValueMapper.h"
Chris Lattner5e665f52007-02-03 00:08:31 +000034#include <map>
Chris Lattnerf7703df2004-01-09 06:12:26 +000035using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000036
Chris Lattner17d145d2003-04-18 03:50:09 +000037// CloneBasicBlock - See comments in Cloning.h
Chris Lattnerf7703df2004-01-09 06:12:26 +000038BasicBlock *llvm::CloneBasicBlock(const BasicBlock *BB,
Devang Patel774cca72010-06-24 00:00:42 +000039 ValueToValueMapTy &VMap,
Benjamin Kramer5deb57c2010-01-27 19:58:47 +000040 const Twine &NameSuffix, Function *F,
Chris Lattnera4c29d22006-01-13 18:39:17 +000041 ClonedCodeInfo *CodeInfo) {
Owen Anderson1d0be152009-08-13 21:58:54 +000042 BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), "", F);
Chris Lattner17d145d2003-04-18 03:50:09 +000043 if (BB->hasName()) NewBB->setName(BB->getName()+NameSuffix);
44
Chris Lattnera4c29d22006-01-13 18:39:17 +000045 bool hasCalls = false, hasDynamicAllocas = false, hasStaticAllocas = false;
46
47 // Loop over all instructions, and copy them over.
Chris Lattner17d145d2003-04-18 03:50:09 +000048 for (BasicBlock::const_iterator II = BB->begin(), IE = BB->end();
49 II != IE; ++II) {
Nick Lewycky67760642009-09-27 07:38:41 +000050 Instruction *NewInst = II->clone();
Chris Lattner17d145d2003-04-18 03:50:09 +000051 if (II->hasName())
52 NewInst->setName(II->getName()+NameSuffix);
53 NewBB->getInstList().push_back(NewInst);
Devang Patel29d3dd82010-06-23 23:55:51 +000054 VMap[II] = NewInst; // Add instruction map to value.
Chris Lattnera4c29d22006-01-13 18:39:17 +000055
Dale Johannesen8aa90fe2009-03-10 22:20:02 +000056 hasCalls |= (isa<CallInst>(II) && !isa<DbgInfoIntrinsic>(II));
Chris Lattnera4c29d22006-01-13 18:39:17 +000057 if (const AllocaInst *AI = dyn_cast<AllocaInst>(II)) {
58 if (isa<ConstantInt>(AI->getArraySize()))
59 hasStaticAllocas = true;
60 else
61 hasDynamicAllocas = true;
62 }
63 }
64
65 if (CodeInfo) {
66 CodeInfo->ContainsCalls |= hasCalls;
Chris Lattnera4c29d22006-01-13 18:39:17 +000067 CodeInfo->ContainsDynamicAllocas |= hasDynamicAllocas;
68 CodeInfo->ContainsDynamicAllocas |= hasStaticAllocas &&
Dan Gohmanecb7a772007-03-22 16:38:57 +000069 BB != &BB->getParent()->getEntryBlock();
Chris Lattner17d145d2003-04-18 03:50:09 +000070 }
71 return NewBB;
72}
73
Chris Lattnerfa703a42002-03-29 19:03:54 +000074// Clone OldFunc into NewFunc, transforming the old arguments into references to
Dan Gohman6cb8c232010-08-26 15:41:53 +000075// VMap values.
Chris Lattnerfa703a42002-03-29 19:03:54 +000076//
Chris Lattnerf7703df2004-01-09 06:12:26 +000077void llvm::CloneFunctionInto(Function *NewFunc, const Function *OldFunc,
Devang Patel774cca72010-06-24 00:00:42 +000078 ValueToValueMapTy &VMap,
Dan Gohman6cb8c232010-08-26 15:41:53 +000079 bool ModuleLevelChanges,
Chris Lattnerec1bea02009-08-27 04:02:30 +000080 SmallVectorImpl<ReturnInst*> &Returns,
Mon P Wangd24397a2011-12-23 02:18:32 +000081 const char *NameSuffix, ClonedCodeInfo *CodeInfo,
James Molloya84a83b2013-05-28 15:17:05 +000082 ValueMapTypeRemapper *TypeMapper,
83 ValueMaterializer *Materializer) {
Chris Lattnerdcd80402002-11-19 21:54:07 +000084 assert(NameSuffix && "NameSuffix cannot be null!");
Misha Brukmanfd939082005-04-21 23:48:37 +000085
Chris Lattnerd1801552002-11-19 22:54:01 +000086#ifndef NDEBUG
Chris Lattnera4c29d22006-01-13 18:39:17 +000087 for (Function::const_arg_iterator I = OldFunc->arg_begin(),
88 E = OldFunc->arg_end(); I != E; ++I)
Devang Patel29d3dd82010-06-23 23:55:51 +000089 assert(VMap.count(I) && "No mapping from source argument specified!");
Chris Lattnerd1801552002-11-19 22:54:01 +000090#endif
Chris Lattnerfa703a42002-03-29 19:03:54 +000091
Stephen Hines36b56882014-04-23 16:57:46 -070092 // Copy all attributes other than those stored in the AttributeSet. We need
93 // to remap the parameter indices of the AttributeSet.
94 AttributeSet NewAttrs = NewFunc->getAttributes();
95 NewFunc->copyAttributesFrom(OldFunc);
96 NewFunc->setAttributes(NewAttrs);
97
Joey Gouly0f57a982013-04-10 10:37:38 +000098 AttributeSet OldAttrs = OldFunc->getAttributes();
99 // Clone any argument attributes that are present in the VMap.
Stephen Hines36b56882014-04-23 16:57:46 -0700100 for (const Argument &OldArg : OldFunc->args())
101 if (Argument *NewArg = dyn_cast<Argument>(VMap[&OldArg])) {
Joey Gouly0f57a982013-04-10 10:37:38 +0000102 AttributeSet attrs =
Stephen Hines36b56882014-04-23 16:57:46 -0700103 OldAttrs.getParamAttributes(OldArg.getArgNo() + 1);
Joey Gouly0f57a982013-04-10 10:37:38 +0000104 if (attrs.getNumSlots() > 0)
Stephen Hines36b56882014-04-23 16:57:46 -0700105 NewArg->addAttr(attrs);
Joey Gouly0f57a982013-04-10 10:37:38 +0000106 }
Andrew Lenharth82cf32e2008-10-07 18:08:38 +0000107
Stephen Hines36b56882014-04-23 16:57:46 -0700108 NewFunc->setAttributes(
109 NewFunc->getAttributes()
110 .addAttributes(NewFunc->getContext(), AttributeSet::ReturnIndex,
111 OldAttrs.getRetAttributes())
112 .addAttributes(NewFunc->getContext(), AttributeSet::FunctionIndex,
113 OldAttrs.getFnAttributes()));
Anton Korobeynikov9e49f1b2008-03-23 16:03:00 +0000114
Chris Lattnerfa703a42002-03-29 19:03:54 +0000115 // Loop over all of the basic blocks in the function, cloning them as
Chris Lattnerdcd80402002-11-19 21:54:07 +0000116 // appropriate. Note that we save BE this way in order to handle cloning of
117 // recursive functions into themselves.
Chris Lattnerfa703a42002-03-29 19:03:54 +0000118 //
119 for (Function::const_iterator BI = OldFunc->begin(), BE = OldFunc->end();
120 BI != BE; ++BI) {
Chris Lattner18961502002-06-25 16:12:52 +0000121 const BasicBlock &BB = *BI;
Misha Brukmanfd939082005-04-21 23:48:37 +0000122
Chris Lattner17d145d2003-04-18 03:50:09 +0000123 // Create a new basic block and copy instructions into it!
Chris Lattnerb5fa5fc2011-01-08 08:15:20 +0000124 BasicBlock *CBB = CloneBasicBlock(&BB, VMap, NameSuffix, NewFunc, CodeInfo);
Chris Lattnerfa703a42002-03-29 19:03:54 +0000125
Eli Friedman4090e1c2011-10-21 20:45:19 +0000126 // Add basic block mapping.
127 VMap[&BB] = CBB;
128
129 // It is only legal to clone a function if a block address within that
130 // function is never referenced outside of the function. Given that, we
131 // want to map block addresses from the old function to block addresses in
132 // the clone. (This is different from the generic ValueMapper
133 // implementation, which generates an invalid blockaddress when
134 // cloning a function.)
135 if (BB.hasAddressTaken()) {
136 Constant *OldBBAddr = BlockAddress::get(const_cast<Function*>(OldFunc),
137 const_cast<BasicBlock*>(&BB));
138 VMap[OldBBAddr] = BlockAddress::get(NewFunc, CBB);
139 }
140
141 // Note return instructions for the caller.
Chris Lattnerdcd80402002-11-19 21:54:07 +0000142 if (ReturnInst *RI = dyn_cast<ReturnInst>(CBB->getTerminator()))
143 Returns.push_back(RI);
Chris Lattnerfa703a42002-03-29 19:03:54 +0000144 }
145
Misha Brukmanfd939082005-04-21 23:48:37 +0000146 // Loop over all of the instructions in the function, fixing up operand
Devang Patel29d3dd82010-06-23 23:55:51 +0000147 // references as we go. This uses VMap to do all the hard work.
Devang Patel29d3dd82010-06-23 23:55:51 +0000148 for (Function::iterator BB = cast<BasicBlock>(VMap[OldFunc->begin()]),
Nick Lewycky280a6e62008-04-25 16:53:59 +0000149 BE = NewFunc->end(); BB != BE; ++BB)
Chris Lattnerfa703a42002-03-29 19:03:54 +0000150 // Loop over all instructions, fixing each one as we find it...
Chris Lattnera33ceaa2004-02-04 21:44:26 +0000151 for (BasicBlock::iterator II = BB->begin(); II != BB->end(); ++II)
Chris Lattnerb5fa5fc2011-01-08 08:15:20 +0000152 RemapInstruction(II, VMap,
Mon P Wangd24397a2011-12-23 02:18:32 +0000153 ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges,
James Molloya84a83b2013-05-28 15:17:05 +0000154 TypeMapper, Materializer);
Chris Lattnerfa703a42002-03-29 19:03:54 +0000155}
Chris Lattner5a8932f2002-11-19 23:12:22 +0000156
Stephen Hines36b56882014-04-23 16:57:46 -0700157// Find the MDNode which corresponds to the DISubprogram data that described F.
158static MDNode* FindSubprogram(const Function *F, DebugInfoFinder &Finder) {
159 for (DISubprogram Subprogram : Finder.subprograms()) {
160 if (Subprogram.describes(F)) return Subprogram;
161 }
162 return NULL;
163}
164
165// Add an operand to an existing MDNode. The new operand will be added at the
166// back of the operand list.
167static void AddOperand(MDNode *Node, Value *Operand) {
168 SmallVector<Value*, 16> Operands;
169 for (unsigned i = 0; i < Node->getNumOperands(); i++) {
170 Operands.push_back(Node->getOperand(i));
171 }
172 Operands.push_back(Operand);
173 MDNode *NewNode = MDNode::get(Node->getContext(), Operands);
174 Node->replaceAllUsesWith(NewNode);
175}
176
177// Clone the module-level debug info associated with OldFunc. The cloned data
178// will point to NewFunc instead.
179static void CloneDebugInfoMetadata(Function *NewFunc, const Function *OldFunc,
180 ValueToValueMapTy &VMap) {
181 DebugInfoFinder Finder;
182 Finder.processModule(*OldFunc->getParent());
183
184 const MDNode *OldSubprogramMDNode = FindSubprogram(OldFunc, Finder);
185 if (!OldSubprogramMDNode) return;
186
187 // Ensure that OldFunc appears in the map.
188 // (if it's already there it must point to NewFunc anyway)
189 VMap[OldFunc] = NewFunc;
190 DISubprogram NewSubprogram(MapValue(OldSubprogramMDNode, VMap));
191
192 for (DICompileUnit CU : Finder.compile_units()) {
193 DIArray Subprograms(CU.getSubprograms());
194
195 // If the compile unit's function list contains the old function, it should
196 // also contain the new one.
197 for (unsigned i = 0; i < Subprograms.getNumElements(); i++) {
198 if ((MDNode*)Subprograms.getElement(i) == OldSubprogramMDNode) {
199 AddOperand(Subprograms, NewSubprogram);
200 }
201 }
202 }
203}
204
Chris Lattner5a8932f2002-11-19 23:12:22 +0000205/// CloneFunction - Return a copy of the specified function, but without
206/// embedding the function into another module. Also, any references specified
Devang Patel29d3dd82010-06-23 23:55:51 +0000207/// in the VMap are changed to refer to their mapped value instead of the
208/// original one. If any of the arguments to the function are in the VMap,
209/// the arguments are deleted from the resultant function. The VMap is
Chris Lattner5a8932f2002-11-19 23:12:22 +0000210/// updated to include mappings from all of the instructions and basicblocks in
211/// the function from their old to new values.
212///
Chris Lattnerb5fa5fc2011-01-08 08:15:20 +0000213Function *llvm::CloneFunction(const Function *F, ValueToValueMapTy &VMap,
Dan Gohman6cb8c232010-08-26 15:41:53 +0000214 bool ModuleLevelChanges,
Chris Lattnera4c29d22006-01-13 18:39:17 +0000215 ClonedCodeInfo *CodeInfo) {
Jay Foad5fdd6c82011-07-12 14:06:48 +0000216 std::vector<Type*> ArgTypes;
Chris Lattner5a8932f2002-11-19 23:12:22 +0000217
218 // The user might be deleting arguments to the function by specifying them in
Devang Patel29d3dd82010-06-23 23:55:51 +0000219 // the VMap. If so, we need to not add the arguments to the arg ty vector
Chris Lattner5a8932f2002-11-19 23:12:22 +0000220 //
Chris Lattnera4c29d22006-01-13 18:39:17 +0000221 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
222 I != E; ++I)
Devang Patel29d3dd82010-06-23 23:55:51 +0000223 if (VMap.count(I) == 0) // Haven't mapped the argument to anything yet?
Chris Lattner5a8932f2002-11-19 23:12:22 +0000224 ArgTypes.push_back(I->getType());
225
226 // Create a new function type...
Owen Andersondebcb012009-07-29 22:17:13 +0000227 FunctionType *FTy = FunctionType::get(F->getFunctionType()->getReturnType(),
Chris Lattner5a8932f2002-11-19 23:12:22 +0000228 ArgTypes, F->getFunctionType()->isVarArg());
229
230 // Create the new function...
Gabor Greif051a9502008-04-06 20:25:17 +0000231 Function *NewF = Function::Create(FTy, F->getLinkage(), F->getName());
Misha Brukmanfd939082005-04-21 23:48:37 +0000232
Chris Lattner5a8932f2002-11-19 23:12:22 +0000233 // Loop over the arguments, copying the names of the mapped arguments over...
Chris Lattnere4d5c442005-03-15 04:54:21 +0000234 Function::arg_iterator DestI = NewF->arg_begin();
Chris Lattnera4c29d22006-01-13 18:39:17 +0000235 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
236 I != E; ++I)
Devang Patel29d3dd82010-06-23 23:55:51 +0000237 if (VMap.count(I) == 0) { // Is this argument preserved?
Chris Lattner5a8932f2002-11-19 23:12:22 +0000238 DestI->setName(I->getName()); // Copy the name over...
Devang Patel29d3dd82010-06-23 23:55:51 +0000239 VMap[I] = DestI++; // Add mapping to VMap
Chris Lattner5a8932f2002-11-19 23:12:22 +0000240 }
241
Stephen Hines36b56882014-04-23 16:57:46 -0700242 if (ModuleLevelChanges)
243 CloneDebugInfoMetadata(NewF, F, VMap);
244
Chris Lattnerec1bea02009-08-27 04:02:30 +0000245 SmallVector<ReturnInst*, 8> Returns; // Ignore returns cloned.
Dan Gohman6cb8c232010-08-26 15:41:53 +0000246 CloneFunctionInto(NewF, F, VMap, ModuleLevelChanges, Returns, "", CodeInfo);
Misha Brukmanfd939082005-04-21 23:48:37 +0000247 return NewF;
Chris Lattner5a8932f2002-11-19 23:12:22 +0000248}
Brian Gaeked0fde302003-11-11 22:41:34 +0000249
Chris Lattner83f03bf2006-05-27 01:22:24 +0000250
251
252namespace {
253 /// PruningFunctionCloner - This class is a private class used to implement
254 /// the CloneAndPruneFunctionInto method.
Nick Lewycky6726b6d2009-10-25 06:33:48 +0000255 struct PruningFunctionCloner {
Chris Lattner83f03bf2006-05-27 01:22:24 +0000256 Function *NewFunc;
257 const Function *OldFunc;
Devang Patel774cca72010-06-24 00:00:42 +0000258 ValueToValueMapTy &VMap;
Dan Gohman6cb8c232010-08-26 15:41:53 +0000259 bool ModuleLevelChanges;
Chris Lattner83f03bf2006-05-27 01:22:24 +0000260 const char *NameSuffix;
261 ClonedCodeInfo *CodeInfo;
Stephen Hines36b56882014-04-23 16:57:46 -0700262 const DataLayout *DL;
Chris Lattner83f03bf2006-05-27 01:22:24 +0000263 public:
264 PruningFunctionCloner(Function *newFunc, const Function *oldFunc,
Devang Patel774cca72010-06-24 00:00:42 +0000265 ValueToValueMapTy &valueMap,
Dan Gohman6cb8c232010-08-26 15:41:53 +0000266 bool moduleLevelChanges,
Chris Lattner83f03bf2006-05-27 01:22:24 +0000267 const char *nameSuffix,
Chris Lattner1dfdf822007-01-30 23:22:39 +0000268 ClonedCodeInfo *codeInfo,
Stephen Hines36b56882014-04-23 16:57:46 -0700269 const DataLayout *DL)
Dan Gohman6cb8c232010-08-26 15:41:53 +0000270 : NewFunc(newFunc), OldFunc(oldFunc),
271 VMap(valueMap), ModuleLevelChanges(moduleLevelChanges),
Stephen Hines36b56882014-04-23 16:57:46 -0700272 NameSuffix(nameSuffix), CodeInfo(codeInfo), DL(DL) {
Chris Lattner83f03bf2006-05-27 01:22:24 +0000273 }
274
275 /// CloneBlock - The specified block is found to be reachable, clone it and
276 /// anything that it can reach.
Chris Lattner67ef2412007-03-02 03:11:20 +0000277 void CloneBlock(const BasicBlock *BB,
278 std::vector<const BasicBlock*> &ToClone);
Chris Lattner83f03bf2006-05-27 01:22:24 +0000279 };
280}
281
282/// CloneBlock - The specified block is found to be reachable, clone it and
283/// anything that it can reach.
Chris Lattner67ef2412007-03-02 03:11:20 +0000284void PruningFunctionCloner::CloneBlock(const BasicBlock *BB,
285 std::vector<const BasicBlock*> &ToClone){
Chandler Carruthafff3302012-03-28 08:38:27 +0000286 WeakVH &BBEntry = VMap[BB];
Chris Lattner83f03bf2006-05-27 01:22:24 +0000287
288 // Have we already cloned this block?
289 if (BBEntry) return;
290
291 // Nope, clone it now.
292 BasicBlock *NewBB;
Owen Anderson1d0be152009-08-13 21:58:54 +0000293 BBEntry = NewBB = BasicBlock::Create(BB->getContext());
Chris Lattner83f03bf2006-05-27 01:22:24 +0000294 if (BB->hasName()) NewBB->setName(BB->getName()+NameSuffix);
295
Eli Friedman4090e1c2011-10-21 20:45:19 +0000296 // It is only legal to clone a function if a block address within that
297 // function is never referenced outside of the function. Given that, we
298 // want to map block addresses from the old function to block addresses in
299 // the clone. (This is different from the generic ValueMapper
300 // implementation, which generates an invalid blockaddress when
301 // cloning a function.)
302 //
303 // Note that we don't need to fix the mapping for unreachable blocks;
304 // the default mapping there is safe.
305 if (BB->hasAddressTaken()) {
306 Constant *OldBBAddr = BlockAddress::get(const_cast<Function*>(OldFunc),
307 const_cast<BasicBlock*>(BB));
308 VMap[OldBBAddr] = BlockAddress::get(NewFunc, NewBB);
309 }
310
311
Chris Lattner83f03bf2006-05-27 01:22:24 +0000312 bool hasCalls = false, hasDynamicAllocas = false, hasStaticAllocas = false;
313
314 // Loop over all instructions, and copy them over, DCE'ing as we go. This
315 // loop doesn't include the terminator.
Chris Lattner35033ef2006-06-01 19:19:23 +0000316 for (BasicBlock::const_iterator II = BB->begin(), IE = --BB->end();
Chris Lattner83f03bf2006-05-27 01:22:24 +0000317 II != IE; ++II) {
Chandler Carruthd54f9a42012-03-25 04:03:40 +0000318 Instruction *NewInst = II->clone();
319
320 // Eagerly remap operands to the newly cloned instruction, except for PHI
321 // nodes for which we defer processing until we update the CFG.
322 if (!isa<PHINode>(NewInst)) {
323 RemapInstruction(NewInst, VMap,
324 ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges);
325
326 // If we can simplify this instruction to some other value, simply add
327 // a mapping to that value rather than inserting a new instruction into
328 // the basic block.
Stephen Hines36b56882014-04-23 16:57:46 -0700329 if (Value *V = SimplifyInstruction(NewInst, DL)) {
Chandler Carruthd54f9a42012-03-25 04:03:40 +0000330 // On the off-chance that this simplifies to an instruction in the old
331 // function, map it back into the new function.
332 if (Value *MappedV = VMap.lookup(V))
333 V = MappedV;
334
335 VMap[II] = V;
336 delete NewInst;
337 continue;
338 }
Chris Lattner83f03bf2006-05-27 01:22:24 +0000339 }
Devang Patelf66d7b52009-02-10 07:48:18 +0000340
Chris Lattner83f03bf2006-05-27 01:22:24 +0000341 if (II->hasName())
342 NewInst->setName(II->getName()+NameSuffix);
Devang Patel29d3dd82010-06-23 23:55:51 +0000343 VMap[II] = NewInst; // Add instruction map to value.
Chandler Carruthd54f9a42012-03-25 04:03:40 +0000344 NewBB->getInstList().push_back(NewInst);
Dale Johannesen8aa90fe2009-03-10 22:20:02 +0000345 hasCalls |= (isa<CallInst>(II) && !isa<DbgInfoIntrinsic>(II));
Chris Lattner83f03bf2006-05-27 01:22:24 +0000346 if (const AllocaInst *AI = dyn_cast<AllocaInst>(II)) {
347 if (isa<ConstantInt>(AI->getArraySize()))
348 hasStaticAllocas = true;
349 else
350 hasDynamicAllocas = true;
351 }
352 }
353
Chris Lattner35033ef2006-06-01 19:19:23 +0000354 // Finally, clone over the terminator.
355 const TerminatorInst *OldTI = BB->getTerminator();
356 bool TerminatorDone = false;
357 if (const BranchInst *BI = dyn_cast<BranchInst>(OldTI)) {
358 if (BI->isConditional()) {
359 // If the condition was a known constant in the callee...
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000360 ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition());
361 // Or is a known constant in the caller...
Rafael Espindola6688c4a2010-10-13 02:08:17 +0000362 if (Cond == 0) {
363 Value *V = VMap[BI->getCondition()];
364 Cond = dyn_cast_or_null<ConstantInt>(V);
365 }
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000366
367 // Constant fold to uncond branch!
368 if (Cond) {
Reid Spencer579dca12007-01-12 04:24:46 +0000369 BasicBlock *Dest = BI->getSuccessor(!Cond->getZExtValue());
Devang Patel29d3dd82010-06-23 23:55:51 +0000370 VMap[OldTI] = BranchInst::Create(Dest, NewBB);
Chris Lattner67ef2412007-03-02 03:11:20 +0000371 ToClone.push_back(Dest);
Chris Lattner35033ef2006-06-01 19:19:23 +0000372 TerminatorDone = true;
373 }
374 }
375 } else if (const SwitchInst *SI = dyn_cast<SwitchInst>(OldTI)) {
376 // If switching on a value known constant in the caller.
377 ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition());
Rafael Espindola6688c4a2010-10-13 02:08:17 +0000378 if (Cond == 0) { // Or known constant after constant prop in the callee...
379 Value *V = VMap[SI->getCondition()];
380 Cond = dyn_cast_or_null<ConstantInt>(V);
381 }
Chris Lattner35033ef2006-06-01 19:19:23 +0000382 if (Cond) { // Constant fold to uncond branch!
Stepan Dyatkovskiyc10fa6c2012-03-08 07:06:20 +0000383 SwitchInst::ConstCaseIt Case = SI->findCaseValue(Cond);
384 BasicBlock *Dest = const_cast<BasicBlock*>(Case.getCaseSuccessor());
Devang Patel29d3dd82010-06-23 23:55:51 +0000385 VMap[OldTI] = BranchInst::Create(Dest, NewBB);
Chris Lattner67ef2412007-03-02 03:11:20 +0000386 ToClone.push_back(Dest);
Chris Lattner35033ef2006-06-01 19:19:23 +0000387 TerminatorDone = true;
388 }
389 }
390
391 if (!TerminatorDone) {
Nick Lewycky67760642009-09-27 07:38:41 +0000392 Instruction *NewInst = OldTI->clone();
Chris Lattner35033ef2006-06-01 19:19:23 +0000393 if (OldTI->hasName())
394 NewInst->setName(OldTI->getName()+NameSuffix);
395 NewBB->getInstList().push_back(NewInst);
Devang Patel29d3dd82010-06-23 23:55:51 +0000396 VMap[OldTI] = NewInst; // Add instruction map to value.
Chris Lattner35033ef2006-06-01 19:19:23 +0000397
398 // Recursively clone any reachable successor blocks.
399 const TerminatorInst *TI = BB->getTerminator();
400 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
Chris Lattner67ef2412007-03-02 03:11:20 +0000401 ToClone.push_back(TI->getSuccessor(i));
Chris Lattner35033ef2006-06-01 19:19:23 +0000402 }
403
Chris Lattner83f03bf2006-05-27 01:22:24 +0000404 if (CodeInfo) {
405 CodeInfo->ContainsCalls |= hasCalls;
Chris Lattner83f03bf2006-05-27 01:22:24 +0000406 CodeInfo->ContainsDynamicAllocas |= hasDynamicAllocas;
407 CodeInfo->ContainsDynamicAllocas |= hasStaticAllocas &&
408 BB != &BB->getParent()->front();
409 }
Chris Lattner83f03bf2006-05-27 01:22:24 +0000410}
411
Chris Lattner83f03bf2006-05-27 01:22:24 +0000412/// CloneAndPruneFunctionInto - This works exactly like CloneFunctionInto,
413/// except that it does some simple constant prop and DCE on the fly. The
414/// effect of this is to copy significantly less code in cases where (for
415/// example) a function call with constant arguments is inlined, and those
416/// constant arguments cause a significant amount of code in the callee to be
Duncan Sandsdc024672007-11-27 13:23:08 +0000417/// dead. Since this doesn't produce an exact copy of the input, it can't be
Chris Lattner83f03bf2006-05-27 01:22:24 +0000418/// used for things like CloneFunction or CloneModule.
419void llvm::CloneAndPruneFunctionInto(Function *NewFunc, const Function *OldFunc,
Devang Patel774cca72010-06-24 00:00:42 +0000420 ValueToValueMapTy &VMap,
Dan Gohman6cb8c232010-08-26 15:41:53 +0000421 bool ModuleLevelChanges,
Chris Lattnerec1bea02009-08-27 04:02:30 +0000422 SmallVectorImpl<ReturnInst*> &Returns,
Chris Lattner83f03bf2006-05-27 01:22:24 +0000423 const char *NameSuffix,
Chris Lattner1dfdf822007-01-30 23:22:39 +0000424 ClonedCodeInfo *CodeInfo,
Stephen Hines36b56882014-04-23 16:57:46 -0700425 const DataLayout *DL,
Devang Patel53bb5c92009-11-10 23:06:00 +0000426 Instruction *TheCall) {
Chris Lattner83f03bf2006-05-27 01:22:24 +0000427 assert(NameSuffix && "NameSuffix cannot be null!");
428
429#ifndef NDEBUG
Jeff Cohend41b30d2006-11-05 19:31:28 +0000430 for (Function::const_arg_iterator II = OldFunc->arg_begin(),
431 E = OldFunc->arg_end(); II != E; ++II)
Devang Patel29d3dd82010-06-23 23:55:51 +0000432 assert(VMap.count(II) && "No mapping from source argument specified!");
Chris Lattner83f03bf2006-05-27 01:22:24 +0000433#endif
Duncan Sands28c3cff2008-05-26 19:58:59 +0000434
Dan Gohman6cb8c232010-08-26 15:41:53 +0000435 PruningFunctionCloner PFC(NewFunc, OldFunc, VMap, ModuleLevelChanges,
Stephen Hines36b56882014-04-23 16:57:46 -0700436 NameSuffix, CodeInfo, DL);
Chris Lattner83f03bf2006-05-27 01:22:24 +0000437
438 // Clone the entry block, and anything recursively reachable from it.
Chris Lattner67ef2412007-03-02 03:11:20 +0000439 std::vector<const BasicBlock*> CloneWorklist;
440 CloneWorklist.push_back(&OldFunc->getEntryBlock());
441 while (!CloneWorklist.empty()) {
442 const BasicBlock *BB = CloneWorklist.back();
443 CloneWorklist.pop_back();
444 PFC.CloneBlock(BB, CloneWorklist);
445 }
Chris Lattner83f03bf2006-05-27 01:22:24 +0000446
447 // Loop over all of the basic blocks in the old function. If the block was
448 // reachable, we have cloned it and the old block is now in the value map:
449 // insert it into the new function in the right order. If not, ignore it.
450 //
Chris Lattner35033ef2006-06-01 19:19:23 +0000451 // Defer PHI resolution until rest of function is resolved.
Chris Lattnerec1bea02009-08-27 04:02:30 +0000452 SmallVector<const PHINode*, 16> PHIToResolve;
Chris Lattner83f03bf2006-05-27 01:22:24 +0000453 for (Function::const_iterator BI = OldFunc->begin(), BE = OldFunc->end();
454 BI != BE; ++BI) {
Rafael Espindola6688c4a2010-10-13 02:08:17 +0000455 Value *V = VMap[BI];
456 BasicBlock *NewBB = cast_or_null<BasicBlock>(V);
Chris Lattner83f03bf2006-05-27 01:22:24 +0000457 if (NewBB == 0) continue; // Dead block.
Chris Lattner35033ef2006-06-01 19:19:23 +0000458
Chris Lattner83f03bf2006-05-27 01:22:24 +0000459 // Add the new block to the new function.
460 NewFunc->getBasicBlockList().push_back(NewBB);
Devang Patel53bb5c92009-11-10 23:06:00 +0000461
Chris Lattner83f03bf2006-05-27 01:22:24 +0000462 // Handle PHI nodes specially, as we have to remove references to dead
463 // blocks.
Chandler Carruthd54f9a42012-03-25 04:03:40 +0000464 for (BasicBlock::const_iterator I = BI->begin(), E = BI->end(); I != E; ++I)
465 if (const PHINode *PN = dyn_cast<PHINode>(I))
466 PHIToResolve.push_back(PN);
467 else
468 break;
469
470 // Finally, remap the terminator instructions, as those can't be remapped
471 // until all BBs are mapped.
472 RemapInstruction(NewBB->getTerminator(), VMap,
473 ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges);
Chris Lattner83f03bf2006-05-27 01:22:24 +0000474 }
Chris Lattner35033ef2006-06-01 19:19:23 +0000475
476 // Defer PHI resolution until rest of function is resolved, PHI resolution
477 // requires the CFG to be up-to-date.
478 for (unsigned phino = 0, e = PHIToResolve.size(); phino != e; ) {
479 const PHINode *OPN = PHIToResolve[phino];
Chris Lattner35033ef2006-06-01 19:19:23 +0000480 unsigned NumPreds = OPN->getNumIncomingValues();
Chris Lattner35033ef2006-06-01 19:19:23 +0000481 const BasicBlock *OldBB = OPN->getParent();
Devang Patel29d3dd82010-06-23 23:55:51 +0000482 BasicBlock *NewBB = cast<BasicBlock>(VMap[OldBB]);
Chris Lattner35033ef2006-06-01 19:19:23 +0000483
484 // Map operands for blocks that are live and remove operands for blocks
485 // that are dead.
486 for (; phino != PHIToResolve.size() &&
487 PHIToResolve[phino]->getParent() == OldBB; ++phino) {
488 OPN = PHIToResolve[phino];
Devang Patel29d3dd82010-06-23 23:55:51 +0000489 PHINode *PN = cast<PHINode>(VMap[OPN]);
Chris Lattner35033ef2006-06-01 19:19:23 +0000490 for (unsigned pred = 0, e = NumPreds; pred != e; ++pred) {
Rafael Espindola6688c4a2010-10-13 02:08:17 +0000491 Value *V = VMap[PN->getIncomingBlock(pred)];
Chris Lattnerb5fa5fc2011-01-08 08:15:20 +0000492 if (BasicBlock *MappedBlock = cast_or_null<BasicBlock>(V)) {
Owen Anderson0a205a42009-07-05 22:41:43 +0000493 Value *InVal = MapValue(PN->getIncomingValue(pred),
Chris Lattnerb5fa5fc2011-01-08 08:15:20 +0000494 VMap,
495 ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges);
Chris Lattner35033ef2006-06-01 19:19:23 +0000496 assert(InVal && "Unknown input value?");
497 PN->setIncomingValue(pred, InVal);
498 PN->setIncomingBlock(pred, MappedBlock);
499 } else {
500 PN->removeIncomingValue(pred, false);
501 --pred, --e; // Revisit the next entry.
502 }
503 }
504 }
505
506 // The loop above has removed PHI entries for those blocks that are dead
507 // and has updated others. However, if a block is live (i.e. copied over)
508 // but its terminator has been changed to not go to this block, then our
509 // phi nodes will have invalid entries. Update the PHI nodes in this
510 // case.
511 PHINode *PN = cast<PHINode>(NewBB->begin());
512 NumPreds = std::distance(pred_begin(NewBB), pred_end(NewBB));
513 if (NumPreds != PN->getNumIncomingValues()) {
514 assert(NumPreds < PN->getNumIncomingValues());
515 // Count how many times each predecessor comes to this block.
516 std::map<BasicBlock*, unsigned> PredCount;
517 for (pred_iterator PI = pred_begin(NewBB), E = pred_end(NewBB);
518 PI != E; ++PI)
519 --PredCount[*PI];
520
521 // Figure out how many entries to remove from each PHI.
522 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
523 ++PredCount[PN->getIncomingBlock(i)];
524
525 // At this point, the excess predecessor entries are positive in the
526 // map. Loop over all of the PHIs and remove excess predecessor
527 // entries.
528 BasicBlock::iterator I = NewBB->begin();
529 for (; (PN = dyn_cast<PHINode>(I)); ++I) {
530 for (std::map<BasicBlock*, unsigned>::iterator PCI =PredCount.begin(),
531 E = PredCount.end(); PCI != E; ++PCI) {
532 BasicBlock *Pred = PCI->first;
533 for (unsigned NumToRemove = PCI->second; NumToRemove; --NumToRemove)
534 PN->removeIncomingValue(Pred, false);
535 }
536 }
537 }
538
539 // If the loops above have made these phi nodes have 0 or 1 operand,
540 // replace them with undef or the input value. We must do this for
541 // correctness, because 0-operand phis are not valid.
542 PN = cast<PHINode>(NewBB->begin());
543 if (PN->getNumIncomingValues() == 0) {
544 BasicBlock::iterator I = NewBB->begin();
545 BasicBlock::const_iterator OldI = OldBB->begin();
546 while ((PN = dyn_cast<PHINode>(I++))) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000547 Value *NV = UndefValue::get(PN->getType());
Chris Lattner35033ef2006-06-01 19:19:23 +0000548 PN->replaceAllUsesWith(NV);
Devang Patel29d3dd82010-06-23 23:55:51 +0000549 assert(VMap[OldI] == PN && "VMap mismatch");
550 VMap[OldI] = NV;
Chris Lattner35033ef2006-06-01 19:19:23 +0000551 PN->eraseFromParent();
552 ++OldI;
553 }
Chris Lattner35033ef2006-06-01 19:19:23 +0000554 }
555 }
Chandler Carruthf8c8a9c2012-03-25 10:34:54 +0000556
557 // Make a second pass over the PHINodes now that all of them have been
558 // remapped into the new function, simplifying the PHINode and performing any
559 // recursive simplifications exposed. This will transparently update the
Chandler Carruthafff3302012-03-28 08:38:27 +0000560 // WeakVH in the VMap. Notably, we rely on that so that if we coalesce
Chandler Carruthf8c8a9c2012-03-25 10:34:54 +0000561 // two PHINodes, the iteration over the old PHIs remains valid, and the
562 // mapping will just map us to the new node (which may not even be a PHI
563 // node).
564 for (unsigned Idx = 0, Size = PHIToResolve.size(); Idx != Size; ++Idx)
565 if (PHINode *PN = dyn_cast<PHINode>(VMap[PHIToResolve[Idx]]))
Stephen Hines36b56882014-04-23 16:57:46 -0700566 recursivelySimplifyInstruction(PN, DL);
Chandler Carruthf8c8a9c2012-03-25 10:34:54 +0000567
Chris Lattnera4646b62006-09-13 21:27:00 +0000568 // Now that the inlined function body has been fully constructed, go through
569 // and zap unconditional fall-through branches. This happen all the time when
570 // specializing code: code specialization turns conditional branches into
571 // uncond branches, and this code folds them.
Chandler Carruthafff3302012-03-28 08:38:27 +0000572 Function::iterator Begin = cast<BasicBlock>(VMap[&OldFunc->getEntryBlock()]);
573 Function::iterator I = Begin;
Chris Lattnera4646b62006-09-13 21:27:00 +0000574 while (I != NewFunc->end()) {
Chandler Carruthafff3302012-03-28 08:38:27 +0000575 // Check if this block has become dead during inlining or other
576 // simplifications. Note that the first block will appear dead, as it has
577 // not yet been wired up properly.
578 if (I != Begin && (pred_begin(I) == pred_end(I) ||
579 I->getSinglePredecessor() == I)) {
580 BasicBlock *DeadBB = I++;
581 DeleteDeadBlock(DeadBB);
582 continue;
583 }
584
585 // We need to simplify conditional branches and switches with a constant
586 // operand. We try to prune these out when cloning, but if the
587 // simplification required looking through PHI nodes, those are only
588 // available after forming the full basic block. That may leave some here,
589 // and we still want to prune the dead code as early as possible.
590 ConstantFoldTerminator(I);
591
Chris Lattnera4646b62006-09-13 21:27:00 +0000592 BranchInst *BI = dyn_cast<BranchInst>(I->getTerminator());
593 if (!BI || BI->isConditional()) { ++I; continue; }
594
595 BasicBlock *Dest = BI->getSuccessor(0);
Chandler Carruthf8c8a9c2012-03-25 10:34:54 +0000596 if (!Dest->getSinglePredecessor()) {
Chris Lattner8e8eda72007-02-01 18:48:38 +0000597 ++I; continue;
598 }
Chandler Carruthf8c8a9c2012-03-25 10:34:54 +0000599
600 // We shouldn't be able to get single-entry PHI nodes here, as instsimplify
601 // above should have zapped all of them..
602 assert(!isa<PHINode>(Dest->begin()));
603
Chris Lattnera4646b62006-09-13 21:27:00 +0000604 // We know all single-entry PHI nodes in the inlined function have been
605 // removed, so we just need to splice the blocks.
606 BI->eraseFromParent();
607
Eric Christophere59fbc02011-06-23 06:24:52 +0000608 // Make all PHI nodes that referred to Dest now refer to I as their source.
609 Dest->replaceAllUsesWith(I);
610
Jay Foad95c3e482011-06-23 09:09:15 +0000611 // Move all the instructions in the succ to the pred.
612 I->getInstList().splice(I->end(), Dest->getInstList());
613
Chris Lattnera4646b62006-09-13 21:27:00 +0000614 // Remove the dest block.
615 Dest->eraseFromParent();
616
617 // Do not increment I, iteratively merge all things this block branches to.
618 }
Chandler Carruth9ceebb72012-04-06 17:21:31 +0000619
620 // Make a final pass over the basic blocks from theh old function to gather
621 // any return instructions which survived folding. We have to do this here
622 // because we can iteratively remove and merge returns above.
623 for (Function::iterator I = cast<BasicBlock>(VMap[&OldFunc->getEntryBlock()]),
624 E = NewFunc->end();
625 I != E; ++I)
626 if (ReturnInst *RI = dyn_cast<ReturnInst>(I->getTerminator()))
627 Returns.push_back(RI);
Chris Lattner83f03bf2006-05-27 01:22:24 +0000628}