1 //===- CloneFunction.cpp - Clone a function into another function ---------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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 //===----------------------------------------------------------------------===//
15 
16 #include "llvm/Transforms/Utils/Cloning.h"
17 #include "llvm/ADT/SetVector.h"
18 #include "llvm/ADT/SmallVector.h"
19 #include "llvm/Analysis/ConstantFolding.h"
20 #include "llvm/Analysis/InstructionSimplify.h"
21 #include "llvm/Analysis/LoopInfo.h"
22 #include "llvm/IR/CFG.h"
23 #include "llvm/IR/Constants.h"
24 #include "llvm/IR/DebugInfo.h"
25 #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"
32 #include "llvm/IR/Module.h"
33 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
34 #include "llvm/Transforms/Utils/Local.h"
35 #include "llvm/Transforms/Utils/ValueMapper.h"
36 #include <map>
37 using namespace llvm;
38 
39 /// See comments in Cloning.h.
40 BasicBlock *llvm::CloneBasicBlock(const BasicBlock *BB,
41                                   ValueToValueMapTy &VMap,
42                                   const Twine &NameSuffix, Function *F,
43                                   ClonedCodeInfo *CodeInfo) {
44   BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), "", F);
45   if (BB->hasName()) NewBB->setName(BB->getName()+NameSuffix);
46 
47   bool hasCalls = false, hasDynamicAllocas = false, hasStaticAllocas = false;
48 
49   // Loop over all instructions, and copy them over.
50   for (BasicBlock::const_iterator II = BB->begin(), IE = BB->end();
51        II != IE; ++II) {
52     Instruction *NewInst = II->clone();
53     if (II->hasName())
54       NewInst->setName(II->getName()+NameSuffix);
55     NewBB->getInstList().push_back(NewInst);
56     VMap[&*II] = NewInst; // Add instruction map to value.
57 
58     hasCalls |= (isa<CallInst>(II) && !isa<DbgInfoIntrinsic>(II));
59     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;
69     CodeInfo->ContainsDynamicAllocas |= hasDynamicAllocas;
70     CodeInfo->ContainsDynamicAllocas |= hasStaticAllocas &&
71                                         BB != &BB->getParent()->getEntryBlock();
72   }
73   return NewBB;
74 }
75 
76 // Clone OldFunc into NewFunc, transforming the old arguments into references to
77 // VMap values.
78 //
79 void llvm::CloneFunctionInto(Function *NewFunc, const Function *OldFunc,
80                              ValueToValueMapTy &VMap,
81                              bool ModuleLevelChanges,
82                              SmallVectorImpl<ReturnInst*> &Returns,
83                              const char *NameSuffix, ClonedCodeInfo *CodeInfo,
84                              ValueMapTypeRemapper *TypeMapper,
85                              ValueMaterializer *Materializer) {
86   assert(NameSuffix && "NameSuffix cannot be null!");
87 
88 #ifndef NDEBUG
89   for (const Argument &I : OldFunc->args())
90     assert(VMap.count(&I) && "No mapping from source argument specified!");
91 #endif
92 
93   // Copy all attributes other than those stored in the AttributeList.  We need
94   // to remap the parameter indices of the AttributeList.
95   AttributeList NewAttrs = NewFunc->getAttributes();
96   NewFunc->copyAttributesFrom(OldFunc);
97   NewFunc->setAttributes(NewAttrs);
98 
99   // 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 
106   SmallVector<AttributeSet, 4> AttrVec(NewFunc->arg_size() + 2);
107   AttributeList OldAttrs = OldFunc->getAttributes();
108 
109   // Copy the return attributes.
110   AttrVec[0] = OldAttrs.getRetAttributes();
111 
112   // Clone any argument attributes that are present in the VMap.
113   for (const Argument &OldArg : OldFunc->args())
114     if (Argument *NewArg = dyn_cast<Argument>(VMap[&OldArg])) {
115       AttrVec[NewArg->getArgNo() + 1] =
116           OldAttrs.getParamAttributes(OldArg.getArgNo() + 1);
117     }
118 
119   // Copy any function attributes.
120   AttrVec.back() = OldAttrs.getFnAttributes();
121 
122   NewFunc->setAttributes(AttributeList::get(NewFunc->getContext(), AttrVec));
123 
124   SmallVector<std::pair<unsigned, MDNode *>, 1> MDs;
125   OldFunc->getAllMetadata(MDs);
126   for (auto MD : MDs)
127     NewFunc->addMetadata(
128         MD.first,
129         *MapMetadata(MD.second, VMap,
130                      ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges,
131                      TypeMapper, Materializer));
132 
133   // Loop over all of the basic blocks in the function, cloning them as
134   // appropriate.  Note that we save BE this way in order to handle cloning of
135   // recursive functions into themselves.
136   //
137   for (Function::const_iterator BI = OldFunc->begin(), BE = OldFunc->end();
138        BI != BE; ++BI) {
139     const BasicBlock &BB = *BI;
140 
141     // Create a new basic block and copy instructions into it!
142     BasicBlock *CBB = CloneBasicBlock(&BB, VMap, NameSuffix, NewFunc, CodeInfo);
143 
144     // Add basic block mapping.
145     VMap[&BB] = CBB;
146 
147     // It is only legal to clone a function if a block address within that
148     // function is never referenced outside of the function.  Given that, we
149     // want to map block addresses from the old function to block addresses in
150     // the clone. (This is different from the generic ValueMapper
151     // implementation, which generates an invalid blockaddress when
152     // cloning a function.)
153     if (BB.hasAddressTaken()) {
154       Constant *OldBBAddr = BlockAddress::get(const_cast<Function*>(OldFunc),
155                                               const_cast<BasicBlock*>(&BB));
156       VMap[OldBBAddr] = BlockAddress::get(NewFunc, CBB);
157     }
158 
159     // Note return instructions for the caller.
160     if (ReturnInst *RI = dyn_cast<ReturnInst>(CBB->getTerminator()))
161       Returns.push_back(RI);
162   }
163 
164   // Loop over all of the instructions in the function, fixing up operand
165   // references as we go.  This uses VMap to do all the hard work.
166   for (Function::iterator BB =
167            cast<BasicBlock>(VMap[&OldFunc->front()])->getIterator(),
168                           BE = NewFunc->end();
169        BB != BE; ++BB)
170     // Loop over all instructions, fixing each one as we find it...
171     for (Instruction &II : *BB)
172       RemapInstruction(&II, VMap,
173                        ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges,
174                        TypeMapper, Materializer);
175 }
176 
177 /// Return a copy of the specified function and add it to that function's
178 /// module.  Also, any references specified in the VMap are changed to refer to
179 /// their mapped value instead of the original one.  If any of the arguments to
180 /// the function are in the VMap, the arguments are deleted from the resultant
181 /// function.  The VMap is updated to include mappings from all of the
182 /// instructions and basicblocks in the function from their old to new values.
183 ///
184 Function *llvm::CloneFunction(Function *F, ValueToValueMapTy &VMap,
185                               ClonedCodeInfo *CodeInfo) {
186   std::vector<Type*> ArgTypes;
187 
188   // The user might be deleting arguments to the function by specifying them in
189   // the VMap.  If so, we need to not add the arguments to the arg ty vector
190   //
191   for (const Argument &I : F->args())
192     if (VMap.count(&I) == 0) // Haven't mapped the argument to anything yet?
193       ArgTypes.push_back(I.getType());
194 
195   // Create a new function type...
196   FunctionType *FTy = FunctionType::get(F->getFunctionType()->getReturnType(),
197                                     ArgTypes, F->getFunctionType()->isVarArg());
198 
199   // Create the new function...
200   Function *NewF =
201       Function::Create(FTy, F->getLinkage(), F->getName(), F->getParent());
202 
203   // Loop over the arguments, copying the names of the mapped arguments over...
204   Function::arg_iterator DestI = NewF->arg_begin();
205   for (const Argument & I : F->args())
206     if (VMap.count(&I) == 0) {     // Is this argument preserved?
207       DestI->setName(I.getName()); // Copy the name over...
208       VMap[&I] = &*DestI++;        // Add mapping to VMap
209     }
210 
211   SmallVector<ReturnInst*, 8> Returns;  // Ignore returns cloned.
212   CloneFunctionInto(NewF, F, VMap, /*ModuleLevelChanges=*/false, Returns, "",
213                     CodeInfo);
214 
215   return NewF;
216 }
217 
218 
219 
220 namespace {
221   /// This is a private class used to implement CloneAndPruneFunctionInto.
222   struct PruningFunctionCloner {
223     Function *NewFunc;
224     const Function *OldFunc;
225     ValueToValueMapTy &VMap;
226     bool ModuleLevelChanges;
227     const char *NameSuffix;
228     ClonedCodeInfo *CodeInfo;
229 
230   public:
231     PruningFunctionCloner(Function *newFunc, const Function *oldFunc,
232                           ValueToValueMapTy &valueMap, bool moduleLevelChanges,
233                           const char *nameSuffix, ClonedCodeInfo *codeInfo)
234         : NewFunc(newFunc), OldFunc(oldFunc), VMap(valueMap),
235           ModuleLevelChanges(moduleLevelChanges), NameSuffix(nameSuffix),
236           CodeInfo(codeInfo) {}
237 
238     /// The specified block is found to be reachable, clone it and
239     /// anything that it can reach.
240     void CloneBlock(const BasicBlock *BB,
241                     BasicBlock::const_iterator StartingInst,
242                     std::vector<const BasicBlock*> &ToClone);
243   };
244 }
245 
246 /// The specified block is found to be reachable, clone it and
247 /// anything that it can reach.
248 void PruningFunctionCloner::CloneBlock(const BasicBlock *BB,
249                                        BasicBlock::const_iterator StartingInst,
250                                        std::vector<const BasicBlock*> &ToClone){
251   WeakVH &BBEntry = VMap[BB];
252 
253   // Have we already cloned this block?
254   if (BBEntry) return;
255 
256   // Nope, clone it now.
257   BasicBlock *NewBB;
258   BBEntry = NewBB = BasicBlock::Create(BB->getContext());
259   if (BB->hasName()) NewBB->setName(BB->getName()+NameSuffix);
260 
261   // It is only legal to clone a function if a block address within that
262   // function is never referenced outside of the function.  Given that, we
263   // want to map block addresses from the old function to block addresses in
264   // the clone. (This is different from the generic ValueMapper
265   // implementation, which generates an invalid blockaddress when
266   // cloning a function.)
267   //
268   // Note that we don't need to fix the mapping for unreachable blocks;
269   // the default mapping there is safe.
270   if (BB->hasAddressTaken()) {
271     Constant *OldBBAddr = BlockAddress::get(const_cast<Function*>(OldFunc),
272                                             const_cast<BasicBlock*>(BB));
273     VMap[OldBBAddr] = BlockAddress::get(NewFunc, NewBB);
274   }
275 
276   bool hasCalls = false, hasDynamicAllocas = false, hasStaticAllocas = false;
277 
278   // Loop over all instructions, and copy them over, DCE'ing as we go.  This
279   // loop doesn't include the terminator.
280   for (BasicBlock::const_iterator II = StartingInst, IE = --BB->end();
281        II != IE; ++II) {
282 
283     Instruction *NewInst = II->clone();
284 
285     // Eagerly remap operands to the newly cloned instruction, except for PHI
286     // nodes for which we defer processing until we update the CFG.
287     if (!isa<PHINode>(NewInst)) {
288       RemapInstruction(NewInst, VMap,
289                        ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges);
290 
291       // If we can simplify this instruction to some other value, simply add
292       // a mapping to that value rather than inserting a new instruction into
293       // the basic block.
294       if (Value *V =
295               SimplifyInstruction(NewInst, BB->getModule()->getDataLayout())) {
296         // On the off-chance that this simplifies to an instruction in the old
297         // function, map it back into the new function.
298         if (Value *MappedV = VMap.lookup(V))
299           V = MappedV;
300 
301         if (!NewInst->mayHaveSideEffects()) {
302           VMap[&*II] = V;
303           delete NewInst;
304           continue;
305         }
306       }
307     }
308 
309     if (II->hasName())
310       NewInst->setName(II->getName()+NameSuffix);
311     VMap[&*II] = NewInst; // Add instruction map to value.
312     NewBB->getInstList().push_back(NewInst);
313     hasCalls |= (isa<CallInst>(II) && !isa<DbgInfoIntrinsic>(II));
314 
315     if (CodeInfo)
316       if (auto CS = ImmutableCallSite(&*II))
317         if (CS.hasOperandBundles())
318           CodeInfo->OperandBundleCallSites.push_back(NewInst);
319 
320     if (const AllocaInst *AI = dyn_cast<AllocaInst>(II)) {
321       if (isa<ConstantInt>(AI->getArraySize()))
322         hasStaticAllocas = true;
323       else
324         hasDynamicAllocas = true;
325     }
326   }
327 
328   // Finally, clone over the terminator.
329   const TerminatorInst *OldTI = BB->getTerminator();
330   bool TerminatorDone = false;
331   if (const BranchInst *BI = dyn_cast<BranchInst>(OldTI)) {
332     if (BI->isConditional()) {
333       // If the condition was a known constant in the callee...
334       ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition());
335       // Or is a known constant in the caller...
336       if (!Cond) {
337         Value *V = VMap.lookup(BI->getCondition());
338         Cond = dyn_cast_or_null<ConstantInt>(V);
339       }
340 
341       // Constant fold to uncond branch!
342       if (Cond) {
343         BasicBlock *Dest = BI->getSuccessor(!Cond->getZExtValue());
344         VMap[OldTI] = BranchInst::Create(Dest, NewBB);
345         ToClone.push_back(Dest);
346         TerminatorDone = true;
347       }
348     }
349   } else if (const SwitchInst *SI = dyn_cast<SwitchInst>(OldTI)) {
350     // If switching on a value known constant in the caller.
351     ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition());
352     if (!Cond) { // Or known constant after constant prop in the callee...
353       Value *V = VMap.lookup(SI->getCondition());
354       Cond = dyn_cast_or_null<ConstantInt>(V);
355     }
356     if (Cond) {     // Constant fold to uncond branch!
357       SwitchInst::ConstCaseHandle Case = *SI->findCaseValue(Cond);
358       BasicBlock *Dest = const_cast<BasicBlock*>(Case.getCaseSuccessor());
359       VMap[OldTI] = BranchInst::Create(Dest, NewBB);
360       ToClone.push_back(Dest);
361       TerminatorDone = true;
362     }
363   }
364 
365   if (!TerminatorDone) {
366     Instruction *NewInst = OldTI->clone();
367     if (OldTI->hasName())
368       NewInst->setName(OldTI->getName()+NameSuffix);
369     NewBB->getInstList().push_back(NewInst);
370     VMap[OldTI] = NewInst;             // Add instruction map to value.
371 
372     if (CodeInfo)
373       if (auto CS = ImmutableCallSite(OldTI))
374         if (CS.hasOperandBundles())
375           CodeInfo->OperandBundleCallSites.push_back(NewInst);
376 
377     // Recursively clone any reachable successor blocks.
378     const TerminatorInst *TI = BB->getTerminator();
379     for (const BasicBlock *Succ : TI->successors())
380       ToClone.push_back(Succ);
381   }
382 
383   if (CodeInfo) {
384     CodeInfo->ContainsCalls          |= hasCalls;
385     CodeInfo->ContainsDynamicAllocas |= hasDynamicAllocas;
386     CodeInfo->ContainsDynamicAllocas |= hasStaticAllocas &&
387       BB != &BB->getParent()->front();
388   }
389 }
390 
391 /// This works like CloneAndPruneFunctionInto, except that it does not clone the
392 /// entire function. Instead it starts at an instruction provided by the caller
393 /// and copies (and prunes) only the code reachable from that instruction.
394 void llvm::CloneAndPruneIntoFromInst(Function *NewFunc, const Function *OldFunc,
395                                      const Instruction *StartingInst,
396                                      ValueToValueMapTy &VMap,
397                                      bool ModuleLevelChanges,
398                                      SmallVectorImpl<ReturnInst *> &Returns,
399                                      const char *NameSuffix,
400                                      ClonedCodeInfo *CodeInfo) {
401   assert(NameSuffix && "NameSuffix cannot be null!");
402 
403   ValueMapTypeRemapper *TypeMapper = nullptr;
404   ValueMaterializer *Materializer = nullptr;
405 
406 #ifndef NDEBUG
407   // If the cloning starts at the beginning of the function, verify that
408   // the function arguments are mapped.
409   if (!StartingInst)
410     for (const Argument &II : OldFunc->args())
411       assert(VMap.count(&II) && "No mapping from source argument specified!");
412 #endif
413 
414   PruningFunctionCloner PFC(NewFunc, OldFunc, VMap, ModuleLevelChanges,
415                             NameSuffix, CodeInfo);
416   const BasicBlock *StartingBB;
417   if (StartingInst)
418     StartingBB = StartingInst->getParent();
419   else {
420     StartingBB = &OldFunc->getEntryBlock();
421     StartingInst = &StartingBB->front();
422   }
423 
424   // Clone the entry block, and anything recursively reachable from it.
425   std::vector<const BasicBlock*> CloneWorklist;
426   PFC.CloneBlock(StartingBB, StartingInst->getIterator(), CloneWorklist);
427   while (!CloneWorklist.empty()) {
428     const BasicBlock *BB = CloneWorklist.back();
429     CloneWorklist.pop_back();
430     PFC.CloneBlock(BB, BB->begin(), CloneWorklist);
431   }
432 
433   // Loop over all of the basic blocks in the old function.  If the block was
434   // reachable, we have cloned it and the old block is now in the value map:
435   // insert it into the new function in the right order.  If not, ignore it.
436   //
437   // Defer PHI resolution until rest of function is resolved.
438   SmallVector<const PHINode*, 16> PHIToResolve;
439   for (const BasicBlock &BI : *OldFunc) {
440     Value *V = VMap.lookup(&BI);
441     BasicBlock *NewBB = cast_or_null<BasicBlock>(V);
442     if (!NewBB) continue;  // Dead block.
443 
444     // Add the new block to the new function.
445     NewFunc->getBasicBlockList().push_back(NewBB);
446 
447     // Handle PHI nodes specially, as we have to remove references to dead
448     // blocks.
449     for (BasicBlock::const_iterator I = BI.begin(), E = BI.end(); I != E; ++I) {
450       // PHI nodes may have been remapped to non-PHI nodes by the caller or
451       // during the cloning process.
452       if (const PHINode *PN = dyn_cast<PHINode>(I)) {
453         if (isa<PHINode>(VMap[PN]))
454           PHIToResolve.push_back(PN);
455         else
456           break;
457       } else {
458         break;
459       }
460     }
461 
462     // Finally, remap the terminator instructions, as those can't be remapped
463     // until all BBs are mapped.
464     RemapInstruction(NewBB->getTerminator(), VMap,
465                      ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges,
466                      TypeMapper, Materializer);
467   }
468 
469   // Defer PHI resolution until rest of function is resolved, PHI resolution
470   // requires the CFG to be up-to-date.
471   for (unsigned phino = 0, e = PHIToResolve.size(); phino != e; ) {
472     const PHINode *OPN = PHIToResolve[phino];
473     unsigned NumPreds = OPN->getNumIncomingValues();
474     const BasicBlock *OldBB = OPN->getParent();
475     BasicBlock *NewBB = cast<BasicBlock>(VMap[OldBB]);
476 
477     // Map operands for blocks that are live and remove operands for blocks
478     // that are dead.
479     for (; phino != PHIToResolve.size() &&
480          PHIToResolve[phino]->getParent() == OldBB; ++phino) {
481       OPN = PHIToResolve[phino];
482       PHINode *PN = cast<PHINode>(VMap[OPN]);
483       for (unsigned pred = 0, e = NumPreds; pred != e; ++pred) {
484         Value *V = VMap.lookup(PN->getIncomingBlock(pred));
485         if (BasicBlock *MappedBlock = cast_or_null<BasicBlock>(V)) {
486           Value *InVal = MapValue(PN->getIncomingValue(pred),
487                                   VMap,
488                         ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges);
489           assert(InVal && "Unknown input value?");
490           PN->setIncomingValue(pred, InVal);
491           PN->setIncomingBlock(pred, MappedBlock);
492         } else {
493           PN->removeIncomingValue(pred, false);
494           --pred;  // Revisit the next entry.
495           --e;
496         }
497       }
498     }
499 
500     // The loop above has removed PHI entries for those blocks that are dead
501     // and has updated others.  However, if a block is live (i.e. copied over)
502     // but its terminator has been changed to not go to this block, then our
503     // phi nodes will have invalid entries.  Update the PHI nodes in this
504     // case.
505     PHINode *PN = cast<PHINode>(NewBB->begin());
506     NumPreds = std::distance(pred_begin(NewBB), pred_end(NewBB));
507     if (NumPreds != PN->getNumIncomingValues()) {
508       assert(NumPreds < PN->getNumIncomingValues());
509       // Count how many times each predecessor comes to this block.
510       std::map<BasicBlock*, unsigned> PredCount;
511       for (pred_iterator PI = pred_begin(NewBB), E = pred_end(NewBB);
512            PI != E; ++PI)
513         --PredCount[*PI];
514 
515       // Figure out how many entries to remove from each PHI.
516       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
517         ++PredCount[PN->getIncomingBlock(i)];
518 
519       // At this point, the excess predecessor entries are positive in the
520       // map.  Loop over all of the PHIs and remove excess predecessor
521       // entries.
522       BasicBlock::iterator I = NewBB->begin();
523       for (; (PN = dyn_cast<PHINode>(I)); ++I) {
524         for (const auto &PCI : PredCount) {
525           BasicBlock *Pred = PCI.first;
526           for (unsigned NumToRemove = PCI.second; NumToRemove; --NumToRemove)
527             PN->removeIncomingValue(Pred, false);
528         }
529       }
530     }
531 
532     // If the loops above have made these phi nodes have 0 or 1 operand,
533     // replace them with undef or the input value.  We must do this for
534     // correctness, because 0-operand phis are not valid.
535     PN = cast<PHINode>(NewBB->begin());
536     if (PN->getNumIncomingValues() == 0) {
537       BasicBlock::iterator I = NewBB->begin();
538       BasicBlock::const_iterator OldI = OldBB->begin();
539       while ((PN = dyn_cast<PHINode>(I++))) {
540         Value *NV = UndefValue::get(PN->getType());
541         PN->replaceAllUsesWith(NV);
542         assert(VMap[&*OldI] == PN && "VMap mismatch");
543         VMap[&*OldI] = NV;
544         PN->eraseFromParent();
545         ++OldI;
546       }
547     }
548   }
549 
550   // Make a second pass over the PHINodes now that all of them have been
551   // remapped into the new function, simplifying the PHINode and performing any
552   // recursive simplifications exposed. This will transparently update the
553   // WeakVH in the VMap. Notably, we rely on that so that if we coalesce
554   // two PHINodes, the iteration over the old PHIs remains valid, and the
555   // mapping will just map us to the new node (which may not even be a PHI
556   // node).
557   const DataLayout &DL = NewFunc->getParent()->getDataLayout();
558   SmallSetVector<const Value *, 8> Worklist;
559   for (unsigned Idx = 0, Size = PHIToResolve.size(); Idx != Size; ++Idx)
560     if (isa<PHINode>(VMap[PHIToResolve[Idx]]))
561       Worklist.insert(PHIToResolve[Idx]);
562 
563   // Note that we must test the size on each iteration, the worklist can grow.
564   for (unsigned Idx = 0; Idx != Worklist.size(); ++Idx) {
565     const Value *OrigV = Worklist[Idx];
566     auto *I = dyn_cast_or_null<Instruction>(VMap.lookup(OrigV));
567     if (!I)
568       continue;
569 
570     // Skip over non-intrinsic callsites, we don't want to remove any nodes from
571     // the CGSCC.
572     CallSite CS = CallSite(I);
573     if (CS && CS.getCalledFunction() && !CS.getCalledFunction()->isIntrinsic())
574       continue;
575 
576     // See if this instruction simplifies.
577     Value *SimpleV = SimplifyInstruction(I, DL);
578     if (!SimpleV)
579       continue;
580 
581     // Stash away all the uses of the old instruction so we can check them for
582     // recursive simplifications after a RAUW. This is cheaper than checking all
583     // uses of To on the recursive step in most cases.
584     for (const User *U : OrigV->users())
585       Worklist.insert(cast<Instruction>(U));
586 
587     // Replace the instruction with its simplified value.
588     I->replaceAllUsesWith(SimpleV);
589 
590     // If the original instruction had no side effects, remove it.
591     if (isInstructionTriviallyDead(I))
592       I->eraseFromParent();
593     else
594       VMap[OrigV] = I;
595   }
596 
597   // Now that the inlined function body has been fully constructed, go through
598   // and zap unconditional fall-through branches. This happens all the time when
599   // specializing code: code specialization turns conditional branches into
600   // uncond branches, and this code folds them.
601   Function::iterator Begin = cast<BasicBlock>(VMap[StartingBB])->getIterator();
602   Function::iterator I = Begin;
603   while (I != NewFunc->end()) {
604     // Check if this block has become dead during inlining or other
605     // simplifications. Note that the first block will appear dead, as it has
606     // not yet been wired up properly.
607     if (I != Begin && (pred_begin(&*I) == pred_end(&*I) ||
608                        I->getSinglePredecessor() == &*I)) {
609       BasicBlock *DeadBB = &*I++;
610       DeleteDeadBlock(DeadBB);
611       continue;
612     }
613 
614     // We need to simplify conditional branches and switches with a constant
615     // operand. We try to prune these out when cloning, but if the
616     // simplification required looking through PHI nodes, those are only
617     // available after forming the full basic block. That may leave some here,
618     // and we still want to prune the dead code as early as possible.
619     ConstantFoldTerminator(&*I);
620 
621     BranchInst *BI = dyn_cast<BranchInst>(I->getTerminator());
622     if (!BI || BI->isConditional()) { ++I; continue; }
623 
624     BasicBlock *Dest = BI->getSuccessor(0);
625     if (!Dest->getSinglePredecessor()) {
626       ++I; continue;
627     }
628 
629     // We shouldn't be able to get single-entry PHI nodes here, as instsimplify
630     // above should have zapped all of them..
631     assert(!isa<PHINode>(Dest->begin()));
632 
633     // We know all single-entry PHI nodes in the inlined function have been
634     // removed, so we just need to splice the blocks.
635     BI->eraseFromParent();
636 
637     // Make all PHI nodes that referred to Dest now refer to I as their source.
638     Dest->replaceAllUsesWith(&*I);
639 
640     // Move all the instructions in the succ to the pred.
641     I->getInstList().splice(I->end(), Dest->getInstList());
642 
643     // Remove the dest block.
644     Dest->eraseFromParent();
645 
646     // Do not increment I, iteratively merge all things this block branches to.
647   }
648 
649   // Make a final pass over the basic blocks from the old function to gather
650   // any return instructions which survived folding. We have to do this here
651   // because we can iteratively remove and merge returns above.
652   for (Function::iterator I = cast<BasicBlock>(VMap[StartingBB])->getIterator(),
653                           E = NewFunc->end();
654        I != E; ++I)
655     if (ReturnInst *RI = dyn_cast<ReturnInst>(I->getTerminator()))
656       Returns.push_back(RI);
657 }
658 
659 
660 /// This works exactly like CloneFunctionInto,
661 /// except that it does some simple constant prop and DCE on the fly.  The
662 /// effect of this is to copy significantly less code in cases where (for
663 /// example) a function call with constant arguments is inlined, and those
664 /// constant arguments cause a significant amount of code in the callee to be
665 /// dead.  Since this doesn't produce an exact copy of the input, it can't be
666 /// used for things like CloneFunction or CloneModule.
667 void llvm::CloneAndPruneFunctionInto(Function *NewFunc, const Function *OldFunc,
668                                      ValueToValueMapTy &VMap,
669                                      bool ModuleLevelChanges,
670                                      SmallVectorImpl<ReturnInst*> &Returns,
671                                      const char *NameSuffix,
672                                      ClonedCodeInfo *CodeInfo,
673                                      Instruction *TheCall) {
674   CloneAndPruneIntoFromInst(NewFunc, OldFunc, &OldFunc->front().front(), VMap,
675                             ModuleLevelChanges, Returns, NameSuffix, CodeInfo);
676 }
677 
678 /// \brief Remaps instructions in \p Blocks using the mapping in \p VMap.
679 void llvm::remapInstructionsInBlocks(
680     const SmallVectorImpl<BasicBlock *> &Blocks, ValueToValueMapTy &VMap) {
681   // Rewrite the code to refer to itself.
682   for (auto *BB : Blocks)
683     for (auto &Inst : *BB)
684       RemapInstruction(&Inst, VMap,
685                        RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
686 }
687 
688 /// \brief Clones a loop \p OrigLoop.  Returns the loop and the blocks in \p
689 /// Blocks.
690 ///
691 /// Updates LoopInfo and DominatorTree assuming the loop is dominated by block
692 /// \p LoopDomBB.  Insert the new blocks before block specified in \p Before.
693 Loop *llvm::cloneLoopWithPreheader(BasicBlock *Before, BasicBlock *LoopDomBB,
694                                    Loop *OrigLoop, ValueToValueMapTy &VMap,
695                                    const Twine &NameSuffix, LoopInfo *LI,
696                                    DominatorTree *DT,
697                                    SmallVectorImpl<BasicBlock *> &Blocks) {
698   assert(OrigLoop->getSubLoops().empty() &&
699          "Loop to be cloned cannot have inner loop");
700   Function *F = OrigLoop->getHeader()->getParent();
701   Loop *ParentLoop = OrigLoop->getParentLoop();
702 
703   Loop *NewLoop = new Loop();
704   if (ParentLoop)
705     ParentLoop->addChildLoop(NewLoop);
706   else
707     LI->addTopLevelLoop(NewLoop);
708 
709   BasicBlock *OrigPH = OrigLoop->getLoopPreheader();
710   assert(OrigPH && "No preheader");
711   BasicBlock *NewPH = CloneBasicBlock(OrigPH, VMap, NameSuffix, F);
712   // To rename the loop PHIs.
713   VMap[OrigPH] = NewPH;
714   Blocks.push_back(NewPH);
715 
716   // Update LoopInfo.
717   if (ParentLoop)
718     ParentLoop->addBasicBlockToLoop(NewPH, *LI);
719 
720   // Update DominatorTree.
721   DT->addNewBlock(NewPH, LoopDomBB);
722 
723   for (BasicBlock *BB : OrigLoop->getBlocks()) {
724     BasicBlock *NewBB = CloneBasicBlock(BB, VMap, NameSuffix, F);
725     VMap[BB] = NewBB;
726 
727     // Update LoopInfo.
728     NewLoop->addBasicBlockToLoop(NewBB, *LI);
729 
730     // Add DominatorTree node. After seeing all blocks, update to correct IDom.
731     DT->addNewBlock(NewBB, NewPH);
732 
733     Blocks.push_back(NewBB);
734   }
735 
736   for (BasicBlock *BB : OrigLoop->getBlocks()) {
737     // Update DominatorTree.
738     BasicBlock *IDomBB = DT->getNode(BB)->getIDom()->getBlock();
739     DT->changeImmediateDominator(cast<BasicBlock>(VMap[BB]),
740                                  cast<BasicBlock>(VMap[IDomBB]));
741   }
742 
743   // Move them physically from the end of the block list.
744   F->getBasicBlockList().splice(Before->getIterator(), F->getBasicBlockList(),
745                                 NewPH);
746   F->getBasicBlockList().splice(Before->getIterator(), F->getBasicBlockList(),
747                                 NewLoop->getHeader()->getIterator(), F->end());
748 
749   return NewLoop;
750 }
751 
752 /// \brief Duplicate non-Phi instructions from the beginning of block up to
753 /// StopAt instruction into a split block between BB and its predecessor.
754 BasicBlock *
755 llvm::DuplicateInstructionsInSplitBetween(BasicBlock *BB, BasicBlock *PredBB,
756                                           Instruction *StopAt,
757                                           ValueToValueMapTy &ValueMapping) {
758   // We are going to have to map operands from the original BB block to the new
759   // copy of the block 'NewBB'.  If there are PHI nodes in BB, evaluate them to
760   // account for entry from PredBB.
761   BasicBlock::iterator BI = BB->begin();
762   for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
763     ValueMapping[PN] = PN->getIncomingValueForBlock(PredBB);
764 
765   BasicBlock *NewBB = SplitEdge(PredBB, BB);
766   NewBB->setName(PredBB->getName() + ".split");
767   Instruction *NewTerm = NewBB->getTerminator();
768 
769   // Clone the non-phi instructions of BB into NewBB, keeping track of the
770   // mapping and using it to remap operands in the cloned instructions.
771   for (; StopAt != &*BI; ++BI) {
772     Instruction *New = BI->clone();
773     New->setName(BI->getName());
774     New->insertBefore(NewTerm);
775     ValueMapping[&*BI] = New;
776 
777     // Remap operands to patch up intra-block references.
778     for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i)
779       if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i))) {
780         auto I = ValueMapping.find(Inst);
781         if (I != ValueMapping.end())
782           New->setOperand(i, I->second);
783       }
784   }
785 
786   return NewBB;
787 }
788