LLVM  8.0.1
BDCE.cpp
Go to the documentation of this file.
1 //===---- BDCE.cpp - Bit-tracking dead code elimination -------------------===//
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 the Bit-Tracking Dead Code Elimination pass. Some
11 // instructions (shifts, some ands, ors, etc.) kill some of their input bits.
12 // We track these dead bits and remove instructions that compute only these
13 // dead bits.
14 //
15 //===----------------------------------------------------------------------===//
16 
18 #include "llvm/ADT/SmallPtrSet.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/ADT/Statistic.h"
24 #include "llvm/IR/InstIterator.h"
25 #include "llvm/IR/Instructions.h"
26 #include "llvm/Pass.h"
27 #include "llvm/Support/Debug.h"
29 #include "llvm/Transforms/Scalar.h"
30 using namespace llvm;
31 
32 #define DEBUG_TYPE "bdce"
33 
34 STATISTIC(NumRemoved, "Number of instructions removed (unused)");
35 STATISTIC(NumSimplified, "Number of instructions trivialized (dead bits)");
36 
37 /// If an instruction is trivialized (dead), then the chain of users of that
38 /// instruction may need to be cleared of assumptions that can no longer be
39 /// guaranteed correct.
42  "Trivializing a non-integer value?");
43 
44  // Initialize the worklist with eligible direct users.
46  for (User *JU : I->users()) {
47  // If all bits of a user are demanded, then we know that nothing below that
48  // in the def-use chain needs to be changed.
49  auto *J = dyn_cast<Instruction>(JU);
50  if (J && J->getType()->isIntOrIntVectorTy() &&
52  WorkList.push_back(J);
53 
54  // Note that we need to check for non-int types above before asking for
55  // demanded bits. Normally, the only way to reach an instruction with an
56  // non-int type is via an instruction that has side effects (or otherwise
57  // will demand its input bits). However, if we have a readnone function
58  // that returns an unsized type (e.g., void), we must avoid asking for the
59  // demanded bits of the function call's return value. A void-returning
60  // readnone function is always dead (and so we can stop walking the use/def
61  // chain here), but the check is necessary to avoid asserting.
62  }
63 
64  // DFS through subsequent users while tracking visits to avoid cycles.
66  while (!WorkList.empty()) {
67  Instruction *J = WorkList.pop_back_val();
68 
69  // NSW, NUW, and exact are based on operands that might have changed.
71 
72  // We do not have to worry about llvm.assume or range metadata:
73  // 1. llvm.assume demands its operand, so trivializing can't change it.
74  // 2. range metadata only applies to memory accesses which demand all bits.
75 
76  Visited.insert(J);
77 
78  for (User *KU : J->users()) {
79  // If all bits of a user are demanded, then we know that nothing below
80  // that in the def-use chain needs to be changed.
81  auto *K = dyn_cast<Instruction>(KU);
82  if (K && !Visited.count(K) && K->getType()->isIntOrIntVectorTy() &&
84  WorkList.push_back(K);
85  }
86  }
87 }
88 
89 static bool bitTrackingDCE(Function &F, DemandedBits &DB) {
91  bool Changed = false;
92  for (Instruction &I : instructions(F)) {
93  // If the instruction has side effects and no non-dbg uses,
94  // skip it. This way we avoid computing known bits on an instruction
95  // that will not help us.
96  if (I.mayHaveSideEffects() && I.use_empty())
97  continue;
98 
99  // Remove instructions that are dead, either because they were not reached
100  // during analysis or have no demanded bits.
101  if (DB.isInstructionDead(&I) ||
102  (I.getType()->isIntOrIntVectorTy() &&
103  DB.getDemandedBits(&I).isNullValue() &&
106  Worklist.push_back(&I);
107  I.dropAllReferences();
108  Changed = true;
109  continue;
110  }
111 
112  for (Use &U : I.operands()) {
113  // DemandedBits only detects dead integer uses.
114  if (!U->getType()->isIntOrIntVectorTy())
115  continue;
116 
117  if (!isa<Instruction>(U) && !isa<Argument>(U))
118  continue;
119 
120  if (!DB.isUseDead(&U))
121  continue;
122 
123  LLVM_DEBUG(dbgs() << "BDCE: Trivializing: " << U << " (all bits dead)\n");
124 
126 
127  // FIXME: In theory we could substitute undef here instead of zero.
128  // This should be reconsidered once we settle on the semantics of
129  // undef, poison, etc.
130  U.set(ConstantInt::get(U->getType(), 0));
131  ++NumSimplified;
132  Changed = true;
133  }
134  }
135 
136  for (Instruction *&I : Worklist) {
137  ++NumRemoved;
138  I->eraseFromParent();
139  }
140 
141  return Changed;
142 }
143 
145  auto &DB = AM.getResult<DemandedBitsAnalysis>(F);
146  if (!bitTrackingDCE(F, DB))
147  return PreservedAnalyses::all();
148 
150  PA.preserveSet<CFGAnalyses>();
151  PA.preserve<GlobalsAA>();
152  return PA;
153 }
154 
155 namespace {
156 struct BDCELegacyPass : public FunctionPass {
157  static char ID; // Pass identification, replacement for typeid
158  BDCELegacyPass() : FunctionPass(ID) {
160  }
161 
162  bool runOnFunction(Function &F) override {
163  if (skipFunction(F))
164  return false;
165  auto &DB = getAnalysis<DemandedBitsWrapperPass>().getDemandedBits();
166  return bitTrackingDCE(F, DB);
167  }
168 
169  void getAnalysisUsage(AnalysisUsage &AU) const override {
170  AU.setPreservesCFG();
173  }
174 };
175 }
176 
177 char BDCELegacyPass::ID = 0;
178 INITIALIZE_PASS_BEGIN(BDCELegacyPass, "bdce",
179  "Bit-Tracking Dead Code Elimination", false, false)
181 INITIALIZE_PASS_END(BDCELegacyPass, "bdce",
182  "Bit-Tracking Dead Code Elimination", false, false)
183 
184 FunctionPass *llvm::createBitTrackingDCEPass() { return new BDCELegacyPass(); }
Legacy wrapper pass to provide the GlobalsAAResult object.
void initializeBDCELegacyPassPass(PassRegistry &)
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Definition: PassManager.h:770
This class represents lattice values for constants.
Definition: AllocatorList.h:24
This is the interface for a simple mod/ref and alias analysis over globals.
bool isInstructionDead(Instruction *I)
Return true if, during analysis, I could not be reached.
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
Definition: BDCE.cpp:144
bool salvageDebugInfo(Instruction &I)
Assuming the instruction I is going to be deleted, attempt to salvage debug users of I by writing the...
Definition: Local.cpp:1591
STATISTIC(NumFunctions, "Total number of functions")
F(f)
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition: PassSupport.h:51
static bool bitTrackingDCE(Function &F, DemandedBits &DB)
Definition: BDCE.cpp:89
A Use represents the edge between a Value definition and its users.
Definition: Use.h:56
An analysis that produces DemandedBits for a function.
Definition: DemandedBits.h:107
void dropPoisonGeneratingFlags()
Drops flags that may cause this instruction to evaluate to poison despite having non-poison inputs...
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:245
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
Definition: Type.h:203
static bool runOnFunction(Function &F, bool PostInlining)
bool isAllOnesValue() const
Determine if all bits are set.
Definition: APInt.h:396
A set of analyses that are preserved following a run of a transformation pass.
Definition: PassManager.h:154
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:371
Represent the analysis usage information of a pass.
Analysis pass providing a never-invalidated alias analysis result.
FunctionPass * createBitTrackingDCEPass()
Definition: BDCE.cpp:184
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:285
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
Definition: SmallPtrSet.h:382
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: PassManager.h:160
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
Bit Tracking Dead Code Elimination
Definition: BDCE.cpp:181
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
Definition: SmallPtrSet.h:418
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:847
static Constant * get(Type *Ty, uint64_t V, bool isSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
Definition: Constants.cpp:622
void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition: Pass.cpp:286
static void clearAssumptionsOfUsers(Instruction *I, DemandedBits &DB)
If an instruction is trivialized (dead), then the chain of users of that instruction may need to be c...
Definition: BDCE.cpp:40
APInt getDemandedBits(Instruction *I)
Return the bits demanded from instruction I.
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:133
bdce
Definition: BDCE.cpp:181
iterator_range< user_iterator > users()
Definition: Value.h:400
Represents analyses that only rely on functions&#39; control flow.
Definition: PassManager.h:115
void preserveSet()
Mark an analysis set as preserved.
Definition: PassManager.h:190
#define I(x, y, z)
Definition: MD5.cpp:58
INITIALIZE_PASS_BEGIN(BDCELegacyPass, "bdce", "Bit-Tracking Dead Code Elimination", false, false) INITIALIZE_PASS_END(BDCELegacyPass
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Definition: Casting.h:323
void preserve()
Mark an analysis as preserved.
Definition: PassManager.h:175
bool isUseDead(Use *U)
Return whether this use is dead by means of not having any demanded bits.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
bool wouldInstructionBeTriviallyDead(Instruction *I, const TargetLibraryInfo *TLI=nullptr)
Return true if the result produced by the instruction would have no side effects if it was not used...
Definition: Local.cpp:356
inst_range instructions(Function *F)
Definition: InstIterator.h:134
A container for analyses that lazily runs them and caches their results.
#define LLVM_DEBUG(X)
Definition: Debug.h:123
bool isNullValue() const
Determine if all bits are clear.
Definition: APInt.h:406