blob: 6ff05fe3e5900f19385ec8f1b0c0e47db935611b [file] [log] [blame]
Chris Lattner8bce9882002-11-19 22:04:49 +00001//===- CloneFunction.cpp - Clone a function into another function ---------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner8bce9882002-11-19 22:04:49 +00009//
10// This file implements the CloneFunctionInto interface, which is used as the
11// low-level function cloner. This is used by the CloneFunction and function
12// inliner to do the dirty work of copying the body of a function around.
13//
14//===----------------------------------------------------------------------===//
Chris Lattner16bfdb52002-03-29 19:03:54 +000015
Chris Lattner16667512002-11-19 20:59:41 +000016#include "llvm/Transforms/Utils/Cloning.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000017#include "llvm/ADT/SmallVector.h"
18#include "llvm/Analysis/ConstantFolding.h"
19#include "llvm/Analysis/InstructionSimplify.h"
Adam Nemet1a689182015-07-10 18:55:09 +000020#include "llvm/Analysis/LoopInfo.h"
Chandler Carruth1305dc32014-03-04 11:45:46 +000021#include "llvm/IR/CFG.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000022#include "llvm/IR/Constants.h"
Chandler Carruth9a4c9e52014-03-06 00:46:21 +000023#include "llvm/IR/DebugInfo.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000024#include "llvm/IR/DerivedTypes.h"
25#include "llvm/IR/Function.h"
26#include "llvm/IR/GlobalVariable.h"
27#include "llvm/IR/Instructions.h"
28#include "llvm/IR/IntrinsicInst.h"
29#include "llvm/IR/LLVMContext.h"
30#include "llvm/IR/Metadata.h"
Alon Mishne07d949f2014-03-12 14:42:51 +000031#include "llvm/IR/Module.h"
Chandler Carruth772c88b2012-03-28 08:38:27 +000032#include "llvm/Transforms/Utils/BasicBlockUtils.h"
33#include "llvm/Transforms/Utils/Local.h"
Dan Gohmana2095032010-08-24 18:50:07 +000034#include "llvm/Transforms/Utils/ValueMapper.h"
Chris Lattner1bfc7ab2007-02-03 00:08:31 +000035#include <map>
Chris Lattnerdf3c3422004-01-09 06:12:26 +000036using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000037
Sanjay Patelabf70232015-03-10 18:41:22 +000038/// See comments in Cloning.h.
Chris Lattnerdf3c3422004-01-09 06:12:26 +000039BasicBlock *llvm::CloneBasicBlock(const BasicBlock *BB,
Devang Pateld8dedee2010-06-24 00:00:42 +000040 ValueToValueMapTy &VMap,
Benjamin Kramer1266d462010-01-27 19:58:47 +000041 const Twine &NameSuffix, Function *F,
Chris Lattneredad1282006-01-13 18:39:17 +000042 ClonedCodeInfo *CodeInfo) {
Owen Anderson55f1c092009-08-13 21:58:54 +000043 BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), "", F);
Chris Lattnere9f42322003-04-18 03:50:09 +000044 if (BB->hasName()) NewBB->setName(BB->getName()+NameSuffix);
45
Chris Lattneredad1282006-01-13 18:39:17 +000046 bool hasCalls = false, hasDynamicAllocas = false, hasStaticAllocas = false;
47
48 // Loop over all instructions, and copy them over.
Chris Lattnere9f42322003-04-18 03:50:09 +000049 for (BasicBlock::const_iterator II = BB->begin(), IE = BB->end();
50 II != IE; ++II) {
Nick Lewycky42fb7452009-09-27 07:38:41 +000051 Instruction *NewInst = II->clone();
Chris Lattnere9f42322003-04-18 03:50:09 +000052 if (II->hasName())
53 NewInst->setName(II->getName()+NameSuffix);
54 NewBB->getInstList().push_back(NewInst);
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +000055 VMap[&*II] = NewInst; // Add instruction map to value.
56
Dale Johannesen900aaa32009-03-10 22:20:02 +000057 hasCalls |= (isa<CallInst>(II) && !isa<DbgInfoIntrinsic>(II));
Chris Lattneredad1282006-01-13 18:39:17 +000058 if (const AllocaInst *AI = dyn_cast<AllocaInst>(II)) {
59 if (isa<ConstantInt>(AI->getArraySize()))
60 hasStaticAllocas = true;
61 else
62 hasDynamicAllocas = true;
63 }
64 }
65
66 if (CodeInfo) {
67 CodeInfo->ContainsCalls |= hasCalls;
Chris Lattneredad1282006-01-13 18:39:17 +000068 CodeInfo->ContainsDynamicAllocas |= hasDynamicAllocas;
69 CodeInfo->ContainsDynamicAllocas |= hasStaticAllocas &&
Dan Gohmandcb291f2007-03-22 16:38:57 +000070 BB != &BB->getParent()->getEntryBlock();
Chris Lattnere9f42322003-04-18 03:50:09 +000071 }
72 return NewBB;
73}
74
Chris Lattner16bfdb52002-03-29 19:03:54 +000075// Clone OldFunc into NewFunc, transforming the old arguments into references to
Dan Gohmanca26f792010-08-26 15:41:53 +000076// VMap values.
Chris Lattner16bfdb52002-03-29 19:03:54 +000077//
Chris Lattnerdf3c3422004-01-09 06:12:26 +000078void llvm::CloneFunctionInto(Function *NewFunc, const Function *OldFunc,
Devang Pateld8dedee2010-06-24 00:00:42 +000079 ValueToValueMapTy &VMap,
Dan Gohmanca26f792010-08-26 15:41:53 +000080 bool ModuleLevelChanges,
Chris Lattnerd84dbb32009-08-27 04:02:30 +000081 SmallVectorImpl<ReturnInst*> &Returns,
Mon P Wang5d44a432011-12-23 02:18:32 +000082 const char *NameSuffix, ClonedCodeInfo *CodeInfo,
James Molloyf6f121e2013-05-28 15:17:05 +000083 ValueMapTypeRemapper *TypeMapper,
84 ValueMaterializer *Materializer) {
Chris Lattnerb1120052002-11-19 21:54:07 +000085 assert(NameSuffix && "NameSuffix cannot be null!");
Misha Brukmanb1c93172005-04-21 23:48:37 +000086
Chris Lattnerc3626182002-11-19 22:54:01 +000087#ifndef NDEBUG
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +000088 for (const Argument &I : OldFunc->args())
89 assert(VMap.count(&I) && "No mapping from source argument specified!");
Chris Lattnerc3626182002-11-19 22:54:01 +000090#endif
Chris Lattner16bfdb52002-03-29 19:03:54 +000091
Reid Kleckner23798a92014-03-26 22:26:35 +000092 // 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
Keno Fischer2ac0c272015-11-16 05:13:30 +000098 // Fix up the personality function that got copied over.
99 if (OldFunc->hasPersonalityFn())
100 NewFunc->setPersonalityFn(
101 MapValue(OldFunc->getPersonalityFn(), VMap,
102 ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges,
103 TypeMapper, Materializer));
104
Joey Gouly81259292013-04-10 10:37:38 +0000105 AttributeSet OldAttrs = OldFunc->getAttributes();
106 // Clone any argument attributes that are present in the VMap.
Reid Kleckner23798a92014-03-26 22:26:35 +0000107 for (const Argument &OldArg : OldFunc->args())
108 if (Argument *NewArg = dyn_cast<Argument>(VMap[&OldArg])) {
Joey Gouly81259292013-04-10 10:37:38 +0000109 AttributeSet attrs =
Reid Kleckner23798a92014-03-26 22:26:35 +0000110 OldAttrs.getParamAttributes(OldArg.getArgNo() + 1);
Joey Gouly81259292013-04-10 10:37:38 +0000111 if (attrs.getNumSlots() > 0)
Reid Kleckner23798a92014-03-26 22:26:35 +0000112 NewArg->addAttr(attrs);
Joey Gouly81259292013-04-10 10:37:38 +0000113 }
Andrew Lenharth5aa1cc42008-10-07 18:08:38 +0000114
Reid Kleckner23798a92014-03-26 22:26:35 +0000115 NewFunc->setAttributes(
116 NewFunc->getAttributes()
117 .addAttributes(NewFunc->getContext(), AttributeSet::ReturnIndex,
118 OldAttrs.getRetAttributes())
119 .addAttributes(NewFunc->getContext(), AttributeSet::FunctionIndex,
120 OldAttrs.getFnAttributes()));
Anton Korobeynikovd38b3fb2008-03-23 16:03:00 +0000121
Peter Collingbourne2bc252a2016-03-30 22:05:13 +0000122 SmallVector<std::pair<unsigned, MDNode *>, 1> MDs;
123 OldFunc->getAllMetadata(MDs);
124 for (auto MD : MDs)
Peter Collingbourne382d81c2016-06-01 01:17:57 +0000125 NewFunc->addMetadata(
Peter Collingbourne2bc252a2016-03-30 22:05:13 +0000126 MD.first,
Peter Collingbourne382d81c2016-06-01 01:17:57 +0000127 *MapMetadata(MD.second, VMap,
128 ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges,
129 TypeMapper, Materializer));
Peter Collingbourne2bc252a2016-03-30 22:05:13 +0000130
Chris Lattner16bfdb52002-03-29 19:03:54 +0000131 // Loop over all of the basic blocks in the function, cloning them as
Chris Lattnerb1120052002-11-19 21:54:07 +0000132 // appropriate. Note that we save BE this way in order to handle cloning of
133 // recursive functions into themselves.
Chris Lattner16bfdb52002-03-29 19:03:54 +0000134 //
135 for (Function::const_iterator BI = OldFunc->begin(), BE = OldFunc->end();
136 BI != BE; ++BI) {
Chris Lattnerfda72b12002-06-25 16:12:52 +0000137 const BasicBlock &BB = *BI;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000138
Chris Lattnere9f42322003-04-18 03:50:09 +0000139 // Create a new basic block and copy instructions into it!
Chris Lattner43f8d162011-01-08 08:15:20 +0000140 BasicBlock *CBB = CloneBasicBlock(&BB, VMap, NameSuffix, NewFunc, CodeInfo);
Chris Lattner16bfdb52002-03-29 19:03:54 +0000141
Eli Friedman688db1d2011-10-21 20:45:19 +0000142 // Add basic block mapping.
143 VMap[&BB] = CBB;
144
145 // It is only legal to clone a function if a block address within that
146 // function is never referenced outside of the function. Given that, we
147 // want to map block addresses from the old function to block addresses in
148 // the clone. (This is different from the generic ValueMapper
149 // implementation, which generates an invalid blockaddress when
150 // cloning a function.)
151 if (BB.hasAddressTaken()) {
152 Constant *OldBBAddr = BlockAddress::get(const_cast<Function*>(OldFunc),
153 const_cast<BasicBlock*>(&BB));
Sanjoy Das1f8fd882015-12-09 20:33:45 +0000154 VMap[OldBBAddr] = BlockAddress::get(NewFunc, CBB);
Eli Friedman688db1d2011-10-21 20:45:19 +0000155 }
156
157 // Note return instructions for the caller.
Chris Lattnerb1120052002-11-19 21:54:07 +0000158 if (ReturnInst *RI = dyn_cast<ReturnInst>(CBB->getTerminator()))
159 Returns.push_back(RI);
Chris Lattner16bfdb52002-03-29 19:03:54 +0000160 }
161
Misha Brukmanb1c93172005-04-21 23:48:37 +0000162 // Loop over all of the instructions in the function, fixing up operand
Devang Patelb8f11de2010-06-23 23:55:51 +0000163 // references as we go. This uses VMap to do all the hard work.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000164 for (Function::iterator BB =
165 cast<BasicBlock>(VMap[&OldFunc->front()])->getIterator(),
166 BE = NewFunc->end();
167 BB != BE; ++BB)
Chris Lattner16bfdb52002-03-29 19:03:54 +0000168 // Loop over all instructions, fixing each one as we find it...
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000169 for (Instruction &II : *BB)
170 RemapInstruction(&II, VMap,
Mon P Wang5d44a432011-12-23 02:18:32 +0000171 ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges,
James Molloyf6f121e2013-05-28 15:17:05 +0000172 TypeMapper, Materializer);
Chris Lattner16bfdb52002-03-29 19:03:54 +0000173}
Chris Lattnerfb311d22002-11-19 23:12:22 +0000174
Peter Collingbournedba99562016-05-10 20:23:24 +0000175/// Return a copy of the specified function and add it to that function's
176/// module. Also, any references specified in the VMap are changed to refer to
177/// their mapped value instead of the original one. If any of the arguments to
178/// the function are in the VMap, the arguments are deleted from the resultant
179/// function. The VMap is updated to include mappings from all of the
180/// instructions and basicblocks in the function from their old to new values.
Chris Lattnerfb311d22002-11-19 23:12:22 +0000181///
Peter Collingbournedba99562016-05-10 20:23:24 +0000182Function *llvm::CloneFunction(Function *F, ValueToValueMapTy &VMap,
Chris Lattneredad1282006-01-13 18:39:17 +0000183 ClonedCodeInfo *CodeInfo) {
Jay Foadb804a2b2011-07-12 14:06:48 +0000184 std::vector<Type*> ArgTypes;
Chris Lattnerfb311d22002-11-19 23:12:22 +0000185
186 // The user might be deleting arguments to the function by specifying them in
Devang Patelb8f11de2010-06-23 23:55:51 +0000187 // the VMap. If so, we need to not add the arguments to the arg ty vector
Chris Lattnerfb311d22002-11-19 23:12:22 +0000188 //
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000189 for (const Argument &I : F->args())
190 if (VMap.count(&I) == 0) // Haven't mapped the argument to anything yet?
191 ArgTypes.push_back(I.getType());
Chris Lattnerfb311d22002-11-19 23:12:22 +0000192
193 // Create a new function type...
Owen Anderson4056ca92009-07-29 22:17:13 +0000194 FunctionType *FTy = FunctionType::get(F->getFunctionType()->getReturnType(),
Chris Lattnerfb311d22002-11-19 23:12:22 +0000195 ArgTypes, F->getFunctionType()->isVarArg());
196
197 // Create the new function...
Peter Collingbournedba99562016-05-10 20:23:24 +0000198 Function *NewF =
199 Function::Create(FTy, F->getLinkage(), F->getName(), F->getParent());
Misha Brukmanb1c93172005-04-21 23:48:37 +0000200
Chris Lattnerfb311d22002-11-19 23:12:22 +0000201 // Loop over the arguments, copying the names of the mapped arguments over...
Chris Lattner531f9e92005-03-15 04:54:21 +0000202 Function::arg_iterator DestI = NewF->arg_begin();
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000203 for (const Argument & I : F->args())
204 if (VMap.count(&I) == 0) { // Is this argument preserved?
205 DestI->setName(I.getName()); // Copy the name over...
206 VMap[&I] = &*DestI++; // Add mapping to VMap
Chris Lattnerfb311d22002-11-19 23:12:22 +0000207 }
208
Chris Lattnerd84dbb32009-08-27 04:02:30 +0000209 SmallVector<ReturnInst*, 8> Returns; // Ignore returns cloned.
Peter Collingbournedba99562016-05-10 20:23:24 +0000210 CloneFunctionInto(NewF, F, VMap, /*ModuleLevelChanges=*/false, Returns, "",
211 CodeInfo);
212
Misha Brukmanb1c93172005-04-21 23:48:37 +0000213 return NewF;
Chris Lattnerfb311d22002-11-19 23:12:22 +0000214}
Brian Gaeke960707c2003-11-11 22:41:34 +0000215
Chris Lattner3df13f42006-05-27 01:22:24 +0000216
217
218namespace {
Sanjay Patelabf70232015-03-10 18:41:22 +0000219 /// This is a private class used to implement CloneAndPruneFunctionInto.
Nick Lewycky02d5f772009-10-25 06:33:48 +0000220 struct PruningFunctionCloner {
Chris Lattner3df13f42006-05-27 01:22:24 +0000221 Function *NewFunc;
222 const Function *OldFunc;
Devang Pateld8dedee2010-06-24 00:00:42 +0000223 ValueToValueMapTy &VMap;
Dan Gohmanca26f792010-08-26 15:41:53 +0000224 bool ModuleLevelChanges;
Chris Lattner3df13f42006-05-27 01:22:24 +0000225 const char *NameSuffix;
226 ClonedCodeInfo *CodeInfo;
Andrew Kaylor527c5dc2015-02-18 18:31:51 +0000227
Chris Lattner3df13f42006-05-27 01:22:24 +0000228 public:
229 PruningFunctionCloner(Function *newFunc, const Function *oldFunc,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000230 ValueToValueMapTy &valueMap, bool moduleLevelChanges,
Easwaran Raman7f187292016-01-08 18:23:17 +0000231 const char *nameSuffix, ClonedCodeInfo *codeInfo)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000232 : NewFunc(newFunc), OldFunc(oldFunc), VMap(valueMap),
233 ModuleLevelChanges(moduleLevelChanges), NameSuffix(nameSuffix),
Easwaran Raman7f187292016-01-08 18:23:17 +0000234 CodeInfo(codeInfo) {}
Chris Lattner3df13f42006-05-27 01:22:24 +0000235
Sanjay Patelabf70232015-03-10 18:41:22 +0000236 /// The specified block is found to be reachable, clone it and
Eric Christophera5ec9252014-05-19 16:04:10 +0000237 /// anything that it can reach.
Easwaran Ramanb1bd3982016-03-08 00:36:35 +0000238 void CloneBlock(const BasicBlock *BB,
Andrew Kaylor527c5dc2015-02-18 18:31:51 +0000239 BasicBlock::const_iterator StartingInst,
Easwaran Ramanb1bd3982016-03-08 00:36:35 +0000240 std::vector<const BasicBlock*> &ToClone);
Chris Lattner3df13f42006-05-27 01:22:24 +0000241 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000242}
Chris Lattner3df13f42006-05-27 01:22:24 +0000243
Sanjay Patelabf70232015-03-10 18:41:22 +0000244/// The specified block is found to be reachable, clone it and
Eric Christophera5ec9252014-05-19 16:04:10 +0000245/// anything that it can reach.
Chris Lattner4bd8cda2007-03-02 03:11:20 +0000246void PruningFunctionCloner::CloneBlock(const BasicBlock *BB,
Andrew Kaylor527c5dc2015-02-18 18:31:51 +0000247 BasicBlock::const_iterator StartingInst,
Easwaran Ramanb1bd3982016-03-08 00:36:35 +0000248 std::vector<const BasicBlock*> &ToClone){
Eric Christophera5ec9252014-05-19 16:04:10 +0000249 WeakVH &BBEntry = VMap[BB];
Gerolf Hoflehner1da7cbd2014-04-26 05:43:41 +0000250
Eric Christophera5ec9252014-05-19 16:04:10 +0000251 // Have we already cloned this block?
252 if (BBEntry) return;
253
Gerolf Hoflehner3282af12014-04-30 22:05:02 +0000254 // Nope, clone it now.
Eric Christophera5ec9252014-05-19 16:04:10 +0000255 BasicBlock *NewBB;
256 BBEntry = NewBB = BasicBlock::Create(BB->getContext());
257 if (BB->hasName()) NewBB->setName(BB->getName()+NameSuffix);
258
259 // It is only legal to clone a function if a block address within that
260 // function is never referenced outside of the function. Given that, we
261 // want to map block addresses from the old function to block addresses in
262 // the clone. (This is different from the generic ValueMapper
263 // implementation, which generates an invalid blockaddress when
264 // cloning a function.)
265 //
266 // Note that we don't need to fix the mapping for unreachable blocks;
267 // the default mapping there is safe.
268 if (BB->hasAddressTaken()) {
269 Constant *OldBBAddr = BlockAddress::get(const_cast<Function*>(OldFunc),
270 const_cast<BasicBlock*>(BB));
271 VMap[OldBBAddr] = BlockAddress::get(NewFunc, NewBB);
272 }
Eli Friedman688db1d2011-10-21 20:45:19 +0000273
Chris Lattner3df13f42006-05-27 01:22:24 +0000274 bool hasCalls = false, hasDynamicAllocas = false, hasStaticAllocas = false;
Andrew Kaylor527c5dc2015-02-18 18:31:51 +0000275
Chris Lattner3df13f42006-05-27 01:22:24 +0000276 // Loop over all instructions, and copy them over, DCE'ing as we go. This
277 // loop doesn't include the terminator.
Andrew Kaylor527c5dc2015-02-18 18:31:51 +0000278 for (BasicBlock::const_iterator II = StartingInst, IE = --BB->end();
Chris Lattner3df13f42006-05-27 01:22:24 +0000279 II != IE; ++II) {
Andrew Kaylor527c5dc2015-02-18 18:31:51 +0000280
Chandler Carruth21211992012-03-25 04:03:40 +0000281 Instruction *NewInst = II->clone();
282
283 // Eagerly remap operands to the newly cloned instruction, except for PHI
284 // nodes for which we defer processing until we update the CFG.
285 if (!isa<PHINode>(NewInst)) {
286 RemapInstruction(NewInst, VMap,
Easwaran Raman7f187292016-01-08 18:23:17 +0000287 ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges);
Chandler Carruth21211992012-03-25 04:03:40 +0000288
289 // If we can simplify this instruction to some other value, simply add
290 // a mapping to that value rather than inserting a new instruction into
291 // the basic block.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000292 if (Value *V =
293 SimplifyInstruction(NewInst, BB->getModule()->getDataLayout())) {
Chandler Carruth21211992012-03-25 04:03:40 +0000294 // On the off-chance that this simplifies to an instruction in the old
295 // function, map it back into the new function.
296 if (Value *MappedV = VMap.lookup(V))
297 V = MappedV;
298
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000299 VMap[&*II] = V;
Chandler Carruth21211992012-03-25 04:03:40 +0000300 delete NewInst;
301 continue;
302 }
Chris Lattner3df13f42006-05-27 01:22:24 +0000303 }
Devang Patel4bed3562009-02-10 07:48:18 +0000304
Chris Lattner3df13f42006-05-27 01:22:24 +0000305 if (II->hasName())
306 NewInst->setName(II->getName()+NameSuffix);
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000307 VMap[&*II] = NewInst; // Add instruction map to value.
Chandler Carruth21211992012-03-25 04:03:40 +0000308 NewBB->getInstList().push_back(NewInst);
Dale Johannesen900aaa32009-03-10 22:20:02 +0000309 hasCalls |= (isa<CallInst>(II) && !isa<DbgInfoIntrinsic>(II));
Sanjoy Das2d161452015-11-18 06:23:38 +0000310
311 if (CodeInfo)
312 if (auto CS = ImmutableCallSite(&*II))
313 if (CS.hasOperandBundles())
314 CodeInfo->OperandBundleCallSites.push_back(NewInst);
315
Chris Lattner3df13f42006-05-27 01:22:24 +0000316 if (const AllocaInst *AI = dyn_cast<AllocaInst>(II)) {
317 if (isa<ConstantInt>(AI->getArraySize()))
318 hasStaticAllocas = true;
319 else
320 hasDynamicAllocas = true;
321 }
322 }
323
Chris Lattnercc340c02006-06-01 19:19:23 +0000324 // Finally, clone over the terminator.
325 const TerminatorInst *OldTI = BB->getTerminator();
326 bool TerminatorDone = false;
327 if (const BranchInst *BI = dyn_cast<BranchInst>(OldTI)) {
328 if (BI->isConditional()) {
329 // If the condition was a known constant in the callee...
Zhou Sheng75b871f2007-01-11 12:24:14 +0000330 ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition());
331 // Or is a known constant in the caller...
Craig Topperf40110f2014-04-25 05:29:35 +0000332 if (!Cond) {
Duncan P. N. Exon Smith3d555ac2016-04-17 18:53:24 +0000333 Value *V = VMap.lookup(BI->getCondition());
Rafael Espindolac2240ad2010-10-13 02:08:17 +0000334 Cond = dyn_cast_or_null<ConstantInt>(V);
335 }
Zhou Sheng75b871f2007-01-11 12:24:14 +0000336
337 // Constant fold to uncond branch!
338 if (Cond) {
Reid Spencercddc9df2007-01-12 04:24:46 +0000339 BasicBlock *Dest = BI->getSuccessor(!Cond->getZExtValue());
Devang Patelb8f11de2010-06-23 23:55:51 +0000340 VMap[OldTI] = BranchInst::Create(Dest, NewBB);
Chris Lattner4bd8cda2007-03-02 03:11:20 +0000341 ToClone.push_back(Dest);
Chris Lattnercc340c02006-06-01 19:19:23 +0000342 TerminatorDone = true;
343 }
344 }
345 } else if (const SwitchInst *SI = dyn_cast<SwitchInst>(OldTI)) {
346 // If switching on a value known constant in the caller.
347 ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition());
Craig Topperf40110f2014-04-25 05:29:35 +0000348 if (!Cond) { // Or known constant after constant prop in the callee...
Duncan P. N. Exon Smith724c5032016-04-17 20:11:09 +0000349 Value *V = VMap.lookup(SI->getCondition());
Rafael Espindolac2240ad2010-10-13 02:08:17 +0000350 Cond = dyn_cast_or_null<ConstantInt>(V);
351 }
Chris Lattnercc340c02006-06-01 19:19:23 +0000352 if (Cond) { // Constant fold to uncond branch!
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +0000353 SwitchInst::ConstCaseIt Case = SI->findCaseValue(Cond);
354 BasicBlock *Dest = const_cast<BasicBlock*>(Case.getCaseSuccessor());
Devang Patelb8f11de2010-06-23 23:55:51 +0000355 VMap[OldTI] = BranchInst::Create(Dest, NewBB);
Chris Lattner4bd8cda2007-03-02 03:11:20 +0000356 ToClone.push_back(Dest);
Chris Lattnercc340c02006-06-01 19:19:23 +0000357 TerminatorDone = true;
358 }
359 }
360
361 if (!TerminatorDone) {
Nick Lewycky42fb7452009-09-27 07:38:41 +0000362 Instruction *NewInst = OldTI->clone();
Chris Lattnercc340c02006-06-01 19:19:23 +0000363 if (OldTI->hasName())
364 NewInst->setName(OldTI->getName()+NameSuffix);
365 NewBB->getInstList().push_back(NewInst);
Devang Patelb8f11de2010-06-23 23:55:51 +0000366 VMap[OldTI] = NewInst; // Add instruction map to value.
Sanjoy Das2d161452015-11-18 06:23:38 +0000367
368 if (CodeInfo)
369 if (auto CS = ImmutableCallSite(OldTI))
370 if (CS.hasOperandBundles())
371 CodeInfo->OperandBundleCallSites.push_back(NewInst);
372
Chris Lattnercc340c02006-06-01 19:19:23 +0000373 // Recursively clone any reachable successor blocks.
374 const TerminatorInst *TI = BB->getTerminator();
Pete Cooperebcd7482015-08-06 20:22:46 +0000375 for (const BasicBlock *Succ : TI->successors())
376 ToClone.push_back(Succ);
Chris Lattnercc340c02006-06-01 19:19:23 +0000377 }
378
Chris Lattner3df13f42006-05-27 01:22:24 +0000379 if (CodeInfo) {
380 CodeInfo->ContainsCalls |= hasCalls;
Chris Lattner3df13f42006-05-27 01:22:24 +0000381 CodeInfo->ContainsDynamicAllocas |= hasDynamicAllocas;
382 CodeInfo->ContainsDynamicAllocas |= hasStaticAllocas &&
383 BB != &BB->getParent()->front();
384 }
Chris Lattner3df13f42006-05-27 01:22:24 +0000385}
386
Sanjay Patelabf70232015-03-10 18:41:22 +0000387/// This works like CloneAndPruneFunctionInto, except that it does not clone the
388/// entire function. Instead it starts at an instruction provided by the caller
389/// and copies (and prunes) only the code reachable from that instruction.
Easwaran Ramanb1bd3982016-03-08 00:36:35 +0000390void llvm::CloneAndPruneIntoFromInst(Function *NewFunc, const Function *OldFunc,
391 const Instruction *StartingInst,
392 ValueToValueMapTy &VMap,
393 bool ModuleLevelChanges,
394 SmallVectorImpl<ReturnInst *> &Returns,
395 const char *NameSuffix,
396 ClonedCodeInfo *CodeInfo) {
Chris Lattner3df13f42006-05-27 01:22:24 +0000397 assert(NameSuffix && "NameSuffix cannot be null!");
Andrew Kaylor527c5dc2015-02-18 18:31:51 +0000398
Andrew Kaylorf22fe4a2015-02-23 20:01:56 +0000399 ValueMapTypeRemapper *TypeMapper = nullptr;
400 ValueMaterializer *Materializer = nullptr;
401
Chris Lattner3df13f42006-05-27 01:22:24 +0000402#ifndef NDEBUG
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000403 // If the cloning starts at the beginning of the function, verify that
Andrew Kaylor527c5dc2015-02-18 18:31:51 +0000404 // the function arguments are mapped.
405 if (!StartingInst)
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000406 for (const Argument &II : OldFunc->args())
407 assert(VMap.count(&II) && "No mapping from source argument specified!");
Chris Lattner3df13f42006-05-27 01:22:24 +0000408#endif
Duncan Sandsdd7daee2008-05-26 19:58:59 +0000409
Dan Gohmanca26f792010-08-26 15:41:53 +0000410 PruningFunctionCloner PFC(NewFunc, OldFunc, VMap, ModuleLevelChanges,
Easwaran Raman7f187292016-01-08 18:23:17 +0000411 NameSuffix, CodeInfo);
Andrew Kaylor527c5dc2015-02-18 18:31:51 +0000412 const BasicBlock *StartingBB;
413 if (StartingInst)
414 StartingBB = StartingInst->getParent();
415 else {
416 StartingBB = &OldFunc->getEntryBlock();
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000417 StartingInst = &StartingBB->front();
Andrew Kaylor527c5dc2015-02-18 18:31:51 +0000418 }
Chris Lattner3df13f42006-05-27 01:22:24 +0000419
Eric Christophera5ec9252014-05-19 16:04:10 +0000420 // Clone the entry block, and anything recursively reachable from it.
Chris Lattner4bd8cda2007-03-02 03:11:20 +0000421 std::vector<const BasicBlock*> CloneWorklist;
Easwaran Ramanb1bd3982016-03-08 00:36:35 +0000422 PFC.CloneBlock(StartingBB, StartingInst->getIterator(), CloneWorklist);
Chris Lattner4bd8cda2007-03-02 03:11:20 +0000423 while (!CloneWorklist.empty()) {
424 const BasicBlock *BB = CloneWorklist.back();
425 CloneWorklist.pop_back();
Easwaran Ramanb1bd3982016-03-08 00:36:35 +0000426 PFC.CloneBlock(BB, BB->begin(), CloneWorklist);
Chris Lattner4bd8cda2007-03-02 03:11:20 +0000427 }
Eric Christophera5ec9252014-05-19 16:04:10 +0000428
Chris Lattner3df13f42006-05-27 01:22:24 +0000429 // Loop over all of the basic blocks in the old function. If the block was
430 // reachable, we have cloned it and the old block is now in the value map:
431 // insert it into the new function in the right order. If not, ignore it.
432 //
Chris Lattnercc340c02006-06-01 19:19:23 +0000433 // Defer PHI resolution until rest of function is resolved.
Chris Lattnerd84dbb32009-08-27 04:02:30 +0000434 SmallVector<const PHINode*, 16> PHIToResolve;
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000435 for (const BasicBlock &BI : *OldFunc) {
Duncan P. N. Exon Smith3d555ac2016-04-17 18:53:24 +0000436 Value *V = VMap.lookup(&BI);
Rafael Espindolac2240ad2010-10-13 02:08:17 +0000437 BasicBlock *NewBB = cast_or_null<BasicBlock>(V);
Eric Christophera5ec9252014-05-19 16:04:10 +0000438 if (!NewBB) continue; // Dead block.
Chris Lattnercc340c02006-06-01 19:19:23 +0000439
Chris Lattner3df13f42006-05-27 01:22:24 +0000440 // Add the new block to the new function.
441 NewFunc->getBasicBlockList().push_back(NewBB);
Devang Patelf6eeaeb2009-11-10 23:06:00 +0000442
Chris Lattner3df13f42006-05-27 01:22:24 +0000443 // Handle PHI nodes specially, as we have to remove references to dead
444 // blocks.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000445 for (BasicBlock::const_iterator I = BI.begin(), E = BI.end(); I != E; ++I) {
Andrew Kaylor3170e562015-03-20 21:42:54 +0000446 // PHI nodes may have been remapped to non-PHI nodes by the caller or
447 // during the cloning process.
448 if (const PHINode *PN = dyn_cast<PHINode>(I)) {
449 if (isa<PHINode>(VMap[PN]))
450 PHIToResolve.push_back(PN);
451 else
452 break;
453 } else {
Chandler Carruth21211992012-03-25 04:03:40 +0000454 break;
Andrew Kaylor3170e562015-03-20 21:42:54 +0000455 }
456 }
Chandler Carruth21211992012-03-25 04:03:40 +0000457
458 // Finally, remap the terminator instructions, as those can't be remapped
459 // until all BBs are mapped.
460 RemapInstruction(NewBB->getTerminator(), VMap,
Andrew Kaylorf22fe4a2015-02-23 20:01:56 +0000461 ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges,
462 TypeMapper, Materializer);
Chris Lattner3df13f42006-05-27 01:22:24 +0000463 }
Chris Lattnercc340c02006-06-01 19:19:23 +0000464
465 // Defer PHI resolution until rest of function is resolved, PHI resolution
466 // requires the CFG to be up-to-date.
467 for (unsigned phino = 0, e = PHIToResolve.size(); phino != e; ) {
468 const PHINode *OPN = PHIToResolve[phino];
Chris Lattnercc340c02006-06-01 19:19:23 +0000469 unsigned NumPreds = OPN->getNumIncomingValues();
Chris Lattnercc340c02006-06-01 19:19:23 +0000470 const BasicBlock *OldBB = OPN->getParent();
Devang Patelb8f11de2010-06-23 23:55:51 +0000471 BasicBlock *NewBB = cast<BasicBlock>(VMap[OldBB]);
Chris Lattnercc340c02006-06-01 19:19:23 +0000472
473 // Map operands for blocks that are live and remove operands for blocks
474 // that are dead.
475 for (; phino != PHIToResolve.size() &&
476 PHIToResolve[phino]->getParent() == OldBB; ++phino) {
477 OPN = PHIToResolve[phino];
Devang Patelb8f11de2010-06-23 23:55:51 +0000478 PHINode *PN = cast<PHINode>(VMap[OPN]);
Chris Lattnercc340c02006-06-01 19:19:23 +0000479 for (unsigned pred = 0, e = NumPreds; pred != e; ++pred) {
Duncan P. N. Exon Smith724c5032016-04-17 20:11:09 +0000480 Value *V = VMap.lookup(PN->getIncomingBlock(pred));
Chris Lattner43f8d162011-01-08 08:15:20 +0000481 if (BasicBlock *MappedBlock = cast_or_null<BasicBlock>(V)) {
Owen Andersone70b6372009-07-05 22:41:43 +0000482 Value *InVal = MapValue(PN->getIncomingValue(pred),
Chris Lattner43f8d162011-01-08 08:15:20 +0000483 VMap,
484 ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges);
Chris Lattnercc340c02006-06-01 19:19:23 +0000485 assert(InVal && "Unknown input value?");
486 PN->setIncomingValue(pred, InVal);
487 PN->setIncomingBlock(pred, MappedBlock);
488 } else {
489 PN->removeIncomingValue(pred, false);
Richard Trieu7a083812016-02-18 22:09:30 +0000490 --pred; // Revisit the next entry.
491 --e;
Chris Lattnercc340c02006-06-01 19:19:23 +0000492 }
493 }
494 }
495
496 // The loop above has removed PHI entries for those blocks that are dead
497 // and has updated others. However, if a block is live (i.e. copied over)
498 // but its terminator has been changed to not go to this block, then our
499 // phi nodes will have invalid entries. Update the PHI nodes in this
500 // case.
501 PHINode *PN = cast<PHINode>(NewBB->begin());
502 NumPreds = std::distance(pred_begin(NewBB), pred_end(NewBB));
503 if (NumPreds != PN->getNumIncomingValues()) {
504 assert(NumPreds < PN->getNumIncomingValues());
505 // Count how many times each predecessor comes to this block.
506 std::map<BasicBlock*, unsigned> PredCount;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000507 for (pred_iterator PI = pred_begin(NewBB), E = pred_end(NewBB);
508 PI != E; ++PI)
509 --PredCount[*PI];
Chris Lattnercc340c02006-06-01 19:19:23 +0000510
511 // Figure out how many entries to remove from each PHI.
512 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
513 ++PredCount[PN->getIncomingBlock(i)];
514
515 // At this point, the excess predecessor entries are positive in the
516 // map. Loop over all of the PHIs and remove excess predecessor
517 // entries.
518 BasicBlock::iterator I = NewBB->begin();
519 for (; (PN = dyn_cast<PHINode>(I)); ++I) {
520 for (std::map<BasicBlock*, unsigned>::iterator PCI =PredCount.begin(),
521 E = PredCount.end(); PCI != E; ++PCI) {
522 BasicBlock *Pred = PCI->first;
523 for (unsigned NumToRemove = PCI->second; NumToRemove; --NumToRemove)
524 PN->removeIncomingValue(Pred, false);
525 }
526 }
527 }
528
529 // If the loops above have made these phi nodes have 0 or 1 operand,
530 // replace them with undef or the input value. We must do this for
531 // correctness, because 0-operand phis are not valid.
532 PN = cast<PHINode>(NewBB->begin());
533 if (PN->getNumIncomingValues() == 0) {
534 BasicBlock::iterator I = NewBB->begin();
535 BasicBlock::const_iterator OldI = OldBB->begin();
536 while ((PN = dyn_cast<PHINode>(I++))) {
Owen Andersonb292b8c2009-07-30 23:03:37 +0000537 Value *NV = UndefValue::get(PN->getType());
Chris Lattnercc340c02006-06-01 19:19:23 +0000538 PN->replaceAllUsesWith(NV);
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000539 assert(VMap[&*OldI] == PN && "VMap mismatch");
540 VMap[&*OldI] = NV;
Chris Lattnercc340c02006-06-01 19:19:23 +0000541 PN->eraseFromParent();
542 ++OldI;
543 }
Chris Lattnercc340c02006-06-01 19:19:23 +0000544 }
545 }
Chandler Carruthef82cf52012-03-25 10:34:54 +0000546
547 // Make a second pass over the PHINodes now that all of them have been
548 // remapped into the new function, simplifying the PHINode and performing any
549 // recursive simplifications exposed. This will transparently update the
Chandler Carruth772c88b2012-03-28 08:38:27 +0000550 // WeakVH in the VMap. Notably, we rely on that so that if we coalesce
Chandler Carruthef82cf52012-03-25 10:34:54 +0000551 // two PHINodes, the iteration over the old PHIs remains valid, and the
552 // mapping will just map us to the new node (which may not even be a PHI
553 // node).
554 for (unsigned Idx = 0, Size = PHIToResolve.size(); Idx != Size; ++Idx)
555 if (PHINode *PN = dyn_cast<PHINode>(VMap[PHIToResolve[Idx]]))
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000556 recursivelySimplifyInstruction(PN);
Chandler Carruthef82cf52012-03-25 10:34:54 +0000557
Chris Lattner237ccf22006-09-13 21:27:00 +0000558 // Now that the inlined function body has been fully constructed, go through
Sanjay Patel51bd9422015-03-10 18:37:05 +0000559 // and zap unconditional fall-through branches. This happens all the time when
Chris Lattner237ccf22006-09-13 21:27:00 +0000560 // specializing code: code specialization turns conditional branches into
561 // uncond branches, and this code folds them.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000562 Function::iterator Begin = cast<BasicBlock>(VMap[StartingBB])->getIterator();
Chandler Carruth772c88b2012-03-28 08:38:27 +0000563 Function::iterator I = Begin;
Chris Lattner237ccf22006-09-13 21:27:00 +0000564 while (I != NewFunc->end()) {
Chandler Carruth772c88b2012-03-28 08:38:27 +0000565 // Check if this block has become dead during inlining or other
566 // simplifications. Note that the first block will appear dead, as it has
567 // not yet been wired up properly.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000568 if (I != Begin && (pred_begin(&*I) == pred_end(&*I) ||
569 I->getSinglePredecessor() == &*I)) {
570 BasicBlock *DeadBB = &*I++;
Chandler Carruth772c88b2012-03-28 08:38:27 +0000571 DeleteDeadBlock(DeadBB);
572 continue;
573 }
574
575 // We need to simplify conditional branches and switches with a constant
576 // operand. We try to prune these out when cloning, but if the
577 // simplification required looking through PHI nodes, those are only
578 // available after forming the full basic block. That may leave some here,
579 // and we still want to prune the dead code as early as possible.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000580 ConstantFoldTerminator(&*I);
Chandler Carruth772c88b2012-03-28 08:38:27 +0000581
Chris Lattner237ccf22006-09-13 21:27:00 +0000582 BranchInst *BI = dyn_cast<BranchInst>(I->getTerminator());
583 if (!BI || BI->isConditional()) { ++I; continue; }
584
585 BasicBlock *Dest = BI->getSuccessor(0);
Chandler Carruthef82cf52012-03-25 10:34:54 +0000586 if (!Dest->getSinglePredecessor()) {
Chris Lattnerce494222007-02-01 18:48:38 +0000587 ++I; continue;
588 }
Chandler Carruthef82cf52012-03-25 10:34:54 +0000589
590 // We shouldn't be able to get single-entry PHI nodes here, as instsimplify
591 // above should have zapped all of them..
592 assert(!isa<PHINode>(Dest->begin()));
593
Chris Lattner237ccf22006-09-13 21:27:00 +0000594 // We know all single-entry PHI nodes in the inlined function have been
595 // removed, so we just need to splice the blocks.
596 BI->eraseFromParent();
597
Eric Christopher96513122011-06-23 06:24:52 +0000598 // 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 +0000599 Dest->replaceAllUsesWith(&*I);
Eric Christopher96513122011-06-23 06:24:52 +0000600
Jay Foad61ea0e42011-06-23 09:09:15 +0000601 // Move all the instructions in the succ to the pred.
602 I->getInstList().splice(I->end(), Dest->getInstList());
603
Chris Lattner237ccf22006-09-13 21:27:00 +0000604 // Remove the dest block.
605 Dest->eraseFromParent();
606
607 // Do not increment I, iteratively merge all things this block branches to.
608 }
Chandler Carruth49da9332012-04-06 17:21:31 +0000609
Sanjay Patel51bd9422015-03-10 18:37:05 +0000610 // Make a final pass over the basic blocks from the old function to gather
Chandler Carruth49da9332012-04-06 17:21:31 +0000611 // any return instructions which survived folding. We have to do this here
612 // because we can iteratively remove and merge returns above.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000613 for (Function::iterator I = cast<BasicBlock>(VMap[StartingBB])->getIterator(),
Chandler Carruth49da9332012-04-06 17:21:31 +0000614 E = NewFunc->end();
615 I != E; ++I)
616 if (ReturnInst *RI = dyn_cast<ReturnInst>(I->getTerminator()))
617 Returns.push_back(RI);
Chris Lattner3df13f42006-05-27 01:22:24 +0000618}
Andrew Kaylor527c5dc2015-02-18 18:31:51 +0000619
620
Sanjay Patelabf70232015-03-10 18:41:22 +0000621/// This works exactly like CloneFunctionInto,
Andrew Kaylor527c5dc2015-02-18 18:31:51 +0000622/// except that it does some simple constant prop and DCE on the fly. The
623/// effect of this is to copy significantly less code in cases where (for
624/// example) a function call with constant arguments is inlined, and those
625/// constant arguments cause a significant amount of code in the callee to be
626/// dead. Since this doesn't produce an exact copy of the input, it can't be
627/// used for things like CloneFunction or CloneModule.
Easwaran Ramanb1bd3982016-03-08 00:36:35 +0000628void llvm::CloneAndPruneFunctionInto(Function *NewFunc, const Function *OldFunc,
629 ValueToValueMapTy &VMap,
630 bool ModuleLevelChanges,
631 SmallVectorImpl<ReturnInst*> &Returns,
632 const char *NameSuffix,
633 ClonedCodeInfo *CodeInfo,
634 Instruction *TheCall) {
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000635 CloneAndPruneIntoFromInst(NewFunc, OldFunc, &OldFunc->front().front(), VMap,
Easwaran Ramanb1bd3982016-03-08 00:36:35 +0000636 ModuleLevelChanges, Returns, NameSuffix, CodeInfo);
Andrew Kaylor527c5dc2015-02-18 18:31:51 +0000637}
Adam Nemet1a689182015-07-10 18:55:09 +0000638
639/// \brief Remaps instructions in \p Blocks using the mapping in \p VMap.
640void llvm::remapInstructionsInBlocks(
641 const SmallVectorImpl<BasicBlock *> &Blocks, ValueToValueMapTy &VMap) {
642 // Rewrite the code to refer to itself.
643 for (auto *BB : Blocks)
644 for (auto &Inst : *BB)
645 RemapInstruction(&Inst, VMap,
Duncan P. N. Exon Smithda68cbc2016-04-07 00:26:43 +0000646 RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
Adam Nemet1a689182015-07-10 18:55:09 +0000647}
648
649/// \brief Clones a loop \p OrigLoop. Returns the loop and the blocks in \p
650/// Blocks.
651///
652/// Updates LoopInfo and DominatorTree assuming the loop is dominated by block
653/// \p LoopDomBB. Insert the new blocks before block specified in \p Before.
654Loop *llvm::cloneLoopWithPreheader(BasicBlock *Before, BasicBlock *LoopDomBB,
655 Loop *OrigLoop, ValueToValueMapTy &VMap,
656 const Twine &NameSuffix, LoopInfo *LI,
657 DominatorTree *DT,
658 SmallVectorImpl<BasicBlock *> &Blocks) {
Vaivaswatha Nagaraj08efb0e2016-04-27 05:25:09 +0000659 assert(OrigLoop->getSubLoops().empty() &&
660 "Loop to be cloned cannot have inner loop");
Adam Nemet1a689182015-07-10 18:55:09 +0000661 Function *F = OrigLoop->getHeader()->getParent();
662 Loop *ParentLoop = OrigLoop->getParentLoop();
663
664 Loop *NewLoop = new Loop();
665 if (ParentLoop)
666 ParentLoop->addChildLoop(NewLoop);
667 else
668 LI->addTopLevelLoop(NewLoop);
669
670 BasicBlock *OrigPH = OrigLoop->getLoopPreheader();
671 assert(OrigPH && "No preheader");
672 BasicBlock *NewPH = CloneBasicBlock(OrigPH, VMap, NameSuffix, F);
673 // To rename the loop PHIs.
674 VMap[OrigPH] = NewPH;
675 Blocks.push_back(NewPH);
676
677 // Update LoopInfo.
678 if (ParentLoop)
679 ParentLoop->addBasicBlockToLoop(NewPH, *LI);
680
681 // Update DominatorTree.
682 DT->addNewBlock(NewPH, LoopDomBB);
683
684 for (BasicBlock *BB : OrigLoop->getBlocks()) {
685 BasicBlock *NewBB = CloneBasicBlock(BB, VMap, NameSuffix, F);
686 VMap[BB] = NewBB;
687
688 // Update LoopInfo.
689 NewLoop->addBasicBlockToLoop(NewBB, *LI);
690
Vikram TVc702b8b2016-06-11 16:41:10 +0000691 // Add DominatorTree node. After seeing all blocks, update to correct IDom.
692 DT->addNewBlock(NewBB, NewPH);
Adam Nemet1a689182015-07-10 18:55:09 +0000693
694 Blocks.push_back(NewBB);
695 }
696
Vikram TVc702b8b2016-06-11 16:41:10 +0000697 for (BasicBlock *BB : OrigLoop->getBlocks()) {
698 // Update DominatorTree.
699 BasicBlock *IDomBB = DT->getNode(BB)->getIDom()->getBlock();
700 DT->changeImmediateDominator(cast<BasicBlock>(VMap[BB]),
701 cast<BasicBlock>(VMap[IDomBB]));
702 }
703
Adam Nemet1a689182015-07-10 18:55:09 +0000704 // Move them physically from the end of the block list.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000705 F->getBasicBlockList().splice(Before->getIterator(), F->getBasicBlockList(),
706 NewPH);
707 F->getBasicBlockList().splice(Before->getIterator(), F->getBasicBlockList(),
708 NewLoop->getHeader()->getIterator(), F->end());
Adam Nemet1a689182015-07-10 18:55:09 +0000709
710 return NewLoop;
711}