Coverage Report

Created: 2019-07-24 05:18

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/lib/Transforms/Scalar/ConstantHoisting.cpp
Line
Count
Source (jump to first uncovered line)
1
//===- ConstantHoisting.cpp - Prepare code for expensive constants --------===//
2
//
3
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
// See https://llvm.org/LICENSE.txt for license information.
5
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
//
7
//===----------------------------------------------------------------------===//
8
//
9
// This pass identifies expensive constants to hoist and coalesces them to
10
// better prepare it for SelectionDAG-based code generation. This works around
11
// the limitations of the basic-block-at-a-time approach.
12
//
13
// First it scans all instructions for integer constants and calculates its
14
// cost. If the constant can be folded into the instruction (the cost is
15
// TCC_Free) or the cost is just a simple operation (TCC_BASIC), then we don't
16
// consider it expensive and leave it alone. This is the default behavior and
17
// the default implementation of getIntImmCost will always return TCC_Free.
18
//
19
// If the cost is more than TCC_BASIC, then the integer constant can't be folded
20
// into the instruction and it might be beneficial to hoist the constant.
21
// Similar constants are coalesced to reduce register pressure and
22
// materialization code.
23
//
24
// When a constant is hoisted, it is also hidden behind a bitcast to force it to
25
// be live-out of the basic block. Otherwise the constant would be just
26
// duplicated and each basic block would have its own copy in the SelectionDAG.
27
// The SelectionDAG recognizes such constants as opaque and doesn't perform
28
// certain transformations on them, which would create a new expensive constant.
29
//
30
// This optimization is only applied to integer constants in instructions and
31
// simple (this means not nested) constant cast expressions. For example:
32
// %0 = load i64* inttoptr (i64 big_constant to i64*)
33
//===----------------------------------------------------------------------===//
34
35
#include "llvm/Transforms/Scalar/ConstantHoisting.h"
36
#include "llvm/ADT/APInt.h"
37
#include "llvm/ADT/DenseMap.h"
38
#include "llvm/ADT/None.h"
39
#include "llvm/ADT/Optional.h"
40
#include "llvm/ADT/SmallPtrSet.h"
41
#include "llvm/ADT/SmallVector.h"
42
#include "llvm/ADT/Statistic.h"
43
#include "llvm/Analysis/BlockFrequencyInfo.h"
44
#include "llvm/Analysis/ProfileSummaryInfo.h"
45
#include "llvm/Analysis/TargetTransformInfo.h"
46
#include "llvm/Transforms/Utils/Local.h"
47
#include "llvm/IR/BasicBlock.h"
48
#include "llvm/IR/Constants.h"
49
#include "llvm/IR/DebugInfoMetadata.h"
50
#include "llvm/IR/Dominators.h"
51
#include "llvm/IR/Function.h"
52
#include "llvm/IR/InstrTypes.h"
53
#include "llvm/IR/Instruction.h"
54
#include "llvm/IR/Instructions.h"
55
#include "llvm/IR/IntrinsicInst.h"
56
#include "llvm/IR/Value.h"
57
#include "llvm/Pass.h"
58
#include "llvm/Support/BlockFrequency.h"
59
#include "llvm/Support/Casting.h"
60
#include "llvm/Support/CommandLine.h"
61
#include "llvm/Support/Debug.h"
62
#include "llvm/Support/raw_ostream.h"
63
#include "llvm/Transforms/Scalar.h"
64
#include "llvm/Transforms/Utils/SizeOpts.h"
65
#include <algorithm>
66
#include <cassert>
67
#include <cstdint>
68
#include <iterator>
69
#include <tuple>
70
#include <utility>
71
72
using namespace llvm;
73
using namespace consthoist;
74
75
#define DEBUG_TYPE "consthoist"
76
77
STATISTIC(NumConstantsHoisted, "Number of constants hoisted");
78
STATISTIC(NumConstantsRebased, "Number of constants rebased");
79
80
static cl::opt<bool> ConstHoistWithBlockFrequency(
81
    "consthoist-with-block-frequency", cl::init(true), cl::Hidden,
82
    cl::desc("Enable the use of the block frequency analysis to reduce the "
83
             "chance to execute const materialization more frequently than "
84
             "without hoisting."));
85
86
static cl::opt<bool> ConstHoistGEP(
87
    "consthoist-gep", cl::init(false), cl::Hidden,
88
    cl::desc("Try hoisting constant gep expressions"));
89
90
static cl::opt<unsigned>
91
MinNumOfDependentToRebase("consthoist-min-num-to-rebase",
92
    cl::desc("Do not rebase if number of dependent constants of a Base is less "
93
             "than this number."),
94
    cl::init(0), cl::Hidden);
95
96
namespace {
97
98
/// The constant hoisting pass.
99
class ConstantHoistingLegacyPass : public FunctionPass {
100
public:
101
  static char ID; // Pass identification, replacement for typeid
102
103
34.5k
  ConstantHoistingLegacyPass() : FunctionPass(ID) {
104
34.5k
    initializeConstantHoistingLegacyPassPass(*PassRegistry::getPassRegistry());
105
34.5k
  }
106
107
  bool runOnFunction(Function &Fn) override;
108
109
490k
  StringRef getPassName() const override { return "Constant Hoisting"; }
110
111
34.3k
  void getAnalysisUsage(AnalysisUsage &AU) const override {
112
34.3k
    AU.setPreservesCFG();
113
34.3k
    if (ConstHoistWithBlockFrequency)
114
34.3k
      AU.addRequired<BlockFrequencyInfoWrapperPass>();
115
34.3k
    AU.addRequired<DominatorTreeWrapperPass>();
116
34.3k
    AU.addRequired<ProfileSummaryInfoWrapperPass>();
117
34.3k
    AU.addRequired<TargetTransformInfoWrapperPass>();
118
34.3k
  }
119
120
private:
121
  ConstantHoistingPass Impl;
122
};
123
124
} // end anonymous namespace
125
126
char ConstantHoistingLegacyPass::ID = 0;
127
128
48.6k
INITIALIZE_PASS_BEGIN(ConstantHoistingLegacyPass, "consthoist",
129
48.6k
                      "Constant Hoisting", false, false)
130
48.6k
INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
131
48.6k
INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
132
48.6k
INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
133
48.6k
INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
134
48.6k
INITIALIZE_PASS_END(ConstantHoistingLegacyPass, "consthoist",
135
                    "Constant Hoisting", false, false)
