LLVM 23.0.0git
ConstantHoisting.cpp
Go to the documentation of this file.
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 getIntImmCostInst 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
36#include "llvm/ADT/APInt.h"
37#include "llvm/ADT/DenseMap.h"
40#include "llvm/ADT/Statistic.h"
44#include "llvm/IR/BasicBlock.h"
45#include "llvm/IR/Constants.h"
46#include "llvm/IR/DataLayout.h"
47#include "llvm/IR/Dominators.h"
48#include "llvm/IR/Function.h"
49#include "llvm/IR/InstrTypes.h"
50#include "llvm/IR/Instruction.h"
53#include "llvm/IR/Operator.h"
54#include "llvm/IR/Value.h"
56#include "llvm/Pass.h"
60#include "llvm/Support/Debug.h"
65#include <cassert>
66#include <iterator>
67#include <tuple>
68#include <utility>
69
70using namespace llvm;
71using namespace consthoist;
72
73#define DEBUG_TYPE "consthoist"
74
75STATISTIC(NumConstantsHoisted, "Number of constants hoisted");
76STATISTIC(NumConstantsRebased, "Number of constants rebased");
77
79 "consthoist-with-block-frequency", cl::init(true), cl::Hidden,
80 cl::desc("Enable the use of the block frequency analysis to reduce the "
81 "chance to execute const materialization more frequently than "
82 "without hoisting."));
83
85 "consthoist-gep", cl::init(false), cl::Hidden,
86 cl::desc("Try hoisting constant gep expressions"));
87
89MinNumOfDependentToRebase("consthoist-min-num-to-rebase",
90 cl::desc("Do not rebase if number of dependent constants of a Base is less "
91 "than this number."),
93
94namespace {
95
96/// The constant hoisting pass.
97class ConstantHoistingLegacyPass : public FunctionPass {
98public:
99 static char ID; // Pass identification, replacement for typeid
100
101 ConstantHoistingLegacyPass() : FunctionPass(ID) {
103 }
104
105 bool runOnFunction(Function &Fn) override;
106
107 StringRef getPassName() const override { return "Constant Hoisting"; }
108
109 void getAnalysisUsage(AnalysisUsage &AU) const override {
110 AU.setPreservesCFG();
112 AU.addRequired<BlockFrequencyInfoWrapperPass>();
113 AU.addRequired<DominatorTreeWrapperPass>();
114 AU.addRequired<ProfileSummaryInfoWrapperPass>();
115 AU.addRequired<TargetTransformInfoWrapperPass>();
116 }
117
118private:
119 ConstantHoistingPass Impl;
120};
121
122} // end anonymous namespace
123
124char ConstantHoistingLegacyPass::ID = 0;
125
126INITIALIZE_PASS_BEGIN(ConstantHoistingLegacyPass, "consthoist",
127 "Constant Hoisting", false, false)
132INITIALIZE_PASS_END(ConstantHoistingLegacyPass, "consthoist",
133 "Constant Hoisting", false, false)
134
136 return new ConstantHoistingLegacyPass();
137}
138
139/// Perform the constant hoisting optimization for the given function.
140bool ConstantHoistingLegacyPass::runOnFunction(Function &Fn) {
141 if (skipFunction(Fn))
142 return false;
143
144 LLVM_DEBUG(dbgs() << "********** Begin Constant Hoisting **********\n");
145 LLVM_DEBUG(dbgs() << "********** Function: " << Fn.getName() << '\n');
146
147 bool MadeChange =
148 Impl.runImpl(Fn, getAnalysis<TargetTransformInfoWrapperPass>().getTTI(Fn),
149 getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
151 ? &getAnalysis<BlockFrequencyInfoWrapperPass>().getBFI()
152 : nullptr,
153 Fn.getEntryBlock(),
154 &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI());
155
156 LLVM_DEBUG(dbgs() << "********** End Constant Hoisting **********\n");
157
158 return MadeChange;
159}
160
161void ConstantHoistingPass::collectMatInsertPts(
162 const RebasedConstantListType &RebasedConstants,
163 SmallVectorImpl<BasicBlock::iterator> &MatInsertPts) const {
164 for (const RebasedConstantInfo &RCI : RebasedConstants)
165 for (const ConstantUser &U : RCI.Uses)
166 MatInsertPts.emplace_back(findMatInsertPt(U.Inst, U.OpndIdx));
167}
168
169/// Find the constant materialization insertion point.
170BasicBlock::iterator ConstantHoistingPass::findMatInsertPt(Instruction *Inst,
171 unsigned Idx) const {
172 // If the operand is a cast instruction, then we have to materialize the
173 // constant before the cast instruction.
174 if (Idx != ~0U) {
175 Value *Opnd = Inst->getOperand(Idx);
176 if (auto CastInst = dyn_cast<Instruction>(Opnd))
177 if (CastInst->isCast())
178 return CastInst->getIterator();
179 }
180
181 // The simple and common case. This also includes constant expressions.
182 if (!isa<PHINode>(Inst) && !Inst->isEHPad())
183 return Inst->getIterator();
184
185 // We can't insert directly before a phi node or an eh pad. Insert before
186 // the terminator of the incoming or dominating block.
187 assert(Entry != Inst->getParent() && "PHI or landing pad in entry block!");
188 BasicBlock *InsertionBlock = nullptr;
189 if (Idx != ~0U && isa<PHINode>(Inst)) {
190 InsertionBlock = cast<PHINode>(Inst)->getIncomingBlock(Idx);
191 if (!InsertionBlock->isEHPad()) {
192 return InsertionBlock->getTerminator()->getIterator();
193 }
194 } else {
195 InsertionBlock = Inst->getParent();
196 }
197
198 // This must be an EH pad. Iterate over immediate dominators until we find a
199 // non-EH pad. We need to skip over catchswitch blocks, which are both EH pads
200 // and terminators.
201 auto *IDom = DT->getNode(InsertionBlock)->getIDom();
202 while (IDom->getBlock()->isEHPad()) {
203 assert(Entry != IDom->getBlock() && "eh pad in entry block");
204 IDom = IDom->getIDom();
205 }
206
207 return IDom->getBlock()->getTerminator()->getIterator();
208}
209
210/// Given \p BBs as input, find another set of BBs which collectively
211/// dominates \p BBs and have the minimal sum of frequencies. Return the BB
212/// set found in \p BBs.
214 BasicBlock *Entry,
216 assert(!BBs.count(Entry) && "Assume Entry is not in BBs");
217 // Nodes on the current path to the root.
219 // Candidates includes any block 'BB' in set 'BBs' that is not strictly
220 // dominated by any other blocks in set 'BBs', and all nodes in the path
221 // in the dominator tree from Entry to 'BB'.
223 for (auto *BB : BBs) {
224 // Ignore unreachable basic blocks.
225 if (!DT.isReachableFromEntry(BB))
226 continue;
227 Path.clear();
228 // Walk up the dominator tree until Entry or another BB in BBs
229 // is reached. Insert the nodes on the way to the Path.
230 BasicBlock *Node = BB;
231 // The "Path" is a candidate path to be added into Candidates set.
232 bool isCandidate = false;
233 do {
234 Path.insert(Node);
235 if (Node == Entry || Candidates.count(Node)) {
236 isCandidate = true;
237 break;
238 }
239 assert(DT.getNode(Node)->getIDom() &&
240 "Entry doens't dominate current Node");
241 Node = DT.getNode(Node)->getIDom()->getBlock();
242 } while (!BBs.count(Node));
243
244 // If isCandidate is false, Node is another Block in BBs dominating
245 // current 'BB'. Drop the nodes on the Path.
246 if (!isCandidate)
247 continue;
248
249 // Add nodes on the Path into Candidates.
250 Candidates.insert_range(Path);
251 }
252
253 // Sort the nodes in Candidates in top-down order and save the nodes
254 // in Orders.
255 unsigned Idx = 0;
257 Orders.push_back(Entry);
258 while (Idx != Orders.size()) {
259 BasicBlock *Node = Orders[Idx++];
260 for (auto *ChildDomNode : DT.getNode(Node)->children()) {
261 if (Candidates.count(ChildDomNode->getBlock()))
262 Orders.push_back(ChildDomNode->getBlock());
263 }
264 }
265
266 // Visit Orders in bottom-up order.
267 using InsertPtsCostPair =
268 std::pair<SetVector<BasicBlock *>, BlockFrequency>;
269
270 // InsertPtsMap is a map from a BB to the best insertion points for the
271 // subtree of BB (subtree not including the BB itself). Pre-populate every
272 // node so that loop below only uses find().
274 for (BasicBlock *Node : Orders)
275 InsertPtsMap.try_emplace(Node);
276 for (BasicBlock *Node : llvm::reverse(Orders)) {
277 bool NodeInBBs = BBs.count(Node);
278 auto &[InsertPts, InsertPtsFreq] = InsertPtsMap.find(Node)->second;
279
280 // Return the optimal insert points in BBs.
281 if (Node == Entry) {
282 BBs.clear();
283 if (InsertPtsFreq > BFI.getBlockFreq(Node) ||
284 (InsertPtsFreq == BFI.getBlockFreq(Node) && InsertPts.size() > 1))
285 BBs.insert(Entry);
286 else
287 BBs.insert_range(InsertPts);
288 break;
289 }
290
291 BasicBlock *Parent = DT.getNode(Node)->getIDom()->getBlock();
292 // Initially, ParentInsertPts is empty and ParentPtsFreq is 0. Every child
293 // will update its parent's ParentInsertPts and ParentPtsFreq.
294 auto &[ParentInsertPts, ParentPtsFreq] = InsertPtsMap.find(Parent)->second;
295 // Choose to insert in Node or in subtree of Node.
296 // Don't hoist to EHPad because we may not find a proper place to insert
297 // in EHPad.
298 // If the total frequency of InsertPts is the same as the frequency of the
299 // target Node, and InsertPts contains more than one nodes, choose hoisting
300 // to reduce code size.
301 if (NodeInBBs ||
302 (!Node->isEHPad() &&
303 (InsertPtsFreq > BFI.getBlockFreq(Node) ||
304 (InsertPtsFreq == BFI.getBlockFreq(Node) && InsertPts.size() > 1)))) {
305 ParentInsertPts.insert(Node);
306 ParentPtsFreq += BFI.getBlockFreq(Node);
307 } else {
308 ParentInsertPts.insert_range(InsertPts);
309 ParentPtsFreq += InsertPtsFreq;
310 }
311 }
312}
313
314/// Find an insertion point that dominates all uses.
315SetVector<BasicBlock::iterator>
316ConstantHoistingPass::findConstantInsertionPoint(
317 const ConstantInfo &ConstInfo,
318 const ArrayRef<BasicBlock::iterator> MatInsertPts) const {
319 assert(!ConstInfo.RebasedConstants.empty() && "Invalid constant info entry.");
320 // Collect all basic blocks.
321 SetVector<BasicBlock *> BBs;
322 SetVector<BasicBlock::iterator> InsertPts;
323
324 for (BasicBlock::iterator MatInsertPt : MatInsertPts)
325 BBs.insert(MatInsertPt->getParent());
326
327 if (BBs.count(Entry)) {
328 InsertPts.insert(Entry->begin());
329 return InsertPts;
330 }
331
332 if (BFI) {
333 findBestInsertionSet(*DT, *BFI, Entry, BBs);
334 for (BasicBlock *BB : BBs)
335 InsertPts.insert(BB->getFirstInsertionPt());
336 return InsertPts;
337 }
338
339 while (BBs.size() >= 2) {
340 BasicBlock *BB, *BB1, *BB2;
341 BB1 = BBs.pop_back_val();
342 BB2 = BBs.pop_back_val();
343 BB = DT->findNearestCommonDominator(BB1, BB2);
344 if (BB == Entry) {
345 InsertPts.insert(Entry->begin());
346 return InsertPts;
347 }
348 BBs.insert(BB);
349 }
350 assert((BBs.size() == 1) && "Expected only one element.");
351 Instruction &FirstInst = (*BBs.begin())->front();
352 InsertPts.insert(findMatInsertPt(&FirstInst));
353 return InsertPts;
354}
355
356/// Record constant integer ConstInt for instruction Inst at operand
357/// index Idx.
358///
359/// The operand at index Idx is not necessarily the constant integer itself. It
360/// could also be a cast instruction or a constant expression that uses the
361/// constant integer.
362void ConstantHoistingPass::collectConstantCandidates(
363 ConstCandMapType &ConstCandMap, Instruction *Inst, unsigned Idx,
364 ConstantInt *ConstInt) {
365 if (ConstInt->getType()->isVectorTy())
366 return;
367
369 // Ask the target about the cost of materializing the constant for the given
370 // instruction and operand index.
371 if (auto IntrInst = dyn_cast<IntrinsicInst>(Inst))
372 Cost = TTI->getIntImmCostIntrin(IntrInst->getIntrinsicID(), Idx,
373 ConstInt->getValue(), ConstInt->getType(),
375 else
377 Inst->getOpcode(), Idx, ConstInt->getValue(), ConstInt->getType(),
379
380 // Ignore cheap integer constants.
382 ConstCandMapType::iterator Itr;
383 bool Inserted;
384 ConstPtrUnionType Cand = ConstInt;
385 std::tie(Itr, Inserted) = ConstCandMap.try_emplace(Cand);
386 if (Inserted) {
387 ConstIntCandVec.push_back(ConstantCandidate(ConstInt));
388 Itr->second = ConstIntCandVec.size() - 1;
389 }
390 ConstIntCandVec[Itr->second].addUser(Inst, Idx, Cost.getValue());
391 LLVM_DEBUG(if (isa<ConstantInt>(Inst->getOperand(Idx))) dbgs()
392 << "Collect constant " << *ConstInt << " from " << *Inst
393 << " with cost " << Cost << '\n';
394 else dbgs() << "Collect constant " << *ConstInt
395 << " indirectly from " << *Inst << " via "
396 << *Inst->getOperand(Idx) << " with cost " << Cost
397 << '\n';);
398 }
399}
400
401/// Record constant GEP expression for instruction Inst at operand index Idx.
402void ConstantHoistingPass::collectConstantCandidates(
403 ConstCandMapType &ConstCandMap, Instruction *Inst, unsigned Idx,
404 ConstantExpr *ConstExpr) {
405 // TODO: Handle vector GEPs
406 if (ConstExpr->getType()->isVectorTy())
407 return;
408
409 GlobalVariable *BaseGV = dyn_cast<GlobalVariable>(ConstExpr->getOperand(0));
410 if (!BaseGV)
411 return;
412
413 // Get offset from the base GV.
414 PointerType *GVPtrTy = cast<PointerType>(BaseGV->getType());
415 IntegerType *OffsetTy = DL->getIndexType(*Ctx, GVPtrTy->getAddressSpace());
416 APInt Offset(DL->getTypeSizeInBits(OffsetTy), /*val*/ 0, /*isSigned*/ true);
417 auto *GEPO = cast<GEPOperator>(ConstExpr);
418
419 // TODO: If we have a mix of inbounds and non-inbounds GEPs, then basing a
420 // non-inbounds GEP on an inbounds GEP is potentially incorrect. Restrict to
421 // inbounds GEP for now -- alternatively, we could drop inbounds from the
422 // constant expression,
423 if (!GEPO->isInBounds())
424 return;
425
426 if (!GEPO->accumulateConstantOffset(*DL, Offset))
427 return;
428
429 if (!Offset.isIntN(32))
430 return;
431
432 // A constant GEP expression that has a GlobalVariable as base pointer is
433 // usually lowered to a load from constant pool. Such operation is unlikely
434 // to be cheaper than compute it by <Base + Offset>, which can be lowered to
435 // an ADD instruction or folded into Load/Store instruction.
437 TTI->getIntImmCostInst(Instruction::Add, 1, Offset, OffsetTy,
439 ConstCandVecType &ExprCandVec = ConstGEPCandMap[BaseGV];
440 ConstCandMapType::iterator Itr;
441 bool Inserted;
442 ConstPtrUnionType Cand = ConstExpr;
443 std::tie(Itr, Inserted) = ConstCandMap.try_emplace(Cand);
444 if (Inserted) {
445 ExprCandVec.push_back(ConstantCandidate(
446 ConstantInt::get(Type::getInt32Ty(*Ctx), Offset.getLimitedValue()),
447 ConstExpr));
448 Itr->second = ExprCandVec.size() - 1;
449 }
450 ExprCandVec[Itr->second].addUser(Inst, Idx, Cost.getValue());
451}
452
453/// Check the operand for instruction Inst at index Idx.
454void ConstantHoistingPass::collectConstantCandidates(
455 ConstCandMapType &ConstCandMap, Instruction *Inst, unsigned Idx) {
456 Value *Opnd = Inst->getOperand(Idx);
457
458 // Visit constant integers.
459 if (auto ConstInt = dyn_cast<ConstantInt>(Opnd)) {
460 collectConstantCandidates(ConstCandMap, Inst, Idx, ConstInt);
461 return;
462 }
463
464 // Visit cast instructions that have constant integers.
465 if (auto CastInst = dyn_cast<Instruction>(Opnd)) {
466 // Only visit cast instructions, which have been skipped. All other
467 // instructions should have already been visited.
468 if (!CastInst->isCast())
469 return;
470
471 if (auto *ConstInt = dyn_cast<ConstantInt>(CastInst->getOperand(0))) {
472 // Pretend the constant is directly used by the instruction and ignore
473 // the cast instruction.
474 collectConstantCandidates(ConstCandMap, Inst, Idx, ConstInt);
475 return;
476 }
477 }
478
479 // Visit constant expressions that have constant integers.
480 if (auto ConstExpr = dyn_cast<ConstantExpr>(Opnd)) {
481 // Handle constant gep expressions.
482 if (ConstHoistGEP && isa<GEPOperator>(ConstExpr))
483 collectConstantCandidates(ConstCandMap, Inst, Idx, ConstExpr);
484
485 // Only visit constant cast expressions.
486 if (!ConstExpr->isCast())
487 return;
488
489 if (auto ConstInt = dyn_cast<ConstantInt>(ConstExpr->getOperand(0))) {
490 // Pretend the constant is directly used by the instruction and ignore
491 // the constant expression.
492 collectConstantCandidates(ConstCandMap, Inst, Idx, ConstInt);
493 return;
494 }
495 }
496}
497
498/// Scan the instruction for expensive integer constants and record them
499/// in the constant candidate vector.
500void ConstantHoistingPass::collectConstantCandidates(
501 ConstCandMapType &ConstCandMap, Instruction *Inst) {
502 // Skip all cast instructions. They are visited indirectly later on.
503 if (Inst->isCast())
504 return;
505
506 // Scan all operands.
507 for (unsigned Idx = 0, E = Inst->getNumOperands(); Idx != E; ++Idx) {
508 // Skip analyzing incoming PHI edges from unreachable blocks.
509 if (auto PHI = dyn_cast<PHINode>(Inst)) {
510 BasicBlock *IncomingBB = PHI->getIncomingBlock(Idx);
511 if (!DT->isReachableFromEntry(IncomingBB))
512 continue;
513 }
514 // The cost of materializing the constants (defined in
515 // `TargetTransformInfo::getIntImmCostInst`) for instructions which only
516 // take constant variables is lower than `TargetTransformInfo::TCC_Basic`.
517 // So it's safe for us to collect constant candidates from all
518 // IntrinsicInsts.
519 if (canReplaceOperandWithVariable(Inst, Idx)) {
520 collectConstantCandidates(ConstCandMap, Inst, Idx);
521 }
522 } // end of for all operands
523}
524
525/// Collect all integer constants in the function that cannot be folded
526/// into an instruction itself.
527void ConstantHoistingPass::collectConstantCandidates(Function &Fn) {
528 ConstCandMapType ConstCandMap;
529 for (BasicBlock &BB : Fn) {
530 // Ignore unreachable basic blocks.
531 if (!DT->isReachableFromEntry(&BB))
532 continue;
533 for (Instruction &Inst : BB)
534 if (!TTI->preferToKeepConstantsAttached(Inst, Fn))
535 collectConstantCandidates(ConstCandMap, &Inst);
536 }
537}
538
539// From a list of constants, one needs to picked as the base and the other
540// constants will be transformed into an offset from that base constant. The
541// question is which we can pick best? For example, consider these constants
542// and their number of uses:
543//
544// Constants| 2 | 4 | 12 | 42 |
545// NumUses | 3 | 2 | 8 | 7 |
546//
547// Selecting constant 12 because it has the most uses will generate negative
548// offsets for constants 2 and 4 (i.e. -10 and -8 respectively). If negative
549// offsets lead to less optimal code generation, then there might be better
550// solutions. Suppose immediates in the range of 0..35 are most optimally
551// supported by the architecture, then selecting constant 2 is most optimal
552// because this will generate offsets: 0, 2, 10, 40. Offsets 0, 2 and 10 are in
553// range 0..35, and thus 3 + 2 + 8 = 13 uses are in range. Selecting 12 would
554// have only 8 uses in range, so choosing 2 as a base is more optimal. Thus, in
555// selecting the base constant the range of the offsets is a very important
556// factor too that we take into account here. This algorithm calculates a total
557// costs for selecting a constant as the base and substract the costs if
558// immediates are out of range. It has quadratic complexity, so we call this
559// function only when we're optimising for size and there are less than 100
560// constants, we fall back to the straightforward algorithm otherwise
561// which does not do all the offset calculations.
562unsigned
563ConstantHoistingPass::maximizeConstantsInRange(ConstCandVecType::iterator S,
564 ConstCandVecType::iterator E,
565 ConstCandVecType::iterator &MaxCostItr) {
566 unsigned NumUses = 0;
567
568 if (!OptForSize || std::distance(S,E) > 100) {
569 for (auto ConstCand = S; ConstCand != E; ++ConstCand) {
570 NumUses += ConstCand->Uses.size();
571 if (ConstCand->CumulativeCost > MaxCostItr->CumulativeCost)
572 MaxCostItr = ConstCand;
573 }
574 return NumUses;
575 }
576
577 LLVM_DEBUG(dbgs() << "== Maximize constants in range ==\n");
578 InstructionCost MaxCost = -1;
579 for (auto ConstCand = S; ConstCand != E; ++ConstCand) {
580 auto Value = ConstCand->ConstInt->getValue();
581 Type *Ty = ConstCand->ConstInt->getType();
583 NumUses += ConstCand->Uses.size();
584 LLVM_DEBUG(dbgs() << "= Constant: " << ConstCand->ConstInt->getValue()
585 << "\n");
586
587 for (auto User : ConstCand->Uses) {
588 unsigned Opcode = User.Inst->getOpcode();
589 unsigned OpndIdx = User.OpndIdx;
590 Cost += TTI->getIntImmCostInst(Opcode, OpndIdx, Value, Ty,
592 LLVM_DEBUG(dbgs() << "Cost: " << Cost << "\n");
593
594 for (auto C2 = S; C2 != E; ++C2) {
595 APInt Diff = C2->ConstInt->getValue() - ConstCand->ConstInt->getValue();
596 const InstructionCost ImmCosts =
597 TTI->getIntImmCodeSizeCost(Opcode, OpndIdx, Diff, Ty);
598 Cost -= ImmCosts;
599 LLVM_DEBUG(dbgs() << "Offset " << Diff << " "
600 << "has penalty: " << ImmCosts << "\n"
601 << "Adjusted cost: " << Cost << "\n");
602 }
603 }
604 LLVM_DEBUG(dbgs() << "Cumulative cost: " << Cost << "\n");
605 if (Cost > MaxCost) {
606 MaxCost = Cost;
607 MaxCostItr = ConstCand;
608 LLVM_DEBUG(dbgs() << "New candidate: " << MaxCostItr->ConstInt->getValue()
609 << "\n");
610 }
611 }
612 return NumUses;
613}
614
615/// Find the base constant within the given range and rebase all other
616/// constants with respect to the base constant.
617void ConstantHoistingPass::findAndMakeBaseConstant(
618 ConstCandVecType::iterator S, ConstCandVecType::iterator E,
619 SmallVectorImpl<consthoist::ConstantInfo> &ConstInfoVec) {
620 auto MaxCostItr = S;
621 unsigned NumUses = maximizeConstantsInRange(S, E, MaxCostItr);
622
623 // Don't hoist constants that have only one use.
624 if (NumUses <= 1)
625 return;
626
627 ConstantInt *ConstInt = MaxCostItr->ConstInt;
628 ConstantExpr *ConstExpr = MaxCostItr->ConstExpr;
629 ConstantInfo ConstInfo;
630 ConstInfo.BaseInt = ConstInt;
631 ConstInfo.BaseExpr = ConstExpr;
632 Type *Ty = ConstInt->getType();
633
634 // Rebase the constants with respect to the base constant.
635 for (auto ConstCand = S; ConstCand != E; ++ConstCand) {
636 APInt Diff = ConstCand->ConstInt->getValue() - ConstInt->getValue();
637 Constant *Offset = Diff == 0 ? nullptr : ConstantInt::get(Ty, Diff);
638 Type *ConstTy =
639 ConstCand->ConstExpr ? ConstCand->ConstExpr->getType() : nullptr;
640 ConstInfo.RebasedConstants.push_back(
641 RebasedConstantInfo(std::move(ConstCand->Uses), Offset, ConstTy));
642 }
643 ConstInfoVec.push_back(std::move(ConstInfo));
644}
645
646/// Finds and combines constant candidates that can be easily
647/// rematerialized with an add from a common base constant.
648void ConstantHoistingPass::findBaseConstants(GlobalVariable *BaseGV) {
649 // If BaseGV is nullptr, find base among candidate constant integers;
650 // Otherwise find base among constant GEPs that share the same BaseGV.
651 ConstCandVecType &ConstCandVec = BaseGV ?
652 ConstGEPCandMap[BaseGV] : ConstIntCandVec;
653 ConstInfoVecType &ConstInfoVec = BaseGV ?
654 ConstGEPInfoMap[BaseGV] : ConstIntInfoVec;
655
656 // Sort the constants by value and type. This invalidates the mapping!
657 llvm::stable_sort(ConstCandVec, [](const ConstantCandidate &LHS,
658 const ConstantCandidate &RHS) {
659 if (LHS.ConstInt->getType() != RHS.ConstInt->getType())
660 return LHS.ConstInt->getBitWidth() < RHS.ConstInt->getBitWidth();
661 return LHS.ConstInt->getValue().ult(RHS.ConstInt->getValue());
662 });
663
664 // Simple linear scan through the sorted constant candidate vector for viable
665 // merge candidates.
666 auto MinValItr = ConstCandVec.begin();
667 for (auto CC = std::next(ConstCandVec.begin()), E = ConstCandVec.end();
668 CC != E; ++CC) {
669 if (MinValItr->ConstInt->getType() == CC->ConstInt->getType()) {
670 Type *MemUseValTy = nullptr;
671 for (auto &U : CC->Uses) {
672 auto *UI = U.Inst;
673 if (LoadInst *LI = dyn_cast<LoadInst>(UI)) {
674 MemUseValTy = LI->getType();
675 break;
676 } else if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
677 // Make sure the constant is used as pointer operand of the StoreInst.
678 if (SI->getPointerOperand() == SI->getOperand(U.OpndIdx)) {
679 MemUseValTy = SI->getValueOperand()->getType();
680 break;
681 }
682 }
683 }
684
685 // Check if the constant is in range of an add with immediate.
686 APInt Diff = CC->ConstInt->getValue() - MinValItr->ConstInt->getValue();
687 if ((Diff.getBitWidth() <= 64) &&
689 // Check if Diff can be used as offset in addressing mode of the user
690 // memory instruction.
691 (!MemUseValTy || TTI->isLegalAddressingMode(MemUseValTy,
692 /*BaseGV*/nullptr, /*BaseOffset*/Diff.getSExtValue(),
693 /*HasBaseReg*/true, /*Scale*/0)))
694 continue;
695 }
696 // We either have now a different constant type or the constant is not in
697 // range of an add with immediate anymore.
698 findAndMakeBaseConstant(MinValItr, CC, ConstInfoVec);
699 // Start a new base constant search.
700 MinValItr = CC;
701 }
702 // Finalize the last base constant search.
703 findAndMakeBaseConstant(MinValItr, ConstCandVec.end(), ConstInfoVec);
704}
705
706/// Updates the operand at Idx in instruction Inst with the result of
707/// instruction Mat. If the instruction is a PHI node then special
708/// handling for duplicate values from the same incoming basic block is
709/// required.
710/// \return The update will always succeed, but the return value indicated if
711/// Mat was used for the update or not.
712static bool updateOperand(Instruction *Inst, unsigned Idx, Instruction *Mat) {
713 if (auto PHI = dyn_cast<PHINode>(Inst)) {
714 // Check if any previous operand of the PHI node has the same incoming basic
715 // block. This is a very odd case that happens when the incoming basic block
716 // has a switch statement. In this case use the same value as the previous
717 // operand(s), otherwise we will fail verification due to different values.
718 // The values are actually the same, but the variable names are different
719 // and the verifier doesn't like that.
720 BasicBlock *IncomingBB = PHI->getIncomingBlock(Idx);
721 for (unsigned i = 0; i < Idx; ++i) {
722 if (PHI->getIncomingBlock(i) == IncomingBB) {
723 Value *IncomingVal = PHI->getIncomingValue(i);
724 Inst->setOperand(Idx, IncomingVal);
725 return false;
726 }
727 }
728 }
729
730 Inst->setOperand(Idx, Mat);
731 return true;
732}
733
734/// Emit materialization code for all rebased constants and update their
735/// users.
736void ConstantHoistingPass::emitBaseConstants(Instruction *Base,
737 UserAdjustment *Adj) {
738 Instruction *Mat = Base;
739
740 // The same offset can be dereferenced to different types in nested struct.
741 if (!Adj->Offset && Adj->Ty && Adj->Ty != Base->getType())
742 Adj->Offset = ConstantInt::get(Type::getInt32Ty(*Ctx), 0);
743
744 if (Adj->Offset) {
745 if (Adj->Ty) {
746 // Constant being rebased is a ConstantExpr.
747 Mat = GetElementPtrInst::Create(Type::getInt8Ty(*Ctx), Base, Adj->Offset,
748 "mat_gep", Adj->MatInsertPt);
749 // Hide it behind a bitcast.
750 Mat = new BitCastInst(Mat, Adj->Ty, "mat_bitcast",
751 Adj->MatInsertPt->getIterator());
752 } else
753 // Constant being rebased is a ConstantInt.
754 Mat =
755 BinaryOperator::Create(Instruction::Add, Base, Adj->Offset,
756 "const_mat", Adj->MatInsertPt->getIterator());
757
758 LLVM_DEBUG(dbgs() << "Materialize constant (" << *Base->getOperand(0)
759 << " + " << *Adj->Offset << ") in BB "
760 << Mat->getParent()->getName() << '\n'
761 << *Mat << '\n');
762 Mat->setDebugLoc(Adj->User.Inst->getDebugLoc());
763 }
764 Value *Opnd = Adj->User.Inst->getOperand(Adj->User.OpndIdx);
765
766 // Visit constant integer.
767 if (isa<ConstantInt>(Opnd)) {
768 LLVM_DEBUG(dbgs() << "Update: " << *Adj->User.Inst << '\n');
769 if (!updateOperand(Adj->User.Inst, Adj->User.OpndIdx, Mat) && Adj->Offset)
770 Mat->eraseFromParent();
771 LLVM_DEBUG(dbgs() << "To : " << *Adj->User.Inst << '\n');
772 return;
773 }
774
775 // Visit cast instruction.
776 if (auto CastInst = dyn_cast<Instruction>(Opnd)) {
777 assert(CastInst->isCast() && "Expected an cast instruction!");
778 // Check if we already have visited this cast instruction before to avoid
779 // unnecessary cloning.
780 Instruction *&ClonedCastInst = ClonedCastMap[CastInst];
781 if (!ClonedCastInst) {
782 ClonedCastInst = CastInst->clone();
783 ClonedCastInst->setOperand(0, Mat);
784 ClonedCastInst->insertAfter(CastInst->getIterator());
785 // Use the same debug location as the original cast instruction.
786 ClonedCastInst->setDebugLoc(CastInst->getDebugLoc());
787 LLVM_DEBUG(dbgs() << "Clone instruction: " << *CastInst << '\n'
788 << "To : " << *ClonedCastInst << '\n');
789 }
790
791 LLVM_DEBUG(dbgs() << "Update: " << *Adj->User.Inst << '\n');
792 updateOperand(Adj->User.Inst, Adj->User.OpndIdx, ClonedCastInst);
793 LLVM_DEBUG(dbgs() << "To : " << *Adj->User.Inst << '\n');
794 return;
795 }
796
797 // Visit constant expression.
798 if (auto ConstExpr = dyn_cast<ConstantExpr>(Opnd)) {
799 if (isa<GEPOperator>(ConstExpr)) {
800 // Operand is a ConstantGEP, replace it.
801 updateOperand(Adj->User.Inst, Adj->User.OpndIdx, Mat);
802 return;
803 }
804
805 // Aside from constant GEPs, only constant cast expressions are collected.
806 assert(ConstExpr->isCast() && "ConstExpr should be a cast");
807 Instruction *ConstExprInst = ConstExpr->getAsInstruction();
808 ConstExprInst->insertBefore(Adj->MatInsertPt);
809 ConstExprInst->setOperand(0, Mat);
810
811 // Use the same debug location as the instruction we are about to update.
812 ConstExprInst->setDebugLoc(Adj->User.Inst->getDebugLoc());
813
814 LLVM_DEBUG(dbgs() << "Create instruction: " << *ConstExprInst << '\n'
815 << "From : " << *ConstExpr << '\n');
816 LLVM_DEBUG(dbgs() << "Update: " << *Adj->User.Inst << '\n');
817 if (!updateOperand(Adj->User.Inst, Adj->User.OpndIdx, ConstExprInst)) {
818 ConstExprInst->eraseFromParent();
819 if (Adj->Offset)
820 Mat->eraseFromParent();
821 }
822 LLVM_DEBUG(dbgs() << "To : " << *Adj->User.Inst << '\n');
823 return;
824 }
825}
826
827/// Hoist and hide the base constant behind a bitcast and emit
828/// materialization code for derived constants.
829bool ConstantHoistingPass::emitBaseConstants(GlobalVariable *BaseGV) {
830 bool MadeChange = false;
831 SmallVectorImpl<consthoist::ConstantInfo> &ConstInfoVec =
832 BaseGV ? ConstGEPInfoMap[BaseGV] : ConstIntInfoVec;
833 for (const consthoist::ConstantInfo &ConstInfo : ConstInfoVec) {
835 collectMatInsertPts(ConstInfo.RebasedConstants, MatInsertPts);
836 SetVector<BasicBlock::iterator> IPSet =
837 findConstantInsertionPoint(ConstInfo, MatInsertPts);
838 // We can have an empty set if the function contains unreachable blocks.
839 if (IPSet.empty())
840 continue;
841
842 unsigned UsesNum = 0;
843 unsigned ReBasesNum = 0;
844 unsigned NotRebasedNum = 0;
845 for (const BasicBlock::iterator &IP : IPSet) {
846 // First, collect constants depending on this IP of the base.
847 UsesNum = 0;
849 unsigned MatCtr = 0;
850 for (auto const &RCI : ConstInfo.RebasedConstants) {
851 UsesNum += RCI.Uses.size();
852 for (auto const &U : RCI.Uses) {
853 const BasicBlock::iterator &MatInsertPt = MatInsertPts[MatCtr++];
854 BasicBlock *OrigMatInsertBB = MatInsertPt->getParent();
855 // If Base constant is to be inserted in multiple places,
856 // generate rebase for U using the Base dominating U.
857 if (IPSet.size() == 1 ||
858 DT->dominates(IP->getParent(), OrigMatInsertBB))
859 ToBeRebased.emplace_back(RCI.Offset, RCI.Ty, MatInsertPt, U);
860 }
861 }
862
863 // If only few constants depend on this IP of base, skip rebasing,
864 // assuming the base and the rebased have the same materialization cost.
865 if (ToBeRebased.size() < MinNumOfDependentToRebase) {
866 NotRebasedNum += ToBeRebased.size();
867 continue;
868 }
869
870 // Emit an instance of the base at this IP.
871 Instruction *Base = nullptr;
872 // Hoist and hide the base constant behind a bitcast.
873 if (ConstInfo.BaseExpr) {
874 assert(BaseGV && "A base constant expression must have an base GV");
875 Type *Ty = ConstInfo.BaseExpr->getType();
876 Base = new BitCastInst(ConstInfo.BaseExpr, Ty, "const", IP);
877 } else {
878 IntegerType *Ty = ConstInfo.BaseInt->getIntegerType();
879 Base = new BitCastInst(ConstInfo.BaseInt, Ty, "const", IP);
880 }
881
882 Base->setDebugLoc(IP->getDebugLoc());
883
884 LLVM_DEBUG(dbgs() << "Hoist constant (" << *ConstInfo.BaseInt
885 << ") to BB " << IP->getParent()->getName() << '\n'
886 << *Base << '\n');
887
888 // Emit materialization code for rebased constants depending on this IP.
889 for (UserAdjustment &R : ToBeRebased) {
890 emitBaseConstants(Base, &R);
891 ReBasesNum++;
892 // Use the same debug location as the last user of the constant.
894 Base->getDebugLoc(), R.User.Inst->getDebugLoc()));
895 }
896 assert(!Base->use_empty() && "The use list is empty!?");
897 assert(isa<Instruction>(Base->user_back()) &&
898 "All uses should be instructions.");
899 }
900 (void)UsesNum;
901 (void)ReBasesNum;
902 (void)NotRebasedNum;
903 // Expect all uses are rebased after rebase is done.
904 assert(UsesNum == (ReBasesNum + NotRebasedNum) &&
905 "Not all uses are rebased");
906
907 NumConstantsHoisted++;
908
909 // Base constant is also included in ConstInfo.RebasedConstants, so
910 // deduct 1 from ConstInfo.RebasedConstants.size().
911 NumConstantsRebased += ConstInfo.RebasedConstants.size() - 1;
912
913 MadeChange = true;
914 }
915 return MadeChange;
916}
917
918/// Check all cast instructions we made a copy of and remove them if they
919/// have no more users.
920void ConstantHoistingPass::deleteDeadCastInst() const {
921 for (auto const &I : ClonedCastMap)
922 if (I.first->use_empty())
923 I.first->eraseFromParent();
924}
925
926/// Optimize expensive integer constants in the given function.
929 BasicBlock &Entry, ProfileSummaryInfo *PSI) {
930 this->TTI = &TTI;
931 this->DT = &DT;
932 this->BFI = BFI;
933 this->DL = &Fn.getDataLayout();
934 this->Ctx = &Fn.getContext();
935 this->Entry = &Entry;
936 this->PSI = PSI;
937 this->OptForSize = llvm::shouldOptimizeForSize(Entry.getParent(), PSI, BFI,
939
940 // Collect all constant candidates.
941 collectConstantCandidates(Fn);
942
943 // Combine constants that can be easily materialized with an add from a common
944 // base constant.
945 if (!ConstIntCandVec.empty())
946 findBaseConstants(nullptr);
947 for (const auto &MapEntry : ConstGEPCandMap)
948 if (!MapEntry.second.empty())
949 findBaseConstants(MapEntry.first);
950
951 // Finally hoist the base constant and emit materialization code for dependent
952 // constants.
953 bool MadeChange = false;
954 if (!ConstIntInfoVec.empty())
955 MadeChange = emitBaseConstants(nullptr);
956 for (const auto &MapEntry : ConstGEPInfoMap)
957 if (!MapEntry.second.empty())
958 MadeChange |= emitBaseConstants(MapEntry.first);
959
960
961 // Cleanup dead instructions.
962 deleteDeadCastInst();
963
964 cleanup();
965
966 return MadeChange;
967}
968
971 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
972 auto &TTI = AM.getResult<TargetIRAnalysis>(F);
975 : nullptr;
976 auto &MAMProxy = AM.getResult<ModuleAnalysisManagerFunctionProxy>(F);
977 auto *PSI = MAMProxy.getCachedResult<ProfileSummaryAnalysis>(*F.getParent());
978 if (!runImpl(F, TTI, DT, BFI, F.getEntryBlock(), PSI))
979 return PreservedAnalyses::all();
980
983 return PA;
984}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
Rewrite undef for PHI
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static void cleanup(BlockFrequencyInfoImplBase &BFI)
Clear all memory not needed downstream.
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static bool runImpl(MachineFunction &MF)
Definition CFIFixup.cpp:304
static bool updateOperand(Instruction *Inst, unsigned Idx, Instruction *Mat)
Updates the operand at Idx in instruction Inst with the result of instruction Mat.
static void findBestInsertionSet(DominatorTree &DT, BlockFrequencyInfo &BFI, BasicBlock *Entry, SetVector< BasicBlock * > &BBs)
Given BBs as input, find another set of BBs which collectively dominates BBs and have the minimal sum...
static cl::opt< unsigned > MinNumOfDependentToRebase("consthoist-min-num-to-rebase", cl::desc("Do not rebase if number of dependent constants of a Base is less " "than this number."), cl::init(0), cl::Hidden)
static cl::opt< bool > ConstHoistWithBlockFrequency("consthoist-with-block-frequency", cl::init(true), cl::Hidden, cl::desc("Enable the use of the block frequency analysis to reduce the " "chance to execute const materialization more frequently than " "without hoisting."))
static cl::opt< bool > ConstHoistGEP("consthoist-gep", cl::init(false), cl::Hidden, cl::desc("Try hoisting constant gep expressions"))
This file contains the declarations for the subclasses of Constant, which represent the different fla...
This file defines the DenseMap class.
static bool runOnFunction(Function &F, bool PostInlining)
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
static bool isCandidate(const MachineInstr *MI, Register &DefedReg, Register FrameReg)
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
static DominatorTree getDomTree(Function &F)
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
#define LLVM_DEBUG(...)
Definition Debug.h:119
This pass exposes codegen information to IR-level passes.
Value * RHS
Value * LHS
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition APInt.h:1511
int64_t getSExtValue() const
Get sign extended value.
Definition APInt.h:1585
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
AnalysisUsage & addRequired()
LLVM_ABI void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition Pass.cpp:275
LLVM Basic Block Representation.
Definition BasicBlock.h:62
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:170
bool isEHPad() const
Return true if this basic block is an exception handling block.
Definition BasicBlock.h:704
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
static LLVM_ABI BinaryOperator * Create(BinaryOps Op, Value *S1, Value *S2, const Twine &Name=Twine(), InsertPosition InsertBefore=nullptr)
Construct a binary instruction, given the opcode and the two operands.
Analysis pass which computes BlockFrequencyInfo.
Legacy analysis pass which computes BlockFrequencyInfo.
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
LLVM_ABI BlockFrequency getBlockFreq(const BasicBlock *BB) const
getblockFreq - Return block frequency.
Represents analyses that only rely on functions' control flow.
Definition Analysis.h:73
LLVM_ABI bool isCast() const
Return true if this is a convert constant expression.
LLVM_ABI Instruction * getAsInstruction() const
Returns an Instruction which implements the same operation as this ConstantExpr.
LLVM_ABI bool runImpl(Function &F, TargetTransformInfo &TTI, DominatorTree &DT, BlockFrequencyInfo *BFI, BasicBlock &Entry, ProfileSummaryInfo *PSI)
Optimize expensive integer constants in the given function.
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
IntegerType * getIntegerType() const
Variant of the getType() method to always return an IntegerType, which reduces the amount of casting ...
Definition Constants.h:198
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition Constants.h:159
static LLVM_ABI DebugLoc getMergedLocation(DebugLoc LocA, DebugLoc LocB)
When two instructions are combined into a single instruction we also need to combine the original loc...
Definition DebugLoc.cpp:169
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:225
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Definition DenseMap.h:301
iterator_range< iterator > children()
DomTreeNodeBase * getIDom() const
NodeT * getBlock() const
Analysis pass which computes a DominatorTree.
Definition Dominators.h:270
DomTreeNodeBase< NodeT > * getNode(const NodeT *BB) const
getNode - return the (Post)DominatorTree node for the specified basic block.
Legacy analysis pass which computes a DominatorTree.
Definition Dominators.h:306
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:151
LLVM_ABI bool isReachableFromEntry(const Use &U) const
Provide an overload for a Use.
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:314
const BasicBlock & getEntryBlock() const
Definition Function.h:809
const DataLayout & getDataLayout() const
Get the data layout of the module this function belongs to.
Definition Function.cpp:358
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function.
Definition Function.cpp:354
static GetElementPtrInst * Create(Type *PointeeType, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
PointerType * getType() const
Global values are always pointers.
CostType getValue() const
This function is intended to be used as sparingly as possible, since the class provides the full rang...
LLVM_ABI Instruction * clone() const
Create a copy of 'this' instruction that is identical in all ways except the following:
bool isCast() const
LLVM_ABI void insertBefore(InstListType::iterator InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified position.
bool isEHPad() const
Return true if the instruction is a variety of EH-block.
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
LLVM_ABI void insertAfter(Instruction *InsertPos)
Insert an unlinked instruction into a basic block immediately after the specified instruction.
static LLVM_ABI PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalyses & preserveSet()
Mark an analysis set as preserved.
Definition Analysis.h:151
An analysis pass based on the new PM to deliver ProfileSummaryInfo.
An analysis pass based on legacy pass manager to deliver ProfileSummaryInfo.
Analysis providing profile information.
A vector that has set insertion semantics.
Definition SetVector.h:57
void insert_range(Range &&R)
Definition SetVector.h:176
size_type count(const_arg_type key) const
Count the number of elements of a given key in the SetVector.
Definition SetVector.h:262
void clear()
Completely clear the SetVector.
Definition SetVector.h:267
bool empty() const
Determine if the SetVector is empty or not.
Definition SetVector.h:100
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:151
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
void insert_range(Range &&R)
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
reference emplace_back(ArgTypes &&... Args)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Analysis pass providing the TargetTransformInfo.
Wrapper pass for TargetTransformInfo.
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
LLVM_ABI bool isLegalAddressingMode(Type *Ty, GlobalValue *BaseGV, int64_t BaseOffset, bool HasBaseReg, int64_t Scale, unsigned AddrSpace=0, Instruction *I=nullptr, int64_t ScalableOffset=0) const
Return true if the addressing mode represented by AM is legal for this target, for a load/store of th...
LLVM_ABI InstructionCost getIntImmCostIntrin(Intrinsic::ID IID, unsigned Idx, const APInt &Imm, Type *Ty, TargetCostKind CostKind) const
LLVM_ABI InstructionCost getIntImmCostInst(unsigned Opc, unsigned Idx, const APInt &Imm, Type *Ty, TargetCostKind CostKind, Instruction *Inst=nullptr) const
Return the expected cost of materialization for the given integer immediate of the specified type for...
@ TCK_SizeAndLatency
The weighted sum of size and latency.
LLVM_ABI bool isLegalAddImmediate(int64_t Imm) const
Return true if the specified immediate is legal add immediate, that is the target has add instruction...
LLVM_ABI bool preferToKeepConstantsAttached(const Instruction &Inst, const Function &Fn) const
It can be advantageous to detach complex constants from their uses to make their generation cheaper.
LLVM_ABI InstructionCost getIntImmCodeSizeCost(unsigned Opc, unsigned Idx, const APInt &Imm, Type *Ty) const
Return the expected cost for the given integer when optimising for size.
@ TCC_Basic
The cost of a typical 'add' instruction.
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:288
void setOperand(unsigned i, Value *Val)
Definition User.h:212
Value * getOperand(unsigned i) const
Definition User.h:207
unsigned getNumOperands() const
Definition User.h:229
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:255
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:319
const ParentTy * getParent() const
Definition ilist_node.h:34
self_iterator getIterator()
Definition ilist_node.h:123
@ Entry
Definition COFF.h:862
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:81
initializer< Ty > init(const Ty &Val)
A private "module" namespace for types and utilities used by ConstantHoisting.
SmallVector< RebasedConstantInfo, 4 > RebasedConstantListType
@ User
could "use" a pointer
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:558
FunctionAddr VTableAddr Value
Definition InstrProf.h:137
void stable_sort(R &&Range)
Definition STLExtras.h:2115
InstructionCost Cost
LLVM_ABI FunctionPass * createConstantHoistingPass()
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
OuterAnalysisManagerProxy< ModuleAnalysisManager, Function > ModuleAnalysisManagerFunctionProxy
Provide the ModuleAnalysisManager to Function proxy.
LLVM_ABI bool shouldOptimizeForSize(const MachineFunction *MF, ProfileSummaryInfo *PSI, const MachineBlockFrequencyInfo *BFI, PGSOQueryType QueryType=PGSOQueryType::Other)
Returns true if machine function MF is suggested to be size-optimized based on the profile.
auto reverse(ContainerTy &&C)
Definition STLExtras.h:407
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
TargetTransformInfo TTI
LLVM_ABI void initializeConstantHoistingLegacyPassPass(PassRegistry &)
LLVM_ABI bool canReplaceOperandWithVariable(const Instruction *I, unsigned OpIdx)
Given an instruction, is it legal to set operand OpIdx to a non-constant value?
Definition Local.cpp:3896
ArrayRef(const T &OneElt) -> ArrayRef< T >
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
RebasedConstantListType RebasedConstants