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/CodeMetrics.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/IR/IntrinsicInst.h"
22 #include "llvm/Support/Debug.h"
23 #include "llvm/Support/raw_ostream.h"
24 
25 #define DEBUG_TYPE "code-metrics"
26 
27 using namespace llvm;
28 
29 static void
30 appendSpeculatableOperands(const Value *V,
31                            SmallPtrSetImpl<const Value *> &Visited,
32                            SmallVectorImpl<const Value *> &Worklist) {
33   const User *U = dyn_cast<User>(V);
34   if (!U)
35     return;
36 
37   for (const Value *Operand : U->operands())
38     if (Visited.insert(Operand).second)
39       if (isSafeToSpeculativelyExecute(Operand))
40         Worklist.push_back(Operand);
41 }
42 
43 static void completeEphemeralValues(SmallPtrSetImpl<const Value *> &Visited,
44                                     SmallVectorImpl<const Value *> &Worklist,
45                                     SmallPtrSetImpl<const Value *> &EphValues) {
46   // Note: We don't speculate PHIs here, so we'll miss instruction chains kept
47   // alive only by ephemeral values.
48 
49   // Walk the worklist using an index but without caching the size so we can
50   // append more entries as we process the worklist. This forms a queue without
51   // quadratic behavior by just leaving processed nodes at the head of the
52   // worklist forever.
53   for (int i = 0; i < (int)Worklist.size(); ++i) {
54     const Value *V = Worklist[i];
55 
56     assert(Visited.count(V) &&
57            "Failed to add a worklist entry to our visited set!");
58 
59     // If all uses of this value are ephemeral, then so is this value.
60     if (!all_of(V->users(), [&](const User *U) { return EphValues.count(U); }))
61       continue;
62 
63     EphValues.insert(V);
64     DEBUG(dbgs() << "Ephemeral Value: " << *V << "\n");
65 
66     // Append any more operands to consider.
67     appendSpeculatableOperands(V, Visited, Worklist);
68   }
69 }
70 
71 // Find all ephemeral values.
72 void CodeMetrics::collectEphemeralValues(
73     const Loop *L, SmallPtrSetImpl<const Value *> &EphValues) {
74   SmallPtrSet<const Value *, 32> Visited;
75   SmallVector<const Value *, 16> Worklist;
76 
77   for (auto &B : L->blocks())
78     for (auto &I : *B)
79       if (auto *II = dyn_cast<IntrinsicInst>(&I))
80         if (II->getIntrinsicID() == Intrinsic::assume &&
81             EphValues.insert(II).second)
82           appendSpeculatableOperands(II, Visited, Worklist);
83 
84   completeEphemeralValues(Visited, Worklist, EphValues);
85 }
86 
87 void CodeMetrics::collectEphemeralValues(
88     const Function *F, SmallPtrSetImpl<const Value *> &EphValues) {
89   SmallPtrSet<const Value *, 32> Visited;
90   SmallVector<const Value *, 16> Worklist;
91 
92   for (auto &B : *F)
93     for (auto &I : B)
94       if (auto *II = dyn_cast<IntrinsicInst>(&I))
95         if (II->getIntrinsicID() == Intrinsic::assume &&
96             EphValues.insert(II).second)
97           appendSpeculatableOperands(II, Visited, Worklist);
98 
99   completeEphemeralValues(Visited, Worklist, 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