LLVM  3.7.0
CodeMetrics.cpp
Go to the documentation of this file.
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 
16 #include "llvm/Analysis/LoopInfo.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"
25 
26 #define DEBUG_TYPE "code-metrics"
27 
28 using namespace llvm;
29 
31  SmallPtrSetImpl<const Value*> &EphValues) {
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  bool FoundNEUse = false;
49  for (const User *I : V->users())
50  if (!EphValues.count(I)) {
51  FoundNEUse = true;
52  break;
53  }
54 
55  if (FoundNEUse)
56  continue;
57 
58  EphValues.insert(V);
59  DEBUG(dbgs() << "Ephemeral Value: " << *V << "\n");
60 
61  if (const User *U = dyn_cast<User>(V))
62  for (const Value *J : U->operands()) {
64  WorkSet.push_back(J);
65  }
66  }
67 }
68 
69 // Find all ephemeral values.
71  const Loop *L, AssumptionCache *AC,
72  SmallPtrSetImpl<const Value *> &EphValues) {
74 
75  for (auto &AssumeVH : AC->assumptions()) {
76  if (!AssumeVH)
77  continue;
78  Instruction *I = cast<Instruction>(AssumeVH);
79 
80  // Filter out call sites outside of the loop so we don't to a function's
81  // worth of work for each of its loops (and, in the common case, ephemeral
82  // values in the loop are likely due to @llvm.assume calls in the loop).
83  if (!L->contains(I->getParent()))
84  continue;
85 
86  WorkSet.push_back(I);
87  }
88 
89  completeEphemeralValues(WorkSet, EphValues);
90 }
91 
93  const Function *F, AssumptionCache *AC,
94  SmallPtrSetImpl<const Value *> &EphValues) {
96 
97  for (auto &AssumeVH : AC->assumptions()) {
98  if (!AssumeVH)
99  continue;
100  Instruction *I = cast<Instruction>(AssumeVH);
101  assert(I->getParent()->getParent() == F &&
102  "Found assumption for the wrong function!");
103  WorkSet.push_back(I);
104  }
105 
106  completeEphemeralValues(WorkSet, EphValues);
107 }
108 
109 /// analyzeBasicBlock - Fill in the current structure with information gleaned
110 /// from the specified block.
112  const TargetTransformInfo &TTI,
113  SmallPtrSetImpl<const Value*> &EphValues) {
114  ++NumBlocks;
115  unsigned NumInstsBeforeThisBB = NumInsts;
116  for (BasicBlock::const_iterator II = BB->begin(), E = BB->end();
117  II != E; ++II) {
118  // Skip ephemeral values.
119  if (EphValues.count(II))
120  continue;
121 
122  // Special handling for calls.
123  if (isa<CallInst>(II) || isa<InvokeInst>(II)) {
124  ImmutableCallSite CS(cast<Instruction>(II));
125 
126  if (const Function *F = CS.getCalledFunction()) {
127  // If a function is both internal and has a single use, then it is
128  // extremely likely to get inlined in the future (it was probably
129  // exposed by an interleaved devirtualization pass).
130  if (!CS.isNoInline() && F->hasInternalLinkage() && F->hasOneUse())
132 
133  // If this call is to function itself, then the function is recursive.
134  // Inlining it into other functions is a bad idea, because this is
135  // basically just a form of loop peeling, and our metrics aren't useful
136  // for that case.
137  if (F == BB->getParent())
138  isRecursive = true;
139 
140  if (TTI.isLoweredToCall(F))
141  ++NumCalls;
142  } else {
143  // We don't want inline asm to count as a call - that would prevent loop
144  // unrolling. The argument setup cost is still real, though.
145  if (!isa<InlineAsm>(CS.getCalledValue()))
146  ++NumCalls;
147  }
148  }
149 
150  if (const AllocaInst *AI = dyn_cast<AllocaInst>(II)) {
151  if (!AI->isStaticAlloca())
152  this->usesDynamicAlloca = true;
153  }
154 
155  if (isa<ExtractElementInst>(II) || II->getType()->isVectorTy())
156  ++NumVectorInsts;
157 
158  if (const CallInst *CI = dyn_cast<CallInst>(II))
159  if (CI->cannotDuplicate())
160  notDuplicatable = true;
161 
162  if (const InvokeInst *InvI = dyn_cast<InvokeInst>(II))
163  if (InvI->cannotDuplicate())
164  notDuplicatable = true;
165 
166  NumInsts += TTI.getUserCost(&*II);
167  }
168 
169  if (isa<ReturnInst>(BB->getTerminator()))
170  ++NumRets;
171 
172  // We never want to inline functions that contain an indirectbr. This is
173  // incorrect because all the blockaddress's (in static global initializers
174  // for example) would be referring to the original function, and this indirect
175  // jump would jump from the inlined copy of the function into the original
176  // function which is extremely undefined behavior.
177  // FIXME: This logic isn't really right; we can safely inline functions
178  // with indirectbr's as long as no other function or global references the
179  // blockaddress of a block within the current function. And as a QOI issue,
180  // if someone is using a blockaddress without an indirectbr, and that
181  // reference somehow ends up in another function or global, we probably
182  // don't want to inline this function.
183  notDuplicatable |= isa<IndirectBrInst>(BB->getTerminator());
184 
185  // Remember NumInsts for this BB.
186  NumBBInsts[BB] = NumInsts - NumInstsBeforeThisBB;
187 }
bool isRecursive
True if this function calls itself.
Definition: CodeMetrics.h:48
unsigned NumVectorInsts
How many instructions produce vector values.
Definition: CodeMetrics.h:80
unsigned NumCalls
Keep track of the number of calls to 'big' functions.
Definition: CodeMetrics.h:69
CallInst - This class represents a function call, abstracting a target machine's calling convention...
size_type count(PtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
Definition: SmallPtrSet.h:276
A cache of .assume calls within a function.
const Function * getParent() const
Return the enclosing method, or null if none.
Definition: BasicBlock.h:111
unsigned NumInlineCandidates
The number of calls to internal functions with a single caller.
Definition: CodeMetrics.h:75
F(f)
bool notDuplicatable
True if this function cannot be duplicated.
Definition: CodeMetrics.h:54
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
Definition: SmallPtrSet.h:242
iterator begin()
Instruction iterator methods.
Definition: BasicBlock.h:231
unsigned NumBlocks
Number of analyzed blocks.
Definition: CodeMetrics.h:63
bool usesDynamicAlloca
True if this function calls alloca (in the C sense).
Definition: CodeMetrics.h:57
bool LLVM_ATTRIBUTE_UNUSED_RESULT empty() const
Definition: SmallVector.h:57
ValTy * getCalledValue() const
getCalledValue - Return the pointer to function that is being called.
Definition: CallSite.h:91
unsigned getUserCost(const User *U) const
Estimate the cost of a given IR user when lowered.
void analyzeBasicBlock(const BasicBlock *BB, const TargetTransformInfo &TTI, SmallPtrSetImpl< const Value * > &EphValues)
Add information about a block to the current state.
LLVM Basic Block Representation.
Definition: BasicBlock.h:65
FunTy * getCalledFunction() const
getCalledFunction - Return the function being called if this is a direct call, otherwise return null ...
Definition: CallSite.h:99
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Definition: SmallPtrSet.h:264
bool contains(const LoopT *L) const
contains - Return true if the specified loop is contained within in this loop.
Definition: LoopInfo.h:105
MutableArrayRef< WeakVH > assumptions()
Access the list of assumption handles currently tracked for this fuction.
iterator erase(iterator I)
Definition: SmallVector.h:455
DenseMap< const BasicBlock *, unsigned > NumBBInsts
Keeps track of basic block code size estimates.
Definition: CodeMetrics.h:66
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
Definition: SmallPtrSet.h:299
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
iterator end()
Definition: BasicBlock.h:233
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:861
bool isNoInline() const
Return true if the call should not be inlined.
Definition: CallSite.h:270
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:123
iterator_range< user_iterator > users()
Definition: Value.h:300
static void completeEphemeralValues(SmallVector< const Value *, 16 > &WorkSet, SmallPtrSetImpl< const Value * > &EphValues)
Definition: CodeMetrics.cpp:30
ImmutableCallSite - establish a view to a call site for examination.
Definition: CallSite.h:418
#define I(x, y, z)
Definition: MD5.cpp:54
TerminatorInst * getTerminator()
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
Definition: BasicBlock.cpp:124
unsigned NumRets
How many 'ret' instructions the blocks contain.
Definition: CodeMetrics.h:83
bool isLoweredToCall(const Function *F) const
Test whether calls to a function lower to actual program function calls.
LLVM Value Representation.
Definition: Value.h:69
InvokeInst - Invoke instruction.
#define DEBUG(X)
Definition: Debug.h:92
bool isSafeToSpeculativelyExecute(const Value *V, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, const TargetLibraryInfo *TLI=nullptr)
isSafeToSpeculativelyExecute - Return true if the instruction does not have any effects besides calcu...
This pass exposes codegen information to IR-level passes.
static void collectEphemeralValues(const Loop *L, AssumptionCache *AC, SmallPtrSetImpl< const Value * > &EphValues)
Collect a loop's ephemeral values (those used only by an assume or similar intrinsics in the loop)...
Definition: CodeMetrics.cpp:70
unsigned NumInsts
Number of instructions in the analyzed blocks.
Definition: CodeMetrics.h:60
const BasicBlock * getParent() const
Definition: Instruction.h:72
AllocaInst - an instruction to allocate memory on the stack.
Definition: Instructions.h:76