blob: 4d33e22fecfbd33a34f7981ef858315c28432824 [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"
David Majnemer909793f2016-08-04 04:24:02 +000017#include "llvm/ADT/SetVector.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000018#include "llvm/ADT/SmallVector.h"
19#include "llvm/Analysis/ConstantFolding.h"
20#include "llvm/Analysis/InstructionSimplify.h"
Adam Nemet1a689182015-07-10 18:55:09 +000021#include "llvm/Analysis/LoopInfo.h"
Chandler Carruth1305dc32014-03-04 11:45:46 +000022#include "llvm/IR/CFG.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000023#include "llvm/IR/Constants.h"
Chandler Carruth9a4c9e52014-03-06 00:46:21 +000024#include "llvm/IR/DebugInfo.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000025#include "llvm/IR/DerivedTypes.h"
26#include "llvm/IR/Function.h"
27#include "llvm/IR/GlobalVariable.h"
28#include "llvm/IR/Instructions.h"
29#include "llvm/IR/IntrinsicInst.h"
30#include "llvm/IR/LLVMContext.h"
31#include "llvm/IR/Metadata.h"
Alon Mishne07d949f2014-03-12 14:42:51 +000032#include "llvm/IR/Module.h"
Chandler Carruth772c88b2012-03-28 08:38:27 +000033#include "llvm/Transforms/Utils/BasicBlockUtils.h"
34#include "llvm/Transforms/Utils/Local.h"
Dan Gohmana2095032010-08-24 18:50:07 +000035#include "llvm/Transforms/Utils/ValueMapper.h"
Chris Lattner1bfc7ab2007-02-03 00:08:31 +000036#include <map>
Chris Lattnerdf3c3422004-01-09 06:12:26 +000037using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000038
Sanjay Patelabf70232015-03-10 18:41:22 +000039/// See comments in Cloning.h.
Chris Lattnerdf3c3422004-01-09 06:12:26 +000040BasicBlock *llvm::CloneBasicBlock(const BasicBlock *BB,
Devang Pateld8dedee2010-06-24 00:00:42 +000041 ValueToValueMapTy &VMap,
Benjamin Kramer1266d462010-01-27 19:58:47 +000042 const Twine &NameSuffix, Function *F,
Chris Lattneredad1282006-01-13 18:39:17 +000043 ClonedCodeInfo *CodeInfo) {
Owen Anderson55f1c092009-08-13 21:58:54 +000044 BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), "", F);
Chris Lattnere9f42322003-04-18 03:50:09 +000045 if (BB->hasName()) NewBB->setName(BB->getName()+NameSuffix);
46
Chris Lattneredad1282006-01-13 18:39:17 +000047 bool hasCalls = false, hasDynamicAllocas = false, hasStaticAllocas = false;
48
49 // Loop over all instructions, and copy them over.
Chris Lattnere9f42322003-04-18 03:50:09 +000050 for (BasicBlock::const_iterator II = BB->begin(), IE = BB->end();
51 II != IE; ++II) {
Nick Lewycky42fb7452009-09-27 07:38:41 +000052 Instruction *NewInst = II->clone();
Chris Lattnere9f42322003-04-18 03:50:09 +000053 if (II->hasName())
54 NewInst->setName(II->getName()+NameSuffix);
55 NewBB->getInstList().push_back(NewInst);
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +000056 VMap[&*II] = NewInst; // Add instruction map to value.
57
Dale Johannesen900aaa32009-03-10 22:20:02 +000058 hasCalls |= (isa<CallInst>(II) && !isa<DbgInfoIntrinsic>(II));
Chris Lattneredad1282006-01-13 18:39:17 +000059 if (const AllocaInst *AI = dyn_cast<AllocaInst>(II)) {
60 if (isa<ConstantInt>(AI->getArraySize()))
61 hasStaticAllocas = true;
62 else
63 hasDynamicAllocas = true;
64 }
65 }
66
67 if (CodeInfo) {
68 CodeInfo->ContainsCalls |= hasCalls;
Chris Lattneredad1282006-01-13 18:39:17 +000069 CodeInfo->ContainsDynamicAllocas |= hasDynamicAllocas;
70 CodeInfo->ContainsDynamicAllocas |= hasStaticAllocas &&
Dan Gohmandcb291f2007-03-22 16:38:57 +000071 BB != &BB->getParent()->getEntryBlock();
Chris Lattnere9f42322003-04-18 03:50:09 +000072 }
73 return NewBB;
74}
75
Chris Lattner16bfdb52002-03-29 19:03:54 +000076// Clone OldFunc into NewFunc, transforming the old arguments into references to
Dan Gohmanca26f792010-08-26 15:41:53 +000077// VMap values.
Chris Lattner16bfdb52002-03-29 19:03:54 +000078//
Chris Lattnerdf3c3422004-01-09 06:12:26 +000079void llvm::CloneFunctionInto(Function *NewFunc, const Function *OldFunc,
Devang Pateld8dedee2010-06-24 00:00:42 +000080 ValueToValueMapTy &VMap,
Dan Gohmanca26f792010-08-26 15:41:53 +000081 bool ModuleLevelChanges,
Chris Lattnerd84dbb32009-08-27 04:02:30 +000082 SmallVectorImpl<ReturnInst*> &Returns,
Mon P Wang5d44a432011-12-23 02:18:32 +000083 const char *NameSuffix, ClonedCodeInfo *CodeInfo,
James Molloyf6f121e2013-05-28 15:17:05 +000084 ValueMapTypeRemapper *TypeMapper,
85 ValueMaterializer *Materializer) {
Chris Lattnerb1120052002-11-19 21:54:07 +000086 assert(NameSuffix && "NameSuffix cannot be null!");
Misha Brukmanb1c93172005-04-21 23:48:37 +000087
Chris Lattnerc3626182002-11-19 22:54:01 +000088#ifndef NDEBUG
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +000089 for (const Argument &I : OldFunc->args())
90 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
Keno Fischer2ac0c272015-11-16 05:13:30 +000099 // Fix up the personality function that got copied over.
100 if (OldFunc->hasPersonalityFn())
101 NewFunc->setPersonalityFn(
102 MapValue(OldFunc->getPersonalityFn(), VMap,
103 ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges,
104 TypeMapper, Materializer));
105
Joey Gouly81259292013-04-10 10:37:38 +0000106 AttributeSet OldAttrs = OldFunc->getAttributes();
107 // Clone any argument attributes that are present in the VMap.
Reid Kleckner23798a92014-03-26 22:26:35 +0000108 for (const Argument &OldArg : OldFunc->args())
109 if (Argument *NewArg = dyn_cast<Argument>(VMap[&OldArg])) {
Joey Gouly81259292013-04-10 10:37:38 +0000110 AttributeSet attrs =
Reid Kleckner23798a92014-03-26 22:26:35 +0000111 OldAttrs.getParamAttributes(OldArg.getArgNo() + 1);
Joey Gouly81259292013-04-10 10:37:38 +0000112 if (attrs.getNumSlots() > 0)
Reid Kleckner23798a92014-03-26 22:26:35 +0000113 NewArg->addAttr(attrs);
Joey Gouly81259292013-04-10 10:37:38 +0000114 }
Andrew Lenharth5aa1cc42008-10-07 18:08:38 +0000115
Reid Kleckner23798a92014-03-26 22:26:35 +0000116 NewFunc->setAttributes(
117 NewFunc->getAttributes()
118 .addAttributes(NewFunc->getContext(), AttributeSet::ReturnIndex,
119 OldAttrs.getRetAttributes())
120 .addAttributes(NewFunc->getContext(), AttributeSet::FunctionIndex,
121 OldAttrs.getFnAttributes()));
Anton Korobeynikovd38b3fb2008-03-23 16:03:00 +0000122
Peter Collingbourne2bc252a2016-03-30 22:05:13 +0000123 SmallVector<std::pair<unsigned, MDNode *>, 1> MDs;
124 OldFunc->getAllMetadata(MDs);
125 for (auto MD : MDs)
Peter Collingbourne382d81c2016-06-01 01:17:57 +0000126 NewFunc->addMetadata(
Peter Collingbourne2bc252a2016-03-30 22:05:13 +0000127 MD.first,
Peter Collingbourne382d81c2016-06-01 01:17:57 +0000128 *MapMetadata(MD.second, VMap,
129 ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges,
130 TypeMapper, Materializer));
Peter Collingbourne2bc252a2016-03-30 22:05:13 +0000131
Chris Lattner16bfdb52002-03-29 19:03:54 +0000132 // Loop over all of the basic blocks in the function, cloning them as
Chris Lattnerb1120052002-11-19 21:54:07 +0000133 // appropriate. Note that we save BE this way in order to handle cloning of
134 // recursive functions into themselves.
Chris Lattner16bfdb52002-03-29 19:03:54 +0000135 //
136 for (Function::const_iterator BI = OldFunc->begin(), BE = OldFunc->end();
137 BI != BE; ++BI) {
Chris Lattnerfda72b12002-06-25 16:12:52 +0000138 const BasicBlock &BB = *BI;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000139
Chris Lattnere9f42322003-04-18 03:50:09 +0000140 // Create a new basic block and copy instructions into it!
Chris Lattner43f8d162011-01-08 08:15:20 +0000141 BasicBlock *CBB = CloneBasicBlock(&BB, VMap, NameSuffix, NewFunc, CodeInfo);
Chris Lattner16bfdb52002-03-29 19:03:54 +0000142
Eli Friedman688db1d2011-10-21 20:45:19 +0000143 // Add basic block mapping.
144 VMap[&BB] = CBB;
145
146 // It is only legal to clone a function if a block address within that
147 // function is never referenced outside of the function. Given that, we
148 // want to map block addresses from the old function to block addresses in
149 // the clone. (This is different from the generic ValueMapper
150 // implementation, which generates an invalid blockaddress when
151 // cloning a function.)
152 if (BB.hasAddressTaken()) {
153 Constant *OldBBAddr = BlockAddress::get(const_cast<Function*>(OldFunc),
154 const_cast<BasicBlock*>(&BB));
Sanjoy Das1f8fd882015-12-09 20:33:45 +0000155 VMap[OldBBAddr] = BlockAddress::get(NewFunc, CBB);
Eli Friedman688db1d2011-10-21 20:45:19 +0000156 }
157
158 // Note return instructions for the caller.
Chris Lattnerb1120052002-11-19 21:54:07 +0000159 if (ReturnInst *RI = dyn_cast<ReturnInst>(CBB->getTerminator()))
160 Returns.push_back(RI);
Chris Lattner16bfdb52002-03-29 19:03:54 +0000161 }
162
Misha Brukmanb1c93172005-04-21 23:48:37 +0000163 // Loop over all of the instructions in the function, fixing up operand
Devang Patelb8f11de2010-06-23 23:55:51 +0000164 // references as we go. This uses VMap to do all the hard work.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000165 for (Function::iterator BB =
166 cast<BasicBlock>(VMap[&OldFunc->front()])->getIterator(),
167 BE = NewFunc->end();
168 BB != BE; ++BB)
Chris Lattner16bfdb52002-03-29 19:03:54 +0000169 // Loop over all instructions, fixing each one as we find it...
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000170 for (Instruction &II : *BB)
171 RemapInstruction(&II, VMap,
Mon P Wang5d44a432011-12-23 02:18:32 +0000172 ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges,
James Molloyf6f121e2013-05-28 15:17:05 +0000173 TypeMapper, Materializer);
Chris Lattner16bfdb52002-03-29 19:03:54 +0000174}
Chris Lattnerfb311d22002-11-19 23:12:22 +0000175
Peter Collingbournedba99562016-05-10 20:23:24 +0000176/// Return a copy of the specified function and add it to that function's
177/// module. Also, any references specified in the VMap are changed to refer to
178/// their mapped value instead of the original one. If any of the arguments to
179/// the function are in the VMap, the arguments are deleted from the resultant
180/// function. The VMap is updated to include mappings from all of the
181/// instructions and basicblocks in the function from their old to new values.
Chris Lattnerfb311d22002-11-19 23:12:22 +0000182///
Peter Collingbournedba99562016-05-10 20:23:24 +0000183Function *llvm::CloneFunction(Function *F, ValueToValueMapTy &VMap,
Chris Lattneredad1282006-01-13 18:39:17 +0000184 ClonedCodeInfo *CodeInfo) {
Jay Foadb804a2b2011-07-12 14:06:48 +0000185 std::vector<Type*> ArgTypes;
Chris Lattnerfb311d22002-11-19 23:12:22 +0000186
187 // The user might be deleting arguments to the function by specifying them in
Devang Patelb8f11de2010-06-23 23:55:51 +0000188 // the VMap. If so, we need to not add the arguments to the arg ty vector
Chris Lattnerfb311d22002-11-19 23:12:22 +0000189 //
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000190 for (const Argument &I : F->args())
191 if (VMap.count(&I) == 0) // Haven't mapped the argument to anything yet?
192 ArgTypes.push_back(I.getType());
Chris Lattnerfb311d22002-11-19 23:12:22 +0000193
194 // Create a new function type...
Owen Anderson4056ca92009-07-29 22:17:13 +0000195 FunctionType *FTy = FunctionType::get(F->getFunctionType()->getReturnType(),
Chris Lattnerfb311d22002-11-19 23:12:22 +0000196 ArgTypes, F->getFunctionType()->isVarArg());
197
198 // Create the new function...
Peter Collingbournedba99562016-05-10 20:23:24 +0000199 Function *NewF =
200 Function::Create(FTy, F->getLinkage(), F->getName(), F->getParent());
Misha Brukmanb1c93172005-04-21 23:48:37 +0000201
Chris Lattnerfb311d22002-11-19 23:12:22 +0000202 // Loop over the arguments, copying the names of the mapped arguments over...
Chris Lattner531f9e92005-03-15 04:54:21 +0000203 Function::arg_iterator DestI = NewF->arg_begin();
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000204 for (const Argument & I : F->args())
205 if (VMap.count(&I) == 0) { // Is this argument preserved?
206 DestI->setName(I.getName()); // Copy the name over...
207 VMap[&I] = &*DestI++; // Add mapping to VMap
Chris Lattnerfb311d22002-11-19 23:12:22 +0000208 }
209
Chris Lattnerd84dbb32009-08-27 04:02:30 +0000210 SmallVector<ReturnInst*, 8> Returns; // Ignore returns cloned.
Peter Collingbournedba99562016-05-10 20:23:24 +0000211 CloneFunctionInto(NewF, F, VMap, /*ModuleLevelChanges=*/false, Returns, "",
212 CodeInfo);
213
Misha Brukmanb1c93172005-04-21 23:48:37 +0000214 return NewF;
Chris Lattnerfb311d22002-11-19 23:12:22 +0000215}
Brian Gaeke960707c2003-11-11 22:41:34 +0000216
Chris Lattner3df13f42006-05-27 01:22:24 +0000217
218
219namespace {
Sanjay Patelabf70232015-03-10 18:41:22 +0000220 /// This is a private class used to implement CloneAndPruneFunctionInto.
Nick Lewycky02d5f772009-10-25 06:33:48 +0000221 struct PruningFunctionCloner {
Chris Lattner3df13f42006-05-27 01:22:24 +0000222 Function *NewFunc;
223 const Function *OldFunc;
Devang Pateld8dedee2010-06-24 00:00:42 +0000224 ValueToValueMapTy &VMap;
Dan Gohmanca26f792010-08-26 15:41:53 +0000225 bool ModuleLevelChanges;
Chris Lattner3df13f42006-05-27 01:22:24 +0000226 const char *NameSuffix;
227 ClonedCodeInfo *CodeInfo;
Andrew Kaylor527c5dc2015-02-18 18:31:51 +0000228
Chris Lattner3df13f42006-05-27 01:22:24 +0000229 public:
230 PruningFunctionCloner(Function *newFunc, const Function *oldFunc,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000231 ValueToValueMapTy &valueMap, bool moduleLevelChanges,
Easwaran Raman7f187292016-01-08 18:23:17 +0000232 const char *nameSuffix, ClonedCodeInfo *codeInfo)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000233 : NewFunc(newFunc), OldFunc(oldFunc), VMap(valueMap),
234 ModuleLevelChanges(moduleLevelChanges), NameSuffix(nameSuffix),
Easwaran Raman7f187292016-01-08 18:23:17 +0000235 CodeInfo(codeInfo) {}
Chris Lattner3df13f42006-05-27 01:22:24 +0000236
Sanjay Patelabf70232015-03-10 18:41:22 +0000237 /// The specified block is found to be reachable, clone it and
Eric Christophera5ec9252014-05-19 16:04:10 +0000238 /// anything that it can reach.
Easwaran Ramanb1bd3982016-03-08 00:36:35 +0000239 void CloneBlock(const BasicBlock *BB,
Andrew Kaylor527c5dc2015-02-18 18:31:51 +0000240 BasicBlock::const_iterator StartingInst,
Easwaran Ramanb1bd3982016-03-08 00:36:35 +0000241 std::vector<const BasicBlock*> &ToClone);
Chris Lattner3df13f42006-05-27 01:22:24 +0000242 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000243}
Chris Lattner3df13f42006-05-27 01:22:24 +0000244
Sanjay Patelabf70232015-03-10 18:41:22 +0000245/// The specified block is found to be reachable, clone it and
Eric Christophera5ec9252014-05-19 16:04:10 +0000246/// anything that it can reach.
Chris Lattner4bd8cda2007-03-02 03:11:20 +0000247void PruningFunctionCloner::CloneBlock(const BasicBlock *BB,
Andrew Kaylor527c5dc2015-02-18 18:31:51 +0000248 BasicBlock::const_iterator StartingInst,
Easwaran Ramanb1bd3982016-03-08 00:36:35 +0000249 std::vector<const BasicBlock*> &ToClone){
Eric Christophera5ec9252014-05-19 16:04:10 +0000250 WeakVH &BBEntry = VMap[BB];
Gerolf Hoflehner1da7cbd2014-04-26 05:43:41 +0000251
Eric Christophera5ec9252014-05-19 16:04:10 +0000252 // Have we already cloned this block?
253 if (BBEntry) return;
254
Gerolf Hoflehner3282af12014-04-30 22:05:02 +0000255 // Nope, clone it now.
Eric Christophera5ec9252014-05-19 16:04:10 +0000256 BasicBlock *NewBB;
257 BBEntry = NewBB = BasicBlock::Create(BB->getContext());
258 if (BB->hasName()) NewBB->setName(BB->getName()+NameSuffix);
259
260 // It is only legal to clone a function if a block address within that
261 // function is never referenced outside of the function. Given that, we
262 // want to map block addresses from the old function to block addresses in
263 // the clone. (This is different from the generic ValueMapper
264 // implementation, which generates an invalid blockaddress when
265 // cloning a function.)
266 //
267 // Note that we don't need to fix the mapping for unreachable blocks;
268 // the default mapping there is safe.
269 if (BB->hasAddressTaken()) {
270 Constant *OldBBAddr = BlockAddress::get(const_cast<Function*>(OldFunc),
271 const_cast<BasicBlock*>(BB));
272 VMap[OldBBAddr] = BlockAddress::get(NewFunc, NewBB);
273 }
Eli Friedman688db1d2011-10-21 20:45:19 +0000274
Chris Lattner3df13f42006-05-27 01:22:24 +0000275 bool hasCalls = false, hasDynamicAllocas = false, hasStaticAllocas = false;
Andrew Kaylor527c5dc2015-02-18 18:31:51 +0000276
Chris Lattner3df13f42006-05-27 01:22:24 +0000277 // Loop over all instructions, and copy them over, DCE'ing as we go. This
278 // loop doesn't include the terminator.
Andrew Kaylor527c5dc2015-02-18 18:31:51 +0000279 for (BasicBlock::const_iterator II = StartingInst, IE = --BB->end();
Chris Lattner3df13f42006-05-27 01:22:24 +0000280 II != IE; ++II) {
Andrew Kaylor527c5dc2015-02-18 18:31:51 +0000281
Chandler Carruth21211992012-03-25 04:03:40 +0000282 Instruction *NewInst = II->clone();
283
284 // Eagerly remap operands to the newly cloned instruction, except for PHI
285 // nodes for which we defer processing until we update the CFG.
286 if (!isa<PHINode>(NewInst)) {
287 RemapInstruction(NewInst, VMap,
Easwaran Raman7f187292016-01-08 18:23:17 +0000288 ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges);
Chandler Carruth21211992012-03-25 04:03:40 +0000289
290 // If we can simplify this instruction to some other value, simply add
291 // a mapping to that value rather than inserting a new instruction into
292 // the basic block.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000293 if (Value *V =
294 SimplifyInstruction(NewInst, BB->getModule()->getDataLayout())) {
Chandler Carruth21211992012-03-25 04:03:40 +0000295 // On the off-chance that this simplifies to an instruction in the old
296 // function, map it back into the new function.
297 if (Value *MappedV = VMap.lookup(V))
298 V = MappedV;
299
David Majnemerb8da3a22016-06-25 00:04:10 +0000300 if (!NewInst->mayHaveSideEffects()) {
301 VMap[&*II] = V;
302 delete NewInst;
303 continue;
304 }
Chandler Carruth21211992012-03-25 04:03:40 +0000305 }
Chris Lattner3df13f42006-05-27 01:22:24 +0000306 }
Devang Patel4bed3562009-02-10 07:48:18 +0000307
Chris Lattner3df13f42006-05-27 01:22:24 +0000308 if (II->hasName())
309 NewInst->setName(II->getName()+NameSuffix);
Nico Weberae2ef4c2016-06-24 22:52:39 +0000310 VMap[&*II] = NewInst; // Add instruction map to value.
Chandler Carruth21211992012-03-25 04:03:40 +0000311 NewBB->getInstList().push_back(NewInst);
Dale Johannesen900aaa32009-03-10 22:20:02 +0000312 hasCalls |= (isa<CallInst>(II) && !isa<DbgInfoIntrinsic>(II));
Sanjoy Das2d161452015-11-18 06:23:38 +0000313
314 if (CodeInfo)
315 if (auto CS = ImmutableCallSite(&*II))
316 if (CS.hasOperandBundles())
317 CodeInfo->OperandBundleCallSites.push_back(NewInst);
318
Chris Lattner3df13f42006-05-27 01:22:24 +0000319 if (const AllocaInst *AI = dyn_cast<AllocaInst>(II)) {
320 if (isa<ConstantInt>(AI->getArraySize()))
321 hasStaticAllocas = true;
322 else
323 hasDynamicAllocas = true;
324 }
325 }
326
Chris Lattnercc340c02006-06-01 19:19:23 +0000327 // Finally, clone over the terminator.
328 const TerminatorInst *OldTI = BB->getTerminator();
329 bool TerminatorDone = false;
330 if (const BranchInst *BI = dyn_cast<BranchInst>(OldTI)) {
331 if (BI->isConditional()) {
332 // If the condition was a known constant in the callee...
Zhou Sheng75b871f2007-01-11 12:24:14 +0000333 ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition());
334 // Or is a known constant in the caller...
Craig Topperf40110f2014-04-25 05:29:35 +0000335 if (!Cond) {
Duncan P. N. Exon Smith3d555ac2016-04-17 18:53:24 +0000336 Value *V = VMap.lookup(BI->getCondition());
Rafael Espindolac2240ad2010-10-13 02:08:17 +0000337 Cond = dyn_cast_or_null<ConstantInt>(V);
338 }
Zhou Sheng75b871f2007-01-11 12:24:14 +0000339
340 // Constant fold to uncond branch!
341 if (Cond) {
Reid Spencercddc9df2007-01-12 04:24:46 +0000342 BasicBlock *Dest = BI->getSuccessor(!Cond->getZExtValue());
Devang Patelb8f11de2010-06-23 23:55:51 +0000343 VMap[OldTI] = BranchInst::Create(Dest, NewBB);
Chris Lattner4bd8cda2007-03-02 03:11:20 +0000344 ToClone.push_back(Dest);
Chris Lattnercc340c02006-06-01 19:19:23 +0000345 TerminatorDone = true;
346 }
347 }
348 } else if (const SwitchInst *SI = dyn_cast<SwitchInst>(OldTI)) {
349 // If switching on a value known constant in the caller.
350 ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition());
Craig Topperf40110f2014-04-25 05:29:35 +0000351 if (!Cond) { // Or known constant after constant prop in the callee...
Duncan P. N. Exon Smith724c5032016-04-17 20:11:09 +0000352 Value *V = VMap.lookup(SI->getCondition());
Rafael Espindolac2240ad2010-10-13 02:08:17 +0000353 Cond = dyn_cast_or_null<ConstantInt>(V);
354 }
Chris Lattnercc340c02006-06-01 19:19:23 +0000355 if (Cond) { // Constant fold to uncond branch!
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +0000356 SwitchInst::ConstCaseIt Case = SI->findCaseValue(Cond);
357 BasicBlock *Dest = const_cast<BasicBlock*>(Case.getCaseSuccessor());
Devang Patelb8f11de2010-06-23 23:55:51 +0000358 VMap[OldTI] = BranchInst::Create(Dest, NewBB);
Chris Lattner4bd8cda2007-03-02 03:11:20 +0000359 ToClone.push_back(Dest);
Chris Lattnercc340c02006-06-01 19:19:23 +0000360 TerminatorDone = true;
361 }
362 }
363
364 if (!TerminatorDone) {
Nick Lewycky42fb7452009-09-27 07:38:41 +0000365 Instruction *NewInst = OldTI->clone();
Chris Lattnercc340c02006-06-01 19:19:23 +0000366 if (OldTI->hasName())
367 NewInst->setName(OldTI->getName()+NameSuffix);
368 NewBB->getInstList().push_back(NewInst);
Devang Patelb8f11de2010-06-23 23:55:51 +0000369 VMap[OldTI] = NewInst; // Add instruction map to value.
Sanjoy Das2d161452015-11-18 06:23:38 +0000370
371 if (CodeInfo)
372 if (auto CS = ImmutableCallSite(OldTI))
373 if (CS.hasOperandBundles())
374 CodeInfo->OperandBundleCallSites.push_back(NewInst);
375
Chris Lattnercc340c02006-06-01 19:19:23 +0000376 // Recursively clone any reachable successor blocks.
377 const TerminatorInst *TI = BB->getTerminator();
Pete Cooperebcd7482015-08-06 20:22:46 +0000378 for (const BasicBlock *Succ : TI->successors())
379 ToClone.push_back(Succ);
Chris Lattnercc340c02006-06-01 19:19:23 +0000380 }
381
Chris Lattner3df13f42006-05-27 01:22:24 +0000382 if (CodeInfo) {
383 CodeInfo->ContainsCalls |= hasCalls;
Chris Lattner3df13f42006-05-27 01:22:24 +0000384 CodeInfo->ContainsDynamicAllocas |= hasDynamicAllocas;
385 CodeInfo->ContainsDynamicAllocas |= hasStaticAllocas &&
386 BB != &BB->getParent()->front();
387 }
Chris Lattner3df13f42006-05-27 01:22:24 +0000388}
389
Sanjay Patelabf70232015-03-10 18:41:22 +0000390/// This works like CloneAndPruneFunctionInto, except that it does not clone the
391/// entire function. Instead it starts at an instruction provided by the caller
392/// and copies (and prunes) only the code reachable from that instruction.
Easwaran Ramanb1bd3982016-03-08 00:36:35 +0000393void llvm::CloneAndPruneIntoFromInst(Function *NewFunc, const Function *OldFunc,
394 const Instruction *StartingInst,
395 ValueToValueMapTy &VMap,
396 bool ModuleLevelChanges,
397 SmallVectorImpl<ReturnInst *> &Returns,
398 const char *NameSuffix,
399 ClonedCodeInfo *CodeInfo) {
Chris Lattner3df13f42006-05-27 01:22:24 +0000400 assert(NameSuffix && "NameSuffix cannot be null!");
Andrew Kaylor527c5dc2015-02-18 18:31:51 +0000401
Andrew Kaylorf22fe4a2015-02-23 20:01:56 +0000402 ValueMapTypeRemapper *TypeMapper = nullptr;
403 ValueMaterializer *Materializer = nullptr;
404
Chris Lattner3df13f42006-05-27 01:22:24 +0000405#ifndef NDEBUG
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000406 // If the cloning starts at the beginning of the function, verify that
Andrew Kaylor527c5dc2015-02-18 18:31:51 +0000407 // the function arguments are mapped.
408 if (!StartingInst)
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000409 for (const Argument &II : OldFunc->args())
410 assert(VMap.count(&II) && "No mapping from source argument specified!");
Chris Lattner3df13f42006-05-27 01:22:24 +0000411#endif
Duncan Sandsdd7daee2008-05-26 19:58:59 +0000412
Dan Gohmanca26f792010-08-26 15:41:53 +0000413 PruningFunctionCloner PFC(NewFunc, OldFunc, VMap, ModuleLevelChanges,
Easwaran Raman7f187292016-01-08 18:23:17 +0000414 NameSuffix, CodeInfo);
Andrew Kaylor527c5dc2015-02-18 18:31:51 +0000415 const BasicBlock *StartingBB;
416 if (StartingInst)
417 StartingBB = StartingInst->getParent();
418 else {
419 StartingBB = &OldFunc->getEntryBlock();
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000420 StartingInst = &StartingBB->front();
Andrew Kaylor527c5dc2015-02-18 18:31:51 +0000421 }
Chris Lattner3df13f42006-05-27 01:22:24 +0000422
Eric Christophera5ec9252014-05-19 16:04:10 +0000423 // Clone the entry block, and anything recursively reachable from it.
Chris Lattner4bd8cda2007-03-02 03:11:20 +0000424 std::vector<const BasicBlock*> CloneWorklist;
Easwaran Ramanb1bd3982016-03-08 00:36:35 +0000425 PFC.CloneBlock(StartingBB, StartingInst->getIterator(), CloneWorklist);
Chris Lattner4bd8cda2007-03-02 03:11:20 +0000426 while (!CloneWorklist.empty()) {
427 const BasicBlock *BB = CloneWorklist.back();
428 CloneWorklist.pop_back();
Easwaran Ramanb1bd3982016-03-08 00:36:35 +0000429 PFC.CloneBlock(BB, BB->begin(), CloneWorklist);
Chris Lattner4bd8cda2007-03-02 03:11:20 +0000430 }
Eric Christophera5ec9252014-05-19 16:04:10 +0000431
Chris Lattner3df13f42006-05-27 01:22:24 +0000432 // Loop over all of the basic blocks in the old function. If the block was
433 // reachable, we have cloned it and the old block is now in the value map:
434 // insert it into the new function in the right order. If not, ignore it.
435 //
Chris Lattnercc340c02006-06-01 19:19:23 +0000436 // Defer PHI resolution until rest of function is resolved.
Chris Lattnerd84dbb32009-08-27 04:02:30 +0000437 SmallVector<const PHINode*, 16> PHIToResolve;
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000438 for (const BasicBlock &BI : *OldFunc) {
Duncan P. N. Exon Smith3d555ac2016-04-17 18:53:24 +0000439 Value *V = VMap.lookup(&BI);
Rafael Espindolac2240ad2010-10-13 02:08:17 +0000440 BasicBlock *NewBB = cast_or_null<BasicBlock>(V);
Eric Christophera5ec9252014-05-19 16:04:10 +0000441 if (!NewBB) continue; // Dead block.
Chris Lattnercc340c02006-06-01 19:19:23 +0000442
Chris Lattner3df13f42006-05-27 01:22:24 +0000443 // Add the new block to the new function.
444 NewFunc->getBasicBlockList().push_back(NewBB);
Devang Patelf6eeaeb2009-11-10 23:06:00 +0000445
Chris Lattner3df13f42006-05-27 01:22:24 +0000446 // Handle PHI nodes specially, as we have to remove references to dead
447 // blocks.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000448 for (BasicBlock::const_iterator I = BI.begin(), E = BI.end(); I != E; ++I) {
Andrew Kaylor3170e562015-03-20 21:42:54 +0000449 // PHI nodes may have been remapped to non-PHI nodes by the caller or
450 // during the cloning process.
451 if (const PHINode *PN = dyn_cast<PHINode>(I)) {
452 if (isa<PHINode>(VMap[PN]))
453 PHIToResolve.push_back(PN);
454 else
455 break;
456 } else {
Chandler Carruth21211992012-03-25 04:03:40 +0000457 break;
Andrew Kaylor3170e562015-03-20 21:42:54 +0000458 }
459 }
Chandler Carruth21211992012-03-25 04:03:40 +0000460
461 // Finally, remap the terminator instructions, as those can't be remapped
462 // until all BBs are mapped.
463 RemapInstruction(NewBB->getTerminator(), VMap,
Andrew Kaylorf22fe4a2015-02-23 20:01:56 +0000464 ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges,
465 TypeMapper, Materializer);
Chris Lattner3df13f42006-05-27 01:22:24 +0000466 }
Chris Lattnercc340c02006-06-01 19:19:23 +0000467
468 // Defer PHI resolution until rest of function is resolved, PHI resolution
469 // requires the CFG to be up-to-date.
470 for (unsigned phino = 0, e = PHIToResolve.size(); phino != e; ) {
471 const PHINode *OPN = PHIToResolve[phino];
Chris Lattnercc340c02006-06-01 19:19:23 +0000472 unsigned NumPreds = OPN->getNumIncomingValues();
Chris Lattnercc340c02006-06-01 19:19:23 +0000473 const BasicBlock *OldBB = OPN->getParent();
Devang Patelb8f11de2010-06-23 23:55:51 +0000474 BasicBlock *NewBB = cast<BasicBlock>(VMap[OldBB]);
Chris Lattnercc340c02006-06-01 19:19:23 +0000475
476 // Map operands for blocks that are live and remove operands for blocks
477 // that are dead.
478 for (; phino != PHIToResolve.size() &&
479 PHIToResolve[phino]->getParent() == OldBB; ++phino) {
480 OPN = PHIToResolve[phino];
Devang Patelb8f11de2010-06-23 23:55:51 +0000481 PHINode *PN = cast<PHINode>(VMap[OPN]);
Chris Lattnercc340c02006-06-01 19:19:23 +0000482 for (unsigned pred = 0, e = NumPreds; pred != e; ++pred) {
Duncan P. N. Exon Smith724c5032016-04-17 20:11:09 +0000483 Value *V = VMap.lookup(PN->getIncomingBlock(pred));
Chris Lattner43f8d162011-01-08 08:15:20 +0000484 if (BasicBlock *MappedBlock = cast_or_null<BasicBlock>(V)) {
Owen Andersone70b6372009-07-05 22:41:43 +0000485 Value *InVal = MapValue(PN->getIncomingValue(pred),
Chris Lattner43f8d162011-01-08 08:15:20 +0000486 VMap,
487 ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges);
Chris Lattnercc340c02006-06-01 19:19:23 +0000488 assert(InVal && "Unknown input value?");
489 PN->setIncomingValue(pred, InVal);
490 PN->setIncomingBlock(pred, MappedBlock);
491 } else {
492 PN->removeIncomingValue(pred, false);
Richard Trieu7a083812016-02-18 22:09:30 +0000493 --pred; // Revisit the next entry.
494 --e;
Chris Lattnercc340c02006-06-01 19:19:23 +0000495 }
496 }
497 }
498
499 // The loop above has removed PHI entries for those blocks that are dead
500 // and has updated others. However, if a block is live (i.e. copied over)
501 // but its terminator has been changed to not go to this block, then our
502 // phi nodes will have invalid entries. Update the PHI nodes in this
503 // case.
504 PHINode *PN = cast<PHINode>(NewBB->begin());
505 NumPreds = std::distance(pred_begin(NewBB), pred_end(NewBB));
506 if (NumPreds != PN->getNumIncomingValues()) {
507 assert(NumPreds < PN->getNumIncomingValues());
508 // Count how many times each predecessor comes to this block.
509 std::map<BasicBlock*, unsigned> PredCount;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000510 for (pred_iterator PI = pred_begin(NewBB), E = pred_end(NewBB);
511 PI != E; ++PI)
512 --PredCount[*PI];
Chris Lattnercc340c02006-06-01 19:19:23 +0000513
514 // Figure out how many entries to remove from each PHI.
515 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
516 ++PredCount[PN->getIncomingBlock(i)];
517
518 // At this point, the excess predecessor entries are positive in the
519 // map. Loop over all of the PHIs and remove excess predecessor
520 // entries.
521 BasicBlock::iterator I = NewBB->begin();
522 for (; (PN = dyn_cast<PHINode>(I)); ++I) {
Benjamin Kramer135f7352016-06-26 12:28:59 +0000523 for (const auto &PCI : PredCount) {
524 BasicBlock *Pred = PCI.first;
525 for (unsigned NumToRemove = PCI.second; NumToRemove; --NumToRemove)
Chris Lattnercc340c02006-06-01 19:19:23 +0000526 PN->removeIncomingValue(Pred, false);
527 }
528 }
529 }
530
531 // If the loops above have made these phi nodes have 0 or 1 operand,
532 // replace them with undef or the input value. We must do this for
533 // correctness, because 0-operand phis are not valid.
534 PN = cast<PHINode>(NewBB->begin());
535 if (PN->getNumIncomingValues() == 0) {
536 BasicBlock::iterator I = NewBB->begin();
537 BasicBlock::const_iterator OldI = OldBB->begin();
538 while ((PN = dyn_cast<PHINode>(I++))) {
Owen Andersonb292b8c2009-07-30 23:03:37 +0000539 Value *NV = UndefValue::get(PN->getType());
Chris Lattnercc340c02006-06-01 19:19:23 +0000540 PN->replaceAllUsesWith(NV);
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000541 assert(VMap[&*OldI] == PN && "VMap mismatch");
542 VMap[&*OldI] = NV;
Chris Lattnercc340c02006-06-01 19:19:23 +0000543 PN->eraseFromParent();
544 ++OldI;
545 }
Chris Lattnercc340c02006-06-01 19:19:23 +0000546 }
547 }
Chandler Carruthef82cf52012-03-25 10:34:54 +0000548
549 // Make a second pass over the PHINodes now that all of them have been
550 // remapped into the new function, simplifying the PHINode and performing any
551 // recursive simplifications exposed. This will transparently update the
Chandler Carruth772c88b2012-03-28 08:38:27 +0000552 // WeakVH in the VMap. Notably, we rely on that so that if we coalesce
Chandler Carruthef82cf52012-03-25 10:34:54 +0000553 // two PHINodes, the iteration over the old PHIs remains valid, and the
554 // mapping will just map us to the new node (which may not even be a PHI
555 // node).
David Majnemer909793f2016-08-04 04:24:02 +0000556 const DataLayout &DL = NewFunc->getParent()->getDataLayout();
557 SmallSetVector<const Value *, 8> Worklist;
Chandler Carruthef82cf52012-03-25 10:34:54 +0000558 for (unsigned Idx = 0, Size = PHIToResolve.size(); Idx != Size; ++Idx)
David Majnemer909793f2016-08-04 04:24:02 +0000559 if (isa<PHINode>(VMap[PHIToResolve[Idx]]))
560 Worklist.insert(PHIToResolve[Idx]);
561
562 // Note that we must test the size on each iteration, the worklist can grow.
563 for (unsigned Idx = 0; Idx != Worklist.size(); ++Idx) {
564 const Value *OrigV = Worklist[Idx];
David Majnemer4eefd6b2016-08-04 04:47:18 +0000565 auto *I = dyn_cast_or_null<Instruction>(VMap.lookup(OrigV));
David Majnemer909793f2016-08-04 04:24:02 +0000566 if (!I)
567 continue;
568
David Majnemer5554eda2016-08-19 16:37:40 +0000569 // Skip over non-intrinsic callsites, we don't want to remove any nodes from
570 // the CGSCC.
571 CallSite CS = CallSite(I);
572 if (CS && CS.getCalledFunction() && !CS.getCalledFunction()->isIntrinsic())
573 continue;
574
David Majnemer909793f2016-08-04 04:24:02 +0000575 // See if this instruction simplifies.
576 Value *SimpleV = SimplifyInstruction(I, DL);
577 if (!SimpleV)
578 continue;
579
580 // Stash away all the uses of the old instruction so we can check them for
581 // recursive simplifications after a RAUW. This is cheaper than checking all
582 // uses of To on the recursive step in most cases.
583 for (const User *U : OrigV->users())
584 Worklist.insert(cast<Instruction>(U));
585
586 // Replace the instruction with its simplified value.
587 I->replaceAllUsesWith(SimpleV);
588
589 // If the original instruction had no side effects, remove it.
590 if (isInstructionTriviallyDead(I))
591 I->eraseFromParent();
592 else
593 VMap[OrigV] = I;
594 }
Chandler Carruthef82cf52012-03-25 10:34:54 +0000595
Chris Lattner237ccf22006-09-13 21:27:00 +0000596 // Now that the inlined function body has been fully constructed, go through
Sanjay Patel51bd9422015-03-10 18:37:05 +0000597 // and zap unconditional fall-through branches. This happens all the time when
Chris Lattner237ccf22006-09-13 21:27:00 +0000598 // specializing code: code specialization turns conditional branches into
599 // uncond branches, and this code folds them.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000600 Function::iterator Begin = cast<BasicBlock>(VMap[StartingBB])->getIterator();
Chandler Carruth772c88b2012-03-28 08:38:27 +0000601 Function::iterator I = Begin;
Chris Lattner237ccf22006-09-13 21:27:00 +0000602 while (I != NewFunc->end()) {
Chandler Carruth772c88b2012-03-28 08:38:27 +0000603 // Check if this block has become dead during inlining or other
604 // simplifications. Note that the first block will appear dead, as it has
605 // not yet been wired up properly.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000606 if (I != Begin && (pred_begin(&*I) == pred_end(&*I) ||
607 I->getSinglePredecessor() == &*I)) {
608 BasicBlock *DeadBB = &*I++;
Chandler Carruth772c88b2012-03-28 08:38:27 +0000609 DeleteDeadBlock(DeadBB);
610 continue;
611 }
612
613 // We need to simplify conditional branches and switches with a constant
614 // operand. We try to prune these out when cloning, but if the
615 // simplification required looking through PHI nodes, those are only
616 // available after forming the full basic block. That may leave some here,
617 // and we still want to prune the dead code as early as possible.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000618 ConstantFoldTerminator(&*I);
Chandler Carruth772c88b2012-03-28 08:38:27 +0000619
Chris Lattner237ccf22006-09-13 21:27:00 +0000620 BranchInst *BI = dyn_cast<BranchInst>(I->getTerminator());
621 if (!BI || BI->isConditional()) { ++I; continue; }
622
623 BasicBlock *Dest = BI->getSuccessor(0);
Chandler Carruthef82cf52012-03-25 10:34:54 +0000624 if (!Dest->getSinglePredecessor()) {
Chris Lattnerce494222007-02-01 18:48:38 +0000625 ++I; continue;
626 }
Chandler Carruthef82cf52012-03-25 10:34:54 +0000627
628 // We shouldn't be able to get single-entry PHI nodes here, as instsimplify
629 // above should have zapped all of them..
630 assert(!isa<PHINode>(Dest->begin()));
631
Chris Lattner237ccf22006-09-13 21:27:00 +0000632 // We know all single-entry PHI nodes in the inlined function have been
633 // removed, so we just need to splice the blocks.
634 BI->eraseFromParent();
635
Eric Christopher96513122011-06-23 06:24:52 +0000636 // Make all PHI nodes that referred to Dest now refer to I as their source.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000637 Dest->replaceAllUsesWith(&*I);
Eric Christopher96513122011-06-23 06:24:52 +0000638
Jay Foad61ea0e42011-06-23 09:09:15 +0000639 // Move all the instructions in the succ to the pred.
640 I->getInstList().splice(I->end(), Dest->getInstList());
641
Chris Lattner237ccf22006-09-13 21:27:00 +0000642 // Remove the dest block.
643 Dest->eraseFromParent();
644
645 // Do not increment I, iteratively merge all things this block branches to.
646 }
Chandler Carruth49da9332012-04-06 17:21:31 +0000647
Sanjay Patel51bd9422015-03-10 18:37:05 +0000648 // Make a final pass over the basic blocks from the old function to gather
Chandler Carruth49da9332012-04-06 17:21:31 +0000649 // any return instructions which survived folding. We have to do this here
650 // because we can iteratively remove and merge returns above.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000651 for (Function::iterator I = cast<BasicBlock>(VMap[StartingBB])->getIterator(),
Chandler Carruth49da9332012-04-06 17:21:31 +0000652 E = NewFunc->end();
653 I != E; ++I)
654 if (ReturnInst *RI = dyn_cast<ReturnInst>(I->getTerminator()))
655 Returns.push_back(RI);
Chris Lattner3df13f42006-05-27 01:22:24 +0000656}
Andrew Kaylor527c5dc2015-02-18 18:31:51 +0000657
658
Sanjay Patelabf70232015-03-10 18:41:22 +0000659/// This works exactly like CloneFunctionInto,
Andrew Kaylor527c5dc2015-02-18 18:31:51 +0000660/// except that it does some simple constant prop and DCE on the fly. The
661/// effect of this is to copy significantly less code in cases where (for
662/// example) a function call with constant arguments is inlined, and those
663/// constant arguments cause a significant amount of code in the callee to be
664/// dead. Since this doesn't produce an exact copy of the input, it can't be
665/// used for things like CloneFunction or CloneModule.
Easwaran Ramanb1bd3982016-03-08 00:36:35 +0000666void llvm::CloneAndPruneFunctionInto(Function *NewFunc, const Function *OldFunc,
667 ValueToValueMapTy &VMap,
668 bool ModuleLevelChanges,
669 SmallVectorImpl<ReturnInst*> &Returns,
670 const char *NameSuffix,
671 ClonedCodeInfo *CodeInfo,
672 Instruction *TheCall) {
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000673 CloneAndPruneIntoFromInst(NewFunc, OldFunc, &OldFunc->front().front(), VMap,
Easwaran Ramanb1bd3982016-03-08 00:36:35 +0000674 ModuleLevelChanges, Returns, NameSuffix, CodeInfo);
Andrew Kaylor527c5dc2015-02-18 18:31:51 +0000675}
Adam Nemet1a689182015-07-10 18:55:09 +0000676
677/// \brief Remaps instructions in \p Blocks using the mapping in \p VMap.
678void llvm::remapInstructionsInBlocks(
679 const SmallVectorImpl<BasicBlock *> &Blocks, ValueToValueMapTy &VMap) {
680 // Rewrite the code to refer to itself.
681 for (auto *BB : Blocks)
682 for (auto &Inst : *BB)
683 RemapInstruction(&Inst, VMap,
Duncan P. N. Exon Smithda68cbc2016-04-07 00:26:43 +0000684 RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
Adam Nemet1a689182015-07-10 18:55:09 +0000685}
686
687/// \brief Clones a loop \p OrigLoop. Returns the loop and the blocks in \p
688/// Blocks.
689///
690/// Updates LoopInfo and DominatorTree assuming the loop is dominated by block
691/// \p LoopDomBB. Insert the new blocks before block specified in \p Before.
692Loop *llvm::cloneLoopWithPreheader(BasicBlock *Before, BasicBlock *LoopDomBB,
693 Loop *OrigLoop, ValueToValueMapTy &VMap,
694 const Twine &NameSuffix, LoopInfo *LI,
695 DominatorTree *DT,
696 SmallVectorImpl<BasicBlock *> &Blocks) {
Vaivaswatha Nagaraj08efb0e2016-04-27 05:25:09 +0000697 assert(OrigLoop->getSubLoops().empty() &&
698 "Loop to be cloned cannot have inner loop");
Adam Nemet1a689182015-07-10 18:55:09 +0000699 Function *F = OrigLoop->getHeader()->getParent();
700 Loop *ParentLoop = OrigLoop->getParentLoop();
701
702 Loop *NewLoop = new Loop();
703 if (ParentLoop)
704 ParentLoop->addChildLoop(NewLoop);
705 else
706 LI->addTopLevelLoop(NewLoop);
707
708 BasicBlock *OrigPH = OrigLoop->getLoopPreheader();
709 assert(OrigPH && "No preheader");
710 BasicBlock *NewPH = CloneBasicBlock(OrigPH, VMap, NameSuffix, F);
711 // To rename the loop PHIs.
712 VMap[OrigPH] = NewPH;
713 Blocks.push_back(NewPH);
714
715 // Update LoopInfo.
716 if (ParentLoop)
717 ParentLoop->addBasicBlockToLoop(NewPH, *LI);
718
719 // Update DominatorTree.
720 DT->addNewBlock(NewPH, LoopDomBB);
721
722 for (BasicBlock *BB : OrigLoop->getBlocks()) {
723 BasicBlock *NewBB = CloneBasicBlock(BB, VMap, NameSuffix, F);
724 VMap[BB] = NewBB;
725
726 // Update LoopInfo.
727 NewLoop->addBasicBlockToLoop(NewBB, *LI);
728
Vikram TVc702b8b2016-06-11 16:41:10 +0000729 // Add DominatorTree node. After seeing all blocks, update to correct IDom.
730 DT->addNewBlock(NewBB, NewPH);
Adam Nemet1a689182015-07-10 18:55:09 +0000731
732 Blocks.push_back(NewBB);
733 }
734
Vikram TVc702b8b2016-06-11 16:41:10 +0000735 for (BasicBlock *BB : OrigLoop->getBlocks()) {
736 // Update DominatorTree.
737 BasicBlock *IDomBB = DT->getNode(BB)->getIDom()->getBlock();
738 DT->changeImmediateDominator(cast<BasicBlock>(VMap[BB]),
739 cast<BasicBlock>(VMap[IDomBB]));
740 }
741
Adam Nemet1a689182015-07-10 18:55:09 +0000742 // Move them physically from the end of the block list.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000743 F->getBasicBlockList().splice(Before->getIterator(), F->getBasicBlockList(),
744 NewPH);
745 F->getBasicBlockList().splice(Before->getIterator(), F->getBasicBlockList(),
746 NewLoop->getHeader()->getIterator(), F->end());
Adam Nemet1a689182015-07-10 18:55:09 +0000747
748 return NewLoop;
749}