1 //===-- ArgumentPromotion.cpp - Promote by-reference arguments ------------===//
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 pass promotes "by reference" arguments to be "by value" arguments.  In
11 // practice, this means looking for internal functions that have pointer
12 // arguments.  If it can prove, through the use of alias analysis, that an
13 // argument is *only* loaded, then it can pass the value into the function
14 // instead of the address of the value.  This can cause recursive simplification
15 // of code and lead to the elimination of allocas (especially in C++ template
16 // code like the STL).
17 //
18 // This pass also handles aggregate arguments that are passed into a function,
19 // scalarizing them if the elements of the aggregate are only loaded.  Note that
20 // by default it refuses to scalarize aggregates which would require passing in
21 // more than three operands to the function, because passing thousands of
22 // operands for a large array or structure is unprofitable! This limit can be
23 // configured or disabled, however.
24 //
25 // Note that this transformation could also be done for arguments that are only
26 // stored to (returning the value instead), but does not currently.  This case
27 // would be best handled when and if LLVM begins supporting multiple return
28 // values from functions.
29 //
30 //===----------------------------------------------------------------------===//
31 
32 #include "llvm/Transforms/IPO.h"
33 #include "llvm/ADT/DepthFirstIterator.h"
34 #include "llvm/ADT/Statistic.h"
35 #include "llvm/ADT/StringExtras.h"
36 #include "llvm/Analysis/AliasAnalysis.h"
37 #include "llvm/Analysis/AssumptionCache.h"
38 #include "llvm/Analysis/BasicAliasAnalysis.h"
39 #include "llvm/Analysis/CallGraph.h"
40 #include "llvm/Analysis/CallGraphSCCPass.h"
41 #include "llvm/Analysis/Loads.h"
42 #include "llvm/Analysis/TargetLibraryInfo.h"
43 #include "llvm/Analysis/ValueTracking.h"
44 #include "llvm/IR/CFG.h"
45 #include "llvm/IR/CallSite.h"
46 #include "llvm/IR/Constants.h"
47 #include "llvm/IR/DataLayout.h"
48 #include "llvm/IR/DebugInfo.h"
49 #include "llvm/IR/DerivedTypes.h"
50 #include "llvm/IR/Instructions.h"
51 #include "llvm/IR/LLVMContext.h"
52 #include "llvm/IR/Module.h"
53 #include "llvm/Support/Debug.h"
54 #include "llvm/Support/raw_ostream.h"
55 #include <set>
56 using namespace llvm;
57 
58 #define DEBUG_TYPE "argpromotion"
59 
60 STATISTIC(NumArgumentsPromoted , "Number of pointer arguments promoted");
61 STATISTIC(NumAggregatesPromoted, "Number of aggregate arguments promoted");
62 STATISTIC(NumByValArgsPromoted , "Number of byval arguments promoted");
63 STATISTIC(NumArgumentsDead     , "Number of dead pointer args eliminated");
64 
65 namespace {
66   /// ArgPromotion - The 'by reference' to 'by value' argument promotion pass.
67   ///
68   struct ArgPromotion : public CallGraphSCCPass {
69     void getAnalysisUsage(AnalysisUsage &AU) const override {
70       AU.addRequired<AssumptionCacheTracker>();
71       AU.addRequired<TargetLibraryInfoWrapperPass>();
72       getAAResultsAnalysisUsage(AU);
73       CallGraphSCCPass::getAnalysisUsage(AU);
74     }
75 
76     bool runOnSCC(CallGraphSCC &SCC) override;
77     static char ID; // Pass identification, replacement for typeid
78     explicit ArgPromotion(unsigned maxElements = 3)
79         : CallGraphSCCPass(ID), maxElements(maxElements) {
80       initializeArgPromotionPass(*PassRegistry::getPassRegistry());
81     }
82 
83     /// A vector used to hold the indices of a single GEP instruction
84     typedef std::vector<uint64_t> IndicesVector;
85 
86   private:
87     bool isDenselyPacked(Type *type, const DataLayout &DL);
88     bool canPaddingBeAccessed(Argument *Arg);
89     CallGraphNode *PromoteArguments(CallGraphNode *CGN);
90     bool isSafeToPromoteArgument(Argument *Arg, bool isByVal,
91                                  AAResults &AAR) const;
92     CallGraphNode *DoPromotion(Function *F,
93                               SmallPtrSetImpl<Argument*> &ArgsToPromote,
94                               SmallPtrSetImpl<Argument*> &ByValArgsToTransform);
95 
96     using llvm::Pass::doInitialization;
97     bool doInitialization(CallGraph &CG) override;
98     /// The maximum number of elements to expand, or 0 for unlimited.
99     unsigned maxElements;
100   };
101 }
102 
103 char ArgPromotion::ID = 0;
104 INITIALIZE_PASS_BEGIN(ArgPromotion, "argpromotion",
105                 "Promote 'by reference' arguments to scalars", false, false)
106 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
107 INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass)
108 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
109 INITIALIZE_PASS_END(ArgPromotion, "argpromotion",
110                 "Promote 'by reference' arguments to scalars", false, false)
111 
112 Pass *llvm::createArgumentPromotionPass(unsigned maxElements) {
113   return new ArgPromotion(maxElements);
114 }
115 
116 bool ArgPromotion::runOnSCC(CallGraphSCC &SCC) {
117   if (skipSCC(SCC))
118     return false;
119 
120   bool Changed = false, LocalChange;
121 
122   do {  // Iterate until we stop promoting from this SCC.
123     LocalChange = false;
124     // Attempt to promote arguments from all functions in this SCC.
125     for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
126       if (CallGraphNode *CGN = PromoteArguments(*I)) {
127         LocalChange = true;
128         SCC.ReplaceNode(*I, CGN);
129       }
130     }
131     Changed |= LocalChange;               // Remember that we changed something.
132   } while (LocalChange);
133 
134   return Changed;
135 }
136 
137 /// \brief Checks if a type could have padding bytes.
138 bool ArgPromotion::isDenselyPacked(Type *type, const DataLayout &DL) {
139 
140   // There is no size information, so be conservative.
141   if (!type->isSized())
142     return false;
143 
144   // If the alloc size is not equal to the storage size, then there are padding
145   // bytes. For x86_fp80 on x86-64, size: 80 alloc size: 128.
146   if (DL.getTypeSizeInBits(type) != DL.getTypeAllocSizeInBits(type))
147     return false;
148 
149   if (!isa<CompositeType>(type))
150     return true;
151 
152   // For homogenous sequential types, check for padding within members.
153   if (SequentialType *seqTy = dyn_cast<SequentialType>(type))
154     return isa<PointerType>(seqTy) ||
155            isDenselyPacked(seqTy->getElementType(), DL);
156 
157   // Check for padding within and between elements of a struct.
158   StructType *StructTy = cast<StructType>(type);
159   const StructLayout *Layout = DL.getStructLayout(StructTy);
160   uint64_t StartPos = 0;
161   for (unsigned i = 0, E = StructTy->getNumElements(); i < E; ++i) {
162     Type *ElTy = StructTy->getElementType(i);
163     if (!isDenselyPacked(ElTy, DL))
164       return false;
165     if (StartPos != Layout->getElementOffsetInBits(i))
166       return false;
167     StartPos += DL.getTypeAllocSizeInBits(ElTy);
168   }
169 
170   return true;
171 }
172 
173 /// \brief Checks if the padding bytes of an argument could be accessed.
174 bool ArgPromotion::canPaddingBeAccessed(Argument *arg) {
175 
176   assert(arg->hasByValAttr());
177 
178   // Track all the pointers to the argument to make sure they are not captured.
179   SmallPtrSet<Value *, 16> PtrValues;
180   PtrValues.insert(arg);
181 
182   // Track all of the stores.
183   SmallVector<StoreInst *, 16> Stores;
184 
185   // Scan through the uses recursively to make sure the pointer is always used
186   // sanely.
187   SmallVector<Value *, 16> WorkList;
188   WorkList.insert(WorkList.end(), arg->user_begin(), arg->user_end());
189   while (!WorkList.empty()) {
190     Value *V = WorkList.back();
191     WorkList.pop_back();
192     if (isa<GetElementPtrInst>(V) || isa<PHINode>(V)) {
193       if (PtrValues.insert(V).second)
194         WorkList.insert(WorkList.end(), V->user_begin(), V->user_end());
195     } else if (StoreInst *Store = dyn_cast<StoreInst>(V)) {
196       Stores.push_back(Store);
197     } else if (!isa<LoadInst>(V)) {
198       return true;
199     }
200   }
201 
202 // Check to make sure the pointers aren't captured
203   for (StoreInst *Store : Stores)
204     if (PtrValues.count(Store->getValueOperand()))
205       return true;
206 
207   return false;
208 }
209 
210 /// PromoteArguments - This method checks the specified function to see if there
211 /// are any promotable arguments and if it is safe to promote the function (for
212 /// example, all callers are direct).  If safe to promote some arguments, it
213 /// calls the DoPromotion method.
214 ///
215 CallGraphNode *ArgPromotion::PromoteArguments(CallGraphNode *CGN) {
216   Function *F = CGN->getFunction();
217 
218   // Make sure that it is local to this module.
219   if (!F || !F->hasLocalLinkage()) return nullptr;
220 
221   // Don't promote arguments for variadic functions. Adding, removing, or
222   // changing non-pack parameters can change the classification of pack
223   // parameters. Frontends encode that classification at the call site in the
224   // IR, while in the callee the classification is determined dynamically based
225   // on the number of registers consumed so far.
226   if (F->isVarArg()) return nullptr;
227 
228   // First check: see if there are any pointer arguments!  If not, quick exit.
229   SmallVector<Argument*, 16> PointerArgs;
230   for (Argument &I : F->args())
231     if (I.getType()->isPointerTy())
232       PointerArgs.push_back(&I);
233   if (PointerArgs.empty()) return nullptr;
234 
235   // Second check: make sure that all callers are direct callers.  We can't
236   // transform functions that have indirect callers.  Also see if the function
237   // is self-recursive.
238   bool isSelfRecursive = false;
239   for (Use &U : F->uses()) {
240     CallSite CS(U.getUser());
241     // Must be a direct call.
242     if (CS.getInstruction() == nullptr || !CS.isCallee(&U)) return nullptr;
243 
244     if (CS.getInstruction()->getParent()->getParent() == F)
245       isSelfRecursive = true;
246   }
247 
248   const DataLayout &DL = F->getParent()->getDataLayout();
249 
250   // We need to manually construct BasicAA directly in order to disable its use
251   // of other function analyses.
252   BasicAAResult BAR(createLegacyPMBasicAAResult(*this, *F));
253 
254   // Construct our own AA results for this function. We do this manually to
255   // work around the limitations of the legacy pass manager.
256   AAResults AAR(createLegacyPMAAResults(*this, *F, BAR));
257 
258   // Check to see which arguments are promotable.  If an argument is promotable,
259   // add it to ArgsToPromote.
260   SmallPtrSet<Argument*, 8> ArgsToPromote;
261   SmallPtrSet<Argument*, 8> ByValArgsToTransform;
262   for (unsigned i = 0, e = PointerArgs.size(); i != e; ++i) {
263     Argument *PtrArg = PointerArgs[i];
264     Type *AgTy = cast<PointerType>(PtrArg->getType())->getElementType();
265 
266     // Replace sret attribute with noalias. This reduces register pressure by
267     // avoiding a register copy.
268     if (PtrArg->hasStructRetAttr()) {
269       unsigned ArgNo = PtrArg->getArgNo();
270       F->setAttributes(
271           F->getAttributes()
272               .removeAttribute(F->getContext(), ArgNo + 1, Attribute::StructRet)
273               .addAttribute(F->getContext(), ArgNo + 1, Attribute::NoAlias));
274       for (Use &U : F->uses()) {
275         CallSite CS(U.getUser());
276         CS.setAttributes(
277             CS.getAttributes()
278                 .removeAttribute(F->getContext(), ArgNo + 1,
279                                  Attribute::StructRet)
280                 .addAttribute(F->getContext(), ArgNo + 1, Attribute::NoAlias));
281       }
282     }
283 
284     // If this is a byval argument, and if the aggregate type is small, just
285     // pass the elements, which is always safe, if the passed value is densely
286     // packed or if we can prove the padding bytes are never accessed. This does
287     // not apply to inalloca.
288     bool isSafeToPromote =
289         PtrArg->hasByValAttr() &&
290         (isDenselyPacked(AgTy, DL) || !canPaddingBeAccessed(PtrArg));
291     if (isSafeToPromote) {
292       if (StructType *STy = dyn_cast<StructType>(AgTy)) {
293         if (maxElements > 0 && STy->getNumElements() > maxElements) {
294           DEBUG(dbgs() << "argpromotion disable promoting argument '"
295                 << PtrArg->getName() << "' because it would require adding more"
296                 << " than " << maxElements << " arguments to the function.\n");
297           continue;
298         }
299 
300         // If all the elements are single-value types, we can promote it.
301         bool AllSimple = true;
302         for (const auto *EltTy : STy->elements()) {
303           if (!EltTy->isSingleValueType()) {
304             AllSimple = false;
305             break;
306           }
307         }
308 
309         // Safe to transform, don't even bother trying to "promote" it.
310         // Passing the elements as a scalar will allow scalarrepl to hack on
311         // the new alloca we introduce.
312         if (AllSimple) {
313           ByValArgsToTransform.insert(PtrArg);
314           continue;
315         }
316       }
317     }
318 
319     // If the argument is a recursive type and we're in a recursive
320     // function, we could end up infinitely peeling the function argument.
321     if (isSelfRecursive) {
322       if (StructType *STy = dyn_cast<StructType>(AgTy)) {
323         bool RecursiveType = false;
324         for (const auto *EltTy : STy->elements()) {
325           if (EltTy == PtrArg->getType()) {
326             RecursiveType = true;
327             break;
328           }
329         }
330         if (RecursiveType)
331           continue;
332       }
333     }
334 
335     // Otherwise, see if we can promote the pointer to its value.
336     if (isSafeToPromoteArgument(PtrArg, PtrArg->hasByValOrInAllocaAttr(), AAR))
337       ArgsToPromote.insert(PtrArg);
338   }
339 
340   // No promotable pointer arguments.
341   if (ArgsToPromote.empty() && ByValArgsToTransform.empty())
342     return nullptr;
343 
344   return DoPromotion(F, ArgsToPromote, ByValArgsToTransform);
345 }
346 
347 /// AllCallersPassInValidPointerForArgument - Return true if we can prove that
348 /// all callees pass in a valid pointer for the specified function argument.
349 static bool AllCallersPassInValidPointerForArgument(Argument *Arg) {
350   Function *Callee = Arg->getParent();
351   const DataLayout &DL = Callee->getParent()->getDataLayout();
352 
353   unsigned ArgNo = Arg->getArgNo();
354 
355   // Look at all call sites of the function.  At this pointer we know we only
356   // have direct callees.
357   for (User *U : Callee->users()) {
358     CallSite CS(U);
359     assert(CS && "Should only have direct calls!");
360 
361     if (!isDereferenceablePointer(CS.getArgument(ArgNo), DL))
362       return false;
363   }
364   return true;
365 }
366 
367 /// Returns true if Prefix is a prefix of longer. That means, Longer has a size
368 /// that is greater than or equal to the size of prefix, and each of the
369 /// elements in Prefix is the same as the corresponding elements in Longer.
370 ///
371 /// This means it also returns true when Prefix and Longer are equal!
372 static bool IsPrefix(const ArgPromotion::IndicesVector &Prefix,
373                      const ArgPromotion::IndicesVector &Longer) {
374   if (Prefix.size() > Longer.size())
375     return false;
376   return std::equal(Prefix.begin(), Prefix.end(), Longer.begin());
377 }
378 
379 
380 /// Checks if Indices, or a prefix of Indices, is in Set.
381 static bool PrefixIn(const ArgPromotion::IndicesVector &Indices,
382                      std::set<ArgPromotion::IndicesVector> &Set) {
383     std::set<ArgPromotion::IndicesVector>::iterator Low;
384     Low = Set.upper_bound(Indices);
385     if (Low != Set.begin())
386       Low--;
387     // Low is now the last element smaller than or equal to Indices. This means
388     // it points to a prefix of Indices (possibly Indices itself), if such
389     // prefix exists.
390     //
391     // This load is safe if any prefix of its operands is safe to load.
392     return Low != Set.end() && IsPrefix(*Low, Indices);
393 }
394 
395 /// Mark the given indices (ToMark) as safe in the given set of indices
396 /// (Safe). Marking safe usually means adding ToMark to Safe. However, if there
397 /// is already a prefix of Indices in Safe, Indices are implicitely marked safe
398 /// already. Furthermore, any indices that Indices is itself a prefix of, are
399 /// removed from Safe (since they are implicitely safe because of Indices now).
400 static void MarkIndicesSafe(const ArgPromotion::IndicesVector &ToMark,
401                             std::set<ArgPromotion::IndicesVector> &Safe) {
402   std::set<ArgPromotion::IndicesVector>::iterator Low;
403   Low = Safe.upper_bound(ToMark);
404   // Guard against the case where Safe is empty
405   if (Low != Safe.begin())
406     Low--;
407   // Low is now the last element smaller than or equal to Indices. This
408   // means it points to a prefix of Indices (possibly Indices itself), if
409   // such prefix exists.
410   if (Low != Safe.end()) {
411     if (IsPrefix(*Low, ToMark))
412       // If there is already a prefix of these indices (or exactly these
413       // indices) marked a safe, don't bother adding these indices
414       return;
415 
416     // Increment Low, so we can use it as a "insert before" hint
417     ++Low;
418   }
419   // Insert
420   Low = Safe.insert(Low, ToMark);
421   ++Low;
422   // If there we're a prefix of longer index list(s), remove those
423   std::set<ArgPromotion::IndicesVector>::iterator End = Safe.end();
424   while (Low != End && IsPrefix(ToMark, *Low)) {
425     std::set<ArgPromotion::IndicesVector>::iterator Remove = Low;
426     ++Low;
427     Safe.erase(Remove);
428   }
429 }
430 
431 /// isSafeToPromoteArgument - As you might guess from the name of this method,
432 /// it checks to see if it is both safe and useful to promote the argument.
433 /// This method limits promotion of aggregates to only promote up to three
434 /// elements of the aggregate in order to avoid exploding the number of
435 /// arguments passed in.
436 bool ArgPromotion::isSafeToPromoteArgument(Argument *Arg,
437                                            bool isByValOrInAlloca,
438                                            AAResults &AAR) const {
439   typedef std::set<IndicesVector> GEPIndicesSet;
440 
441   // Quick exit for unused arguments
442   if (Arg->use_empty())
443     return true;
444 
445   // We can only promote this argument if all of the uses are loads, or are GEP
446   // instructions (with constant indices) that are subsequently loaded.
447   //
448   // Promoting the argument causes it to be loaded in the caller
449   // unconditionally. This is only safe if we can prove that either the load
450   // would have happened in the callee anyway (ie, there is a load in the entry
451   // block) or the pointer passed in at every call site is guaranteed to be
452   // valid.
453   // In the former case, invalid loads can happen, but would have happened
454   // anyway, in the latter case, invalid loads won't happen. This prevents us
455   // from introducing an invalid load that wouldn't have happened in the
456   // original code.
457   //
458   // This set will contain all sets of indices that are loaded in the entry
459   // block, and thus are safe to unconditionally load in the caller.
460   //
461   // This optimization is also safe for InAlloca parameters, because it verifies
462   // that the address isn't captured.
463   GEPIndicesSet SafeToUnconditionallyLoad;
464 
465   // This set contains all the sets of indices that we are planning to promote.
466   // This makes it possible to limit the number of arguments added.
467   GEPIndicesSet ToPromote;
468 
469   // If the pointer is always valid, any load with first index 0 is valid.
470   if (isByValOrInAlloca || AllCallersPassInValidPointerForArgument(Arg))
471     SafeToUnconditionallyLoad.insert(IndicesVector(1, 0));
472 
473   // First, iterate the entry block and mark loads of (geps of) arguments as
474   // safe.
475   BasicBlock &EntryBlock = Arg->getParent()->front();
476   // Declare this here so we can reuse it
477   IndicesVector Indices;
478   for (Instruction &I : EntryBlock)
479     if (LoadInst *LI = dyn_cast<LoadInst>(&I)) {
480       Value *V = LI->getPointerOperand();
481       if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(V)) {
482         V = GEP->getPointerOperand();
483         if (V == Arg) {
484           // This load actually loads (part of) Arg? Check the indices then.
485           Indices.reserve(GEP->getNumIndices());
486           for (User::op_iterator II = GEP->idx_begin(), IE = GEP->idx_end();
487                II != IE; ++II)
488             if (ConstantInt *CI = dyn_cast<ConstantInt>(*II))
489               Indices.push_back(CI->getSExtValue());
490             else
491               // We found a non-constant GEP index for this argument? Bail out
492               // right away, can't promote this argument at all.
493               return false;
494 
495           // Indices checked out, mark them as safe
496           MarkIndicesSafe(Indices, SafeToUnconditionallyLoad);
497           Indices.clear();
498         }
499       } else if (V == Arg) {
500         // Direct loads are equivalent to a GEP with a single 0 index.
501         MarkIndicesSafe(IndicesVector(1, 0), SafeToUnconditionallyLoad);
502       }
503     }
504 
505   // Now, iterate all uses of the argument to see if there are any uses that are
506   // not (GEP+)loads, or any (GEP+)loads that are not safe to promote.
507   SmallVector<LoadInst*, 16> Loads;
508   IndicesVector Operands;
509   for (Use &U : Arg->uses()) {
510     User *UR = U.getUser();
511     Operands.clear();
512     if (LoadInst *LI = dyn_cast<LoadInst>(UR)) {
513       // Don't hack volatile/atomic loads
514       if (!LI->isSimple()) return false;
515       Loads.push_back(LI);
516       // Direct loads are equivalent to a GEP with a zero index and then a load.
517       Operands.push_back(0);
518     } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(UR)) {
519       if (GEP->use_empty()) {
520         // Dead GEP's cause trouble later.  Just remove them if we run into
521         // them.
522         GEP->eraseFromParent();
523         // TODO: This runs the above loop over and over again for dead GEPs
524         // Couldn't we just do increment the UI iterator earlier and erase the
525         // use?
526         return isSafeToPromoteArgument(Arg, isByValOrInAlloca, AAR);
527       }
528 
529       // Ensure that all of the indices are constants.
530       for (User::op_iterator i = GEP->idx_begin(), e = GEP->idx_end();
531         i != e; ++i)
532         if (ConstantInt *C = dyn_cast<ConstantInt>(*i))
533           Operands.push_back(C->getSExtValue());
534         else
535           return false;  // Not a constant operand GEP!
536 
537       // Ensure that the only users of the GEP are load instructions.
538       for (User *GEPU : GEP->users())
539         if (LoadInst *LI = dyn_cast<LoadInst>(GEPU)) {
540           // Don't hack volatile/atomic loads
541           if (!LI->isSimple()) return false;
542           Loads.push_back(LI);
543         } else {
544           // Other uses than load?
545           return false;
546         }
547     } else {
548       return false;  // Not a load or a GEP.
549     }
550 
551     // Now, see if it is safe to promote this load / loads of this GEP. Loading
552     // is safe if Operands, or a prefix of Operands, is marked as safe.
553     if (!PrefixIn(Operands, SafeToUnconditionallyLoad))
554       return false;
555 
556     // See if we are already promoting a load with these indices. If not, check
557     // to make sure that we aren't promoting too many elements.  If so, nothing
558     // to do.
559     if (ToPromote.find(Operands) == ToPromote.end()) {
560       if (maxElements > 0 && ToPromote.size() == maxElements) {
561         DEBUG(dbgs() << "argpromotion not promoting argument '"
562               << Arg->getName() << "' because it would require adding more "
563               << "than " << maxElements << " arguments to the function.\n");
564         // We limit aggregate promotion to only promoting up to a fixed number
565         // of elements of the aggregate.
566         return false;
567       }
568       ToPromote.insert(std::move(Operands));
569     }
570   }
571 
572   if (Loads.empty()) return true;  // No users, this is a dead argument.
573 
574   // Okay, now we know that the argument is only used by load instructions and
575   // it is safe to unconditionally perform all of them. Use alias analysis to
576   // check to see if the pointer is guaranteed to not be modified from entry of
577   // the function to each of the load instructions.
578 
579   // Because there could be several/many load instructions, remember which
580   // blocks we know to be transparent to the load.
581   SmallPtrSet<BasicBlock*, 16> TranspBlocks;
582 
583   for (unsigned i = 0, e = Loads.size(); i != e; ++i) {
584     // Check to see if the load is invalidated from the start of the block to
585     // the load itself.
586     LoadInst *Load = Loads[i];
587     BasicBlock *BB = Load->getParent();
588 
589     MemoryLocation Loc = MemoryLocation::get(Load);
590     if (AAR.canInstructionRangeModRef(BB->front(), *Load, Loc, MRI_Mod))
591       return false;  // Pointer is invalidated!
592 
593     // Now check every path from the entry block to the load for transparency.
594     // To do this, we perform a depth first search on the inverse CFG from the
595     // loading block.
596     for (BasicBlock *P : predecessors(BB)) {
597       for (BasicBlock *TranspBB : inverse_depth_first_ext(P, TranspBlocks))
598         if (AAR.canBasicBlockModify(*TranspBB, Loc))
599           return false;
600     }
601   }
602 
603   // If the path from the entry of the function to each load is free of
604   // instructions that potentially invalidate the load, we can make the
605   // transformation!
606   return true;
607 }
608 
609 /// DoPromotion - This method actually performs the promotion of the specified
610 /// arguments, and returns the new function.  At this point, we know that it's
611 /// safe to do so.
612 CallGraphNode *ArgPromotion::DoPromotion(Function *F,
613                              SmallPtrSetImpl<Argument*> &ArgsToPromote,
614                              SmallPtrSetImpl<Argument*> &ByValArgsToTransform) {
615 
616   // Start by computing a new prototype for the function, which is the same as
617   // the old function, but has modified arguments.
618   FunctionType *FTy = F->getFunctionType();
619   std::vector<Type*> Params;
620 
621   typedef std::set<std::pair<Type *, IndicesVector>> ScalarizeTable;
622 
623   // ScalarizedElements - If we are promoting a pointer that has elements
624   // accessed out of it, keep track of which elements are accessed so that we
625   // can add one argument for each.
626   //
627   // Arguments that are directly loaded will have a zero element value here, to
628   // handle cases where there are both a direct load and GEP accesses.
629   //
630   std::map<Argument*, ScalarizeTable> ScalarizedElements;
631 
632   // OriginalLoads - Keep track of a representative load instruction from the
633   // original function so that we can tell the alias analysis implementation
634   // what the new GEP/Load instructions we are inserting look like.
635   // We need to keep the original loads for each argument and the elements
636   // of the argument that are accessed.
637   std::map<std::pair<Argument*, IndicesVector>, LoadInst*> OriginalLoads;
638 
639   // Attribute - Keep track of the parameter attributes for the arguments
640   // that we are *not* promoting. For the ones that we do promote, the parameter
641   // attributes are lost
642   SmallVector<AttributeSet, 8> AttributesVec;
643   const AttributeSet &PAL = F->getAttributes();
644 
645   // Add any return attributes.
646   if (PAL.hasAttributes(AttributeSet::ReturnIndex))
647     AttributesVec.push_back(AttributeSet::get(F->getContext(),
648                                               PAL.getRetAttributes()));
649 
650   // First, determine the new argument list
651   unsigned ArgIndex = 1;
652   for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E;
653        ++I, ++ArgIndex) {
654     if (ByValArgsToTransform.count(&*I)) {
655       // Simple byval argument? Just add all the struct element types.
656       Type *AgTy = cast<PointerType>(I->getType())->getElementType();
657       StructType *STy = cast<StructType>(AgTy);
658       Params.insert(Params.end(), STy->element_begin(), STy->element_end());
659       ++NumByValArgsPromoted;
660     } else if (!ArgsToPromote.count(&*I)) {
661       // Unchanged argument
662       Params.push_back(I->getType());
663       AttributeSet attrs = PAL.getParamAttributes(ArgIndex);
664       if (attrs.hasAttributes(ArgIndex)) {
665         AttrBuilder B(attrs, ArgIndex);
666         AttributesVec.
667           push_back(AttributeSet::get(F->getContext(), Params.size(), B));
668       }
669     } else if (I->use_empty()) {
670       // Dead argument (which are always marked as promotable)
671       ++NumArgumentsDead;
672     } else {
673       // Okay, this is being promoted. This means that the only uses are loads
674       // or GEPs which are only used by loads
675 
676       // In this table, we will track which indices are loaded from the argument
677       // (where direct loads are tracked as no indices).
678       ScalarizeTable &ArgIndices = ScalarizedElements[&*I];
679       for (User *U : I->users()) {
680         Instruction *UI = cast<Instruction>(U);
681         Type *SrcTy;
682         if (LoadInst *L = dyn_cast<LoadInst>(UI))
683           SrcTy = L->getType();
684         else
685           SrcTy = cast<GetElementPtrInst>(UI)->getSourceElementType();
686         IndicesVector Indices;
687         Indices.reserve(UI->getNumOperands() - 1);
688         // Since loads will only have a single operand, and GEPs only a single
689         // non-index operand, this will record direct loads without any indices,
690         // and gep+loads with the GEP indices.
691         for (User::op_iterator II = UI->op_begin() + 1, IE = UI->op_end();
692              II != IE; ++II)
693           Indices.push_back(cast<ConstantInt>(*II)->getSExtValue());
694         // GEPs with a single 0 index can be merged with direct loads
695         if (Indices.size() == 1 && Indices.front() == 0)
696           Indices.clear();
697         ArgIndices.insert(std::make_pair(SrcTy, Indices));
698         LoadInst *OrigLoad;
699         if (LoadInst *L = dyn_cast<LoadInst>(UI))
700           OrigLoad = L;
701         else
702           // Take any load, we will use it only to update Alias Analysis
703           OrigLoad = cast<LoadInst>(UI->user_back());
704         OriginalLoads[std::make_pair(&*I, Indices)] = OrigLoad;
705       }
706 
707       // Add a parameter to the function for each element passed in.
708       for (ScalarizeTable::iterator SI = ArgIndices.begin(),
709              E = ArgIndices.end(); SI != E; ++SI) {
710         // not allowed to dereference ->begin() if size() is 0
711         Params.push_back(GetElementPtrInst::getIndexedType(
712             cast<PointerType>(I->getType()->getScalarType())->getElementType(),
713             SI->second));
714         assert(Params.back());
715       }
716 
717       if (ArgIndices.size() == 1 && ArgIndices.begin()->second.empty())
718         ++NumArgumentsPromoted;
719       else
720         ++NumAggregatesPromoted;
721     }
722   }
723 
724   // Add any function attributes.
725   if (PAL.hasAttributes(AttributeSet::FunctionIndex))
726     AttributesVec.push_back(AttributeSet::get(FTy->getContext(),
727                                               PAL.getFnAttributes()));
728 
729   Type *RetTy = FTy->getReturnType();
730 
731   // Construct the new function type using the new arguments.
732   FunctionType *NFTy = FunctionType::get(RetTy, Params, FTy->isVarArg());
733 
734   // Create the new function body and insert it into the module.
735   Function *NF = Function::Create(NFTy, F->getLinkage(), F->getName());
736   NF->copyAttributesFrom(F);
737 
738   // Patch the pointer to LLVM function in debug info descriptor.
739   NF->setSubprogram(F->getSubprogram());
740   F->setSubprogram(nullptr);
741 
742   DEBUG(dbgs() << "ARG PROMOTION:  Promoting to:" << *NF << "\n"
743         << "From: " << *F);
744 
745   // Recompute the parameter attributes list based on the new arguments for
746   // the function.
747   NF->setAttributes(AttributeSet::get(F->getContext(), AttributesVec));
748   AttributesVec.clear();
749 
750   F->getParent()->getFunctionList().insert(F->getIterator(), NF);
751   NF->takeName(F);
752 
753   // Get the callgraph information that we need to update to reflect our
754   // changes.
755   CallGraph &CG = getAnalysis<CallGraphWrapperPass>().getCallGraph();
756 
757   // Get a new callgraph node for NF.
758   CallGraphNode *NF_CGN = CG.getOrInsertFunction(NF);
759 
760   // Loop over all of the callers of the function, transforming the call sites
761   // to pass in the loaded pointers.
762   //
763   SmallVector<Value*, 16> Args;
764   while (!F->use_empty()) {
765     CallSite CS(F->user_back());
766     assert(CS.getCalledFunction() == F);
767     Instruction *Call = CS.getInstruction();
768     const AttributeSet &CallPAL = CS.getAttributes();
769 
770     // Add any return attributes.
771     if (CallPAL.hasAttributes(AttributeSet::ReturnIndex))
772       AttributesVec.push_back(AttributeSet::get(F->getContext(),
773                                                 CallPAL.getRetAttributes()));
774 
775     // Loop over the operands, inserting GEP and loads in the caller as
776     // appropriate.
777     CallSite::arg_iterator AI = CS.arg_begin();
778     ArgIndex = 1;
779     for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
780          I != E; ++I, ++AI, ++ArgIndex)
781       if (!ArgsToPromote.count(&*I) && !ByValArgsToTransform.count(&*I)) {
782         Args.push_back(*AI);          // Unmodified argument
783 
784         if (CallPAL.hasAttributes(ArgIndex)) {
785           AttrBuilder B(CallPAL, ArgIndex);
786           AttributesVec.
787             push_back(AttributeSet::get(F->getContext(), Args.size(), B));
788         }
789       } else if (ByValArgsToTransform.count(&*I)) {
790         // Emit a GEP and load for each element of the struct.
791         Type *AgTy = cast<PointerType>(I->getType())->getElementType();
792         StructType *STy = cast<StructType>(AgTy);
793         Value *Idxs[2] = {
794               ConstantInt::get(Type::getInt32Ty(F->getContext()), 0), nullptr };
795         for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
796           Idxs[1] = ConstantInt::get(Type::getInt32Ty(F->getContext()), i);
797           Value *Idx = GetElementPtrInst::Create(
798               STy, *AI, Idxs, (*AI)->getName() + "." + Twine(i), Call);
799           // TODO: Tell AA about the new values?
800           Args.push_back(new LoadInst(Idx, Idx->getName()+".val", Call));
801         }
802       } else if (!I->use_empty()) {
803         // Non-dead argument: insert GEPs and loads as appropriate.
804         ScalarizeTable &ArgIndices = ScalarizedElements[&*I];
805         // Store the Value* version of the indices in here, but declare it now
806         // for reuse.
807         std::vector<Value*> Ops;
808         for (ScalarizeTable::iterator SI = ArgIndices.begin(),
809                E = ArgIndices.end(); SI != E; ++SI) {
810           Value *V = *AI;
811           LoadInst *OrigLoad = OriginalLoads[std::make_pair(&*I, SI->second)];
812           if (!SI->second.empty()) {
813             Ops.reserve(SI->second.size());
814             Type *ElTy = V->getType();
815             for (IndicesVector::const_iterator II = SI->second.begin(),
816                                                IE = SI->second.end();
817                  II != IE; ++II) {
818               // Use i32 to index structs, and i64 for others (pointers/arrays).
819               // This satisfies GEP constraints.
820               Type *IdxTy = (ElTy->isStructTy() ?
821                     Type::getInt32Ty(F->getContext()) :
822                     Type::getInt64Ty(F->getContext()));
823               Ops.push_back(ConstantInt::get(IdxTy, *II));
824               // Keep track of the type we're currently indexing.
825               ElTy = cast<CompositeType>(ElTy)->getTypeAtIndex(*II);
826             }
827             // And create a GEP to extract those indices.
828             V = GetElementPtrInst::Create(SI->first, V, Ops,
829                                           V->getName() + ".idx", Call);
830             Ops.clear();
831           }
832           // Since we're replacing a load make sure we take the alignment
833           // of the previous load.
834           LoadInst *newLoad = new LoadInst(V, V->getName()+".val", Call);
835           newLoad->setAlignment(OrigLoad->getAlignment());
836           // Transfer the AA info too.
837           AAMDNodes AAInfo;
838           OrigLoad->getAAMetadata(AAInfo);
839           newLoad->setAAMetadata(AAInfo);
840 
841           Args.push_back(newLoad);
842         }
843       }
844 
845     // Push any varargs arguments on the list.
846     for (; AI != CS.arg_end(); ++AI, ++ArgIndex) {
847       Args.push_back(*AI);
848       if (CallPAL.hasAttributes(ArgIndex)) {
849         AttrBuilder B(CallPAL, ArgIndex);
850         AttributesVec.
851           push_back(AttributeSet::get(F->getContext(), Args.size(), B));
852       }
853     }
854 
855     // Add any function attributes.
856     if (CallPAL.hasAttributes(AttributeSet::FunctionIndex))
857       AttributesVec.push_back(AttributeSet::get(Call->getContext(),
858                                                 CallPAL.getFnAttributes()));
859 
860     SmallVector<OperandBundleDef, 1> OpBundles;
861     CS.getOperandBundlesAsDefs(OpBundles);
862 
863     Instruction *New;
864     if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
865       New = InvokeInst::Create(NF, II->getNormalDest(), II->getUnwindDest(),
866                                Args, OpBundles, "", Call);
867       cast<InvokeInst>(New)->setCallingConv(CS.getCallingConv());
868       cast<InvokeInst>(New)->setAttributes(AttributeSet::get(II->getContext(),
869                                                             AttributesVec));
870     } else {
871       New = CallInst::Create(NF, Args, OpBundles, "", Call);
872       cast<CallInst>(New)->setCallingConv(CS.getCallingConv());
873       cast<CallInst>(New)->setAttributes(AttributeSet::get(New->getContext(),
874                                                           AttributesVec));
875       if (cast<CallInst>(Call)->isTailCall())
876         cast<CallInst>(New)->setTailCall();
877     }
878     New->setDebugLoc(Call->getDebugLoc());
879     Args.clear();
880     AttributesVec.clear();
881 
882     // Update the callgraph to know that the callsite has been transformed.
883     CallGraphNode *CalleeNode = CG[Call->getParent()->getParent()];
884     CalleeNode->replaceCallEdge(CS, CallSite(New), NF_CGN);
885 
886     if (!Call->use_empty()) {
887       Call->replaceAllUsesWith(New);
888       New->takeName(Call);
889     }
890 
891     // Finally, remove the old call from the program, reducing the use-count of
892     // F.
893     Call->eraseFromParent();
894   }
895 
896   // Since we have now created the new function, splice the body of the old
897   // function right into the new function, leaving the old rotting hulk of the
898   // function empty.
899   NF->getBasicBlockList().splice(NF->begin(), F->getBasicBlockList());
900 
901   // Loop over the argument list, transferring uses of the old arguments over to
902   // the new arguments, also transferring over the names as well.
903   //
904   for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(),
905        I2 = NF->arg_begin(); I != E; ++I) {
906     if (!ArgsToPromote.count(&*I) && !ByValArgsToTransform.count(&*I)) {
907       // If this is an unmodified argument, move the name and users over to the
908       // new version.
909       I->replaceAllUsesWith(&*I2);
910       I2->takeName(&*I);
911       ++I2;
912       continue;
913     }
914 
915     if (ByValArgsToTransform.count(&*I)) {
916       // In the callee, we create an alloca, and store each of the new incoming
917       // arguments into the alloca.
918       Instruction *InsertPt = &NF->begin()->front();
919 
920       // Just add all the struct element types.
921       Type *AgTy = cast<PointerType>(I->getType())->getElementType();
922       Value *TheAlloca = new AllocaInst(AgTy, nullptr, "", InsertPt);
923       StructType *STy = cast<StructType>(AgTy);
924       Value *Idxs[2] = {
925             ConstantInt::get(Type::getInt32Ty(F->getContext()), 0), nullptr };
926 
927       for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
928         Idxs[1] = ConstantInt::get(Type::getInt32Ty(F->getContext()), i);
929         Value *Idx = GetElementPtrInst::Create(
930             AgTy, TheAlloca, Idxs, TheAlloca->getName() + "." + Twine(i),
931             InsertPt);
932         I2->setName(I->getName()+"."+Twine(i));
933         new StoreInst(&*I2++, Idx, InsertPt);
934       }
935 
936       // Anything that used the arg should now use the alloca.
937       I->replaceAllUsesWith(TheAlloca);
938       TheAlloca->takeName(&*I);
939 
940       // If the alloca is used in a call, we must clear the tail flag since
941       // the callee now uses an alloca from the caller.
942       for (User *U : TheAlloca->users()) {
943         CallInst *Call = dyn_cast<CallInst>(U);
944         if (!Call)
945           continue;
946         Call->setTailCall(false);
947       }
948       continue;
949     }
950 
951     if (I->use_empty())
952       continue;
953 
954     // Otherwise, if we promoted this argument, then all users are load
955     // instructions (or GEPs with only load users), and all loads should be
956     // using the new argument that we added.
957     ScalarizeTable &ArgIndices = ScalarizedElements[&*I];
958 
959     while (!I->use_empty()) {
960       if (LoadInst *LI = dyn_cast<LoadInst>(I->user_back())) {
961         assert(ArgIndices.begin()->second.empty() &&
962                "Load element should sort to front!");
963         I2->setName(I->getName()+".val");
964         LI->replaceAllUsesWith(&*I2);
965         LI->eraseFromParent();
966         DEBUG(dbgs() << "*** Promoted load of argument '" << I->getName()
967               << "' in function '" << F->getName() << "'\n");
968       } else {
969         GetElementPtrInst *GEP = cast<GetElementPtrInst>(I->user_back());
970         IndicesVector Operands;
971         Operands.reserve(GEP->getNumIndices());
972         for (User::op_iterator II = GEP->idx_begin(), IE = GEP->idx_end();
973              II != IE; ++II)
974           Operands.push_back(cast<ConstantInt>(*II)->getSExtValue());
975 
976         // GEPs with a single 0 index can be merged with direct loads
977         if (Operands.size() == 1 && Operands.front() == 0)
978           Operands.clear();
979 
980         Function::arg_iterator TheArg = I2;
981         for (ScalarizeTable::iterator It = ArgIndices.begin();
982              It->second != Operands; ++It, ++TheArg) {
983           assert(It != ArgIndices.end() && "GEP not handled??");
984         }
985 
986         std::string NewName = I->getName();
987         for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
988             NewName += "." + utostr(Operands[i]);
989         }
990         NewName += ".val";
991         TheArg->setName(NewName);
992 
993         DEBUG(dbgs() << "*** Promoted agg argument '" << TheArg->getName()
994               << "' of function '" << NF->getName() << "'\n");
995 
996         // All of the uses must be load instructions.  Replace them all with
997         // the argument specified by ArgNo.
998         while (!GEP->use_empty()) {
999           LoadInst *L = cast<LoadInst>(GEP->user_back());
1000           L->replaceAllUsesWith(&*TheArg);
1001           L->eraseFromParent();
1002         }
1003         GEP->eraseFromParent();
1004       }
1005     }
1006 
1007     // Increment I2 past all of the arguments added for this promoted pointer.
1008     std::advance(I2, ArgIndices.size());
1009   }
1010 
1011   NF_CGN->stealCalledFunctionsFrom(CG[F]);
1012 
1013   // Now that the old function is dead, delete it.  If there is a dangling
1014   // reference to the CallgraphNode, just leave the dead function around for
1015   // someone else to nuke.
1016   CallGraphNode *CGN = CG[F];
1017   if (CGN->getNumReferences() == 0)
1018     delete CG.removeFunctionFromModule(CGN);
1019   else
1020     F->setLinkage(Function::ExternalLinkage);
1021 
1022   return NF_CGN;
1023 }
1024 
1025 bool ArgPromotion::doInitialization(CallGraph &CG) {
1026   return CallGraphSCCPass::doInitialization(CG);
1027 }
1028