xref: /llvm-project/llvm/lib/Analysis/CodeMetrics.cpp (revision 0a16c228463ca58c7828b5fd9bdd10b3ba612bbf)
1 //===- CodeMetrics.cpp - Code cost measurements ---------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements code cost measurement utilities.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/Analysis/AssumptionCache.h"
15 #include "llvm/Analysis/CodeMetrics.h"
16 #include "llvm/Analysis/LoopInfo.h"
17 #include "llvm/Analysis/TargetTransformInfo.h"
18 #include "llvm/Analysis/ValueTracking.h"
19 #include "llvm/IR/CallSite.h"
20 #include "llvm/IR/DataLayout.h"
21 #include "llvm/IR/Function.h"
22 #include "llvm/IR/IntrinsicInst.h"
23 #include "llvm/Support/Debug.h"
24 #include "llvm/Support/raw_ostream.h"
25 
26 #define DEBUG_TYPE "code-metrics"
27 
28 using namespace llvm;
29 
30 static void completeEphemeralValues(SmallVector<const Value *, 16> &WorkSet,
31                                     SmallPtrSetImpl<const Value*> &EphValues) {
32   SmallPtrSet<const Value *, 32> Visited;
33 
34   // Make sure that all of the items in WorkSet are in our EphValues set.
35   EphValues.insert(WorkSet.begin(), WorkSet.end());
36 
37   // Note: We don't speculate PHIs here, so we'll miss instruction chains kept
38   // alive only by ephemeral values.
39 
40   while (!WorkSet.empty()) {
41     const Value *V = WorkSet.front();
42     WorkSet.erase(WorkSet.begin());
43 
44     if (!Visited.insert(V).second)
45       continue;
46 
47     // If all uses of this value are ephemeral, then so is this value.
48     if (!all_of(V->users(), [&](const User *U) { return EphValues.count(U); }))
49       continue;
50 
51     EphValues.insert(V);
52     DEBUG(dbgs() << "Ephemeral Value: " << *V << "\n");
53 
54     if (const User *U = dyn_cast<User>(V))
55       for (const Value *J : U->operands()) {
56         if (isSafeToSpeculativelyExecute(J))
57           WorkSet.push_back(J);
58       }
59   }
60 }
61 
62 // Find all ephemeral values.
63 void CodeMetrics::collectEphemeralValues(
64     const Loop *L, AssumptionCache *AC,
65     SmallPtrSetImpl<const Value *> &EphValues) {
66   SmallVector<const Value *, 16> WorkSet;
67 
68   for (auto &AssumeVH : AC->assumptions()) {
69     if (!AssumeVH)
70       continue;
71     Instruction *I = cast<Instruction>(AssumeVH);
72 
73     // Filter out call sites outside of the loop so we don't to a function's
74     // worth of work for each of its loops (and, in the common case, ephemeral
75     // values in the loop are likely due to @llvm.assume calls in the loop).
76     if (!L->contains(I->getParent()))
77       continue;
78 
79     WorkSet.push_back(I);
80   }
81 
82   completeEphemeralValues(WorkSet, EphValues);
83 }
84 
85 void CodeMetrics::collectEphemeralValues(
86     const Function *F, AssumptionCache *AC,
87     SmallPtrSetImpl<const Value *> &EphValues) {
88   SmallVector<const Value *, 16> WorkSet;
89 
90   for (auto &AssumeVH : AC->assumptions()) {
91     if (!AssumeVH)
92       continue;
93     Instruction *I = cast<Instruction>(AssumeVH);
94     assert(I->getParent()->getParent() == F &&
95            "Found assumption for the wrong function!");
96     WorkSet.push_back(I);
97   }
98 
99   completeEphemeralValues(WorkSet, EphValues);
100 }
101 
102 /// Fill in the current structure with information gleaned from the specified
103 /// block.
104 void CodeMetrics::analyzeBasicBlock(const BasicBlock *BB,
105                                     const TargetTransformInfo &TTI,
106                                     const SmallPtrSetImpl<const Value*> &EphValues) {
107   ++NumBlocks;
108   unsigned NumInstsBeforeThisBB = NumInsts;
109   for (const Instruction &I : *BB) {
110     // Skip ephemeral values.
111     if (EphValues.count(&I))
112       continue;
113 
114     // Special handling for calls.
115     if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
116       ImmutableCallSite CS(&I);
117 
118       if (const Function *F = CS.getCalledFunction()) {
119         // If a function is both internal and has a single use, then it is
120         // extremely likely to get inlined in the future (it was probably
121         // exposed by an interleaved devirtualization pass).
122         if (!CS.isNoInline() && F->hasInternalLinkage() && F->hasOneUse())
123           ++NumInlineCandidates;
124 
125         // If this call is to function itself, then the function is recursive.
126         // Inlining it into other functions is a bad idea, because this is
127         // basically just a form of loop peeling, and our metrics aren't useful
128         // for that case.
129         if (F == BB->getParent())
130           isRecursive = true;
131 
132         if (TTI.isLoweredToCall(F))
133           ++NumCalls;
134       } else {
135         // We don't want inline asm to count as a call - that would prevent loop
136         // unrolling. The argument setup cost is still real, though.
137         if (!isa<InlineAsm>(CS.getCalledValue()))
138           ++NumCalls;
139       }
140     }
141 
142     if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
143       if (!AI->isStaticAlloca())
144         this->usesDynamicAlloca = true;
145     }
146 
147     if (isa<ExtractElementInst>(I) || I.getType()->isVectorTy())
148       ++NumVectorInsts;
149 
150     if (I.getType()->isTokenTy() && I.isUsedOutsideOfBlock(BB))
151       notDuplicatable = true;
152 
153     if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
154       if (CI->cannotDuplicate())
155         notDuplicatable = true;
156       if (CI->isConvergent())
157         convergent = true;
158     }
159 
160     if (const InvokeInst *InvI = dyn_cast<InvokeInst>(&I))
161       if (InvI->cannotDuplicate())
162         notDuplicatable = true;
163 
164     NumInsts += TTI.getUserCost(&I);
165   }
166 
167   if (isa<ReturnInst>(BB->getTerminator()))
168     ++NumRets;
169 
170   // We never want to inline functions that contain an indirectbr.  This is
171   // incorrect because all the blockaddress's (in static global initializers
172   // for example) would be referring to the original function, and this indirect
173   // jump would jump from the inlined copy of the function into the original
174   // function which is extremely undefined behavior.
175   // FIXME: This logic isn't really right; we can safely inline functions
176   // with indirectbr's as long as no other function or global references the
177   // blockaddress of a block within the current function.  And as a QOI issue,
178   // if someone is using a blockaddress without an indirectbr, and that
179   // reference somehow ends up in another function or global, we probably
180   // don't want to inline this function.
181   notDuplicatable |= isa<IndirectBrInst>(BB->getTerminator());
182 
183   // Remember NumInsts for this BB.
184   NumBBInsts[BB] = NumInsts - NumInstsBeforeThisBB;
185 }
186