ConstantHoisting.h 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //==- ConstantHoisting.h - Prepare code for expensive constants --*- C++ -*-==//
  7. //
  8. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  9. // See https://llvm.org/LICENSE.txt for license information.
  10. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  11. //
  12. //===----------------------------------------------------------------------===//
  13. //
  14. // This pass identifies expensive constants to hoist and coalesces them to
  15. // better prepare it for SelectionDAG-based code generation. This works around
  16. // the limitations of the basic-block-at-a-time approach.
  17. //
  18. // First it scans all instructions for integer constants and calculates its
  19. // cost. If the constant can be folded into the instruction (the cost is
  20. // TCC_Free) or the cost is just a simple operation (TCC_BASIC), then we don't
  21. // consider it expensive and leave it alone. This is the default behavior and
  22. // the default implementation of getIntImmCostInst will always return TCC_Free.
  23. //
  24. // If the cost is more than TCC_BASIC, then the integer constant can't be folded
  25. // into the instruction and it might be beneficial to hoist the constant.
  26. // Similar constants are coalesced to reduce register pressure and
  27. // materialization code.
  28. //
  29. // When a constant is hoisted, it is also hidden behind a bitcast to force it to
  30. // be live-out of the basic block. Otherwise the constant would be just
  31. // duplicated and each basic block would have its own copy in the SelectionDAG.
  32. // The SelectionDAG recognizes such constants as opaque and doesn't perform
  33. // certain transformations on them, which would create a new expensive constant.
  34. //
  35. // This optimization is only applied to integer constants in instructions and
  36. // simple (this means not nested) constant cast expressions. For example:
  37. // %0 = load i64* inttoptr (i64 big_constant to i64*)
  38. //
  39. //===----------------------------------------------------------------------===//
  40. #ifndef LLVM_TRANSFORMS_SCALAR_CONSTANTHOISTING_H
  41. #define LLVM_TRANSFORMS_SCALAR_CONSTANTHOISTING_H
  42. #include "llvm/ADT/DenseMap.h"
  43. #include "llvm/ADT/MapVector.h"
  44. #include "llvm/ADT/PointerUnion.h"
  45. #include "llvm/ADT/SetVector.h"
  46. #include "llvm/ADT/SmallPtrSet.h"
  47. #include "llvm/ADT/SmallVector.h"
  48. #include "llvm/IR/PassManager.h"
  49. #include <algorithm>
  50. #include <vector>
  51. namespace llvm {
  52. class BasicBlock;
  53. class BlockFrequencyInfo;
  54. class Constant;
  55. class ConstantInt;
  56. class ConstantExpr;
  57. class DominatorTree;
  58. class Function;
  59. class GlobalVariable;
  60. class Instruction;
  61. class ProfileSummaryInfo;
  62. class TargetTransformInfo;
  63. /// A private "module" namespace for types and utilities used by
  64. /// ConstantHoisting. These are implementation details and should not be used by
  65. /// clients.
  66. namespace consthoist {
  67. /// Keeps track of the user of a constant and the operand index where the
  68. /// constant is used.
  69. struct ConstantUser {
  70. Instruction *Inst;
  71. unsigned OpndIdx;
  72. ConstantUser(Instruction *Inst, unsigned Idx) : Inst(Inst), OpndIdx(Idx) {}
  73. };
  74. using ConstantUseListType = SmallVector<ConstantUser, 8>;
  75. /// Keeps track of a constant candidate and its uses.
  76. struct ConstantCandidate {
  77. ConstantUseListType Uses;
  78. // If the candidate is a ConstantExpr (currely only constant GEP expressions
  79. // whose base pointers are GlobalVariables are supported), ConstInt records
  80. // its offset from the base GV, ConstExpr tracks the candidate GEP expr.
  81. ConstantInt *ConstInt;
  82. ConstantExpr *ConstExpr;
  83. unsigned CumulativeCost = 0;
  84. ConstantCandidate(ConstantInt *ConstInt, ConstantExpr *ConstExpr=nullptr) :
  85. ConstInt(ConstInt), ConstExpr(ConstExpr) {}
  86. /// Add the user to the use list and update the cost.
  87. void addUser(Instruction *Inst, unsigned Idx, unsigned Cost) {
  88. CumulativeCost += Cost;
  89. Uses.push_back(ConstantUser(Inst, Idx));
  90. }
  91. };
  92. /// This represents a constant that has been rebased with respect to a
  93. /// base constant. The difference to the base constant is recorded in Offset.
  94. struct RebasedConstantInfo {
  95. ConstantUseListType Uses;
  96. Constant *Offset;
  97. Type *Ty;
  98. RebasedConstantInfo(ConstantUseListType &&Uses, Constant *Offset,
  99. Type *Ty=nullptr) : Uses(std::move(Uses)), Offset(Offset), Ty(Ty) {}
  100. };
  101. using RebasedConstantListType = SmallVector<RebasedConstantInfo, 4>;
  102. /// A base constant and all its rebased constants.
  103. struct ConstantInfo {
  104. // If the candidate is a ConstantExpr (currely only constant GEP expressions
  105. // whose base pointers are GlobalVariables are supported), ConstInt records
  106. // its offset from the base GV, ConstExpr tracks the candidate GEP expr.
  107. ConstantInt *BaseInt;
  108. ConstantExpr *BaseExpr;
  109. RebasedConstantListType RebasedConstants;
  110. };
  111. } // end namespace consthoist
  112. class ConstantHoistingPass : public PassInfoMixin<ConstantHoistingPass> {
  113. public:
  114. PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM);
  115. // Glue for old PM.
  116. bool runImpl(Function &F, TargetTransformInfo &TTI, DominatorTree &DT,
  117. BlockFrequencyInfo *BFI, BasicBlock &Entry,
  118. ProfileSummaryInfo *PSI);
  119. void cleanup() {
  120. ClonedCastMap.clear();
  121. ConstIntCandVec.clear();
  122. for (auto MapEntry : ConstGEPCandMap)
  123. MapEntry.second.clear();
  124. ConstGEPCandMap.clear();
  125. ConstIntInfoVec.clear();
  126. for (auto MapEntry : ConstGEPInfoMap)
  127. MapEntry.second.clear();
  128. ConstGEPInfoMap.clear();
  129. }
  130. private:
  131. using ConstPtrUnionType = PointerUnion<ConstantInt *, ConstantExpr *>;
  132. using ConstCandMapType = DenseMap<ConstPtrUnionType, unsigned>;
  133. const TargetTransformInfo *TTI;
  134. DominatorTree *DT;
  135. BlockFrequencyInfo *BFI;
  136. LLVMContext *Ctx;
  137. const DataLayout *DL;
  138. BasicBlock *Entry;
  139. ProfileSummaryInfo *PSI;
  140. /// Keeps track of constant candidates found in the function.
  141. using ConstCandVecType = std::vector<consthoist::ConstantCandidate>;
  142. using GVCandVecMapType = MapVector<GlobalVariable *, ConstCandVecType>;
  143. ConstCandVecType ConstIntCandVec;
  144. GVCandVecMapType ConstGEPCandMap;
  145. /// These are the final constants we decided to hoist.
  146. using ConstInfoVecType = SmallVector<consthoist::ConstantInfo, 8>;
  147. using GVInfoVecMapType = MapVector<GlobalVariable *, ConstInfoVecType>;
  148. ConstInfoVecType ConstIntInfoVec;
  149. GVInfoVecMapType ConstGEPInfoMap;
  150. /// Keep track of cast instructions we already cloned.
  151. MapVector<Instruction *, Instruction *> ClonedCastMap;
  152. Instruction *findMatInsertPt(Instruction *Inst, unsigned Idx = ~0U) const;
  153. SetVector<Instruction *>
  154. findConstantInsertionPoint(const consthoist::ConstantInfo &ConstInfo) const;
  155. void collectConstantCandidates(ConstCandMapType &ConstCandMap,
  156. Instruction *Inst, unsigned Idx,
  157. ConstantInt *ConstInt);
  158. void collectConstantCandidates(ConstCandMapType &ConstCandMap,
  159. Instruction *Inst, unsigned Idx,
  160. ConstantExpr *ConstExpr);
  161. void collectConstantCandidates(ConstCandMapType &ConstCandMap,
  162. Instruction *Inst, unsigned Idx);
  163. void collectConstantCandidates(ConstCandMapType &ConstCandMap,
  164. Instruction *Inst);
  165. void collectConstantCandidates(Function &Fn);
  166. void findAndMakeBaseConstant(ConstCandVecType::iterator S,
  167. ConstCandVecType::iterator E,
  168. SmallVectorImpl<consthoist::ConstantInfo> &ConstInfoVec);
  169. unsigned maximizeConstantsInRange(ConstCandVecType::iterator S,
  170. ConstCandVecType::iterator E,
  171. ConstCandVecType::iterator &MaxCostItr);
  172. // If BaseGV is nullptr, find base among Constant Integer candidates;
  173. // otherwise find base among constant GEPs sharing BaseGV as base pointer.
  174. void findBaseConstants(GlobalVariable *BaseGV);
  175. void emitBaseConstants(Instruction *Base, Constant *Offset, Type *Ty,
  176. const consthoist::ConstantUser &ConstUser);
  177. // If BaseGV is nullptr, emit Constant Integer base; otherwise emit
  178. // constant GEP base.
  179. bool emitBaseConstants(GlobalVariable *BaseGV);
  180. void deleteDeadCastInst() const;
  181. };
  182. } // end namespace llvm
  183. #endif // LLVM_TRANSFORMS_SCALAR_CONSTANTHOISTING_H
  184. #ifdef __GNUC__
  185. #pragma GCC diagnostic pop
  186. #endif