136
137
34.5k
FunctionPass *llvm::createConstantHoistingPass() {
138
34.5k
  return new ConstantHoistingLegacyPass();
139
34.5k
}
140
141
/// Perform the constant hoisting optimization for the given function.
142
490k
bool ConstantHoistingLegacyPass::runOnFunction(Function &Fn) {
143
490k
  if (skipFunction(Fn))
144
272
    return false;
145
489k
146
489k
  LLVM_DEBUG(dbgs() << "********** Begin Constant Hoisting **********\n");
147
489k
  LLVM_DEBUG(dbgs() << "********** Function: " << Fn.getName() << '\n');
148
489k
149
489k
  bool MadeChange =
150
489k
      Impl.runImpl(Fn, getAnalysis<TargetTransformInfoWrapperPass>().getTTI(Fn),
151
489k
                   getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
152
489k
                   ConstHoistWithBlockFrequency
153
489k
                       ? 
&getAnalysis<BlockFrequencyInfoWrapperPass>().getBFI()489k
154
489k
                       : 
nullptr2
,
155
489k
                   Fn.getEntryBlock(),
156
489k
                   &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI());
157
489k
158
489k
  if (MadeChange) {
159
5.02k
    LLVM_DEBUG(dbgs() << "********** Function after Constant Hoisting: "
160
5.02k
                      << Fn.getName() << '\n');
161
5.02k
    LLVM_DEBUG(dbgs() << Fn);
162
5.02k
  }
163
489k
  LLVM_DEBUG(dbgs() << "********** End Constant Hoisting **********\n");
164
489k
165
489k
  return MadeChange;
166
489k
}
167
168
/// Find the constant materialization insertion point.
169
Instruction *ConstantHoistingPass::findMatInsertPt(Instruction *Inst,
170
394k
                                                   unsigned Idx) const {
171
394k
  // If the operand is a cast instruction, then we have to materialize the
172
394k
  // constant before the cast instruction.
173
394k
  if (Idx != ~0U) {
174
394k
    Value *Opnd = Inst->getOperand(Idx);
175
394k
    if (auto CastInst = dyn_cast<Instruction>(Opnd))
176
159k
      if (CastInst->isCast())
177
159k
        return CastInst;
178
234k
  }
179
234k
180
234k
  // The simple and common case. This also includes constant expressions.
181
234k
  if (!isa<PHINode>(Inst) && 
!Inst->isEHPad()228k
)
182
228k
    return Inst;
183
6.15k
184
6.15k
  // We can't insert directly before a phi node or an eh pad. Insert before
185
6.15k
  // the terminator of the incoming or dominating block.
186
6.15k
  assert(Entry != Inst->getParent() && "PHI or landing pad in entry block!");
187
6.15k
  if (Idx != ~0U && 
isa<PHINode>(Inst)6.15k
)
188
6.15k
    return cast<PHINode>(Inst)->getIncomingBlock(Idx)->getTerminator();
189
1
190
1
  // This must be an EH pad. Iterate over immediate dominators until we find a
191
1
  // non-EH pad. We need to skip over catchswitch blocks, which are both EH pads
192
1
  // and terminators.
193
1
  auto IDom = DT->getNode(Inst->getParent())->getIDom();
194
2
  while (IDom->getBlock()->isEHPad()) {
195
1
    assert(Entry != IDom->getBlock() && "eh pad in entry block");
196
1
    IDom = IDom->getIDom();
197
1
  }
198
1
199
1
  return IDom->getBlock()->getTerminator();
200
1
}
201
202
/// Given \p BBs as input, find another set of BBs which collectively
203
/// dominates \p BBs and have the minimal sum of frequencies. Return the BB
204
/// set found in \p BBs.
205
static void findBestInsertionSet(DominatorTree &DT, BlockFrequencyInfo &BFI,
206
                                 BasicBlock *Entry,
207
7.58k
                                 SmallPtrSet<BasicBlock *, 8> &BBs) {
208
7.58k
  assert(!BBs.count(Entry) && "Assume Entry is not in BBs");
209
7.58k
  // Nodes on the current path to the root.
210
7.58k
  SmallPtrSet<BasicBlock *, 8> Path;
211
7.58k
  // Candidates includes any block 'BB' in set 'BBs' that is not strictly
212
7.58k
  // dominated by any other blocks in set 'BBs', and all nodes in the path
213
7.58k
  // in the dominator tree from Entry to 'BB'.
214
7.58k
  SmallPtrSet<BasicBlock *, 16> Candidates;
215
28.3k
  for (auto BB : BBs) {
216
28.3k
    // Ignore unreachable basic blocks.
217
28.3k
    if (!DT.isReachableFromEntry(BB))
218
2
      continue;
219
28.3k
    Path.clear();
220
28.3k
    // Walk up the dominator tree until Entry or another BB in BBs
221
28.3k
    // is reached. Insert the nodes on the way to the Path.
222
28.3k
    BasicBlock *Node = BB;
223
28.3k
    // The "Path" is a candidate path to be added into Candidates set.
224
28.3k
    bool isCandidate = false;
225
1.47M
    do {
226
1.47M
      Path.insert(Node);
227
1.47M
      if (Node == Entry || 
Candidates.count(Node)1.46M
) {
228
18.8k
        isCandidate = true;
229
18.8k
        break;
230
18.8k
      }
231
1.45M
      assert(DT.getNode(Node)->getIDom() &&
232
1.45M
             "Entry doens't dominate current Node");
233
1.45M
      Node = DT.getNode(Node)->getIDom()->getBlock();
234
1.45M
    } while (!BBs.count(Node));
235
28.3k
236
28.3k
    // If isCandidate is false, Node is another Block in BBs dominating
237
28.3k
    // current 'BB'. Drop the nodes on the Path.
238
28.3k
    if (!isCandidate)
239
9.43k
      continue;
240
18.8k
241
18.8k
    // Add nodes on the Path into Candidates.
242
18.8k
    Candidates.insert(Path.begin(), Path.end());
243
18.8k
  }
244
7.58k
245
7.58k
  // Sort the nodes in Candidates in top-down order and save the nodes
246
7.58k
  // in Orders.
247
7.58k
  unsigned Idx = 0;
248
7.58k
  SmallVector<BasicBlock *, 16> Orders;
249
7.58k
  Orders.push_back(Entry);
250
1.40M
  while (Idx != Orders.size()) {
251
1.39M
    BasicBlock *Node = Orders[Idx++];
252
2.78M
    for (auto ChildDomNode : DT.getNode(Node)->getChildren()) {
253
2.78M
      if (Candidates.count(ChildDomNode->getBlock()))
254
1.38M
        Orders.push_back(ChildDomNode->getBlock());
255
2.78M
    }
256
1.39M
  }
257
7.58k
258
7.58k
  // Visit Orders in bottom-up order.
259
7.58k
  using InsertPtsCostPair =
260
7.58k
      std::pair<SmallPtrSet<BasicBlock *, 16>, BlockFrequency>;
261
7.58k
262
7.58k
  // InsertPtsMap is a map from a BB to the best insertion points for the
263
7.58k
  // subtree of BB (subtree not including the BB itself).
264
7.58k
  DenseMap<BasicBlock *, InsertPtsCostPair> InsertPtsMap;
265
7.58k
  InsertPtsMap.reserve(Orders.size() + 1);
266
1.39M
  for (auto RIt = Orders.rbegin(); RIt != Orders.rend(); 
RIt++1.38M
) {
267
1.39M
    BasicBlock *Node = *RIt;
268
1.39M
    bool NodeInBBs = BBs.count(Node);
269
1.39M
    SmallPtrSet<BasicBlock *, 16> &InsertPts = InsertPtsMap[Node].first;
270
1.39M
    BlockFrequency &InsertPtsFreq = InsertPtsMap[Node].second;
271
1.39M
272
1.39M
    // Return the optimal insert points in BBs.
273
1.39M
    if (Node == Entry) {
274
7.58k
      BBs.clear();
275
7.58k
      if (InsertPtsFreq > BFI.getBlockFreq(Node) ||
276
7.58k
          
(7.45k
InsertPtsFreq == BFI.getBlockFreq(Node)7.45k
&&
InsertPts.size() > 12.79k
))
277
153
        BBs.insert(Entry);
278
7.43k
      else
279
7.43k
        BBs.insert(InsertPts.begin(), InsertPts.end());
280
7.58k
      break;
281
7.58k
    }
282
1.38M
283
1.38M
    BasicBlock *Parent = DT.getNode(Node)->getIDom()->getBlock();
284
1.38M
    // Initially, ParentInsertPts is empty and ParentPtsFreq is 0. Every child
285
1.38M
    // will update its parent's ParentInsertPts and ParentPtsFreq.
286
1.38M
    SmallPtrSet<BasicBlock *, 16> &ParentInsertPts = InsertPtsMap[Parent].first;
287
1.38M
    BlockFrequency &ParentPtsFreq = InsertPtsMap[Parent].second;
288
1.38M
    // Choose to insert in Node or in subtree of Node.
289
1.38M
    // Don't hoist to EHPad because we may not find a proper place to insert
290
1.38M
    // in EHPad.
291
1.38M
    // If the total frequency of InsertPts is the same as the frequency of the
292
1.38M
    // target Node, and InsertPts contains more than one nodes, choose hoisting
293
1.38M
    // to reduce code size.
294
1.38M
    if (NodeInBBs ||
295
1.38M
        
(1.37M
!Node->isEHPad()1.37M
&&
296
1.37M
         
(1.37M
InsertPtsFreq > BFI.getBlockFreq(Node)1.37M
||
297
1.37M
          
(1.36M
InsertPtsFreq == BFI.getBlockFreq(Node)1.36M
&&
InsertPts.size() > 11.33M
)))) {
298
24.9k
      ParentInsertPts.insert(Node);
299
24.9k
      ParentPtsFreq += BFI.getBlockFreq(Node);
300
1.36M
    } else {
301
1.36M
      ParentInsertPts.insert(InsertPts.begin(), InsertPts.end());
302
1.36M
      ParentPtsFreq += InsertPtsFreq;
303
1.36M
    }
304
1.38M
  }
305
7.58k
}
306
307
/// Find an insertion point that dominates all uses.
308
SmallPtrSet<Instruction *, 8> ConstantHoistingPass::findConstantInsertionPoint(
309
8.84k
    const ConstantInfo &ConstInfo) const {
310
8.84k
  assert(!ConstInfo.RebasedConstants.empty() && "Invalid constant info entry.");
311
8.84k
  // Collect all basic blocks.
312
8.84k
  SmallPtrSet<BasicBlock *, 8> BBs;
313
8.84k
  SmallPtrSet<Instruction *, 8> InsertPts;
314
8.84k
  for (auto const &RCI : ConstInfo.RebasedConstants)
315
10.3k
    for (auto const &U : RCI.Uses)
316
37.2k
      BBs.insert(findMatInsertPt(U.Inst, U.OpndIdx)->getParent());
317
8.84k
318
8.84k
  if (BBs.count(Entry)) {
319
1.25k
    InsertPts.insert(&Entry->front());
320
1.25k
    return InsertPts;
321
1.25k
  }
322
7.59k
323
7.59k
  if (BFI) {
324
7.58k
    findBestInsertionSet(*DT, *BFI, Entry, BBs);
325
13.9k
    for (auto BB : BBs) {
326
13.9k
      BasicBlock::iterator InsertPt = BB->begin();
327
23.5k
      for (; isa<PHINode>(InsertPt) || 
InsertPt->isEHPad()13.9k
;
++InsertPt9.58k
)
328
9.58k
        ;
329
13.9k
      InsertPts.insert(&*InsertPt);
330
13.9k
    }
331
7.58k
    return InsertPts;
332
7.58k
  }
333
1
334
2
  
while (1
BBs.size() >= 2) {
335
1
    BasicBlock *BB, *BB1, *BB2;
336
1
    BB1 = *BBs.begin();
337
1
    BB2 = *std::next(BBs.begin());
338
1
    BB = DT->findNearestCommonDominator(BB1, BB2);
339
1
    if (BB == Entry) {
340
0
      InsertPts.insert(&Entry->front());
341
0
      return InsertPts;
342
0
    }
343
1
    BBs.erase(BB1);
344
1
    BBs.erase(BB2);
345
1
    BBs.insert(BB);
346
1
  }
347
1
  assert((BBs.size() == 1) && "Expected only one element.");
348
1
  Instruction &FirstInst = (*BBs.begin())->front();
349
1
  InsertPts.insert(findMatInsertPt(&FirstInst));
350
1
  return InsertPts;
351
1
}
352
353
/// Record constant integer ConstInt for instruction Inst at operand
354
/// index Idx.
355
///
356
/// The operand at index Idx is not necessarily the constant integer itself. It
357
/// could also be a cast instruction or a constant expression that uses the
358
/// constant integer.
359
void ConstantHoistingPass::collectConstantCandidates(
360
    ConstCandMapType &ConstCandMap, Instruction *Inst, unsigned Idx,
361
4.82M
    ConstantInt *ConstInt) {
362
4.82M
  unsigned Cost;
363
4.82M
  // Ask the target about the cost of materializing the constant for the given
364
4.82M
  // instruction and operand index.
365
4.82M
  if (auto IntrInst = dyn_cast<IntrinsicInst>(Inst))
366
335k
    Cost = TTI->getIntImmCost(IntrInst->getIntrinsicID(), Idx,
367
335k
                              ConstInt->getValue(), ConstInt->getType());
368
4.48M
  else
369
4.48M
    Cost = TTI->getIntImmCost(Inst->getOpcode(), Idx, ConstInt->getValue(),
370
4.48M
                              ConstInt->getType());
371
4.82M
372
4.82M
  // Ignore cheap integer constants.
373
4.82M
  if (Cost > TargetTransformInfo::TCC_Basic) {
374
49.7k
    ConstCandMapType::iterator Itr;
375
49.7k
    bool Inserted;
376
49.7k
    ConstPtrUnionType Cand = ConstInt;
377
49.7k
    std::tie(Itr, Inserted) = ConstCandMap.insert(std::make_pair(Cand, 0));
378
49.7k
    if (Inserted) {
379
22.8k
      ConstIntCandVec.push_back(ConstantCandidate(ConstInt));
380
22.8k
      Itr->second = ConstIntCandVec.size() - 1;
381
22.8k
    }
382
49.7k
    ConstIntCandVec[Itr->second].addUser(Inst, Idx, Cost);
383
49.7k
    LLVM_DEBUG(if (isa<ConstantInt>(Inst->getOperand(Idx))) dbgs()
384
49.7k
                   << "Collect constant " << *ConstInt << " from " << *Inst
385
49.7k
                   << " with cost " << Cost << '\n';
386
49.7k
               else dbgs() << "Collect constant " << *ConstInt
387
49.7k
                           << " indirectly from " << *Inst << " via "
388
49.7k
                           << *Inst->getOperand(Idx) << " with cost " << Cost
389
49.7k
                           << '\n';);
390
49.7k
  }
391
4.82M
}
392
393
/// Record constant GEP expression for instruction Inst at operand index Idx.
394
void ConstantHoistingPass::collectConstantCandidates(
395
    ConstCandMapType &ConstCandMap, Instruction *Inst, unsigned Idx,
396
21
    ConstantExpr *ConstExpr) {
397
21
  // TODO: Handle vector GEPs
398
21
  if (ConstExpr->getType()->isVectorTy())
399
0
    return;
400
21
401
21
  GlobalVariable *BaseGV = dyn_cast<GlobalVariable>(ConstExpr->getOperand(0));
402
21
  if (!BaseGV)
403
0
    return;
404
21
405
21
  // Get offset from the base GV.
406
21
  PointerType *GVPtrTy = dyn_cast<PointerType>(BaseGV->getType());
407
21
  IntegerType *PtrIntTy = DL->getIntPtrType(*Ctx, GVPtrTy->getAddressSpace());
408
21
  APInt Offset(DL->getTypeSizeInBits(PtrIntTy), /*val*/0, /*isSigned*/true);
409
21
  auto *GEPO = cast<GEPOperator>(ConstExpr);
410
21
  if (!GEPO->accumulateConstantOffset(*DL, Offset))
411
0
    return;
412
21
413
21
  if (!Offset.isIntN(32))
414
0
    return;
415
21
416
21
  // A constant GEP expression that has a GlobalVariable as base pointer is
417
21
  // usually lowered to a load from constant pool. Such operation is unlikely
418
21
  // to be cheaper than compute it by <Base + Offset>, which can be lowered to
419
21
  // an ADD instruction or folded into Load/Store instruction.
420
21
  int Cost = TTI->getIntImmCost(Instruction::Add, 1, Offset, PtrIntTy);
421
21
  ConstCandVecType &ExprCandVec = ConstGEPCandMap[BaseGV];
422
21
  ConstCandMapType::iterator Itr;
423
21
  bool Inserted;
424
21
  ConstPtrUnionType Cand = ConstExpr;
425
21
  std::tie(Itr, Inserted) = ConstCandMap.insert(std::make_pair(Cand, 0));
426
21
  if (Inserted) {
427
21
    ExprCandVec.push_back(ConstantCandidate(
428
21
        ConstantInt::get(Type::getInt32Ty(*Ctx), Offset.getLimitedValue()),
429
21
        ConstExpr));
430
21
    Itr->second = ExprCandVec.size() - 1;
431
21
  }
432
21
  ExprCandVec[Itr->second].addUser(Inst, Idx, Cost);
433
21
}
434
435
/// Check the operand for instruction Inst at index Idx.
436
void ConstantHoistingPass::collectConstantCandidates(
437
26.6M
    ConstCandMapType &ConstCandMap, Instruction *Inst, unsigned Idx) {
438
26.6M
  Value *Opnd = Inst->getOperand(Idx);
439
26.6M
440
26.6M
  // Visit constant integers.
441
26.6M
  if (auto ConstInt = dyn_cast<ConstantInt>(Opnd)) {
442
4.81M
    collectConstantCandidates(ConstCandMap, Inst, Idx, ConstInt);
443
4.81M
    return;
444
4.81M
  }
445
21.8M
446
21.8M
  // Visit cast instructions that have constant integers.
447
21.8M
  if (auto CastInst = dyn_cast<Instruction>(Opnd)) {
448
12.9M
    // Only visit cast instructions, which have been skipped. All other
449
12.9M
    // instructions should have already been visited.
450
12.9M
    if (!CastInst->isCast())
451
11.0M
      return;
452
1.88M
453
1.88M
    if (auto *ConstInt = dyn_cast<ConstantInt>(CastInst->getOperand(0))) {
454
481
      // Pretend the constant is directly used by the instruction and ignore
455
481
      // the cast instruction.
456
481
      collectConstantCandidates(ConstCandMap, Inst, Idx, ConstInt);
457
481
      return;
458
481
    }
459
10.7M
  }
460
10.7M
461
10.7M
  // Visit constant expressions that have constant integers.
462
10.7M
  if (auto ConstExpr = dyn_cast<ConstantExpr>(Opnd)) {
463
766k
    // Handle constant gep expressions.
464
766k
    if (ConstHoistGEP && 
ConstExpr->isGEPWithNoNotionalOverIndexing()29
)
465
21
      collectConstantCandidates(ConstCandMap, Inst, Idx, ConstExpr);
466
766k
467
766k
    // Only visit constant cast expressions.
468
766k
    if (!ConstExpr->isCast())
469
668k
      return;
470
97.4k
471
97.4k
    if (auto ConstInt = dyn_cast<ConstantInt>(ConstExpr->getOperand(0))) {
472
6.14k
      // Pretend the constant is directly used by the instruction and ignore
473
6.14k
      // the constant expression.
474
6.14k
      collectConstantCandidates(ConstCandMap, Inst, Idx, ConstInt);
475
6.14k
      return;
476
6.14k
    }
477
97.4k
  }
478
10.7M
}
479
480
/// Scan the instruction for expensive integer constants and record them
481
/// in the constant candidate vector.
482
void ConstantHoistingPass::collectConstantCandidates(
483
14.3M
    ConstCandMapType &ConstCandMap, Instruction *Inst) {
484
14.3M
  // Skip all cast instructions. They are visited indirectly later on.
485
14.3M
  if (Inst->isCast())
486
1.36M
    return;
487
12.9M
488
12.9M
  // Scan all operands.
489
41.7M
  
for (unsigned Idx = 0, E = Inst->getNumOperands(); 12.9M
Idx != E;
++Idx28.7M
) {
490
28.7M
    // The cost of materializing the constants (defined in
491
28.7M
    // `TargetTransformInfo::getIntImmCost`) for instructions which only take
492
28.7M
    // constant variables is lower than `TargetTransformInfo::TCC_Basic`. So
493
28.7M
    // it's safe for us to collect constant candidates from all IntrinsicInsts.
494
28.7M
    if (canReplaceOperandWithVariable(Inst, Idx) || 
isa<IntrinsicInst>(Inst)2.88M
) {
495
26.6M
      collectConstantCandidates(ConstCandMap, Inst, Idx);
496
26.6M
    }
497
28.7M
  } // end of for all operands
498
12.9M
}
499
500
/// Collect all integer constants in the function that cannot be folded
501
/// into an instruction itself.
502
489k
void ConstantHoistingPass::collectConstantCandidates(Function &Fn) {
503
489k
  ConstCandMapType ConstCandMap;
504
489k
  for (BasicBlock &BB : Fn)
505
2.69M
    for (Instruction &Inst : BB)
506
14.3M
      collectConstantCandidates(ConstCandMap, &Inst);
507
489k
}
508
509
// This helper function is necessary to deal with values that have different
510
// bit widths (APInt Operator- does not like that). If the value cannot be
511
// represented in uint64 we return an "empty" APInt. This is then interpreted
512
// as the value is not in range.
513
2.61k
static Optional<APInt> calculateOffsetDiff(const APInt &V1, const APInt &V2) {
514
2.61k
  Optional<APInt> Res = None;
515
2.61k
  unsigned BW = V1.getBitWidth() > V2.getBitWidth() ?
516
2.61k
                
V1.getBitWidth()0
: V2.getBitWidth();
517
2.61k
  uint64_t LimVal1 = V1.getLimitedValue();
518
2.61k
  uint64_t LimVal2 = V2.getLimitedValue();
519
2.61k
520
2.61k
  if (LimVal1 == ~0ULL || 
LimVal2 == ~0ULL2.50k
)
521
111
    return Res;
522
2.50k
523
2.50k
  uint64_t Diff = LimVal1 - LimVal2;
524
2.50k
  return APInt(BW, Diff, true);
525
2.50k
}
526
527
// From a list of constants, one needs to picked as the base and the other
528
// constants will be transformed into an offset from that base constant. The
529
// question is which we can pick best? For example, consider these constants
530
// and their number of uses:
531
//
532
//  Constants| 2 | 4 | 12 | 42 |
533
//  NumUses  | 3 | 2 |  8 |  7 |
534
//
535
// Selecting constant 12 because it has the most uses will generate negative
536
// offsets for constants 2 and 4 (i.e. -10 and -8 respectively). If negative
537
// offsets lead to less optimal code generation, then there might be better
538
// solutions. Suppose immediates in the range of 0..35 are most optimally
539
// supported by the architecture, then selecting constant 2 is most optimal
540
// because this will generate offsets: 0, 2, 10, 40. Offsets 0, 2 and 10 are in
541
// range 0..35, and thus 3 + 2 + 8 = 13 uses are in range. Selecting 12 would
542
// have only 8 uses in range, so choosing 2 as a base is more optimal. Thus, in
543
// selecting the base constant the range of the offsets is a very important
544
// factor too that we take into account here. This algorithm calculates a total
545
// costs for selecting a constant as the base and substract the costs if
546
// immediates are out of range. It has quadratic complexity, so we call this
547
// function only when we're optimising for size and there are less than 100
548
// constants, we fall back to the straightforward algorithm otherwise
549
// which does not do all the offset calculations.
550
unsigned
551
ConstantHoistingPass::maximizeConstantsInRange(ConstCandVecType::iterator S,
552
                                           ConstCandVecType::iterator E,
553
21.3k
                                           ConstCandVecType::iterator &MaxCostItr) {
554
21.3k
  unsigned NumUses = 0;
555
21.3k
556
21.3k
  bool OptForSize = Entry->getParent()->hasOptSize() ||
557
21.3k
                    
llvm::shouldOptimizeForSize(Entry->getParent(), PSI, BFI)20.3k
;
558
21.3k
  if (!OptForSize || 
std::distance(S,E) > 100948
) {
559
42.1k
    for (auto ConstCand = S; ConstCand != E; 
++ConstCand21.7k
) {
560
21.7k
      NumUses += ConstCand->Uses.size();
561
21.7k
      if (ConstCand->CumulativeCost > MaxCostItr->CumulativeCost)
562
118
        MaxCostItr = ConstCand;
563
21.7k
    }
564
20.3k
    return NumUses;
565
20.3k
  }
566
948
567
948
  LLVM_DEBUG(dbgs() << "== Maximize constants in range ==\n");
568
948
  int MaxCost = -1;
569
2.07k
  for (auto ConstCand = S; ConstCand != E; 
++ConstCand1.12k
) {
570
1.12k
    auto Value = ConstCand->ConstInt->getValue();
571
1.12k
    Type *Ty = ConstCand->ConstInt->getType();
572
1.12k
    int Cost = 0;
573
1.12k
    NumUses += ConstCand->Uses.size();
574
1.12k
    LLVM_DEBUG(dbgs() << "= Constant: " << ConstCand->ConstInt->getValue()
575
1.12k
                      << "\n");
576
1.12k
577
1.80k
    for (auto User : ConstCand->Uses) {
578
1.80k
      unsigned Opcode = User.Inst->getOpcode();
579
1.80k
      unsigned OpndIdx = User.OpndIdx;
580
1.80k
      Cost += TTI->getIntImmCost(Opcode, OpndIdx, Value, Ty);
581
1.80k
      LLVM_DEBUG(dbgs() << "Cost: " << Cost << "\n");
582
1.80k
583
4.41k
      for (auto C2 = S; C2 != E; 
++C22.61k
) {
584
2.61k
        Optional<APInt> Diff = calculateOffsetDiff(
585
2.61k
                                   C2->ConstInt->getValue(),
586
2.61k
                                   ConstCand->ConstInt->getValue());
587
2.61k
        if (Diff) {
588
2.50k
          const int ImmCosts =
589
2.50k
            TTI->getIntImmCodeSizeCost(Opcode, OpndIdx, Diff.getValue(), Ty);
590
2.50k
          Cost -= ImmCosts;
591
2.50k
          LLVM_DEBUG(dbgs() << "Offset " << Diff.getValue() << " "
592
2.50k
                            << "has penalty: " << ImmCosts << "\n"
593
2.50k
                            << "Adjusted cost: " << Cost << "\n");
594
2.50k
        }
595
2.61k
      }
596
1.80k
    }
597
1.12k
    LLVM_DEBUG(dbgs() << "Cumulative cost: " << Cost << "\n");
598
1.12k
    if (Cost > MaxCost) {
599
984
      MaxCost = Cost;
600
984
      MaxCostItr = ConstCand;
601
984
      LLVM_DEBUG(dbgs() << "New candidate: " << MaxCostItr->ConstInt->getValue()
602
984
                        << "\n");
603
984
    }
604
1.12k
  }
605
948
  return NumUses;
606
948
}
607
608
/// Find the base constant within the given range and rebase all other
609
/// constants with respect to the base constant.
610
void ConstantHoistingPass::findAndMakeBaseConstant(
611
    ConstCandVecType::iterator S, ConstCandVecType::iterator E,
612
21.3k
    SmallVectorImpl<consthoist::ConstantInfo> &ConstInfoVec) {
613
21.3k
  auto MaxCostItr = S;
614
21.3k
  unsigned NumUses = maximizeConstantsInRange(S, E, MaxCostItr);
615
21.3k
616
21.3k
  // Don't hoist constants that have only one use.
617
21.3k
  if (NumUses <= 1)
618
12.4k
    return;
619
8.84k
620
8.84k
  ConstantInt *ConstInt = MaxCostItr->ConstInt;
621
8.84k
  ConstantExpr *ConstExpr = MaxCostItr->ConstExpr;
622
8.84k
  ConstantInfo ConstInfo;
623
8.84k
  ConstInfo.BaseInt = ConstInt;
624
8.84k
  ConstInfo.BaseExpr = ConstExpr;
625
8.84k
  Type *Ty = ConstInt->getType();
626
8.84k
627
8.84k
  // Rebase the constants with respect to the base constant.
628
19.2k
  for (auto ConstCand = S; ConstCand != E; 
++ConstCand10.3k
) {
629
10.3k
    APInt Diff = ConstCand->ConstInt->getValue() - ConstInt->getValue();
630
10.3k
    Constant *Offset = Diff == 0 ? 
nullptr8.84k
:
ConstantInt::get(Ty, Diff)1.55k
;
631
10.3k
    Type *ConstTy =
632
10.3k
        ConstCand->ConstExpr ? 
ConstCand->ConstExpr->getType()21
:
nullptr10.3k
;
633
10.3k
    ConstInfo.RebasedConstants.push_back(
634
10.3k
      RebasedConstantInfo(std::move(ConstCand->Uses), Offset, ConstTy));
635
10.3k
  }
636
8.84k
  ConstInfoVec.push_back(std::move(ConstInfo));
637
8.84k
}
638
639
/// Finds and combines constant candidates that can be easily
640
/// rematerialized with an add from a common base constant.
641
10.4k
void ConstantHoistingPass::findBaseConstants(GlobalVariable *BaseGV) {
642
10.4k
  // If BaseGV is nullptr, find base among candidate constant integers;
643
10.4k
  // Otherwise find base among constant GEPs that share the same BaseGV.
644
10.4k
  ConstCandVecType &ConstCandVec = BaseGV ?
645
10.3k
      
ConstGEPCandMap[BaseGV]5
: ConstIntCandVec;
646
10.4k
  ConstInfoVecType &ConstInfoVec = BaseGV ?
647
10.3k
      
ConstGEPInfoMap[BaseGV]5
: ConstIntInfoVec;
648
10.4k
649
10.4k
  // Sort the constants by value and type. This invalidates the mapping!
650
10.4k
  llvm::stable_sort(ConstCandVec, [](const ConstantCandidate &LHS,
651
29.1k
                                     const ConstantCandidate &RHS) {
652
29.1k
    if (LHS.ConstInt->getType() != RHS.ConstInt->getType())
653
760
      return LHS.ConstInt->getType()->getBitWidth() <
654
760
             RHS.ConstInt->getType()->getBitWidth();
655
28.3k
    return LHS.ConstInt->getValue().ult(RHS.ConstInt->getValue());
656
28.3k
  });
657
10.4k
658
10.4k
  // Simple linear scan through the sorted constant candidate vector for viable
659
10.4k
  // merge candidates.
660
10.4k
  auto MinValItr = ConstCandVec.begin();
661
10.4k
  for (auto CC = std::next(ConstCandVec.begin()), E = ConstCandVec.end();
662
22.8k
       CC != E; 
++CC12.4k
) {
663
12.4k
    if (MinValItr->ConstInt->getType() == CC->ConstInt->getType()) {
664
12.2k
      Type *MemUseValTy = nullptr;
665
24.4k
      for (auto &U : CC->Uses) {
666
24.4k
        auto *UI = U.Inst;
667
24.4k
        if (LoadInst *LI = dyn_cast<LoadInst>(UI)) {
668
60
          MemUseValTy = LI->getType();
669
60
          break;
670
24.4k
        } else if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
671
651
          // Make sure the constant is used as pointer operand of the StoreInst.
672
651
          if (SI->getPointerOperand() == SI->getOperand(U.OpndIdx)) {
673
28
            MemUseValTy = SI->getValueOperand()->getType();
674
28
            break;
675
28
          }
676
651
        }
677
24.4k
      }
678
12.2k
679
12.2k
      // Check if the constant is in range of an add with immediate.
680
12.2k
      APInt Diff = CC->ConstInt->getValue() - MinValItr->ConstInt->getValue();
681
12.2k
      if ((Diff.getBitWidth() <= 64) &&
682
12.2k
          
TTI->isLegalAddImmediate(Diff.getSExtValue())12.2k
&&
683
12.2k
          // Check if Diff can be used as offset in addressing mode of the user
684
12.2k
          // memory instruction.
685
12.2k
          
(1.56k
!MemUseValTy1.56k
|| TTI->isLegalAddressingMode(MemUseValTy,
686
85
           /*BaseGV*/nullptr, /*BaseOffset*/Diff.getSExtValue(),
687
85
           /*HasBaseReg*/true, /*Scale*/0)))
688
1.55k
        continue;
689
10.9k
    }
690
10.9k
    // We either have now a different constant type or the constant is not in
691
10.9k
    // range of an add with immediate anymore.
692
10.9k
    findAndMakeBaseConstant(MinValItr, CC, ConstInfoVec);
693
10.9k
    // Start a new base constant search.
694
10.9k
    MinValItr = CC;
695
10.9k
  }
