LLVM  8.0.0svn
ConstantHoisting.h
Go to the documentation of this file.
1 //==- ConstantHoisting.h - Prepare code for expensive constants --*- C++ -*-==//
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 pass identifies expensive constants to hoist and coalesces them to
11 // better prepare it for SelectionDAG-based code generation. This works around
12 // the limitations of the basic-block-at-a-time approach.
13 //
14 // First it scans all instructions for integer constants and calculates its
15 // cost. If the constant can be folded into the instruction (the cost is
16 // TCC_Free) or the cost is just a simple operation (TCC_BASIC), then we don't
17 // consider it expensive and leave it alone. This is the default behavior and
18 // the default implementation of getIntImmCost will always return TCC_Free.
19 //
20 // If the cost is more than TCC_BASIC, then the integer constant can't be folded
21 // into the instruction and it might be beneficial to hoist the constant.
22 // Similar constants are coalesced to reduce register pressure and
23 // materialization code.
24 //
25 // When a constant is hoisted, it is also hidden behind a bitcast to force it to
26 // be live-out of the basic block. Otherwise the constant would be just
27 // duplicated and each basic block would have its own copy in the SelectionDAG.
28 // The SelectionDAG recognizes such constants as opaque and doesn't perform
29 // certain transformations on them, which would create a new expensive constant.
30 //
31 // This optimization is only applied to integer constants in instructions and
32 // simple (this means not nested) constant cast expressions. For example:
33 // %0 = load i64* inttoptr (i64 big_constant to i64*)
34 //
35 //===----------------------------------------------------------------------===//
36 
37 #ifndef LLVM_TRANSFORMS_SCALAR_CONSTANTHOISTING_H
38 #define LLVM_TRANSFORMS_SCALAR_CONSTANTHOISTING_H
39 
40 #include "llvm/ADT/DenseMap.h"
41 #include "llvm/ADT/PointerUnion.h"
42 #include "llvm/ADT/SmallPtrSet.h"
43 #include "llvm/ADT/SmallVector.h"
44 #include "llvm/IR/PassManager.h"
45 #include <algorithm>
46 #include <vector>
47 
48 namespace llvm {
49 
50 class BasicBlock;
51 class BlockFrequencyInfo;
52 class Constant;
53 class ConstantInt;
54 class ConstantExpr;
55 class DominatorTree;
56 class Function;
57 class GlobalVariable;
58 class Instruction;
59 class TargetTransformInfo;
60 
61 /// A private "module" namespace for types and utilities used by
62 /// ConstantHoisting. These are implementation details and should not be used by
63 /// clients.
64 namespace consthoist {
65 
66 /// Keeps track of the user of a constant and the operand index where the
67 /// constant is used.
68 struct ConstantUser {
70  unsigned OpndIdx;
71 
72  ConstantUser(Instruction *Inst, unsigned Idx) : Inst(Inst), OpndIdx(Idx) {}
73 };
74 
76 
77 /// Keeps track of a constant candidate and its uses.
80  // If the candidate is a ConstantExpr (currely only constant GEP expressions
81  // whose base pointers are GlobalVariables are supported), ConstInt records
82  // its offset from the base GV, ConstExpr tracks the candidate GEP expr.
85  unsigned CumulativeCost = 0;
86 
87  ConstantCandidate(ConstantInt *ConstInt, ConstantExpr *ConstExpr=nullptr) :
88  ConstInt(ConstInt), ConstExpr(ConstExpr) {}
89 
90  /// Add the user to the use list and update the cost.
91  void addUser(Instruction *Inst, unsigned Idx, unsigned Cost) {
92  CumulativeCost += Cost;
93  Uses.push_back(ConstantUser(Inst, Idx));
94  }
95 };
96 
97 /// This represents a constant that has been rebased with respect to a
98 /// base constant. The difference to the base constant is recorded in Offset.
103 
105  Type *Ty=nullptr) : Uses(std::move(Uses)), Offset(Offset), Ty(Ty) {}
106 };
107 
109 
110 /// A base constant and all its rebased constants.
111 struct ConstantInfo {
112  // If the candidate is a ConstantExpr (currely only constant GEP expressions
113  // whose base pointers are GlobalVariables are supported), ConstInt records
114  // its offset from the base GV, ConstExpr tracks the candidate GEP expr.
118 };
119 
120 } // end namespace consthoist
121 
122 class ConstantHoistingPass : public PassInfoMixin<ConstantHoistingPass> {
123 public:
125 
126  // Glue for old PM.
129 
130  void releaseMemory() {
131  ClonedCastMap.clear();
132  ConstIntCandVec.clear();
133  for (auto MapEntry : ConstGEPCandMap)
134  MapEntry.second.clear();
135  ConstGEPCandMap.clear();
136  ConstIntInfoVec.clear();
137  for (auto MapEntry : ConstGEPInfoMap)
138  MapEntry.second.clear();
139  ConstGEPInfoMap.clear();
140  }
141 
142 private:
145 
146  const TargetTransformInfo *TTI;
147  DominatorTree *DT;
149  LLVMContext *Ctx;
150  const DataLayout *DL;
151  BasicBlock *Entry;
152 
153  /// Keeps track of constant candidates found in the function.
154  using ConstCandVecType = std::vector<consthoist::ConstantCandidate>;
156  ConstCandVecType ConstIntCandVec;
157  GVCandVecMapType ConstGEPCandMap;
158 
159  /// These are the final constants we decided to hoist.
162  ConstInfoVecType ConstIntInfoVec;
163  GVInfoVecMapType ConstGEPInfoMap;
164 
165  /// Keep track of cast instructions we already cloned.
167 
168  Instruction *findMatInsertPt(Instruction *Inst, unsigned Idx = ~0U) const;
170  findConstantInsertionPoint(const consthoist::ConstantInfo &ConstInfo) const;
171  void collectConstantCandidates(ConstCandMapType &ConstCandMap,
172  Instruction *Inst, unsigned Idx,
173  ConstantInt *ConstInt);
174  void collectConstantCandidates(ConstCandMapType &ConstCandMap,
175  Instruction *Inst, unsigned Idx,
176  ConstantExpr *ConstExpr);
177  void collectConstantCandidates(ConstCandMapType &ConstCandMap,
178  Instruction *Inst, unsigned Idx);
179  void collectConstantCandidates(ConstCandMapType &ConstCandMap,
180  Instruction *Inst);
181  void collectConstantCandidates(Function &Fn);
182  void findAndMakeBaseConstant(ConstCandVecType::iterator S,
183  ConstCandVecType::iterator E,
185  unsigned maximizeConstantsInRange(ConstCandVecType::iterator S,
186  ConstCandVecType::iterator E,
187  ConstCandVecType::iterator &MaxCostItr);
188  // If BaseGV is nullptr, find base among Constant Integer candidates;
189  // otherwise find base among constant GEPs sharing BaseGV as base pointer.
190  void findBaseConstants(GlobalVariable *BaseGV);
191  void emitBaseConstants(Instruction *Base, Constant *Offset, Type *Ty,
192  const consthoist::ConstantUser &ConstUser);
193  // If BaseGV is nullptr, emit Constant Integer base; otherwise emit
194  // constant GEP base.
195  bool emitBaseConstants(GlobalVariable *BaseGV);
196  void deleteDeadCastInst() const;
197  bool optimizeConstants(Function &Fn);
198 };
199 
200 } // end namespace llvm
201 
202 #endif // LLVM_TRANSFORMS_SCALAR_CONSTANTHOISTING_H
void push_back(const T &Elt)
Definition: SmallVector.h:218
A parsed version of the target data layout string in and methods for querying it. ...
Definition: DataLayout.h:111
static bool runImpl(Function &F, TargetLibraryInfo &TLI, DominatorTree &DT)
This is the entry point for all transforms.
ConstantCandidate(ConstantInt *ConstInt, ConstantExpr *ConstExpr=nullptr)
A base constant and all its rebased constants.
Compute iterated dominance frontiers using a linear time algorithm.
Definition: AllocatorList.h:24
Various leaf nodes.
Definition: ISDOpcodes.h:60
Keeps track of a constant candidate and its uses.
void addUser(Instruction *Inst, unsigned Idx, unsigned Cost)
Add the user to the use list and update the cost.
F(f)
This represents a constant that has been rebased with respect to a base constant. ...
Definition: BitVector.h:938
A constant value that is initialized with an expression using other constant values.
Definition: Constants.h:885
A CRTP mix-in to automatically provide informational APIs needed for passes.
Definition: PassManager.h:366
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
Definition: Dominators.h:145
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
A set of analyses that are preserved following a run of a transformation pass.
Definition: PassManager.h:154
LLVM Basic Block Representation.
Definition: BasicBlock.h:59
The instances of the Type class are immutable: once they are created, they are never changed...
Definition: Type.h:46
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:69
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This is an important base class in LLVM.
Definition: Constant.h:42
Keeps track of the user of a constant and the operand index where the constant is used...
RebasedConstantInfo(ConstantUseListType &&Uses, Constant *Offset, Type *Ty=nullptr)
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
Definition: SmallPtrSet.h:418
This is the shared class of boolean and integer constants.
Definition: Constants.h:84
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
ConstantUser(Instruction *Inst, unsigned Idx)
A container for analyses that lazily runs them and caches their results.
RebasedConstantListType RebasedConstants
This header defines various interfaces for pass management in LLVM.
A discriminated union of two pointer types, with the discriminator in the low bit of the pointer...
Definition: PointerUnion.h:87