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