696
10.4k
  // Finalize the last base constant search.
697
10.4k
  findAndMakeBaseConstant(MinValItr, ConstCandVec.end(), ConstInfoVec);
698
10.4k
}
699
700
/// Updates the operand at Idx in instruction Inst with the result of
701
///        instruction Mat. If the instruction is a PHI node then special
702
///        handling for duplicate values form the same incoming basic block is
703
///        required.
704
/// \return The update will always succeed, but the return value indicated if
705
///         Mat was used for the update or not.
706
37.2k
static bool updateOperand(Instruction *Inst, unsigned Idx, Instruction *Mat) {
707
37.2k
  if (auto PHI = dyn_cast<PHINode>(Inst)) {
708
2.93k
    // Check if any previous operand of the PHI node has the same incoming basic
709
2.93k
    // block. This is a very odd case that happens when the incoming basic block
710
2.93k
    // has a switch statement. In this case use the same value as the previous
711
2.93k
    // operand(s), otherwise we will fail verification due to different values.
712
2.93k
    // The values are actually the same, but the variable names are different
713
2.93k
    // and the verifier doesn't like that.
714
2.93k
    BasicBlock *IncomingBB = PHI->getIncomingBlock(Idx);
715
22.2k
    for (unsigned i = 0; i < Idx; 
++i19.3k
) {
716
19.3k
      if (PHI->getIncomingBlock(i) == IncomingBB) {
717
6
        Value *IncomingVal = PHI->getIncomingValue(i);
718
6
        Inst->setOperand(Idx, IncomingVal);
719
6
        return false;
720
6
      }
721
19.3k
    }
722
2.93k
  }
723
37.2k
724
37.2k
  Inst->setOperand(Idx, Mat);
725
37.2k
  return true;
726
37.2k
}
727
728
/// Emit materialization code for all rebased constants and update their
729
/// users.
730
void ConstantHoistingPass::emitBaseConstants(Instruction *Base,
731
                                             Constant *Offset,
732
                                             Type *Ty,
733
37.2k
                                             const ConstantUser &ConstUser) {
734
37.2k
  Instruction *Mat = Base;
735
37.2k
736
37.2k
  // The same offset can be dereferenced to different types in nested struct.
737
37.2k
  if (!Offset && 
Ty35.0k
&&
Ty != Base->getType()8
)
738
1
    Offset = ConstantInt::get(Type::getInt32Ty(*Ctx), 0);
739
37.2k
740
37.2k
  if (Offset) {
741
2.23k
    Instruction *InsertionPt = findMatInsertPt(ConstUser.Inst,
742
2.23k
                                               ConstUser.OpndIdx);
743
2.23k
    if (Ty) {
744
14
      // Constant being rebased is a ConstantExpr.
745
14
      PointerType *Int8PtrTy = Type::getInt8PtrTy(*Ctx,
746
14
          cast<PointerType>(Ty)->getAddressSpace());
747
14
      Base = new BitCastInst(Base, Int8PtrTy, "base_bitcast", InsertionPt);
748
14
      Mat = GetElementPtrInst::Create(Int8PtrTy->getElementType(), Base,
749
14
          Offset, "mat_gep", InsertionPt);
750
14
      Mat = new BitCastInst(Mat, Ty, "mat_bitcast", InsertionPt);
751
14
    } else
752
2.22k
      // Constant being rebased is a ConstantInt.
753
2.22k
      Mat = BinaryOperator::Create(Instruction::Add, Base, Offset,
754
2.22k
                                 "const_mat", InsertionPt);
755
2.23k
756
2.23k
    LLVM_DEBUG(dbgs() << "Materialize constant (" << *Base->getOperand(0)
757
2.23k
                      << " + " << *Offset << ") in BB "
758
2.23k
                      << Mat->getParent()->getName() << '\n'
759
2.23k
                      << *Mat << '\n');
760
2.23k
    Mat->setDebugLoc(ConstUser.Inst->getDebugLoc());
761
2.23k
  }
762
37.2k
  Value *Opnd = ConstUser.Inst->getOperand(ConstUser.OpndIdx);
763
37.2k
764
37.2k
  // Visit constant integer.
765
37.2k
  if (isa<ConstantInt>(Opnd)) {
766
35.8k
    LLVM_DEBUG(dbgs() << "Update: " << *ConstUser.Inst << '\n');
767
35.8k
    if (!updateOperand(ConstUser.Inst, ConstUser.OpndIdx, Mat) && 
Offset4
)
768
2
      Mat->eraseFromParent();
769
35.8k
    LLVM_DEBUG(dbgs() << "To    : " << *ConstUser.Inst << '\n');
770
35.8k
    return;
771
35.8k
  }
772
1.40k
773
1.40k
  // Visit cast instruction.
774
1.40k
  if (auto CastInst = dyn_cast<Instruction>(Opnd)) {
775
68
    assert(CastInst->isCast() && "Expected an cast instruction!");
776
68
    // Check if we already have visited this cast instruction before to avoid
777
68
    // unnecessary cloning.
778
68
    Instruction *&ClonedCastInst = ClonedCastMap[CastInst];
779
68
    if (!ClonedCastInst) {
780
22
      ClonedCastInst = CastInst->clone();
781
22
      ClonedCastInst->setOperand(0, Mat);
782
22
      ClonedCastInst->insertAfter(CastInst);
783
22
      // Use the same debug location as the original cast instruction.
784
22
      ClonedCastInst->setDebugLoc(CastInst->getDebugLoc());
785
22
      LLVM_DEBUG(dbgs() << "Clone instruction: " << *CastInst << '\n'
786
22
                        << "To               : " << *ClonedCastInst << '\n');
787
22
    }
788
68
789
68
    LLVM_DEBUG(dbgs() << "Update: " << *ConstUser.Inst << '\n');
790
68
    updateOperand(ConstUser.Inst, ConstUser.OpndIdx, ClonedCastInst);
791
68
    LLVM_DEBUG(dbgs() << "To    : " << *ConstUser.Inst << '\n');
792
68
    return;
793
68
  }
794
1.33k
795
1.33k
  // Visit constant expression.
796
1.33k
  if (auto ConstExpr = dyn_cast<ConstantExpr>(Opnd)) {
797
1.33k
    if (ConstExpr->isGEPWithNoNotionalOverIndexing()) {
798
21
      // Operand is a ConstantGEP, replace it.
799
21
      updateOperand(ConstUser.Inst, ConstUser.OpndIdx, Mat);
800
21
      return;
801
21
    }
802
1.31k
803
1.31k
    // Aside from constant GEPs, only constant cast expressions are collected.
804
1.31k
    assert(ConstExpr->isCast() && "ConstExpr should be a cast");
805
1.31k
    Instruction *ConstExprInst = ConstExpr->getAsInstruction();
806
1.31k
    ConstExprInst->setOperand(0, Mat);
807
1.31k
    ConstExprInst->insertBefore(findMatInsertPt(ConstUser.Inst,
808
1.31k
                                                ConstUser.OpndIdx));
809
1.31k
810
1.31k
    // Use the same debug location as the instruction we are about to update.
811
1.31k
    ConstExprInst->setDebugLoc(ConstUser.Inst->getDebugLoc());
812
1.31k
813
1.31k
    LLVM_DEBUG(dbgs() << "Create instruction: " << *ConstExprInst << '\n'
814
1.31k
                      << "From              : " << *ConstExpr << '\n');
815
1.31k
    LLVM_DEBUG(dbgs() << "Update: " << *ConstUser.Inst << '\n');
816
1.31k
    if (!updateOperand(ConstUser.Inst, ConstUser.OpndIdx, ConstExprInst)) {
817
2
      ConstExprInst->eraseFromParent();
818
2
      if (Offset)
819
2
        Mat->eraseFromParent();
820
2
    }
821
1.31k
    LLVM_DEBUG(dbgs() << "To    : " << *ConstUser.Inst << '\n');
822
1.31k
    return;
823
1.31k
  }
824
1.33k
}
825
826
/// Hoist and hide the base constant behind a bitcast and emit
827
/// materialization code for derived constants.
828
5.03k
bool ConstantHoistingPass::emitBaseConstants(GlobalVariable *BaseGV) {
829
5.03k
  bool MadeChange = false;
830
5.03k
  SmallVectorImpl<consthoist::ConstantInfo> &ConstInfoVec =
831
5.03k
      BaseGV ? 
ConstGEPInfoMap[BaseGV]5
:
ConstIntInfoVec5.02k
;
832
8.84k
  for (auto const &ConstInfo : ConstInfoVec) {
833
8.84k
    SmallPtrSet<Instruction *, 8> IPSet = findConstantInsertionPoint(ConstInfo);
834
8.84k
    // We can have an empty set if the function contains unreachable blocks.
835
8.84k
    if (IPSet.empty())
836
2
      continue;
837
8.84k
838
8.84k
    unsigned UsesNum = 0;
839
8.84k
    unsigned ReBasesNum = 0;
840
8.84k
    unsigned NotRebasedNum = 0;
841
15.1k
    for (Instruction *IP : IPSet) {
842
15.1k
      // First, collect constants depending on this IP of the base.
843
15.1k
      unsigned Uses = 0;
844
15.1k
      using RebasedUse = std::tuple<Constant *, Type *, ConstantUser>;
845
15.1k
      SmallVector<RebasedUse, 4> ToBeRebased;
846
16.8k
      for (auto const &RCI : ConstInfo.RebasedConstants) {
847
353k
        for (auto const &U : RCI.Uses) {
848
353k
          Uses++;
849
353k
          BasicBlock *OrigMatInsertBB =
850
353k
              findMatInsertPt(U.Inst, U.OpndIdx)->getParent();
851
353k
          // If Base constant is to be inserted in multiple places,
852
353k
          // generate rebase for U using the Base dominating U.
853
353k
          if (IPSet.size() == 1 ||
854
353k
              
DT->dominates(IP->getParent(), OrigMatInsertBB)331k
)
855
37.2k
            ToBeRebased.push_back(RebasedUse(RCI.Offset, RCI.Ty, U));
856
353k
        }
857
16.8k
      }
858
15.1k
      UsesNum = Uses;
859
15.1k
860
15.1k
      // If only few constants depend on this IP of base, skip rebasing,
861
15.1k
      // assuming the base and the rebased have the same materialization cost.
862
15.1k
      if (ToBeRebased.size() < MinNumOfDependentToRebase) {
863
7
        NotRebasedNum += ToBeRebased.size();
864
7
        continue;
865
7
      }
866
15.1k
867
15.1k
      // Emit an instance of the base at this IP.
868
15.1k
      Instruction *Base = nullptr;
869
15.1k
      // Hoist and hide the base constant behind a bitcast.
870
15.1k
      if (ConstInfo.BaseExpr) {
871
7
        assert(BaseGV && "A base constant expression must have an base GV");
872
7
        Type *Ty = ConstInfo.BaseExpr->getType();
873
7
        Base = new BitCastInst(ConstInfo.BaseExpr, Ty, "const", IP);
874
15.1k
      } else {
875
15.1k
        IntegerType *Ty = ConstInfo.BaseInt->getType();
876
15.1k
        Base = new BitCastInst(ConstInfo.BaseInt, Ty, "const", IP);
877
15.1k
      }
878
15.1k
879
15.1k
      Base->setDebugLoc(IP->getDebugLoc());
880
15.1k
881
15.1k
      LLVM_DEBUG(dbgs() << "Hoist constant (" << *ConstInfo.BaseInt
882
15.1k
                        << ") to BB " << IP->getParent()->getName() << '\n'
883
15.1k
                        << *Base << '\n');
884
15.1k
885
15.1k
      // Emit materialization code for rebased constants depending on this IP.
886
37.2k
      for (auto const &R : ToBeRebased) {
887
37.2k
        Constant *Off = std::get<0>(R);
888
37.2k
        Type *Ty = std::get<1>(R);
889
37.2k
        ConstantUser U = std::get<2>(R);
890
37.2k
        emitBaseConstants(Base, Off, Ty, U);
891
37.2k
        ReBasesNum++;
892
37.2k
        // Use the same debug location as the last user of the constant.
893
37.2k
        Base->setDebugLoc(DILocation::getMergedLocation(
894
37.2k
            Base->getDebugLoc(), U.Inst->getDebugLoc()));
895
37.2k
      }
896
15.1k
      assert(!Base->use_empty() && "The use list is empty!?");
897
15.1k
      assert(isa<Instruction>(Base->user_back()) &&
898
15.1k
             "All uses should be instructions.");
899
15.1k
    }
900
8.84k
    (void)UsesNum;
901
8.84k
    (void)ReBasesNum;
902
8.84k
    (void)NotRebasedNum;
903
8.84k
    // Expect all uses are rebased after rebase is done.
904
8.84k
    assert(UsesNum == (ReBasesNum + NotRebasedNum) &&
905
8.84k
           "Not all uses are rebased");
906
8.84k
907
8.84k
    NumConstantsHoisted++;
908
8.84k
909
8.84k
    // Base constant is also included in ConstInfo.RebasedConstants, so
910
8.84k
    // deduct 1 from ConstInfo.RebasedConstants.size().
911
8.84k
    NumConstantsRebased += ConstInfo.RebasedConstants.size() - 1;
912
8.84k
913
8.84k
    MadeChange = true;
914
8.84k
  }
915
5.03k
  return MadeChange;
916
5.03k
}
917
918
/// Check all cast instructions we made a copy of and remove them if they
919
/// have no more users.
920
489k
void ConstantHoistingPass::deleteDeadCastInst() const {
921
489k
  for (auto const &I : ClonedCastMap)
922
22
    if (I.first->use_empty())
923
18
      I.first->eraseFromParent();
924
489k
}
925
926
/// Optimize expensive integer constants in the given function.
927
bool ConstantHoistingPass::runImpl(Function &Fn, TargetTransformInfo &TTI,
928
                                   DominatorTree &DT, BlockFrequencyInfo *BFI,
929
489k
                                   BasicBlock &Entry, ProfileSummaryInfo *PSI) {
930
489k
  this->TTI = &TTI;
931
489k
  this->DT = &DT;
932
489k
  this->BFI = BFI;
933
489k
  this->DL = &Fn.getParent()->getDataLayout();
934
489k
  this->Ctx = &Fn.getContext();
935
489k
  this->Entry = &Entry;
936
489k
  this->PSI = PSI;
937
489k
  // Collect all constant candidates.
938
489k
  collectConstantCandidates(Fn);
939
489k
940
489k
  // Combine constants that can be easily materialized with an add from a common
941
489k
  // base constant.
942
489k
  if (!ConstIntCandVec.empty())
943
10.3k
    findBaseConstants(nullptr);
944
489k
  for (auto &MapEntry : ConstGEPCandMap)
945
5
    if (!MapEntry.second.empty())
946
5
      findBaseConstants(MapEntry.first);
947
489k
948
489k
  // Finally hoist the base constant and emit materialization code for dependent
949
489k
  // constants.
950
489k
  bool MadeChange = false;
951
489k
  if (!ConstIntInfoVec.empty())
952
5.02k
    MadeChange = emitBaseConstants(nullptr);
953
489k
  for (auto MapEntry : ConstGEPInfoMap)
954
5
    if (!MapEntry.second.empty())
955
5
      MadeChange |= emitBaseConstants(MapEntry.first);
956
489k
957
489k
958
489k
  // Cleanup dead instructions.
959
489k
  deleteDeadCastInst();
960
489k
961
489k
  cleanup();
962
489k
963
489k
  return MadeChange;
964
489k
}
965
966
PreservedAnalyses ConstantHoistingPass::run(Function &F,
967
6
                                            FunctionAnalysisManager &AM) {
968
6
  auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
969
6
  auto &TTI = AM.getResult<TargetIRAnalysis>(F);
970
6
  auto BFI = ConstHoistWithBlockFrequency
971
6
                 ? &AM.getResult<BlockFrequencyAnalysis>(F)
972
6
                 : 
nullptr0
;
973
6
  auto &MAM = AM.getResult<ModuleAnalysisManagerFunctionProxy>(F).getManager();
974
6
  auto *PSI = MAM.getCachedResult<ProfileSummaryAnalysis>(*F.getParent());
975
6
  if (!runImpl(F, TTI, DT, BFI, F.getEntryBlock(), PSI))
976
0
    return PreservedAnalyses::all();
977
6
978
6
  PreservedAnalyses PA;
979
6
  PA.preserveSet<CFGAnalyses>();
980
6
  return PA;
981
6
}