blob: 1b28c35238e9ca264324d3506dd1a7e4a2e6548c [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"
Chris Lattnera4c29d22006-01-13 18:39:17 +000017#include "llvm/Constants.h"
Chris Lattner5a8932f2002-11-19 23:12:22 +000018#include "llvm/DerivedTypes.h"
Chris Lattnera4c29d22006-01-13 18:39:17 +000019#include "llvm/Instructions.h"
Devang Patelf66d7b52009-02-10 07:48:18 +000020#include "llvm/IntrinsicInst.h"
Nate Begeman4be30ac2008-04-25 06:37:06 +000021#include "llvm/GlobalVariable.h"
Chris Lattnerfa703a42002-03-29 19:03:54 +000022#include "llvm/Function.h"
Devang Patel53bb5c92009-11-10 23:06:00 +000023#include "llvm/LLVMContext.h"
Chris Lattnerf0908a32009-12-31 03:02:08 +000024#include "llvm/Metadata.h"
Chris Lattner35033ef2006-06-01 19:19:23 +000025#include "llvm/Support/CFG.h"
Dan Gohman05ea54e2010-08-24 18:50:07 +000026#include "llvm/Transforms/Utils/ValueMapper.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000027#include "llvm/Analysis/ConstantFolding.h"
Devang Patel517576d2009-04-15 00:17:06 +000028#include "llvm/Analysis/DebugInfo.h"
Chris Lattner9fa038d2007-01-30 23:13:49 +000029#include "llvm/ADT/SmallVector.h"
Chris Lattner5e665f52007-02-03 00:08:31 +000030#include <map>
Chris Lattnerf7703df2004-01-09 06:12:26 +000031using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000032
Chris Lattner17d145d2003-04-18 03:50:09 +000033// CloneBasicBlock - See comments in Cloning.h
Chris Lattnerf7703df2004-01-09 06:12:26 +000034BasicBlock *llvm::CloneBasicBlock(const BasicBlock *BB,
Devang Patel774cca72010-06-24 00:00:42 +000035 ValueToValueMapTy &VMap,
Benjamin Kramer5deb57c2010-01-27 19:58:47 +000036 const Twine &NameSuffix, Function *F,
Chris Lattnera4c29d22006-01-13 18:39:17 +000037 ClonedCodeInfo *CodeInfo) {
Owen Anderson1d0be152009-08-13 21:58:54 +000038 BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), "", F);
Chris Lattner17d145d2003-04-18 03:50:09 +000039 if (BB->hasName()) NewBB->setName(BB->getName()+NameSuffix);
40
Chris Lattnera4c29d22006-01-13 18:39:17 +000041 bool hasCalls = false, hasDynamicAllocas = false, hasStaticAllocas = false;
42
43 // Loop over all instructions, and copy them over.
Chris Lattner17d145d2003-04-18 03:50:09 +000044 for (BasicBlock::const_iterator II = BB->begin(), IE = BB->end();
45 II != IE; ++II) {
Nick Lewycky67760642009-09-27 07:38:41 +000046 Instruction *NewInst = II->clone();
Chris Lattner17d145d2003-04-18 03:50:09 +000047 if (II->hasName())
48 NewInst->setName(II->getName()+NameSuffix);
49 NewBB->getInstList().push_back(NewInst);
Devang Patel29d3dd82010-06-23 23:55:51 +000050 VMap[II] = NewInst; // Add instruction map to value.
Chris Lattnera4c29d22006-01-13 18:39:17 +000051
Dale Johannesen8aa90fe2009-03-10 22:20:02 +000052 hasCalls |= (isa<CallInst>(II) && !isa<DbgInfoIntrinsic>(II));
Chris Lattnera4c29d22006-01-13 18:39:17 +000053 if (const AllocaInst *AI = dyn_cast<AllocaInst>(II)) {
54 if (isa<ConstantInt>(AI->getArraySize()))
55 hasStaticAllocas = true;
56 else
57 hasDynamicAllocas = true;
58 }
59 }
60
61 if (CodeInfo) {
62 CodeInfo->ContainsCalls |= hasCalls;
Chris Lattnera4c29d22006-01-13 18:39:17 +000063 CodeInfo->ContainsDynamicAllocas |= hasDynamicAllocas;
64 CodeInfo->ContainsDynamicAllocas |= hasStaticAllocas &&
Dan Gohmanecb7a772007-03-22 16:38:57 +000065 BB != &BB->getParent()->getEntryBlock();
Chris Lattner17d145d2003-04-18 03:50:09 +000066 }
67 return NewBB;
68}
69
Chris Lattnerfa703a42002-03-29 19:03:54 +000070// Clone OldFunc into NewFunc, transforming the old arguments into references to
Dan Gohman6cb8c232010-08-26 15:41:53 +000071// VMap values.
Chris Lattnerfa703a42002-03-29 19:03:54 +000072//
Chris Lattnerf7703df2004-01-09 06:12:26 +000073void llvm::CloneFunctionInto(Function *NewFunc, const Function *OldFunc,
Devang Patel774cca72010-06-24 00:00:42 +000074 ValueToValueMapTy &VMap,
Dan Gohman6cb8c232010-08-26 15:41:53 +000075 bool ModuleLevelChanges,
Chris Lattnerec1bea02009-08-27 04:02:30 +000076 SmallVectorImpl<ReturnInst*> &Returns,
Mon P Wangd24397a2011-12-23 02:18:32 +000077 const char *NameSuffix, ClonedCodeInfo *CodeInfo,
78 ValueMapTypeRemapper *TypeMapper) {
Chris Lattnerdcd80402002-11-19 21:54:07 +000079 assert(NameSuffix && "NameSuffix cannot be null!");
Misha Brukmanfd939082005-04-21 23:48:37 +000080
Chris Lattnerd1801552002-11-19 22:54:01 +000081#ifndef NDEBUG
Chris Lattnera4c29d22006-01-13 18:39:17 +000082 for (Function::const_arg_iterator I = OldFunc->arg_begin(),
83 E = OldFunc->arg_end(); I != E; ++I)
Devang Patel29d3dd82010-06-23 23:55:51 +000084 assert(VMap.count(I) && "No mapping from source argument specified!");
Chris Lattnerd1801552002-11-19 22:54:01 +000085#endif
Chris Lattnerfa703a42002-03-29 19:03:54 +000086
Duncan Sands28c3cff2008-05-26 19:58:59 +000087 // Clone any attributes.
Andrew Lenharth82cf32e2008-10-07 18:08:38 +000088 if (NewFunc->arg_size() == OldFunc->arg_size())
89 NewFunc->copyAttributesFrom(OldFunc);
90 else {
Devang Patel29d3dd82010-06-23 23:55:51 +000091 //Some arguments were deleted with the VMap. Copy arguments one by one
Andrew Lenharth82cf32e2008-10-07 18:08:38 +000092 for (Function::const_arg_iterator I = OldFunc->arg_begin(),
93 E = OldFunc->arg_end(); I != E; ++I)
Devang Patel29d3dd82010-06-23 23:55:51 +000094 if (Argument* Anew = dyn_cast<Argument>(VMap[I]))
Andrew Lenharth82cf32e2008-10-07 18:08:38 +000095 Anew->addAttr( OldFunc->getAttributes()
96 .getParamAttributes(I->getArgNo() + 1));
97 NewFunc->setAttributes(NewFunc->getAttributes()
98 .addAttr(0, OldFunc->getAttributes()
99 .getRetAttributes()));
100 NewFunc->setAttributes(NewFunc->getAttributes()
101 .addAttr(~0, OldFunc->getAttributes()
102 .getFnAttributes()));
103
104 }
Anton Korobeynikov9e49f1b2008-03-23 16:03:00 +0000105
Chris Lattnerfa703a42002-03-29 19:03:54 +0000106 // Loop over all of the basic blocks in the function, cloning them as
Chris Lattnerdcd80402002-11-19 21:54:07 +0000107 // appropriate. Note that we save BE this way in order to handle cloning of
108 // recursive functions into themselves.
Chris Lattnerfa703a42002-03-29 19:03:54 +0000109 //
110 for (Function::const_iterator BI = OldFunc->begin(), BE = OldFunc->end();
111 BI != BE; ++BI) {
Chris Lattner18961502002-06-25 16:12:52 +0000112 const BasicBlock &BB = *BI;
Misha Brukmanfd939082005-04-21 23:48:37 +0000113
Chris Lattner17d145d2003-04-18 03:50:09 +0000114 // Create a new basic block and copy instructions into it!
Chris Lattnerb5fa5fc2011-01-08 08:15:20 +0000115 BasicBlock *CBB = CloneBasicBlock(&BB, VMap, NameSuffix, NewFunc, CodeInfo);
Chris Lattnerfa703a42002-03-29 19:03:54 +0000116
Eli Friedman4090e1c2011-10-21 20:45:19 +0000117 // Add basic block mapping.
118 VMap[&BB] = CBB;
119
120 // It is only legal to clone a function if a block address within that
121 // function is never referenced outside of the function. Given that, we
122 // want to map block addresses from the old function to block addresses in
123 // the clone. (This is different from the generic ValueMapper
124 // implementation, which generates an invalid blockaddress when
125 // cloning a function.)
126 if (BB.hasAddressTaken()) {
127 Constant *OldBBAddr = BlockAddress::get(const_cast<Function*>(OldFunc),
128 const_cast<BasicBlock*>(&BB));
129 VMap[OldBBAddr] = BlockAddress::get(NewFunc, CBB);
130 }
131
132 // Note return instructions for the caller.
Chris Lattnerdcd80402002-11-19 21:54:07 +0000133 if (ReturnInst *RI = dyn_cast<ReturnInst>(CBB->getTerminator()))
134 Returns.push_back(RI);
Chris Lattnerfa703a42002-03-29 19:03:54 +0000135 }
136
Misha Brukmanfd939082005-04-21 23:48:37 +0000137 // Loop over all of the instructions in the function, fixing up operand
Devang Patel29d3dd82010-06-23 23:55:51 +0000138 // references as we go. This uses VMap to do all the hard work.
Devang Patel29d3dd82010-06-23 23:55:51 +0000139 for (Function::iterator BB = cast<BasicBlock>(VMap[OldFunc->begin()]),
Nick Lewycky280a6e62008-04-25 16:53:59 +0000140 BE = NewFunc->end(); BB != BE; ++BB)
Chris Lattnerfa703a42002-03-29 19:03:54 +0000141 // Loop over all instructions, fixing each one as we find it...
Chris Lattnera33ceaa2004-02-04 21:44:26 +0000142 for (BasicBlock::iterator II = BB->begin(); II != BB->end(); ++II)
Chris Lattnerb5fa5fc2011-01-08 08:15:20 +0000143 RemapInstruction(II, VMap,
Mon P Wangd24397a2011-12-23 02:18:32 +0000144 ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges,
145 TypeMapper);
Chris Lattnerfa703a42002-03-29 19:03:54 +0000146}
Chris Lattner5a8932f2002-11-19 23:12:22 +0000147
148/// CloneFunction - Return a copy of the specified function, but without
149/// embedding the function into another module. Also, any references specified
Devang Patel29d3dd82010-06-23 23:55:51 +0000150/// in the VMap are changed to refer to their mapped value instead of the
151/// original one. If any of the arguments to the function are in the VMap,
152/// the arguments are deleted from the resultant function. The VMap is
Chris Lattner5a8932f2002-11-19 23:12:22 +0000153/// updated to include mappings from all of the instructions and basicblocks in
154/// the function from their old to new values.
155///
Chris Lattnerb5fa5fc2011-01-08 08:15:20 +0000156Function *llvm::CloneFunction(const Function *F, ValueToValueMapTy &VMap,
Dan Gohman6cb8c232010-08-26 15:41:53 +0000157 bool ModuleLevelChanges,
Chris Lattnera4c29d22006-01-13 18:39:17 +0000158 ClonedCodeInfo *CodeInfo) {
Jay Foad5fdd6c82011-07-12 14:06:48 +0000159 std::vector<Type*> ArgTypes;
Chris Lattner5a8932f2002-11-19 23:12:22 +0000160
161 // The user might be deleting arguments to the function by specifying them in
Devang Patel29d3dd82010-06-23 23:55:51 +0000162 // the VMap. If so, we need to not add the arguments to the arg ty vector
Chris Lattner5a8932f2002-11-19 23:12:22 +0000163 //
Chris Lattnera4c29d22006-01-13 18:39:17 +0000164 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
165 I != E; ++I)
Devang Patel29d3dd82010-06-23 23:55:51 +0000166 if (VMap.count(I) == 0) // Haven't mapped the argument to anything yet?
Chris Lattner5a8932f2002-11-19 23:12:22 +0000167 ArgTypes.push_back(I->getType());
168
169 // Create a new function type...
Owen Andersondebcb012009-07-29 22:17:13 +0000170 FunctionType *FTy = FunctionType::get(F->getFunctionType()->getReturnType(),
Chris Lattner5a8932f2002-11-19 23:12:22 +0000171 ArgTypes, F->getFunctionType()->isVarArg());
172
173 // Create the new function...
Gabor Greif051a9502008-04-06 20:25:17 +0000174 Function *NewF = Function::Create(FTy, F->getLinkage(), F->getName());
Misha Brukmanfd939082005-04-21 23:48:37 +0000175
Chris Lattner5a8932f2002-11-19 23:12:22 +0000176 // Loop over the arguments, copying the names of the mapped arguments over...
Chris Lattnere4d5c442005-03-15 04:54:21 +0000177 Function::arg_iterator DestI = NewF->arg_begin();
Chris Lattnera4c29d22006-01-13 18:39:17 +0000178 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
179 I != E; ++I)
Devang Patel29d3dd82010-06-23 23:55:51 +0000180 if (VMap.count(I) == 0) { // Is this argument preserved?
Chris Lattner5a8932f2002-11-19 23:12:22 +0000181 DestI->setName(I->getName()); // Copy the name over...
Devang Patel29d3dd82010-06-23 23:55:51 +0000182 VMap[I] = DestI++; // Add mapping to VMap
Chris Lattner5a8932f2002-11-19 23:12:22 +0000183 }
184
Chris Lattnerec1bea02009-08-27 04:02:30 +0000185 SmallVector<ReturnInst*, 8> Returns; // Ignore returns cloned.
Dan Gohman6cb8c232010-08-26 15:41:53 +0000186 CloneFunctionInto(NewF, F, VMap, ModuleLevelChanges, Returns, "", CodeInfo);
Misha Brukmanfd939082005-04-21 23:48:37 +0000187 return NewF;
Chris Lattner5a8932f2002-11-19 23:12:22 +0000188}
Brian Gaeked0fde302003-11-11 22:41:34 +0000189
Chris Lattner83f03bf2006-05-27 01:22:24 +0000190
191
192namespace {
193 /// PruningFunctionCloner - This class is a private class used to implement
194 /// the CloneAndPruneFunctionInto method.
Nick Lewycky6726b6d2009-10-25 06:33:48 +0000195 struct PruningFunctionCloner {
Chris Lattner83f03bf2006-05-27 01:22:24 +0000196 Function *NewFunc;
197 const Function *OldFunc;
Devang Patel774cca72010-06-24 00:00:42 +0000198 ValueToValueMapTy &VMap;
Dan Gohman6cb8c232010-08-26 15:41:53 +0000199 bool ModuleLevelChanges;
Chris Lattnerec1bea02009-08-27 04:02:30 +0000200 SmallVectorImpl<ReturnInst*> &Returns;
Chris Lattner83f03bf2006-05-27 01:22:24 +0000201 const char *NameSuffix;
202 ClonedCodeInfo *CodeInfo;
Chris Lattner1dfdf822007-01-30 23:22:39 +0000203 const TargetData *TD;
Chris Lattner83f03bf2006-05-27 01:22:24 +0000204 public:
205 PruningFunctionCloner(Function *newFunc, const Function *oldFunc,
Devang Patel774cca72010-06-24 00:00:42 +0000206 ValueToValueMapTy &valueMap,
Dan Gohman6cb8c232010-08-26 15:41:53 +0000207 bool moduleLevelChanges,
Chris Lattnerec1bea02009-08-27 04:02:30 +0000208 SmallVectorImpl<ReturnInst*> &returns,
Chris Lattner83f03bf2006-05-27 01:22:24 +0000209 const char *nameSuffix,
Chris Lattner1dfdf822007-01-30 23:22:39 +0000210 ClonedCodeInfo *codeInfo,
211 const TargetData *td)
Dan Gohman6cb8c232010-08-26 15:41:53 +0000212 : NewFunc(newFunc), OldFunc(oldFunc),
213 VMap(valueMap), ModuleLevelChanges(moduleLevelChanges),
214 Returns(returns), NameSuffix(nameSuffix), CodeInfo(codeInfo), TD(td) {
Chris Lattner83f03bf2006-05-27 01:22:24 +0000215 }
216
217 /// CloneBlock - The specified block is found to be reachable, clone it and
218 /// anything that it can reach.
Chris Lattner67ef2412007-03-02 03:11:20 +0000219 void CloneBlock(const BasicBlock *BB,
220 std::vector<const BasicBlock*> &ToClone);
Chris Lattner83f03bf2006-05-27 01:22:24 +0000221
222 public:
223 /// ConstantFoldMappedInstruction - Constant fold the specified instruction,
Devang Patel29d3dd82010-06-23 23:55:51 +0000224 /// mapping its operands through VMap if they are available.
Chris Lattner83f03bf2006-05-27 01:22:24 +0000225 Constant *ConstantFoldMappedInstruction(const Instruction *I);
226 };
227}
228
229/// CloneBlock - The specified block is found to be reachable, clone it and
230/// anything that it can reach.
Chris Lattner67ef2412007-03-02 03:11:20 +0000231void PruningFunctionCloner::CloneBlock(const BasicBlock *BB,
232 std::vector<const BasicBlock*> &ToClone){
Rafael Espindola6688c4a2010-10-13 02:08:17 +0000233 TrackingVH<Value> &BBEntry = VMap[BB];
Chris Lattner83f03bf2006-05-27 01:22:24 +0000234
235 // Have we already cloned this block?
236 if (BBEntry) return;
237
238 // Nope, clone it now.
239 BasicBlock *NewBB;
Owen Anderson1d0be152009-08-13 21:58:54 +0000240 BBEntry = NewBB = BasicBlock::Create(BB->getContext());
Chris Lattner83f03bf2006-05-27 01:22:24 +0000241 if (BB->hasName()) NewBB->setName(BB->getName()+NameSuffix);
242
Eli Friedman4090e1c2011-10-21 20:45:19 +0000243 // It is only legal to clone a function if a block address within that
244 // function is never referenced outside of the function. Given that, we
245 // want to map block addresses from the old function to block addresses in
246 // the clone. (This is different from the generic ValueMapper
247 // implementation, which generates an invalid blockaddress when
248 // cloning a function.)
249 //
250 // Note that we don't need to fix the mapping for unreachable blocks;
251 // the default mapping there is safe.
252 if (BB->hasAddressTaken()) {
253 Constant *OldBBAddr = BlockAddress::get(const_cast<Function*>(OldFunc),
254 const_cast<BasicBlock*>(BB));
255 VMap[OldBBAddr] = BlockAddress::get(NewFunc, NewBB);
256 }
257
258
Chris Lattner83f03bf2006-05-27 01:22:24 +0000259 bool hasCalls = false, hasDynamicAllocas = false, hasStaticAllocas = false;
260
261 // Loop over all instructions, and copy them over, DCE'ing as we go. This
262 // loop doesn't include the terminator.
Chris Lattner35033ef2006-06-01 19:19:23 +0000263 for (BasicBlock::const_iterator II = BB->begin(), IE = --BB->end();
Chris Lattner83f03bf2006-05-27 01:22:24 +0000264 II != IE; ++II) {
265 // If this instruction constant folds, don't bother cloning the instruction,
266 // instead, just add the constant to the value map.
267 if (Constant *C = ConstantFoldMappedInstruction(II)) {
Devang Patel29d3dd82010-06-23 23:55:51 +0000268 VMap[II] = C;
Chris Lattner83f03bf2006-05-27 01:22:24 +0000269 continue;
270 }
Devang Patelf66d7b52009-02-10 07:48:18 +0000271
Nick Lewycky67760642009-09-27 07:38:41 +0000272 Instruction *NewInst = II->clone();
Chris Lattner83f03bf2006-05-27 01:22:24 +0000273 if (II->hasName())
274 NewInst->setName(II->getName()+NameSuffix);
275 NewBB->getInstList().push_back(NewInst);
Devang Patel29d3dd82010-06-23 23:55:51 +0000276 VMap[II] = NewInst; // Add instruction map to value.
Chris Lattner83f03bf2006-05-27 01:22:24 +0000277
Dale Johannesen8aa90fe2009-03-10 22:20:02 +0000278 hasCalls |= (isa<CallInst>(II) && !isa<DbgInfoIntrinsic>(II));
Chris Lattner83f03bf2006-05-27 01:22:24 +0000279 if (const AllocaInst *AI = dyn_cast<AllocaInst>(II)) {
280 if (isa<ConstantInt>(AI->getArraySize()))
281 hasStaticAllocas = true;
282 else
283 hasDynamicAllocas = true;
284 }
285 }
286
Chris Lattner35033ef2006-06-01 19:19:23 +0000287 // Finally, clone over the terminator.
288 const TerminatorInst *OldTI = BB->getTerminator();
289 bool TerminatorDone = false;
290 if (const BranchInst *BI = dyn_cast<BranchInst>(OldTI)) {
291 if (BI->isConditional()) {
292 // If the condition was a known constant in the callee...
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000293 ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition());
294 // Or is a known constant in the caller...
Rafael Espindola6688c4a2010-10-13 02:08:17 +0000295 if (Cond == 0) {
296 Value *V = VMap[BI->getCondition()];
297 Cond = dyn_cast_or_null<ConstantInt>(V);
298 }
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000299
300 // Constant fold to uncond branch!
301 if (Cond) {
Reid Spencer579dca12007-01-12 04:24:46 +0000302 BasicBlock *Dest = BI->getSuccessor(!Cond->getZExtValue());
Devang Patel29d3dd82010-06-23 23:55:51 +0000303 VMap[OldTI] = BranchInst::Create(Dest, NewBB);
Chris Lattner67ef2412007-03-02 03:11:20 +0000304 ToClone.push_back(Dest);
Chris Lattner35033ef2006-06-01 19:19:23 +0000305 TerminatorDone = true;
306 }
307 }
308 } else if (const SwitchInst *SI = dyn_cast<SwitchInst>(OldTI)) {
309 // If switching on a value known constant in the caller.
310 ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition());
Rafael Espindola6688c4a2010-10-13 02:08:17 +0000311 if (Cond == 0) { // Or known constant after constant prop in the callee...
312 Value *V = VMap[SI->getCondition()];
313 Cond = dyn_cast_or_null<ConstantInt>(V);
314 }
Chris Lattner35033ef2006-06-01 19:19:23 +0000315 if (Cond) { // Constant fold to uncond branch!
Stepan Dyatkovskiyc10fa6c2012-03-08 07:06:20 +0000316 SwitchInst::ConstCaseIt Case = SI->findCaseValue(Cond);
317 BasicBlock *Dest = const_cast<BasicBlock*>(Case.getCaseSuccessor());
Devang Patel29d3dd82010-06-23 23:55:51 +0000318 VMap[OldTI] = BranchInst::Create(Dest, NewBB);
Chris Lattner67ef2412007-03-02 03:11:20 +0000319 ToClone.push_back(Dest);
Chris Lattner35033ef2006-06-01 19:19:23 +0000320 TerminatorDone = true;
321 }
322 }
323
324 if (!TerminatorDone) {
Nick Lewycky67760642009-09-27 07:38:41 +0000325 Instruction *NewInst = OldTI->clone();
Chris Lattner35033ef2006-06-01 19:19:23 +0000326 if (OldTI->hasName())
327 NewInst->setName(OldTI->getName()+NameSuffix);
328 NewBB->getInstList().push_back(NewInst);
Devang Patel29d3dd82010-06-23 23:55:51 +0000329 VMap[OldTI] = NewInst; // Add instruction map to value.
Chris Lattner35033ef2006-06-01 19:19:23 +0000330
331 // Recursively clone any reachable successor blocks.
332 const TerminatorInst *TI = BB->getTerminator();
333 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
Chris Lattner67ef2412007-03-02 03:11:20 +0000334 ToClone.push_back(TI->getSuccessor(i));
Chris Lattner35033ef2006-06-01 19:19:23 +0000335 }
336
Chris Lattner83f03bf2006-05-27 01:22:24 +0000337 if (CodeInfo) {
338 CodeInfo->ContainsCalls |= hasCalls;
Chris Lattner83f03bf2006-05-27 01:22:24 +0000339 CodeInfo->ContainsDynamicAllocas |= hasDynamicAllocas;
340 CodeInfo->ContainsDynamicAllocas |= hasStaticAllocas &&
341 BB != &BB->getParent()->front();
342 }
343
344 if (ReturnInst *RI = dyn_cast<ReturnInst>(NewBB->getTerminator()))
345 Returns.push_back(RI);
Chris Lattner83f03bf2006-05-27 01:22:24 +0000346}
347
348/// ConstantFoldMappedInstruction - Constant fold the specified instruction,
Devang Patel29d3dd82010-06-23 23:55:51 +0000349/// mapping its operands through VMap if they are available.
Chris Lattner83f03bf2006-05-27 01:22:24 +0000350Constant *PruningFunctionCloner::
351ConstantFoldMappedInstruction(const Instruction *I) {
Chris Lattner9fa038d2007-01-30 23:13:49 +0000352 SmallVector<Constant*, 8> Ops;
Chris Lattner83f03bf2006-05-27 01:22:24 +0000353 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
354 if (Constant *Op = dyn_cast_or_null<Constant>(MapValue(I->getOperand(i),
Chris Lattnerb5fa5fc2011-01-08 08:15:20 +0000355 VMap,
356 ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges)))
Chris Lattner83f03bf2006-05-27 01:22:24 +0000357 Ops.push_back(Op);
358 else
359 return 0; // All operands not constant!
360
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000361 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
Chris Lattner8f73dea2009-11-09 23:06:58 +0000362 return ConstantFoldCompareInstOperands(CI->getPredicate(), Ops[0], Ops[1],
363 TD);
Nate Begeman4be30ac2008-04-25 06:37:06 +0000364
Nate Begeman4182db42008-04-25 17:45:52 +0000365 if (const LoadInst *LI = dyn_cast<LoadInst>(I))
Nick Lewycky267236a2011-10-02 09:12:55 +0000366 if (!LI->isVolatile())
367 return ConstantFoldLoadFromConstPtr(Ops[0], TD);
Nate Begeman4be30ac2008-04-25 06:37:06 +0000368
Jay Foad1d2f5692011-07-19 13:32:40 +0000369 return ConstantFoldInstOperands(I->getOpcode(), I->getType(), Ops, TD);
Chris Lattner83f03bf2006-05-27 01:22:24 +0000370}
371
Chris Lattner83f03bf2006-05-27 01:22:24 +0000372/// CloneAndPruneFunctionInto - This works exactly like CloneFunctionInto,
373/// except that it does some simple constant prop and DCE on the fly. The
374/// effect of this is to copy significantly less code in cases where (for
375/// example) a function call with constant arguments is inlined, and those
376/// constant arguments cause a significant amount of code in the callee to be
Duncan Sandsdc024672007-11-27 13:23:08 +0000377/// dead. Since this doesn't produce an exact copy of the input, it can't be
Chris Lattner83f03bf2006-05-27 01:22:24 +0000378/// used for things like CloneFunction or CloneModule.
379void llvm::CloneAndPruneFunctionInto(Function *NewFunc, const Function *OldFunc,
Devang Patel774cca72010-06-24 00:00:42 +0000380 ValueToValueMapTy &VMap,
Dan Gohman6cb8c232010-08-26 15:41:53 +0000381 bool ModuleLevelChanges,
Chris Lattnerec1bea02009-08-27 04:02:30 +0000382 SmallVectorImpl<ReturnInst*> &Returns,
Chris Lattner83f03bf2006-05-27 01:22:24 +0000383 const char *NameSuffix,
Chris Lattner1dfdf822007-01-30 23:22:39 +0000384 ClonedCodeInfo *CodeInfo,
Devang Patel53bb5c92009-11-10 23:06:00 +0000385 const TargetData *TD,
386 Instruction *TheCall) {
Chris Lattner83f03bf2006-05-27 01:22:24 +0000387 assert(NameSuffix && "NameSuffix cannot be null!");
388
389#ifndef NDEBUG
Jeff Cohend41b30d2006-11-05 19:31:28 +0000390 for (Function::const_arg_iterator II = OldFunc->arg_begin(),
391 E = OldFunc->arg_end(); II != E; ++II)
Devang Patel29d3dd82010-06-23 23:55:51 +0000392 assert(VMap.count(II) && "No mapping from source argument specified!");
Chris Lattner83f03bf2006-05-27 01:22:24 +0000393#endif
Duncan Sands28c3cff2008-05-26 19:58:59 +0000394
Dan Gohman6cb8c232010-08-26 15:41:53 +0000395 PruningFunctionCloner PFC(NewFunc, OldFunc, VMap, ModuleLevelChanges,
396 Returns, NameSuffix, CodeInfo, TD);
Chris Lattner83f03bf2006-05-27 01:22:24 +0000397
398 // Clone the entry block, and anything recursively reachable from it.
Chris Lattner67ef2412007-03-02 03:11:20 +0000399 std::vector<const BasicBlock*> CloneWorklist;
400 CloneWorklist.push_back(&OldFunc->getEntryBlock());
401 while (!CloneWorklist.empty()) {
402 const BasicBlock *BB = CloneWorklist.back();
403 CloneWorklist.pop_back();
404 PFC.CloneBlock(BB, CloneWorklist);
405 }
Chris Lattner83f03bf2006-05-27 01:22:24 +0000406
407 // Loop over all of the basic blocks in the old function. If the block was
408 // reachable, we have cloned it and the old block is now in the value map:
409 // insert it into the new function in the right order. If not, ignore it.
410 //
Chris Lattner35033ef2006-06-01 19:19:23 +0000411 // Defer PHI resolution until rest of function is resolved.
Chris Lattnerec1bea02009-08-27 04:02:30 +0000412 SmallVector<const PHINode*, 16> PHIToResolve;
Chris Lattner83f03bf2006-05-27 01:22:24 +0000413 for (Function::const_iterator BI = OldFunc->begin(), BE = OldFunc->end();
414 BI != BE; ++BI) {
Rafael Espindola6688c4a2010-10-13 02:08:17 +0000415 Value *V = VMap[BI];
416 BasicBlock *NewBB = cast_or_null<BasicBlock>(V);
Chris Lattner83f03bf2006-05-27 01:22:24 +0000417 if (NewBB == 0) continue; // Dead block.
Chris Lattner35033ef2006-06-01 19:19:23 +0000418
Chris Lattner83f03bf2006-05-27 01:22:24 +0000419 // Add the new block to the new function.
420 NewFunc->getBasicBlockList().push_back(NewBB);
421
422 // Loop over all of the instructions in the block, fixing up operand
Devang Patel29d3dd82010-06-23 23:55:51 +0000423 // references as we go. This uses VMap to do all the hard work.
Chris Lattner83f03bf2006-05-27 01:22:24 +0000424 //
425 BasicBlock::iterator I = NewBB->begin();
Devang Patel53bb5c92009-11-10 23:06:00 +0000426
Chris Lattner83f03bf2006-05-27 01:22:24 +0000427 // Handle PHI nodes specially, as we have to remove references to dead
428 // blocks.
429 if (PHINode *PN = dyn_cast<PHINode>(I)) {
Chris Lattner35033ef2006-06-01 19:19:23 +0000430 // Skip over all PHI nodes, remembering them for later.
431 BasicBlock::const_iterator OldI = BI->begin();
Devang Patel2cf158e2011-07-08 18:01:31 +0000432 for (; (PN = dyn_cast<PHINode>(I)); ++I, ++OldI)
Chris Lattner35033ef2006-06-01 19:19:23 +0000433 PHIToResolve.push_back(cast<PHINode>(OldI));
Chris Lattner83f03bf2006-05-27 01:22:24 +0000434 }
435
436 // Otherwise, remap the rest of the instructions normally.
Devang Patel2cf158e2011-07-08 18:01:31 +0000437 for (; I != NewBB->end(); ++I)
Chris Lattnerb5fa5fc2011-01-08 08:15:20 +0000438 RemapInstruction(I, VMap,
439 ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges);
Chris Lattner83f03bf2006-05-27 01:22:24 +0000440 }
Chris Lattner35033ef2006-06-01 19:19:23 +0000441
442 // Defer PHI resolution until rest of function is resolved, PHI resolution
443 // requires the CFG to be up-to-date.
444 for (unsigned phino = 0, e = PHIToResolve.size(); phino != e; ) {
445 const PHINode *OPN = PHIToResolve[phino];
Chris Lattner35033ef2006-06-01 19:19:23 +0000446 unsigned NumPreds = OPN->getNumIncomingValues();
Chris Lattner35033ef2006-06-01 19:19:23 +0000447 const BasicBlock *OldBB = OPN->getParent();
Devang Patel29d3dd82010-06-23 23:55:51 +0000448 BasicBlock *NewBB = cast<BasicBlock>(VMap[OldBB]);
Chris Lattner35033ef2006-06-01 19:19:23 +0000449
450 // Map operands for blocks that are live and remove operands for blocks
451 // that are dead.
452 for (; phino != PHIToResolve.size() &&
453 PHIToResolve[phino]->getParent() == OldBB; ++phino) {
454 OPN = PHIToResolve[phino];
Devang Patel29d3dd82010-06-23 23:55:51 +0000455 PHINode *PN = cast<PHINode>(VMap[OPN]);
Chris Lattner35033ef2006-06-01 19:19:23 +0000456 for (unsigned pred = 0, e = NumPreds; pred != e; ++pred) {
Rafael Espindola6688c4a2010-10-13 02:08:17 +0000457 Value *V = VMap[PN->getIncomingBlock(pred)];
Chris Lattnerb5fa5fc2011-01-08 08:15:20 +0000458 if (BasicBlock *MappedBlock = cast_or_null<BasicBlock>(V)) {
Owen Anderson0a205a42009-07-05 22:41:43 +0000459 Value *InVal = MapValue(PN->getIncomingValue(pred),
Chris Lattnerb5fa5fc2011-01-08 08:15:20 +0000460 VMap,
461 ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges);
Chris Lattner35033ef2006-06-01 19:19:23 +0000462 assert(InVal && "Unknown input value?");
463 PN->setIncomingValue(pred, InVal);
464 PN->setIncomingBlock(pred, MappedBlock);
465 } else {
466 PN->removeIncomingValue(pred, false);
467 --pred, --e; // Revisit the next entry.
468 }
469 }
470 }
471
472 // The loop above has removed PHI entries for those blocks that are dead
473 // and has updated others. However, if a block is live (i.e. copied over)
474 // but its terminator has been changed to not go to this block, then our
475 // phi nodes will have invalid entries. Update the PHI nodes in this
476 // case.
477 PHINode *PN = cast<PHINode>(NewBB->begin());
478 NumPreds = std::distance(pred_begin(NewBB), pred_end(NewBB));
479 if (NumPreds != PN->getNumIncomingValues()) {
480 assert(NumPreds < PN->getNumIncomingValues());
481 // Count how many times each predecessor comes to this block.
482 std::map<BasicBlock*, unsigned> PredCount;
483 for (pred_iterator PI = pred_begin(NewBB), E = pred_end(NewBB);
484 PI != E; ++PI)
485 --PredCount[*PI];
486
487 // Figure out how many entries to remove from each PHI.
488 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
489 ++PredCount[PN->getIncomingBlock(i)];
490
491 // At this point, the excess predecessor entries are positive in the
492 // map. Loop over all of the PHIs and remove excess predecessor
493 // entries.
494 BasicBlock::iterator I = NewBB->begin();
495 for (; (PN = dyn_cast<PHINode>(I)); ++I) {
496 for (std::map<BasicBlock*, unsigned>::iterator PCI =PredCount.begin(),
497 E = PredCount.end(); PCI != E; ++PCI) {
498 BasicBlock *Pred = PCI->first;
499 for (unsigned NumToRemove = PCI->second; NumToRemove; --NumToRemove)
500 PN->removeIncomingValue(Pred, false);
501 }
502 }
503 }
504
505 // If the loops above have made these phi nodes have 0 or 1 operand,
506 // replace them with undef or the input value. We must do this for
507 // correctness, because 0-operand phis are not valid.
508 PN = cast<PHINode>(NewBB->begin());
509 if (PN->getNumIncomingValues() == 0) {
510 BasicBlock::iterator I = NewBB->begin();
511 BasicBlock::const_iterator OldI = OldBB->begin();
512 while ((PN = dyn_cast<PHINode>(I++))) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000513 Value *NV = UndefValue::get(PN->getType());
Chris Lattner35033ef2006-06-01 19:19:23 +0000514 PN->replaceAllUsesWith(NV);
Devang Patel29d3dd82010-06-23 23:55:51 +0000515 assert(VMap[OldI] == PN && "VMap mismatch");
516 VMap[OldI] = NV;
Chris Lattner35033ef2006-06-01 19:19:23 +0000517 PN->eraseFromParent();
518 ++OldI;
519 }
Chris Lattner35033ef2006-06-01 19:19:23 +0000520 }
Chris Lattner8e8eda72007-02-01 18:48:38 +0000521 // NOTE: We cannot eliminate single entry phi nodes here, because of
Devang Patel29d3dd82010-06-23 23:55:51 +0000522 // VMap. Single entry phi nodes can have multiple VMap entries
523 // pointing at them. Thus, deleting one would require scanning the VMap
Chris Lattner8e8eda72007-02-01 18:48:38 +0000524 // to update any entries in it that would require that. This would be
525 // really slow.
Chris Lattner35033ef2006-06-01 19:19:23 +0000526 }
Chris Lattnera4646b62006-09-13 21:27:00 +0000527
528 // Now that the inlined function body has been fully constructed, go through
529 // and zap unconditional fall-through branches. This happen all the time when
530 // specializing code: code specialization turns conditional branches into
531 // uncond branches, and this code folds them.
Devang Patel29d3dd82010-06-23 23:55:51 +0000532 Function::iterator I = cast<BasicBlock>(VMap[&OldFunc->getEntryBlock()]);
Chris Lattnera4646b62006-09-13 21:27:00 +0000533 while (I != NewFunc->end()) {
534 BranchInst *BI = dyn_cast<BranchInst>(I->getTerminator());
535 if (!BI || BI->isConditional()) { ++I; continue; }
536
Chris Lattner8e8eda72007-02-01 18:48:38 +0000537 // Note that we can't eliminate uncond branches if the destination has
538 // single-entry PHI nodes. Eliminating the single-entry phi nodes would
Devang Patel29d3dd82010-06-23 23:55:51 +0000539 // require scanning the VMap to update any entries that point to the phi
Chris Lattner8e8eda72007-02-01 18:48:38 +0000540 // node.
Chris Lattnera4646b62006-09-13 21:27:00 +0000541 BasicBlock *Dest = BI->getSuccessor(0);
Chris Lattner8e8eda72007-02-01 18:48:38 +0000542 if (!Dest->getSinglePredecessor() || isa<PHINode>(Dest->begin())) {
543 ++I; continue;
544 }
Chris Lattnera4646b62006-09-13 21:27:00 +0000545
546 // We know all single-entry PHI nodes in the inlined function have been
547 // removed, so we just need to splice the blocks.
548 BI->eraseFromParent();
549
Eric Christophere59fbc02011-06-23 06:24:52 +0000550 // Make all PHI nodes that referred to Dest now refer to I as their source.
551 Dest->replaceAllUsesWith(I);
552
Jay Foad95c3e482011-06-23 09:09:15 +0000553 // Move all the instructions in the succ to the pred.
554 I->getInstList().splice(I->end(), Dest->getInstList());
555
Chris Lattnera4646b62006-09-13 21:27:00 +0000556 // Remove the dest block.
557 Dest->eraseFromParent();
558
559 // Do not increment I, iteratively merge all things this block branches to.
560 }
Chris Lattner83f03bf2006-05-27 01:22:24 +0000561}