13c256fbfSChandler Carruth //===- CodeMetrics.cpp - Code cost measurements ---------------------------===//
23c256fbfSChandler Carruth //
33c256fbfSChandler Carruth //                     The LLVM Compiler Infrastructure
43c256fbfSChandler Carruth //
53c256fbfSChandler Carruth // This file is distributed under the University of Illinois Open Source
63c256fbfSChandler Carruth // License. See LICENSE.TXT for details.
73c256fbfSChandler Carruth //
83c256fbfSChandler Carruth //===----------------------------------------------------------------------===//
93c256fbfSChandler Carruth //
103c256fbfSChandler Carruth // This file implements code cost measurement utilities.
113c256fbfSChandler Carruth //
123c256fbfSChandler Carruth //===----------------------------------------------------------------------===//
133c256fbfSChandler Carruth 
14*aec2fa35SDaniel Jasper #include "llvm/Analysis/AssumptionCache.h"
153c256fbfSChandler Carruth #include "llvm/Analysis/CodeMetrics.h"
1657f03ddaSHal Finkel #include "llvm/Analysis/LoopInfo.h"
17bb9caa92SChandler Carruth #include "llvm/Analysis/TargetTransformInfo.h"
1857f03ddaSHal Finkel #include "llvm/Analysis/ValueTracking.h"
19219b89b9SChandler Carruth #include "llvm/IR/CallSite.h"
209fb823bbSChandler Carruth #include "llvm/IR/DataLayout.h"
219fb823bbSChandler Carruth #include "llvm/IR/Function.h"
229fb823bbSChandler Carruth #include "llvm/IR/IntrinsicInst.h"
2357f03ddaSHal Finkel #include "llvm/Support/Debug.h"
24799003bfSBenjamin Kramer #include "llvm/Support/raw_ostream.h"
2557f03ddaSHal Finkel 
2657f03ddaSHal Finkel #define DEBUG_TYPE "code-metrics"
273c256fbfSChandler Carruth 
283c256fbfSChandler Carruth using namespace llvm;
293c256fbfSChandler Carruth 
30e2f36bcbSChandler Carruth static void
31e2f36bcbSChandler Carruth appendSpeculatableOperands(const Value *V,
32e2f36bcbSChandler Carruth                            SmallPtrSetImpl<const Value *> &Visited,
33e2f36bcbSChandler Carruth                            SmallVectorImpl<const Value *> &Worklist) {
34e2f36bcbSChandler Carruth   const User *U = dyn_cast<User>(V);
35e2f36bcbSChandler Carruth   if (!U)
36e2f36bcbSChandler Carruth     return;
37e2f36bcbSChandler Carruth 
38e2f36bcbSChandler Carruth   for (const Value *Operand : U->operands())
39e2f36bcbSChandler Carruth     if (Visited.insert(Operand).second)
40e2f36bcbSChandler Carruth       if (isSafeToSpeculativelyExecute(Operand))
41e2f36bcbSChandler Carruth         Worklist.push_back(Operand);
42e2f36bcbSChandler Carruth }
43e2f36bcbSChandler Carruth 
44e2f36bcbSChandler Carruth static void completeEphemeralValues(SmallPtrSetImpl<const Value *> &Visited,
45e2f36bcbSChandler Carruth                                     SmallVectorImpl<const Value *> &Worklist,
4657f03ddaSHal Finkel                                     SmallPtrSetImpl<const Value *> &EphValues) {
4757f03ddaSHal Finkel   // Note: We don't speculate PHIs here, so we'll miss instruction chains kept
4857f03ddaSHal Finkel   // alive only by ephemeral values.
4957f03ddaSHal Finkel 
50e2f36bcbSChandler Carruth   // Walk the worklist using an index but without caching the size so we can
51e2f36bcbSChandler Carruth   // append more entries as we process the worklist. This forms a queue without
52e2f36bcbSChandler Carruth   // quadratic behavior by just leaving processed nodes at the head of the
53e2f36bcbSChandler Carruth   // worklist forever.
54e2f36bcbSChandler Carruth   for (int i = 0; i < (int)Worklist.size(); ++i) {
55e2f36bcbSChandler Carruth     const Value *V = Worklist[i];
568683d2b0SHal Finkel 
57e2f36bcbSChandler Carruth     assert(Visited.count(V) &&
58e2f36bcbSChandler Carruth            "Failed to add a worklist entry to our visited set!");
5957f03ddaSHal Finkel 
6057f03ddaSHal Finkel     // If all uses of this value are ephemeral, then so is this value.
610a16c228SDavid Majnemer     if (!all_of(V->users(), [&](const User *U) { return EphValues.count(U); }))
6257f03ddaSHal Finkel       continue;
6357f03ddaSHal Finkel 
6457f03ddaSHal Finkel     EphValues.insert(V);
6557f03ddaSHal Finkel     DEBUG(dbgs() << "Ephemeral Value: " << *V << "\n");
6657f03ddaSHal Finkel 
67e2f36bcbSChandler Carruth     // Append any more operands to consider.
68e2f36bcbSChandler Carruth     appendSpeculatableOperands(V, Visited, Worklist);
6957f03ddaSHal Finkel   }
7057f03ddaSHal Finkel }
7157f03ddaSHal Finkel 
7257f03ddaSHal Finkel // Find all ephemeral values.
7366b3130cSChandler Carruth void CodeMetrics::collectEphemeralValues(
74*aec2fa35SDaniel Jasper     const Loop *L, AssumptionCache *AC,
75*aec2fa35SDaniel Jasper     SmallPtrSetImpl<const Value *> &EphValues) {
76e2f36bcbSChandler Carruth   SmallPtrSet<const Value *, 32> Visited;
77e2f36bcbSChandler Carruth   SmallVector<const Value *, 16> Worklist;
7857f03ddaSHal Finkel 
79*aec2fa35SDaniel Jasper   for (auto &AssumeVH : AC->assumptions()) {
80*aec2fa35SDaniel Jasper     if (!AssumeVH)
81*aec2fa35SDaniel Jasper       continue;
82*aec2fa35SDaniel Jasper     Instruction *I = cast<Instruction>(AssumeVH);
83*aec2fa35SDaniel Jasper 
84*aec2fa35SDaniel Jasper     // Filter out call sites outside of the loop so we don't do a function's
85*aec2fa35SDaniel Jasper     // worth of work for each of its loops (and, in the common case, ephemeral
86*aec2fa35SDaniel Jasper     // values in the loop are likely due to @llvm.assume calls in the loop).
87*aec2fa35SDaniel Jasper     if (!L->contains(I->getParent()))
88*aec2fa35SDaniel Jasper       continue;
89*aec2fa35SDaniel Jasper 
90*aec2fa35SDaniel Jasper     if (EphValues.insert(I).second)
91*aec2fa35SDaniel Jasper       appendSpeculatableOperands(I, Visited, Worklist);
92*aec2fa35SDaniel Jasper   }
9357f03ddaSHal Finkel 
94e2f36bcbSChandler Carruth   completeEphemeralValues(Visited, Worklist, EphValues);
9557f03ddaSHal Finkel }
9657f03ddaSHal Finkel 
9766b3130cSChandler Carruth void CodeMetrics::collectEphemeralValues(
98*aec2fa35SDaniel Jasper     const Function *F, AssumptionCache *AC,
99*aec2fa35SDaniel Jasper     SmallPtrSetImpl<const Value *> &EphValues) {
100e2f36bcbSChandler Carruth   SmallPtrSet<const Value *, 32> Visited;
101e2f36bcbSChandler Carruth   SmallVector<const Value *, 16> Worklist;
10257f03ddaSHal Finkel 
103*aec2fa35SDaniel Jasper   for (auto &AssumeVH : AC->assumptions()) {
104*aec2fa35SDaniel Jasper     if (!AssumeVH)
105*aec2fa35SDaniel Jasper       continue;
106*aec2fa35SDaniel Jasper     Instruction *I = cast<Instruction>(AssumeVH);
107*aec2fa35SDaniel Jasper     assert(I->getParent()->getParent() == F &&
108*aec2fa35SDaniel Jasper            "Found assumption for the wrong function!");
109*aec2fa35SDaniel Jasper 
110*aec2fa35SDaniel Jasper     if (EphValues.insert(I).second)
111*aec2fa35SDaniel Jasper       appendSpeculatableOperands(I, Visited, Worklist);
112*aec2fa35SDaniel Jasper   }
11357f03ddaSHal Finkel 
114e2f36bcbSChandler Carruth   completeEphemeralValues(Visited, Worklist, EphValues);
11557f03ddaSHal Finkel }
11657f03ddaSHal Finkel 
117b8d071bcSSanjay Patel /// Fill in the current structure with information gleaned from the specified
118b8d071bcSSanjay Patel /// block.
1190539c071SChandler Carruth void CodeMetrics::analyzeBasicBlock(const BasicBlock *BB,
12057f03ddaSHal Finkel                                     const TargetTransformInfo &TTI,
121031b1bc0SSebastian Pop                                     const SmallPtrSetImpl<const Value*> &EphValues) {
1220539c071SChandler Carruth   ++NumBlocks;
1230539c071SChandler Carruth   unsigned NumInstsBeforeThisBB = NumInsts;
124b8d071bcSSanjay Patel   for (const Instruction &I : *BB) {
12557f03ddaSHal Finkel     // Skip ephemeral values.
126b8d071bcSSanjay Patel     if (EphValues.count(&I))
12757f03ddaSHal Finkel       continue;
12857f03ddaSHal Finkel 
1290539c071SChandler Carruth     // Special handling for calls.
130b8d071bcSSanjay Patel     if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
131b8d071bcSSanjay Patel       ImmutableCallSite CS(&I);
1323c256fbfSChandler Carruth 
1333c256fbfSChandler Carruth       if (const Function *F = CS.getCalledFunction()) {
1343c256fbfSChandler Carruth         // If a function is both internal and has a single use, then it is
1353c256fbfSChandler Carruth         // extremely likely to get inlined in the future (it was probably
1363c256fbfSChandler Carruth         // exposed by an interleaved devirtualization pass).
1373c256fbfSChandler Carruth         if (!CS.isNoInline() && F->hasInternalLinkage() && F->hasOneUse())
1383c256fbfSChandler Carruth           ++NumInlineCandidates;
1393c256fbfSChandler Carruth 
1403c256fbfSChandler Carruth         // If this call is to function itself, then the function is recursive.
1413c256fbfSChandler Carruth         // Inlining it into other functions is a bad idea, because this is
1423c256fbfSChandler Carruth         // basically just a form of loop peeling, and our metrics aren't useful
1433c256fbfSChandler Carruth         // for that case.
1443c256fbfSChandler Carruth         if (F == BB->getParent())
1453c256fbfSChandler Carruth           isRecursive = true;
1463c256fbfSChandler Carruth 
1470ba8db45SChandler Carruth         if (TTI.isLoweredToCall(F))
1480ba8db45SChandler Carruth           ++NumCalls;
1490ba8db45SChandler Carruth       } else {
1503c256fbfSChandler Carruth         // We don't want inline asm to count as a call - that would prevent loop
1513c256fbfSChandler Carruth         // unrolling. The argument setup cost is still real, though.
1523c256fbfSChandler Carruth         if (!isa<InlineAsm>(CS.getCalledValue()))
1533c256fbfSChandler Carruth           ++NumCalls;
1543c256fbfSChandler Carruth       }
1553c256fbfSChandler Carruth     }
1563c256fbfSChandler Carruth 
157b8d071bcSSanjay Patel     if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
1583c256fbfSChandler Carruth       if (!AI->isStaticAlloca())
1593c256fbfSChandler Carruth         this->usesDynamicAlloca = true;
1603c256fbfSChandler Carruth     }
1613c256fbfSChandler Carruth 
162b8d071bcSSanjay Patel     if (isa<ExtractElementInst>(I) || I.getType()->isVectorTy())
1633c256fbfSChandler Carruth       ++NumVectorInsts;
1643c256fbfSChandler Carruth 
165b8d071bcSSanjay Patel     if (I.getType()->isTokenTy() && I.isUsedOutsideOfBlock(BB))
166b611e3f5SDavid Majnemer       notDuplicatable = true;
167b611e3f5SDavid Majnemer 
168b8d071bcSSanjay Patel     if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
169576ef3c6SEli Bendersky       if (CI->cannotDuplicate())
1704f6fb953SJames Molloy         notDuplicatable = true;
171144c5a6cSJustin Lebar       if (CI->isConvergent())
172144c5a6cSJustin Lebar         convergent = true;
173144c5a6cSJustin Lebar     }
1744f6fb953SJames Molloy 
175b8d071bcSSanjay Patel     if (const InvokeInst *InvI = dyn_cast<InvokeInst>(&I))
176576ef3c6SEli Bendersky       if (InvI->cannotDuplicate())
1774f6fb953SJames Molloy         notDuplicatable = true;
1784f6fb953SJames Molloy 
179b8d071bcSSanjay Patel     NumInsts += TTI.getUserCost(&I);
1803c256fbfSChandler Carruth   }
1813c256fbfSChandler Carruth 
1823c256fbfSChandler Carruth   if (isa<ReturnInst>(BB->getTerminator()))
1833c256fbfSChandler Carruth     ++NumRets;
1843c256fbfSChandler Carruth 
1853c256fbfSChandler Carruth   // We never want to inline functions that contain an indirectbr.  This is
1863c256fbfSChandler Carruth   // incorrect because all the blockaddress's (in static global initializers
1873c256fbfSChandler Carruth   // for example) would be referring to the original function, and this indirect
1883c256fbfSChandler Carruth   // jump would jump from the inlined copy of the function into the original
1893c256fbfSChandler Carruth   // function which is extremely undefined behavior.
1903c256fbfSChandler Carruth   // FIXME: This logic isn't really right; we can safely inline functions
1913c256fbfSChandler Carruth   // with indirectbr's as long as no other function or global references the
1923c256fbfSChandler Carruth   // blockaddress of a block within the current function.  And as a QOI issue,
1933c256fbfSChandler Carruth   // if someone is using a blockaddress without an indirectbr, and that
1943c256fbfSChandler Carruth   // reference somehow ends up in another function or global, we probably
1953c256fbfSChandler Carruth   // don't want to inline this function.
1964f6fb953SJames Molloy   notDuplicatable |= isa<IndirectBrInst>(BB->getTerminator());
1973c256fbfSChandler Carruth 
1983c256fbfSChandler Carruth   // Remember NumInsts for this BB.
1993c256fbfSChandler Carruth   NumBBInsts[BB] = NumInsts - NumInstsBeforeThisBB;
2003c256fbfSChandler Carruth }
201