25fef5f500ff9d168eb4de86048744e8d247a897
[oota-llvm.git] / lib / Transforms / Scalar / ConstantHoisting.cpp
1 //===- ConstantHoisting.cpp - Prepare code for expensive constants --------===//
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 experessions. For example:
33 // %0 = load i64* inttoptr (i64 big_constant to i64*)
34 //===----------------------------------------------------------------------===//
35
36 #define DEBUG_TYPE "consthoist"
37 #include "llvm/Transforms/Scalar.h"
38 #include "llvm/ADT/SmallSet.h"
39 #include "llvm/ADT/SmallVector.h"
40 #include "llvm/ADT/Statistic.h"
41 #include "llvm/Analysis/TargetTransformInfo.h"
42 #include "llvm/IR/Constants.h"
43 #include "llvm/IR/Dominators.h"
44 #include "llvm/IR/IntrinsicInst.h"
45 #include "llvm/Pass.h"
46 #include "llvm/Support/Debug.h"
47
48 using namespace llvm;
49
50 STATISTIC(NumConstantsHoisted, "Number of constants hoisted");
51 STATISTIC(NumConstantsRebased, "Number of constants rebased");
52
53 namespace {
54 struct ConstantUser;
55 struct RebasedConstantInfo;
56
57 typedef SmallVector<ConstantUser, 8> ConstantUseListType;
58 typedef SmallVector<RebasedConstantInfo, 4> RebasedConstantListType;
59
60 /// \brief Keeps track of the user of a constant and the operand index where the
61 /// constant is used.
62 struct ConstantUser {
63   Instruction *Inst;
64   unsigned OpndIdx;
65
66   ConstantUser(Instruction *Inst, unsigned Idx) : Inst(Inst), OpndIdx(Idx) { }
67 };
68
69 /// \brief Keeps track of a constant candidate and its usees.
70 struct ConstantCandidate {
71   ConstantUseListType Uses;
72   ConstantInt *ConstInt;
73   unsigned CumulativeCost;
74
75   ConstantCandidate(ConstantInt *ConstInt)
76     : ConstInt(ConstInt), CumulativeCost(0) { }
77
78   /// \brief Add the user to the use list and update the cost.
79   void addUser(Instruction *Inst, unsigned Idx, unsigned Cost) {
80     CumulativeCost += Cost;
81     Uses.push_back(ConstantUser(Inst, Idx));
82   }
83 };
84
85 /// \brief This represents a constant that has been rebased with respect to a
86 /// base constant. The difference to the base constant is recorded in Offset.
87 struct RebasedConstantInfo {
88   ConstantUseListType Uses;
89   Constant *Offset;
90
91   RebasedConstantInfo(ConstantUseListType &&Uses, Constant *Offset)
92     : Uses(Uses), Offset(Offset) { }
93 };
94
95 /// \brief A base constant and all its rebased constants.
96 struct ConstantInfo {
97   ConstantInt *BaseConstant;
98   RebasedConstantListType RebasedConstants;
99 };
100
101 /// \brief The constant hoisting pass.
102 class ConstantHoisting : public FunctionPass {
103   typedef DenseMap<ConstantInt *, unsigned> ConstCandMapType;
104   typedef std::vector<ConstantCandidate> ConstCandVecType;
105
106   const TargetTransformInfo *TTI;
107   DominatorTree *DT;
108   BasicBlock *Entry;
109
110   /// Keeps track of constant candidates found in the function.
111   ConstCandMapType ConstCandMap;
112   ConstCandVecType ConstCandVec;
113
114   /// Keep track of cast instructions we already cloned.
115   SmallDenseMap<Instruction *, Instruction *> ClonedCastMap;
116
117   /// These are the final constants we decided to hoist.
118   SmallVector<ConstantInfo, 8> ConstantVec;
119 public:
120   static char ID; // Pass identification, replacement for typeid
121   ConstantHoisting() : FunctionPass(ID), TTI(0), DT(0), Entry(0) {
122     initializeConstantHoistingPass(*PassRegistry::getPassRegistry());
123   }
124
125   bool runOnFunction(Function &Fn) override;
126
127   const char *getPassName() const override { return "Constant Hoisting"; }
128
129   void getAnalysisUsage(AnalysisUsage &AU) const override {
130     AU.setPreservesCFG();
131     AU.addRequired<DominatorTreeWrapperPass>();
132     AU.addRequired<TargetTransformInfo>();
133   }
134
135 private:
136   /// \brief Initialize the pass.
137   void setup(Function &Fn) {
138     DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
139     TTI = &getAnalysis<TargetTransformInfo>();
140     Entry = &Fn.getEntryBlock();
141   }
142
143   /// \brief Cleanup.
144   void cleanup() {
145     ConstantVec.clear();
146     ClonedCastMap.clear();
147     ConstCandVec.clear();
148     ConstCandMap.clear();
149
150     TTI = nullptr;
151     DT = nullptr;
152     Entry = nullptr;
153   }
154
155   Instruction *findMatInsertPt(Instruction *Inst, unsigned Idx = ~0U) const;
156   Instruction *findConstantInsertionPoint(const ConstantInfo &ConstInfo) const;
157   void collectConstantCandidates(Instruction *Inst, unsigned Idx,
158                                  ConstantInt *ConstInt);
159   void collectConstantCandidates(Instruction *Inst);
160   void collectConstantCandidates(Function &Fn);
161   void findAndMakeBaseConstant(ConstCandVecType::iterator S,
162                                ConstCandVecType::iterator E);
163   void findBaseConstants();
164   void emitBaseConstants(Instruction *Base, Constant *Offset,
165                          const ConstantUser &ConstUser);
166   bool emitBaseConstants();
167   void deleteDeadCastInst() const;
168   bool optimizeConstants(Function &Fn);
169 };
170 }
171
172 char ConstantHoisting::ID = 0;
173 INITIALIZE_PASS_BEGIN(ConstantHoisting, "consthoist", "Constant Hoisting",
174                       false, false)
175 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
176 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
177 INITIALIZE_PASS_END(ConstantHoisting, "consthoist", "Constant Hoisting",
178                     false, false)
179
180 FunctionPass *llvm::createConstantHoistingPass() {
181   return new ConstantHoisting();
182 }
183
184 /// \brief Perform the constant hoisting optimization for the given function.
185 bool ConstantHoisting::runOnFunction(Function &Fn) {
186   DEBUG(dbgs() << "********** Begin Constant Hoisting **********\n");
187   DEBUG(dbgs() << "********** Function: " << Fn.getName() << '\n');
188
189   setup(Fn);
190
191   bool MadeChange = optimizeConstants(Fn);
192
193   if (MadeChange) {
194     DEBUG(dbgs() << "********** Function after Constant Hoisting: "
195                  << Fn.getName() << '\n');
196     DEBUG(dbgs() << Fn);
197   }
198   DEBUG(dbgs() << "********** End Constant Hoisting **********\n");
199
200   cleanup();
201
202   return MadeChange;
203 }
204
205
206 /// \brief Find the constant materialization insertion point.
207 Instruction *ConstantHoisting::findMatInsertPt(Instruction *Inst,
208                                                unsigned Idx) const {
209   // The simple and common case.
210   if (!isa<PHINode>(Inst) && !isa<LandingPadInst>(Inst))
211     return Inst;
212
213   // We can't insert directly before a phi node or landing pad. Insert before
214   // the terminator of the incoming or dominating block.
215   assert(Entry != Inst->getParent() && "PHI or landing pad in entry block!");
216   if (Idx != ~0U && isa<PHINode>(Inst))
217     return cast<PHINode>(Inst)->getIncomingBlock(Idx)->getTerminator();
218
219   BasicBlock *IDom = DT->getNode(Inst->getParent())->getIDom()->getBlock();
220   return IDom->getTerminator();
221 }
222
223 /// \brief Find an insertion point that dominates all uses.
224 Instruction *ConstantHoisting::
225 findConstantInsertionPoint(const ConstantInfo &ConstInfo) const {
226   assert(!ConstInfo.RebasedConstants.empty() && "Invalid constant info entry.");
227   // Collect all basic blocks.
228   SmallPtrSet<BasicBlock *, 8> BBs;
229   for (auto const &RCI : ConstInfo.RebasedConstants)
230     for (auto const &U : RCI.Uses)
231       BBs.insert(U.Inst->getParent());
232
233   if (BBs.count(Entry))
234     return &Entry->front();
235
236   while (BBs.size() >= 2) {
237     BasicBlock *BB, *BB1, *BB2;
238     BB1 = *BBs.begin();
239     BB2 = *std::next(BBs.begin());
240     BB = DT->findNearestCommonDominator(BB1, BB2);
241     if (BB == Entry)
242       return &Entry->front();
243     BBs.erase(BB1);
244     BBs.erase(BB2);
245     BBs.insert(BB);
246   }
247   assert((BBs.size() == 1) && "Expected only one element.");
248   Instruction &FirstInst = (*BBs.begin())->front();
249   return findMatInsertPt(&FirstInst);
250 }
251
252
253 /// \brief Record constant integer ConstInt for instruction Inst at operand
254 /// index Idx.
255 ///
256 /// The operand at index Idx is not necessarily the constant inetger itself. It
257 /// could also be a cast instruction or a constant expression that uses the
258 // constant integer.
259 void ConstantHoisting::collectConstantCandidates(Instruction *Inst,
260                                                  unsigned Idx,
261                                                  ConstantInt *ConstInt) {
262   unsigned Cost;
263   // Ask the target about the cost of materializing the constant for the given
264   // instruction.
265   if (auto IntrInst = dyn_cast<IntrinsicInst>(Inst))
266     Cost = TTI->getIntImmCost(IntrInst->getIntrinsicID(),
267                               ConstInt->getValue(), ConstInt->getType());
268   else
269     Cost = TTI->getIntImmCost(Inst->getOpcode(), ConstInt->getValue(),
270                               ConstInt->getType());
271
272   // Ignore cheap integer constants.
273   if (Cost > TargetTransformInfo::TCC_Basic) {
274     ConstCandMapType::iterator Itr;
275     bool Inserted;
276     std::tie(Itr, Inserted) = ConstCandMap.insert(std::make_pair(ConstInt, 0));
277     if (Inserted) {
278       ConstCandVec.push_back(ConstantCandidate(ConstInt));
279       Itr->second = ConstCandVec.size() - 1;
280     }
281     ConstCandVec[Itr->second].addUser(Inst, Idx, Cost);
282     DEBUG(if (isa<ConstantInt>(Inst->getOperand(Idx)))
283             dbgs() << "Collect constant " << *ConstInt << " from " << *Inst
284                    << " with cost " << Cost << '\n';
285           else
286           dbgs() << "Collect constant " << *ConstInt << " indirectly from "
287                  << *Inst << " via " << *Inst->getOperand(Idx) << " with cost "
288                  << Cost << '\n';
289     );
290   }
291 }
292
293 /// \brief Scan the instruction for expensive integer constants and record them
294 /// in the constant candidate vector.
295 void ConstantHoisting::collectConstantCandidates(Instruction *Inst) {
296   // Skip all cast instructions. They are visited indirectly later on.
297   if (Inst->isCast())
298     return;
299
300   // Can't handle inline asm. Skip it.
301   if (auto Call = dyn_cast<CallInst>(Inst))
302     if (isa<InlineAsm>(Call->getCalledValue()))
303       return;
304
305   // Scan all operands.
306   for (unsigned Idx = 0, E = Inst->getNumOperands(); Idx != E; ++Idx) {
307     Value *Opnd = Inst->getOperand(Idx);
308
309     // Vist constant integers.
310     if (auto ConstInt = dyn_cast<ConstantInt>(Opnd)) {
311       collectConstantCandidates(Inst, Idx, ConstInt);
312       continue;
313     }
314
315     // Visit cast instructions that have constant integers.
316     if (auto CastInst = dyn_cast<Instruction>(Opnd)) {
317       // Only visit cast instructions, which have been skipped. All other
318       // instructions should have already been visited.
319       if (!CastInst->isCast())
320         continue;
321
322       if (auto *ConstInt = dyn_cast<ConstantInt>(CastInst->getOperand(0))) {
323         // Pretend the constant is directly used by the instruction and ignore
324         // the cast instruction.
325         collectConstantCandidates(Inst, Idx, ConstInt);
326         continue;
327       }
328     }
329
330     // Visit constant expressions that have constant integers.
331     if (auto ConstExpr = dyn_cast<ConstantExpr>(Opnd)) {
332       // Only visit constant cast expressions.
333       if (!ConstExpr->isCast())
334         continue;
335
336       if (auto ConstInt = dyn_cast<ConstantInt>(ConstExpr->getOperand(0))) {
337         // Pretend the constant is directly used by the instruction and ignore
338         // the constant expression.
339         collectConstantCandidates(Inst, Idx, ConstInt);
340         continue;
341       }
342     }
343   } // end of for all operands
344 }
345
346 /// \brief Collect all integer constants in the function that cannot be folded
347 /// into an instruction itself.
348 void ConstantHoisting::collectConstantCandidates(Function &Fn) {
349   for (Function::iterator BB : Fn)
350     for (BasicBlock::iterator Inst : *BB)
351       collectConstantCandidates(Inst);
352 }
353
354 /// \brief Find the base constant within the given range and rebase all other
355 /// constants with respect to the base constant.
356 void ConstantHoisting::findAndMakeBaseConstant(ConstCandVecType::iterator S,
357                                                ConstCandVecType::iterator E) {
358   auto MaxCostItr = S;
359   unsigned NumUses = 0;
360   // Use the constant that has the maximum cost as base constant.
361   for (auto ConstCand = S; ConstCand != E; ++ConstCand) {
362     NumUses += ConstCand->Uses.size();
363     if (ConstCand->CumulativeCost > MaxCostItr->CumulativeCost)
364       MaxCostItr = ConstCand;
365   }
366
367   // Don't hoist constants that have only one use.
368   if (NumUses <= 1)
369     return;
370
371   ConstantInfo ConstInfo;
372   ConstInfo.BaseConstant = MaxCostItr->ConstInt;
373   Type *Ty = ConstInfo.BaseConstant->getType();
374
375   // Rebase the constants with respect to the base constant.
376   for (auto ConstCand = S; ConstCand != E; ++ConstCand) {
377     APInt Diff = ConstCand->ConstInt->getValue() -
378                  ConstInfo.BaseConstant->getValue();
379     Constant *Offset = Diff == 0 ? nullptr : ConstantInt::get(Ty, Diff);
380     ConstInfo.RebasedConstants.push_back(
381       RebasedConstantInfo(std::move(ConstCand->Uses), Offset));
382   }
383   ConstantVec.push_back(ConstInfo);
384 }
385
386 /// \brief Finds and combines constant candidates that can be easily
387 /// rematerialized with an add from a common base constant.
388 void ConstantHoisting::findBaseConstants() {
389   // Sort the constants by value and type. This invalidates the mapping!
390   std::sort(ConstCandVec.begin(), ConstCandVec.end(),
391             [](const ConstantCandidate &LHS, const ConstantCandidate &RHS) {
392     if (LHS.ConstInt->getType() != RHS.ConstInt->getType())
393       return LHS.ConstInt->getType()->getBitWidth() <
394              RHS.ConstInt->getType()->getBitWidth();
395     return LHS.ConstInt->getValue().ult(RHS.ConstInt->getValue());
396   });
397
398   // Simple linear scan through the sorted constant candidate vector for viable
399   // merge candidates.
400   auto MinValItr = ConstCandVec.begin();
401   for (auto CC = std::next(ConstCandVec.begin()), E = ConstCandVec.end();
402        CC != E; ++CC) {
403     if (MinValItr->ConstInt->getType() == CC->ConstInt->getType()) {
404       // Check if the constant is in range of an add with immediate.
405       APInt Diff = CC->ConstInt->getValue() - MinValItr->ConstInt->getValue();
406       if ((Diff.getBitWidth() <= 64) &&
407           TTI->isLegalAddImmediate(Diff.getSExtValue()))
408         continue;
409     }
410     // We either have now a different constant type or the constant is not in
411     // range of an add with immediate anymore.
412     findAndMakeBaseConstant(MinValItr, CC);
413     // Start a new base constant search.
414     MinValItr = CC;
415   }
416   // Finalize the last base constant search.
417   findAndMakeBaseConstant(MinValItr, ConstCandVec.end());
418 }
419
420 /// \brief Emit materialization code for all rebased constants and update their
421 /// users.
422 void ConstantHoisting::emitBaseConstants(Instruction *Base, Constant *Offset,
423                                          const ConstantUser &ConstUser) {
424   Instruction *Mat = Base;
425   if (Offset) {
426     Instruction *InsertionPt = findMatInsertPt(ConstUser.Inst,
427                                                ConstUser.OpndIdx);
428     Mat = BinaryOperator::Create(Instruction::Add, Base, Offset,
429                                  "const_mat", InsertionPt);
430
431     DEBUG(dbgs() << "Materialize constant (" << *Base->getOperand(0)
432                  << " + " << *Offset << ") in BB "
433                  << Mat->getParent()->getName() << '\n' << *Mat << '\n');
434     Mat->setDebugLoc(ConstUser.Inst->getDebugLoc());
435   }
436   Value *Opnd = ConstUser.Inst->getOperand(ConstUser.OpndIdx);
437
438   // Visit constant integer.
439   if (isa<ConstantInt>(Opnd)) {
440     DEBUG(dbgs() << "Update: " << *ConstUser.Inst << '\n');
441     ConstUser.Inst->setOperand(ConstUser.OpndIdx, Mat);
442     DEBUG(dbgs() << "To    : " << *ConstUser.Inst << '\n');
443     return;
444   }
445
446   // Visit cast instruction.
447   if (auto CastInst = dyn_cast<Instruction>(Opnd)) {
448     assert(CastInst->isCast() && "Expected an cast instruction!");
449     // Check if we already have visited this cast instruction before to avoid
450     // unnecessary cloning.
451     Instruction *&ClonedCastInst = ClonedCastMap[CastInst];
452     if (!ClonedCastInst) {
453       ClonedCastInst = CastInst->clone();
454       ClonedCastInst->setOperand(0, Mat);
455       ClonedCastInst->insertAfter(CastInst);
456       // Use the same debug location as the original cast instruction.
457       ClonedCastInst->setDebugLoc(CastInst->getDebugLoc());
458       DEBUG(dbgs() << "Clone instruction: " << *ClonedCastInst << '\n'
459                    << "To               : " << *CastInst << '\n');
460     }
461
462     DEBUG(dbgs() << "Update: " << *ConstUser.Inst << '\n');
463     ConstUser.Inst->setOperand(ConstUser.OpndIdx, ClonedCastInst);
464     DEBUG(dbgs() << "To    : " << *ConstUser.Inst << '\n');
465     return;
466   }
467
468   // Visit constant expression.
469   if (auto ConstExpr = dyn_cast<ConstantExpr>(Opnd)) {
470     Instruction *ConstExprInst = ConstExpr->getAsInstruction();
471     ConstExprInst->setOperand(0, Mat);
472     ConstExprInst->insertBefore(findMatInsertPt(ConstUser.Inst,
473                                                 ConstUser.OpndIdx));
474
475     // Use the same debug location as the instruction we are about to update.
476     ConstExprInst->setDebugLoc(ConstUser.Inst->getDebugLoc());
477
478     DEBUG(dbgs() << "Create instruction: " << *ConstExprInst << '\n'
479                  << "From              : " << *ConstExpr << '\n');
480     DEBUG(dbgs() << "Update: " << *ConstUser.Inst << '\n');
481     ConstUser.Inst->setOperand(ConstUser.OpndIdx, ConstExprInst);
482     DEBUG(dbgs() << "To    : " << *ConstUser.Inst << '\n');
483     return;
484   }
485 }
486
487 /// \brief Hoist and hide the base constant behind a bitcast and emit
488 /// materialization code for derived constants.
489 bool ConstantHoisting::emitBaseConstants() {
490   bool MadeChange = false;
491   for (auto const &ConstInfo : ConstantVec) {
492     // Hoist and hide the base constant behind a bitcast.
493     Instruction *IP = findConstantInsertionPoint(ConstInfo);
494     IntegerType *Ty = ConstInfo.BaseConstant->getType();
495     Instruction *Base =
496       new BitCastInst(ConstInfo.BaseConstant, Ty, "const", IP);
497     DEBUG(dbgs() << "Hoist constant (" << *ConstInfo.BaseConstant << ") to BB "
498                  << IP->getParent()->getName() << '\n' << *Base << '\n');
499     NumConstantsHoisted++;
500
501     // Emit materialization code for all rebased constants.
502     for (auto const &RCI : ConstInfo.RebasedConstants) {
503       NumConstantsRebased++;
504       for (auto const &U : RCI.Uses)
505         emitBaseConstants(Base, RCI.Offset, U);
506     }
507
508     // Use the same debug location as the last user of the constant.
509     assert(!Base->use_empty() && "The use list is empty!?");
510     assert(isa<Instruction>(Base->user_back()) &&
511            "All uses should be instructions.");
512     Base->setDebugLoc(cast<Instruction>(Base->user_back())->getDebugLoc());
513
514     // Correct for base constant, which we counted above too.
515     NumConstantsRebased--;
516     MadeChange = true;
517   }
518   return MadeChange;
519 }
520
521 /// \brief Check all cast instructions we made a copy of and remove them if they
522 /// have no more users.
523 void ConstantHoisting::deleteDeadCastInst() const {
524   for (auto const &I : ClonedCastMap)
525     if (I.first->use_empty())
526       I.first->removeFromParent();
527 }
528
529 /// \brief Optimize expensive integer constants in the given function.
530 bool ConstantHoisting::optimizeConstants(Function &Fn) {
531   // Collect all constant candidates.
532   collectConstantCandidates(Fn);
533
534   // There are no constant candidates to worry about.
535   if (ConstCandVec.empty())
536     return false;
537
538   // Combine constants that can be easily materialized with an add from a common
539   // base constant.
540   findBaseConstants();
541
542   // There are no constants to emit.
543   if (ConstantVec.empty())
544     return false;
545
546   // Finally hoist the base constant and emit materializating code for dependent
547   // constants.
548   bool MadeChange = emitBaseConstants();
549
550   // Cleanup dead instructions.
551   deleteDeadCastInst();
552
553   return MadeChange;
554 }