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