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