LLVM  6.0.0svn
SimplifyInstructions.cpp
Go to the documentation of this file.
1 //===------ SimplifyInstructions.cpp - Remove redundant instructions ------===//
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 is a utility pass used for testing the InstructionSimplify analysis.
11 // The analysis is applied to every instruction, and if it simplifies then the
12 // instruction is replaced by the simplification. If you are looking for a pass
13 // that performs serious instruction folding, use the instcombine pass instead.
14 //
15 //===----------------------------------------------------------------------===//
16 
19 #include "llvm/ADT/SmallPtrSet.h"
20 #include "llvm/ADT/Statistic.h"
25 #include "llvm/IR/DataLayout.h"
26 #include "llvm/IR/Dominators.h"
27 #include "llvm/IR/Function.h"
28 #include "llvm/IR/Type.h"
29 #include "llvm/Pass.h"
30 #include "llvm/Transforms/Scalar.h"
32 using namespace llvm;
33 
34 #define DEBUG_TYPE "instsimplify"
35 
36 STATISTIC(NumSimplified, "Number of redundant instructions removed");
37 
38 static bool runImpl(Function &F, const SimplifyQuery &SQ,
40  SmallPtrSet<const Instruction *, 8> S1, S2, *ToSimplify = &S1, *Next = &S2;
41  bool Changed = false;
42 
43  do {
44  for (BasicBlock *BB : depth_first(&F.getEntryBlock())) {
45  // Here be subtlety: the iterator must be incremented before the loop
46  // body (not sure why), so a range-for loop won't work here.
47  for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE;) {
48  Instruction *I = &*BI++;
49  // The first time through the loop ToSimplify is empty and we try to
50  // simplify all instructions. On later iterations ToSimplify is not
51  // empty and we only bother simplifying instructions that are in it.
52  if (!ToSimplify->empty() && !ToSimplify->count(I))
53  continue;
54 
55  // Don't waste time simplifying unused instructions.
56  if (!I->use_empty()) {
57  if (Value *V = SimplifyInstruction(I, SQ, ORE)) {
58  // Mark all uses for resimplification next time round the loop.
59  for (User *U : I->users())
60  Next->insert(cast<Instruction>(U));
61  I->replaceAllUsesWith(V);
62  ++NumSimplified;
63  Changed = true;
64  }
65  }
67  // RecursivelyDeleteTriviallyDeadInstruction can remove more than one
68  // instruction, so simply incrementing the iterator does not work.
69  // When instructions get deleted re-iterate instead.
70  BI = BB->begin();
71  BE = BB->end();
72  Changed = true;
73  }
74  }
75  }
76 
77  // Place the list of instructions to simplify on the next loop iteration
78  // into ToSimplify.
79  std::swap(ToSimplify, Next);
80  Next->clear();
81  } while (!ToSimplify->empty());
82 
83  return Changed;
84 }
85 
86 namespace {
87  struct InstSimplifier : public FunctionPass {
88  static char ID; // Pass identification, replacement for typeid
89  InstSimplifier() : FunctionPass(ID) {
91  }
92 
93  void getAnalysisUsage(AnalysisUsage &AU) const override {
94  AU.setPreservesCFG();
99  }
100 
101  /// runOnFunction - Remove instructions that simplify.
102  bool runOnFunction(Function &F) override {
103  if (skipFunction(F))
104  return false;
105 
106  const DominatorTree *DT =
107  &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
108  const TargetLibraryInfo *TLI =
109  &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
110  AssumptionCache *AC =
111  &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
113  &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
114  const DataLayout &DL = F.getParent()->getDataLayout();
115  const SimplifyQuery SQ(DL, TLI, DT, AC);
116  return runImpl(F, SQ, ORE);
117  }
118  };
119 }
120 
121 char InstSimplifier::ID = 0;
122 INITIALIZE_PASS_BEGIN(InstSimplifier, "instsimplify",
123  "Remove redundant instructions", false, false)
129  "Remove redundant instructions", false, false)
130 char &llvm::InstructionSimplifierID = InstSimplifier::ID;
131 
132 // Public interface to the simplify instructions pass.
134  return new InstSimplifier();
135 }
136 
139  auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
140  auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
141  auto &AC = AM.getResult<AssumptionAnalysis>(F);
143  const DataLayout &DL = F.getParent()->getDataLayout();
144  const SimplifyQuery SQ(DL, &TLI, &DT, &AC);
145  bool Changed = runImpl(F, SQ, &ORE);
146  if (!Changed)
147  return PreservedAnalyses::all();
148 
150  PA.preserveSet<CFGAnalyses>();
151  return PA;
152 }
A parsed version of the target data layout string in and methods for querying it. ...
Definition: DataLayout.h:109
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:687
Compute iterated dominance frontiers using a linear time algorithm.
Definition: AllocatorList.h:24
static bool runImpl(Function &F, const SimplifyQuery &SQ, OptimizationRemarkEmitter *ORE)
An immutable pass that tracks lazily created AssumptionCache objects.
A cache of .assume calls within a function.
STATISTIC(NumFunctions, "Total number of functions")
Analysis pass which computes a DominatorTree.
Definition: Dominators.h:238
F(f)
const TargetLibraryInfo * TLI
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition: PassSupport.h:51
const DataLayout & getDataLayout() const
Get the data layout for the module&#39;s target platform.
Definition: Module.cpp:361
char & InstructionSimplifierID
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition: Value.cpp:430
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
Definition: Dominators.h:140
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
const BasicBlock & getEntryBlock() const
Definition: Function.h:572
static bool runOnFunction(Function &F, bool PostInlining)
A set of analyses that are preserved following a run of a transformation pass.
Definition: PassManager.h:153
LLVM Basic Block Representation.
Definition: BasicBlock.h:59
LLVM_NODISCARD bool empty() const
Definition: SmallPtrSet.h:92
Represent the analysis usage information of a pass.
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
void initializeInstSimplifierPass(PassRegistry &)
INITIALIZE_PASS_BEGIN(InstSimplifier, "instsimplify", "Remove redundant instructions", false, false) INITIALIZE_PASS_END(InstSimplifier
bool RecursivelyDeleteTriviallyDeadInstructions(Value *V, const TargetLibraryInfo *TLI=nullptr)
If the specified value is a trivially dead instruction, delete it.
Definition: Local.cpp:401
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: PassManager.h:159
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
A function analysis which provides an AssumptionCache.
Iterator for intrusive lists based on ilist_node.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
Definition: SmallPtrSet.h:418
Provides information about what library functions are available for the current target.
void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition: Pass.cpp:285
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition: BitVector.h:923
iterator_range< user_iterator > users()
Definition: Value.h:401
Represents analyses that only rely on functions&#39; control flow.
Definition: PassManager.h:114
void preserveSet()
Mark an analysis set as preserved.
Definition: PassManager.h:189
#define I(x, y, z)
Definition: MD5.cpp:58
Analysis pass providing the TargetLibraryInfo.
iterator_range< df_iterator< T > > depth_first(const T &G)
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:556
LLVM Value Representation.
Definition: Value.h:73
OptimizationRemarkEmitter legacy analysis pass.
inst_range instructions(Function *F)
Definition: InstIterator.h:134
A container for analyses that lazily runs them and caches their results.
Legacy analysis pass which computes a DominatorTree.
Definition: Dominators.h:267
FunctionPass * createInstructionSimplifierPass()
Value * SimplifyInstruction(Instruction *I, const SimplifyQuery &Q, OptimizationRemarkEmitter *ORE=nullptr)
See if we can compute a simplified version of this instruction.
The optimization diagnostic interface.
bool use_empty() const
Definition: Value.h:328