12bb61ba2SHal Finkel //===---- BDCE.cpp - Bit-tracking dead code elimination -------------------===//
22bb61ba2SHal Finkel //
32bb61ba2SHal Finkel //                     The LLVM Compiler Infrastructure
42bb61ba2SHal Finkel //
52bb61ba2SHal Finkel // This file is distributed under the University of Illinois Open Source
62bb61ba2SHal Finkel // License. See LICENSE.TXT for details.
72bb61ba2SHal Finkel //
82bb61ba2SHal Finkel //===----------------------------------------------------------------------===//
92bb61ba2SHal Finkel //
102bb61ba2SHal Finkel // This file implements the Bit-Tracking Dead Code Elimination pass. Some
112bb61ba2SHal Finkel // instructions (shifts, some ands, ors, etc.) kill some of their input bits.
122bb61ba2SHal Finkel // We track these dead bits and remove instructions that compute only these
132bb61ba2SHal Finkel // dead bits.
142bb61ba2SHal Finkel //
152bb61ba2SHal Finkel //===----------------------------------------------------------------------===//
162bb61ba2SHal Finkel 
17655a145eSDavide Italiano #include "llvm/Transforms/Scalar/BDCE.h"
18fe346f9fSSanjay Patel #include "llvm/ADT/SmallPtrSet.h"
192bb61ba2SHal Finkel #include "llvm/ADT/SmallVector.h"
202bb61ba2SHal Finkel #include "llvm/ADT/Statistic.h"
2187405c7fSJames Molloy #include "llvm/Analysis/DemandedBits.h"
22655a145eSDavide Italiano #include "llvm/Analysis/GlobalsModRef.h"
2331b98d2eSDavid Blaikie #include "llvm/Transforms/Utils/Local.h"
242bb61ba2SHal Finkel #include "llvm/IR/InstIterator.h"
252bb61ba2SHal Finkel #include "llvm/IR/Instructions.h"
262bb61ba2SHal Finkel #include "llvm/Pass.h"
272bb61ba2SHal Finkel #include "llvm/Support/Debug.h"
282bb61ba2SHal Finkel #include "llvm/Support/raw_ostream.h"
29655a145eSDavide Italiano #include "llvm/Transforms/Scalar.h"
302bb61ba2SHal Finkel using namespace llvm;
312bb61ba2SHal Finkel 
322bb61ba2SHal Finkel #define DEBUG_TYPE "bdce"
332bb61ba2SHal Finkel 
342bb61ba2SHal Finkel STATISTIC(NumRemoved, "Number of instructions removed (unused)");
352bb61ba2SHal Finkel STATISTIC(NumSimplified, "Number of instructions trivialized (dead bits)");
362bb61ba2SHal Finkel 
37fe346f9fSSanjay Patel /// If an instruction is trivialized (dead), then the chain of users of that
38fe346f9fSSanjay Patel /// instruction may need to be cleared of assumptions that can no longer be
39fe346f9fSSanjay Patel /// guaranteed correct.
40fe346f9fSSanjay Patel static void clearAssumptionsOfUsers(Instruction *I, DemandedBits &DB) {
41*110cf052SNikita Popov   assert(I->getType()->isIntOrIntVectorTy() &&
42*110cf052SNikita Popov          "Trivializing a non-integer value?");
43fe346f9fSSanjay Patel 
44fe346f9fSSanjay Patel   // Initialize the worklist with eligible direct users.
45fe346f9fSSanjay Patel   SmallVector<Instruction *, 16> WorkList;
46fe346f9fSSanjay Patel   for (User *JU : I->users()) {
47a1067d9bSSanjay Patel     // If all bits of a user are demanded, then we know that nothing below that
48a1067d9bSSanjay Patel     // in the def-use chain needs to be changed.
49fe346f9fSSanjay Patel     auto *J = dyn_cast<Instruction>(JU);
50*110cf052SNikita Popov     if (J && J->getType()->isIntOrIntVectorTy() &&
519e54b709SHal Finkel         !DB.getDemandedBits(J).isAllOnesValue())
52fe346f9fSSanjay Patel       WorkList.push_back(J);
539e54b709SHal Finkel 
54*110cf052SNikita Popov     // Note that we need to check for non-int types above before asking for
559e54b709SHal Finkel     // demanded bits. Normally, the only way to reach an instruction with an
56*110cf052SNikita Popov     // non-int type is via an instruction that has side effects (or otherwise
579e54b709SHal Finkel     // will demand its input bits). However, if we have a readnone function
589e54b709SHal Finkel     // that returns an unsized type (e.g., void), we must avoid asking for the
599e54b709SHal Finkel     // demanded bits of the function call's return value. A void-returning
609e54b709SHal Finkel     // readnone function is always dead (and so we can stop walking the use/def
619e54b709SHal Finkel     // chain here), but the check is necessary to avoid asserting.
62fe346f9fSSanjay Patel   }
63fe346f9fSSanjay Patel 
64fe346f9fSSanjay Patel   // DFS through subsequent users while tracking visits to avoid cycles.
65fe346f9fSSanjay Patel   SmallPtrSet<Instruction *, 16> Visited;
66fe346f9fSSanjay Patel   while (!WorkList.empty()) {
67fe346f9fSSanjay Patel     Instruction *J = WorkList.pop_back_val();
68fe346f9fSSanjay Patel 
69fe346f9fSSanjay Patel     // NSW, NUW, and exact are based on operands that might have changed.
70fe346f9fSSanjay Patel     J->dropPoisonGeneratingFlags();
71fe346f9fSSanjay Patel 
72fe346f9fSSanjay Patel     // We do not have to worry about llvm.assume or range metadata:
73fe346f9fSSanjay Patel     // 1. llvm.assume demands its operand, so trivializing can't change it.
74fe346f9fSSanjay Patel     // 2. range metadata only applies to memory accesses which demand all bits.
75fe346f9fSSanjay Patel 
76fe346f9fSSanjay Patel     Visited.insert(J);
77fe346f9fSSanjay Patel 
78fe346f9fSSanjay Patel     for (User *KU : J->users()) {
79a1067d9bSSanjay Patel       // If all bits of a user are demanded, then we know that nothing below
80a1067d9bSSanjay Patel       // that in the def-use chain needs to be changed.
81fe346f9fSSanjay Patel       auto *K = dyn_cast<Instruction>(KU);
82*110cf052SNikita Popov       if (K && !Visited.count(K) && K->getType()->isIntOrIntVectorTy() &&
839e54b709SHal Finkel           !DB.getDemandedBits(K).isAllOnesValue())
84fe346f9fSSanjay Patel         WorkList.push_back(K);
85fe346f9fSSanjay Patel     }
86fe346f9fSSanjay Patel   }
87fe346f9fSSanjay Patel }
88fe346f9fSSanjay Patel 
89655a145eSDavide Italiano static bool bitTrackingDCE(Function &F, DemandedBits &DB) {
902bb61ba2SHal Finkel   SmallVector<Instruction*, 128> Worklist;
912bb61ba2SHal Finkel   bool Changed = false;
9278199518SNico Rieck   for (Instruction &I : instructions(F)) {
93043e6613SDavide Italiano     // If the instruction has side effects and no non-dbg uses,
941ed53963SDavide Italiano     // skip it. This way we avoid computing known bits on an instruction
951ed53963SDavide Italiano     // that will not help us.
96043e6613SDavide Italiano     if (I.mayHaveSideEffects() && I.use_empty())
97043e6613SDavide Italiano       continue;
98043e6613SDavide Italiano 
99*110cf052SNikita Popov     if (I.getType()->isIntOrIntVectorTy() &&
10087405c7fSJames Molloy         !DB.getDemandedBits(&I).getBoolValue()) {
1012bb61ba2SHal Finkel       // For live instructions that have all dead bits, first make them dead by
1022bb61ba2SHal Finkel       // replacing all uses with something else. Then, if they don't need to
1032bb61ba2SHal Finkel       // remain live (because they have side effects, etc.) we can remove them.
104d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "BDCE: Trivializing: " << I << " (all bits dead)\n");
105fe346f9fSSanjay Patel 
106fe346f9fSSanjay Patel       clearAssumptionsOfUsers(&I, DB);
107fe346f9fSSanjay Patel 
1082bb61ba2SHal Finkel       // FIXME: In theory we could substitute undef here instead of zero.
1092bb61ba2SHal Finkel       // This should be reconsidered once we settle on the semantics of
1102bb61ba2SHal Finkel       // undef, poison, etc.
1112bb61ba2SHal Finkel       Value *Zero = ConstantInt::get(I.getType(), 0);
1122bb61ba2SHal Finkel       ++NumSimplified;
1131ed53963SDavide Italiano       I.replaceNonMetadataUsesWith(Zero);
1142bb61ba2SHal Finkel       Changed = true;
1152bb61ba2SHal Finkel     }
11687405c7fSJames Molloy     if (!DB.isInstructionDead(&I))
1172bb61ba2SHal Finkel       continue;
1182bb61ba2SHal Finkel 
11956492f91SVedant Kumar     salvageDebugInfo(I);
1202bb61ba2SHal Finkel     Worklist.push_back(&I);
1212bb61ba2SHal Finkel     I.dropAllReferences();
1222bb61ba2SHal Finkel     Changed = true;
1232bb61ba2SHal Finkel   }
1242bb61ba2SHal Finkel 
1252bb61ba2SHal Finkel   for (Instruction *&I : Worklist) {
1262bb61ba2SHal Finkel     ++NumRemoved;
1272bb61ba2SHal Finkel     I->eraseFromParent();
1282bb61ba2SHal Finkel   }
1292bb61ba2SHal Finkel 
1302bb61ba2SHal Finkel   return Changed;
1312bb61ba2SHal Finkel }
1322bb61ba2SHal Finkel 
133655a145eSDavide Italiano PreservedAnalyses BDCEPass::run(Function &F, FunctionAnalysisManager &AM) {
134655a145eSDavide Italiano   auto &DB = AM.getResult<DemandedBitsAnalysis>(F);
135bdc29714SDavide Italiano   if (!bitTrackingDCE(F, DB))
136655a145eSDavide Italiano     return PreservedAnalyses::all();
137bdc29714SDavide Italiano 
138ca68a3ecSChandler Carruth   PreservedAnalyses PA;
139ca68a3ecSChandler Carruth   PA.preserveSet<CFGAnalyses>();
140bdc29714SDavide Italiano   PA.preserve<GlobalsAA>();
141bdc29714SDavide Italiano   return PA;
1422bb61ba2SHal Finkel }
1432bb61ba2SHal Finkel 
144655a145eSDavide Italiano namespace {
145655a145eSDavide Italiano struct BDCELegacyPass : public FunctionPass {
146655a145eSDavide Italiano   static char ID; // Pass identification, replacement for typeid
147655a145eSDavide Italiano   BDCELegacyPass() : FunctionPass(ID) {
148655a145eSDavide Italiano     initializeBDCELegacyPassPass(*PassRegistry::getPassRegistry());
149655a145eSDavide Italiano   }
150655a145eSDavide Italiano 
151655a145eSDavide Italiano   bool runOnFunction(Function &F) override {
152655a145eSDavide Italiano     if (skipFunction(F))
153655a145eSDavide Italiano       return false;
154655a145eSDavide Italiano     auto &DB = getAnalysis<DemandedBitsWrapperPass>().getDemandedBits();
155655a145eSDavide Italiano     return bitTrackingDCE(F, DB);
156655a145eSDavide Italiano   }
157655a145eSDavide Italiano 
158655a145eSDavide Italiano   void getAnalysisUsage(AnalysisUsage &AU) const override {
159655a145eSDavide Italiano     AU.setPreservesCFG();
160655a145eSDavide Italiano     AU.addRequired<DemandedBitsWrapperPass>();
161655a145eSDavide Italiano     AU.addPreserved<GlobalsAAWrapperPass>();
162655a145eSDavide Italiano   }
163655a145eSDavide Italiano };
164655a145eSDavide Italiano }
165655a145eSDavide Italiano 
166655a145eSDavide Italiano char BDCELegacyPass::ID = 0;
167655a145eSDavide Italiano INITIALIZE_PASS_BEGIN(BDCELegacyPass, "bdce",
168655a145eSDavide Italiano                       "Bit-Tracking Dead Code Elimination", false, false)
169655a145eSDavide Italiano INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass)
170655a145eSDavide Italiano INITIALIZE_PASS_END(BDCELegacyPass, "bdce",
171655a145eSDavide Italiano                     "Bit-Tracking Dead Code Elimination", false, false)
172655a145eSDavide Italiano 
173655a145eSDavide Italiano FunctionPass *llvm::createBitTrackingDCEPass() { return new BDCELegacyPass(); }
174