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