1 //===---- BDCE.cpp - Bit-tracking dead code elimination -------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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
15 //===----------------------------------------------------------------------===//
17 #include "llvm/Transforms/Scalar/BDCE.h"
18 #include "llvm/ADT/SmallPtrSet.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/ADT/Statistic.h"
21 #include "llvm/Analysis/DemandedBits.h"
22 #include "llvm/Analysis/GlobalsModRef.h"
23 #include "llvm/IR/InstIterator.h"
24 #include "llvm/IR/Instructions.h"
25 #include "llvm/Pass.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Support/raw_ostream.h"
28 #include "llvm/Transforms/Scalar.h"
31 #define DEBUG_TYPE "bdce"
33 STATISTIC(NumRemoved, "Number of instructions removed (unused)");
34 STATISTIC(NumSimplified, "Number of instructions trivialized (dead bits)");
36 /// If an instruction is trivialized (dead), then the chain of users of that
37 /// instruction may need to be cleared of assumptions that can no longer be
38 /// guaranteed correct.
39 static void clearAssumptionsOfUsers(Instruction *I, DemandedBits &DB) {
40 assert(I->getType()->isIntegerTy() && "Trivializing a non-integer value?");
42 // Initialize the worklist with eligible direct users.
43 SmallVector<Instruction *, 16> WorkList;
44 for (User *JU : I->users()) {
45 // If all bits of a user are demanded, then we know that nothing below that
46 // in the def-use chain needs to be changed.
47 auto *J = dyn_cast<Instruction>(JU);
48 if (J && J->getType()->isSized() &&
49 !DB.getDemandedBits(J).isAllOnesValue())
50 WorkList.push_back(J);
52 // Note that we need to check for unsized types above before asking for
53 // demanded bits. Normally, the only way to reach an instruction with an
54 // unsized type is via an instruction that has side effects (or otherwise
55 // will demand its input bits). However, if we have a readnone function
56 // that returns an unsized type (e.g., void), we must avoid asking for the
57 // demanded bits of the function call's return value. A void-returning
58 // readnone function is always dead (and so we can stop walking the use/def
59 // chain here), but the check is necessary to avoid asserting.
62 // DFS through subsequent users while tracking visits to avoid cycles.
63 SmallPtrSet<Instruction *, 16> Visited;
64 while (!WorkList.empty()) {
65 Instruction *J = WorkList.pop_back_val();
67 // NSW, NUW, and exact are based on operands that might have changed.
68 J->dropPoisonGeneratingFlags();
70 // We do not have to worry about llvm.assume or range metadata:
71 // 1. llvm.assume demands its operand, so trivializing can't change it.
72 // 2. range metadata only applies to memory accesses which demand all bits.
76 for (User *KU : J->users()) {
77 // If all bits of a user are demanded, then we know that nothing below
78 // that in the def-use chain needs to be changed.
79 auto *K = dyn_cast<Instruction>(KU);
80 if (K && !Visited.count(K) && K->getType()->isSized() &&
81 !DB.getDemandedBits(K).isAllOnesValue())
82 WorkList.push_back(K);
87 static bool bitTrackingDCE(Function &F, DemandedBits &DB) {
88 SmallVector<Instruction*, 128> Worklist;
90 for (Instruction &I : instructions(F)) {
91 // If the instruction has side effects and no non-dbg uses,
92 // skip it. This way we avoid computing known bits on an instruction
93 // that will not help us.
94 if (I.mayHaveSideEffects() && I.use_empty())
97 if (I.getType()->isIntegerTy() &&
98 !DB.getDemandedBits(&I).getBoolValue()) {
99 // For live instructions that have all dead bits, first make them dead by
100 // replacing all uses with something else. Then, if they don't need to
101 // remain live (because they have side effects, etc.) we can remove them.
102 DEBUG(dbgs() << "BDCE: Trivializing: " << I << " (all bits dead)\n");
104 clearAssumptionsOfUsers(&I, DB);
106 // FIXME: In theory we could substitute undef here instead of zero.
107 // This should be reconsidered once we settle on the semantics of
108 // undef, poison, etc.
109 Value *Zero = ConstantInt::get(I.getType(), 0);
111 I.replaceNonMetadataUsesWith(Zero);
114 if (!DB.isInstructionDead(&I))
117 Worklist.push_back(&I);
118 I.dropAllReferences();
122 for (Instruction *&I : Worklist) {
124 I->eraseFromParent();
130 PreservedAnalyses BDCEPass::run(Function &F, FunctionAnalysisManager &AM) {
131 auto &DB = AM.getResult<DemandedBitsAnalysis>(F);
132 if (!bitTrackingDCE(F, DB))
133 return PreservedAnalyses::all();
135 PreservedAnalyses PA;
136 PA.preserveSet<CFGAnalyses>();
137 PA.preserve<GlobalsAA>();
142 struct BDCELegacyPass : public FunctionPass {
143 static char ID; // Pass identification, replacement for typeid
144 BDCELegacyPass() : FunctionPass(ID) {
145 initializeBDCELegacyPassPass(*PassRegistry::getPassRegistry());
148 bool runOnFunction(Function &F) override {
151 auto &DB = getAnalysis<DemandedBitsWrapperPass>().getDemandedBits();
152 return bitTrackingDCE(F, DB);
155 void getAnalysisUsage(AnalysisUsage &AU) const override {
156 AU.setPreservesCFG();
157 AU.addRequired<DemandedBitsWrapperPass>();
158 AU.addPreserved<GlobalsAAWrapperPass>();
163 char BDCELegacyPass::ID = 0;
164 INITIALIZE_PASS_BEGIN(BDCELegacyPass, "bdce",
165 "Bit-Tracking Dead Code Elimination", false, false)
166 INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass)
167 INITIALIZE_PASS_END(BDCELegacyPass, "bdce",
168 "Bit-Tracking Dead Code Elimination", false, false)
170 FunctionPass *llvm::createBitTrackingDCEPass() { return new BDCELegacyPass(); }