1f26beda7SJuergen Ributzka //===- ConstantHoisting.cpp - Prepare code for expensive constants --------===//
2f26beda7SJuergen Ributzka //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6f26beda7SJuergen Ributzka //
7f26beda7SJuergen Ributzka //===----------------------------------------------------------------------===//
8f26beda7SJuergen Ributzka //
9f26beda7SJuergen Ributzka // This pass identifies expensive constants to hoist and coalesces them to
10f26beda7SJuergen Ributzka // better prepare it for SelectionDAG-based code generation. This works around
11f26beda7SJuergen Ributzka // the limitations of the basic-block-at-a-time approach.
12f26beda7SJuergen Ributzka //
13f26beda7SJuergen Ributzka // First it scans all instructions for integer constants and calculates its
14f26beda7SJuergen Ributzka // cost. If the constant can be folded into the instruction (the cost is
15f26beda7SJuergen Ributzka // TCC_Free) or the cost is just a simple operation (TCC_BASIC), then we don't
16f26beda7SJuergen Ributzka // consider it expensive and leave it alone. This is the default behavior and
1785ba5f63SReid Kleckner // the default implementation of getIntImmCostInst will always return TCC_Free.
18f26beda7SJuergen Ributzka //
19f26beda7SJuergen Ributzka // If the cost is more than TCC_BASIC, then the integer constant can't be folded
20f26beda7SJuergen Ributzka // into the instruction and it might be beneficial to hoist the constant.
21f26beda7SJuergen Ributzka // Similar constants are coalesced to reduce register pressure and
22f26beda7SJuergen Ributzka // materialization code.
23f26beda7SJuergen Ributzka //
24f26beda7SJuergen Ributzka // When a constant is hoisted, it is also hidden behind a bitcast to force it to
25f26beda7SJuergen Ributzka // be live-out of the basic block. Otherwise the constant would be just
26f26beda7SJuergen Ributzka // duplicated and each basic block would have its own copy in the SelectionDAG.
27f26beda7SJuergen Ributzka // The SelectionDAG recognizes such constants as opaque and doesn't perform
28f26beda7SJuergen Ributzka // certain transformations on them, which would create a new expensive constant.
29f26beda7SJuergen Ributzka //
30f26beda7SJuergen Ributzka // This optimization is only applied to integer constants in instructions and
31f0dff49aSJuergen Ributzka // simple (this means not nested) constant cast expressions. For example:
32f26beda7SJuergen Ributzka // %0 = load i64* inttoptr (i64 big_constant to i64*)
33f26beda7SJuergen Ributzka //===----------------------------------------------------------------------===//
34f26beda7SJuergen Ributzka
35071d8306SMichael Kuperstein #include "llvm/Transforms/Scalar/ConstantHoisting.h"
368002c504SEugene Zelenko #include "llvm/ADT/APInt.h"
378002c504SEugene Zelenko #include "llvm/ADT/DenseMap.h"
388002c504SEugene Zelenko #include "llvm/ADT/None.h"
398002c504SEugene Zelenko #include "llvm/ADT/Optional.h"
408002c504SEugene Zelenko #include "llvm/ADT/SmallPtrSet.h"
41a29a5b84SJuergen Ributzka #include "llvm/ADT/SmallVector.h"
42f26beda7SJuergen Ributzka #include "llvm/ADT/Statistic.h"
438002c504SEugene Zelenko #include "llvm/Analysis/BlockFrequencyInfo.h"
4409e539fcSHiroshi Yamauchi #include "llvm/Analysis/ProfileSummaryInfo.h"
458002c504SEugene Zelenko #include "llvm/Analysis/TargetTransformInfo.h"
468002c504SEugene Zelenko #include "llvm/IR/BasicBlock.h"
47f26beda7SJuergen Ributzka #include "llvm/IR/Constants.h"
482be39228SDavid Blaikie #include "llvm/IR/DebugInfoMetadata.h"
498002c504SEugene Zelenko #include "llvm/IR/Dominators.h"
508002c504SEugene Zelenko #include "llvm/IR/Function.h"
518002c504SEugene Zelenko #include "llvm/IR/InstrTypes.h"
528002c504SEugene Zelenko #include "llvm/IR/Instruction.h"
538002c504SEugene Zelenko #include "llvm/IR/Instructions.h"
54f26beda7SJuergen Ributzka #include "llvm/IR/IntrinsicInst.h"
55a494ae43Sserge-sans-paille #include "llvm/IR/Operator.h"
568002c504SEugene Zelenko #include "llvm/IR/Value.h"
5705da2fe5SReid Kleckner #include "llvm/InitializePasses.h"
58f26beda7SJuergen Ributzka #include "llvm/Pass.h"
598002c504SEugene Zelenko #include "llvm/Support/BlockFrequency.h"
608002c504SEugene Zelenko #include "llvm/Support/Casting.h"
618002c504SEugene Zelenko #include "llvm/Support/CommandLine.h"
62f26beda7SJuergen Ributzka #include "llvm/Support/Debug.h"
63799003bfSBenjamin Kramer #include "llvm/Support/raw_ostream.h"
64071d8306SMichael Kuperstein #include "llvm/Transforms/Scalar.h"
6505da2fe5SReid Kleckner #include "llvm/Transforms/Utils/Local.h"
6609e539fcSHiroshi Yamauchi #include "llvm/Transforms/Utils/SizeOpts.h"
678002c504SEugene Zelenko #include <algorithm>
688002c504SEugene Zelenko #include <cassert>
698002c504SEugene Zelenko #include <cstdint>
708002c504SEugene Zelenko #include <iterator>
7199aa6e15SNAKAMURA Takumi #include <tuple>
728002c504SEugene Zelenko #include <utility>
73f26beda7SJuergen Ributzka
74f26beda7SJuergen Ributzka using namespace llvm;
75071d8306SMichael Kuperstein using namespace consthoist;
76f26beda7SJuergen Ributzka
77964daaafSChandler Carruth #define DEBUG_TYPE "consthoist"
78964daaafSChandler Carruth
79f26beda7SJuergen Ributzka STATISTIC(NumConstantsHoisted, "Number of constants hoisted");
80f26beda7SJuergen Ributzka STATISTIC(NumConstantsRebased, "Number of constants rebased");
81f26beda7SJuergen Ributzka
82337d4d95SWei Mi static cl::opt<bool> ConstHoistWithBlockFrequency(
8375867550SWei Mi "consthoist-with-block-frequency", cl::init(true), cl::Hidden,
84337d4d95SWei Mi cl::desc("Enable the use of the block frequency analysis to reduce the "
85337d4d95SWei Mi "chance to execute const materialization more frequently than "
86337d4d95SWei Mi "without hoisting."));
87337d4d95SWei Mi
88a0aa41d7SZhaoshi Zheng static cl::opt<bool> ConstHoistGEP(
89a0aa41d7SZhaoshi Zheng "consthoist-gep", cl::init(false), cl::Hidden,
90a0aa41d7SZhaoshi Zheng cl::desc("Try hoisting constant gep expressions"));
91a0aa41d7SZhaoshi Zheng
9295710337SZhaoshi Zheng static cl::opt<unsigned>
9395710337SZhaoshi Zheng MinNumOfDependentToRebase("consthoist-min-num-to-rebase",
9495710337SZhaoshi Zheng cl::desc("Do not rebase if number of dependent constants of a Base is less "
9595710337SZhaoshi Zheng "than this number."),
9695710337SZhaoshi Zheng cl::init(0), cl::Hidden);
9795710337SZhaoshi Zheng
98f26beda7SJuergen Ributzka namespace {
998002c504SEugene Zelenko
1005f8f34e4SAdrian Prantl /// The constant hoisting pass.
101071d8306SMichael Kuperstein class ConstantHoistingLegacyPass : public FunctionPass {
102f26beda7SJuergen Ributzka public:
103f26beda7SJuergen Ributzka static char ID; // Pass identification, replacement for typeid
1048002c504SEugene Zelenko
ConstantHoistingLegacyPass()105071d8306SMichael Kuperstein ConstantHoistingLegacyPass() : FunctionPass(ID) {
106071d8306SMichael Kuperstein initializeConstantHoistingLegacyPassPass(*PassRegistry::getPassRegistry());
107f26beda7SJuergen Ributzka }
108f26beda7SJuergen Ributzka
1095429c06bSJuergen Ributzka bool runOnFunction(Function &Fn) override;
110f26beda7SJuergen Ributzka
getPassName() const111117296c0SMehdi Amini StringRef getPassName() const override { return "Constant Hoisting"; }
112f26beda7SJuergen Ributzka
getAnalysisUsage(AnalysisUsage & AU) const1133e4c697cSCraig Topper void getAnalysisUsage(AnalysisUsage &AU) const override {
114f26beda7SJuergen Ributzka AU.setPreservesCFG();
115337d4d95SWei Mi if (ConstHoistWithBlockFrequency)
116337d4d95SWei Mi AU.addRequired<BlockFrequencyInfoWrapperPass>();
117f26beda7SJuergen Ributzka AU.addRequired<DominatorTreeWrapperPass>();
11809e539fcSHiroshi Yamauchi AU.addRequired<ProfileSummaryInfoWrapperPass>();
119705b185fSChandler Carruth AU.addRequired<TargetTransformInfoWrapperPass>();
120f26beda7SJuergen Ributzka }
121f26beda7SJuergen Ributzka
122f26beda7SJuergen Ributzka private:
123071d8306SMichael Kuperstein ConstantHoistingPass Impl;
124f26beda7SJuergen Ributzka };
1258002c504SEugene Zelenko
1268002c504SEugene Zelenko } // end anonymous namespace
127f26beda7SJuergen Ributzka
128071d8306SMichael Kuperstein char ConstantHoistingLegacyPass::ID = 0;
1298002c504SEugene Zelenko
130071d8306SMichael Kuperstein INITIALIZE_PASS_BEGIN(ConstantHoistingLegacyPass, "consthoist",
131071d8306SMichael Kuperstein "Constant Hoisting", false, false)
INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)132337d4d95SWei Mi INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
133f26beda7SJuergen Ributzka INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
13409e539fcSHiroshi Yamauchi INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
135705b185fSChandler Carruth INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
136071d8306SMichael Kuperstein INITIALIZE_PASS_END(ConstantHoistingLegacyPass, "consthoist",
137071d8306SMichael Kuperstein "Constant Hoisting", false, false)
138f26beda7SJuergen Ributzka
139f26beda7SJuergen Ributzka FunctionPass *llvm::createConstantHoistingPass() {
140071d8306SMichael Kuperstein return new ConstantHoistingLegacyPass();
141f26beda7SJuergen Ributzka }
142f26beda7SJuergen Ributzka
1435f8f34e4SAdrian Prantl /// Perform the constant hoisting optimization for the given function.
runOnFunction(Function & Fn)144071d8306SMichael Kuperstein bool ConstantHoistingLegacyPass::runOnFunction(Function &Fn) {
145aa641a51SAndrew Kaylor if (skipFunction(Fn))
146f5443238SAndrea Di Biagio return false;
147f5443238SAndrea Di Biagio
148d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "********** Begin Constant Hoisting **********\n");
149d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "********** Function: " << Fn.getName() << '\n');
150f26beda7SJuergen Ributzka
151337d4d95SWei Mi bool MadeChange =
152337d4d95SWei Mi Impl.runImpl(Fn, getAnalysis<TargetTransformInfoWrapperPass>().getTTI(Fn),
153337d4d95SWei Mi getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
154337d4d95SWei Mi ConstHoistWithBlockFrequency
155337d4d95SWei Mi ? &getAnalysis<BlockFrequencyInfoWrapperPass>().getBFI()
156337d4d95SWei Mi : nullptr,
15709e539fcSHiroshi Yamauchi Fn.getEntryBlock(),
15809e539fcSHiroshi Yamauchi &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI());
1595429c06bSJuergen Ributzka
1605429c06bSJuergen Ributzka if (MadeChange) {
161d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "********** Function after Constant Hoisting: "
1625429c06bSJuergen Ributzka << Fn.getName() << '\n');
163d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << Fn);
1645429c06bSJuergen Ributzka }
165d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "********** End Constant Hoisting **********\n");
1665429c06bSJuergen Ributzka
1675429c06bSJuergen Ributzka return MadeChange;
168f26beda7SJuergen Ributzka }
169f26beda7SJuergen Ributzka
1705f8f34e4SAdrian Prantl /// Find the constant materialization insertion point.
findMatInsertPt(Instruction * Inst,unsigned Idx) const171071d8306SMichael Kuperstein Instruction *ConstantHoistingPass::findMatInsertPt(Instruction *Inst,
1725429c06bSJuergen Ributzka unsigned Idx) const {
173575bcb77SJuergen Ributzka // If the operand is a cast instruction, then we have to materialize the
174575bcb77SJuergen Ributzka // constant before the cast instruction.
175575bcb77SJuergen Ributzka if (Idx != ~0U) {
176575bcb77SJuergen Ributzka Value *Opnd = Inst->getOperand(Idx);
177575bcb77SJuergen Ributzka if (auto CastInst = dyn_cast<Instruction>(Opnd))
178575bcb77SJuergen Ributzka if (CastInst->isCast())
179575bcb77SJuergen Ributzka return CastInst;
180575bcb77SJuergen Ributzka }
181575bcb77SJuergen Ributzka
182575bcb77SJuergen Ributzka // The simple and common case. This also includes constant expressions.
183ba275f99SDavid Majnemer if (!isa<PHINode>(Inst) && !Inst->isEHPad())
1845429c06bSJuergen Ributzka return Inst;
1855429c06bSJuergen Ributzka
186ba275f99SDavid Majnemer // We can't insert directly before a phi node or an eh pad. Insert before
1875429c06bSJuergen Ributzka // the terminator of the incoming or dominating block.
1885429c06bSJuergen Ributzka assert(Entry != Inst->getParent() && "PHI or landing pad in entry block!");
1898bfef787SMichael Holman BasicBlock *InsertionBlock = nullptr;
1908bfef787SMichael Holman if (Idx != ~0U && isa<PHINode>(Inst)) {
1918bfef787SMichael Holman InsertionBlock = cast<PHINode>(Inst)->getIncomingBlock(Idx);
1928bfef787SMichael Holman if (!InsertionBlock->isEHPad()) {
1938bfef787SMichael Holman return InsertionBlock->getTerminator();
1948bfef787SMichael Holman }
1958bfef787SMichael Holman } else {
1968bfef787SMichael Holman InsertionBlock = Inst->getParent();
1978bfef787SMichael Holman }
1985429c06bSJuergen Ributzka
199d80b69faSReid Kleckner // This must be an EH pad. Iterate over immediate dominators until we find a
200d80b69faSReid Kleckner // non-EH pad. We need to skip over catchswitch blocks, which are both EH pads
201d80b69faSReid Kleckner // and terminators.
2028bfef787SMichael Holman auto *IDom = DT->getNode(InsertionBlock)->getIDom();
203d80b69faSReid Kleckner while (IDom->getBlock()->isEHPad()) {
204d80b69faSReid Kleckner assert(Entry != IDom->getBlock() && "eh pad in entry block");
205d80b69faSReid Kleckner IDom = IDom->getIDom();
206d80b69faSReid Kleckner }
207d80b69faSReid Kleckner
208d80b69faSReid Kleckner return IDom->getBlock()->getTerminator();
2095429c06bSJuergen Ributzka }
2105429c06bSJuergen Ributzka
2115f8f34e4SAdrian Prantl /// Given \p BBs as input, find another set of BBs which collectively
212337d4d95SWei Mi /// dominates \p BBs and have the minimal sum of frequencies. Return the BB
213337d4d95SWei Mi /// set found in \p BBs.
findBestInsertionSet(DominatorTree & DT,BlockFrequencyInfo & BFI,BasicBlock * Entry,SetVector<BasicBlock * > & BBs)214debb3c35SBenjamin Kramer static void findBestInsertionSet(DominatorTree &DT, BlockFrequencyInfo &BFI,
215337d4d95SWei Mi BasicBlock *Entry,
216403e08d4SEli Friedman SetVector<BasicBlock *> &BBs) {
217337d4d95SWei Mi assert(!BBs.count(Entry) && "Assume Entry is not in BBs");
218337d4d95SWei Mi // Nodes on the current path to the root.
219337d4d95SWei Mi SmallPtrSet<BasicBlock *, 8> Path;
220337d4d95SWei Mi // Candidates includes any block 'BB' in set 'BBs' that is not strictly
221337d4d95SWei Mi // dominated by any other blocks in set 'BBs', and all nodes in the path
222337d4d95SWei Mi // in the dominator tree from Entry to 'BB'.
223337d4d95SWei Mi SmallPtrSet<BasicBlock *, 16> Candidates;
224337d4d95SWei Mi for (auto BB : BBs) {
2256e32b46bSSanjay Patel // Ignore unreachable basic blocks.
2266e32b46bSSanjay Patel if (!DT.isReachableFromEntry(BB))
2276e32b46bSSanjay Patel continue;
228337d4d95SWei Mi Path.clear();
229337d4d95SWei Mi // Walk up the dominator tree until Entry or another BB in BBs
230337d4d95SWei Mi // is reached. Insert the nodes on the way to the Path.
231337d4d95SWei Mi BasicBlock *Node = BB;
232337d4d95SWei Mi // The "Path" is a candidate path to be added into Candidates set.
233337d4d95SWei Mi bool isCandidate = false;
234337d4d95SWei Mi do {
235337d4d95SWei Mi Path.insert(Node);
236337d4d95SWei Mi if (Node == Entry || Candidates.count(Node)) {
237337d4d95SWei Mi isCandidate = true;
238337d4d95SWei Mi break;
239337d4d95SWei Mi }
240337d4d95SWei Mi assert(DT.getNode(Node)->getIDom() &&
241337d4d95SWei Mi "Entry doens't dominate current Node");
242337d4d95SWei Mi Node = DT.getNode(Node)->getIDom()->getBlock();
243337d4d95SWei Mi } while (!BBs.count(Node));
244337d4d95SWei Mi
245337d4d95SWei Mi // If isCandidate is false, Node is another Block in BBs dominating
246337d4d95SWei Mi // current 'BB'. Drop the nodes on the Path.
247337d4d95SWei Mi if (!isCandidate)
248337d4d95SWei Mi continue;
249337d4d95SWei Mi
250337d4d95SWei Mi // Add nodes on the Path into Candidates.
251337d4d95SWei Mi Candidates.insert(Path.begin(), Path.end());
252337d4d95SWei Mi }
253337d4d95SWei Mi
254337d4d95SWei Mi // Sort the nodes in Candidates in top-down order and save the nodes
255337d4d95SWei Mi // in Orders.
256337d4d95SWei Mi unsigned Idx = 0;
257337d4d95SWei Mi SmallVector<BasicBlock *, 16> Orders;
258337d4d95SWei Mi Orders.push_back(Entry);
259337d4d95SWei Mi while (Idx != Orders.size()) {
260337d4d95SWei Mi BasicBlock *Node = Orders[Idx++];
26176c5cb05SNicolai Hähnle for (auto ChildDomNode : DT.getNode(Node)->children()) {
262337d4d95SWei Mi if (Candidates.count(ChildDomNode->getBlock()))
263337d4d95SWei Mi Orders.push_back(ChildDomNode->getBlock());
264337d4d95SWei Mi }
265337d4d95SWei Mi }
266337d4d95SWei Mi
267337d4d95SWei Mi // Visit Orders in bottom-up order.
2688002c504SEugene Zelenko using InsertPtsCostPair =
269403e08d4SEli Friedman std::pair<SetVector<BasicBlock *>, BlockFrequency>;
2708002c504SEugene Zelenko
271337d4d95SWei Mi // InsertPtsMap is a map from a BB to the best insertion points for the
272337d4d95SWei Mi // subtree of BB (subtree not including the BB itself).
273337d4d95SWei Mi DenseMap<BasicBlock *, InsertPtsCostPair> InsertPtsMap;
274337d4d95SWei Mi InsertPtsMap.reserve(Orders.size() + 1);
2757787a8f1SKazu Hirata for (BasicBlock *Node : llvm::reverse(Orders)) {
276337d4d95SWei Mi bool NodeInBBs = BBs.count(Node);
277403e08d4SEli Friedman auto &InsertPts = InsertPtsMap[Node].first;
278337d4d95SWei Mi BlockFrequency &InsertPtsFreq = InsertPtsMap[Node].second;
279337d4d95SWei Mi
280337d4d95SWei Mi // Return the optimal insert points in BBs.
281337d4d95SWei Mi if (Node == Entry) {
282337d4d95SWei Mi BBs.clear();
28320526b27SWei Mi if (InsertPtsFreq > BFI.getBlockFreq(Node) ||
28420526b27SWei Mi (InsertPtsFreq == BFI.getBlockFreq(Node) && InsertPts.size() > 1))
285337d4d95SWei Mi BBs.insert(Entry);
286337d4d95SWei Mi else
287337d4d95SWei Mi BBs.insert(InsertPts.begin(), InsertPts.end());
288337d4d95SWei Mi break;
289337d4d95SWei Mi }
290337d4d95SWei Mi
291337d4d95SWei Mi BasicBlock *Parent = DT.getNode(Node)->getIDom()->getBlock();
292337d4d95SWei Mi // Initially, ParentInsertPts is empty and ParentPtsFreq is 0. Every child
293337d4d95SWei Mi // will update its parent's ParentInsertPts and ParentPtsFreq.
294403e08d4SEli Friedman auto &ParentInsertPts = InsertPtsMap[Parent].first;
295337d4d95SWei Mi BlockFrequency &ParentPtsFreq = InsertPtsMap[Parent].second;
296337d4d95SWei Mi // Choose to insert in Node or in subtree of Node.
29720526b27SWei Mi // Don't hoist to EHPad because we may not find a proper place to insert
29820526b27SWei Mi // in EHPad.
29920526b27SWei Mi // If the total frequency of InsertPts is the same as the frequency of the
30020526b27SWei Mi // target Node, and InsertPts contains more than one nodes, choose hoisting
30120526b27SWei Mi // to reduce code size.
30220526b27SWei Mi if (NodeInBBs ||
30320526b27SWei Mi (!Node->isEHPad() &&
30420526b27SWei Mi (InsertPtsFreq > BFI.getBlockFreq(Node) ||
30520526b27SWei Mi (InsertPtsFreq == BFI.getBlockFreq(Node) && InsertPts.size() > 1)))) {
306337d4d95SWei Mi ParentInsertPts.insert(Node);
307337d4d95SWei Mi ParentPtsFreq += BFI.getBlockFreq(Node);
308337d4d95SWei Mi } else {
309337d4d95SWei Mi ParentInsertPts.insert(InsertPts.begin(), InsertPts.end());
310337d4d95SWei Mi ParentPtsFreq += InsertPtsFreq;
311337d4d95SWei Mi }
312337d4d95SWei Mi }
313337d4d95SWei Mi }
314337d4d95SWei Mi
3155f8f34e4SAdrian Prantl /// Find an insertion point that dominates all uses.
findConstantInsertionPoint(const ConstantInfo & ConstInfo) const316403e08d4SEli Friedman SetVector<Instruction *> ConstantHoistingPass::findConstantInsertionPoint(
317071d8306SMichael Kuperstein const ConstantInfo &ConstInfo) const {
3185429c06bSJuergen Ributzka assert(!ConstInfo.RebasedConstants.empty() && "Invalid constant info entry.");
319c81000b8SJuergen Ributzka // Collect all basic blocks.
320403e08d4SEli Friedman SetVector<BasicBlock *> BBs;
321403e08d4SEli Friedman SetVector<Instruction *> InsertPts;
3225429c06bSJuergen Ributzka for (auto const &RCI : ConstInfo.RebasedConstants)
323c81000b8SJuergen Ributzka for (auto const &U : RCI.Uses)
324575bcb77SJuergen Ributzka BBs.insert(findMatInsertPt(U.Inst, U.OpndIdx)->getParent());
3255429c06bSJuergen Ributzka
326337d4d95SWei Mi if (BBs.count(Entry)) {
327337d4d95SWei Mi InsertPts.insert(&Entry->front());
328337d4d95SWei Mi return InsertPts;
329337d4d95SWei Mi }
330337d4d95SWei Mi
331337d4d95SWei Mi if (BFI) {
332337d4d95SWei Mi findBestInsertionSet(*DT, *BFI, Entry, BBs);
333337d4d95SWei Mi for (auto BB : BBs) {
334337d4d95SWei Mi BasicBlock::iterator InsertPt = BB->begin();
335337d4d95SWei Mi for (; isa<PHINode>(InsertPt) || InsertPt->isEHPad(); ++InsertPt)
336337d4d95SWei Mi ;
337337d4d95SWei Mi InsertPts.insert(&*InsertPt);
338337d4d95SWei Mi }
339337d4d95SWei Mi return InsertPts;
340337d4d95SWei Mi }
3415429c06bSJuergen Ributzka
3425429c06bSJuergen Ributzka while (BBs.size() >= 2) {
3435429c06bSJuergen Ributzka BasicBlock *BB, *BB1, *BB2;
344403e08d4SEli Friedman BB1 = BBs.pop_back_val();
345403e08d4SEli Friedman BB2 = BBs.pop_back_val();
3465429c06bSJuergen Ributzka BB = DT->findNearestCommonDominator(BB1, BB2);
347337d4d95SWei Mi if (BB == Entry) {
348337d4d95SWei Mi InsertPts.insert(&Entry->front());
349337d4d95SWei Mi return InsertPts;
350337d4d95SWei Mi }
3515429c06bSJuergen Ributzka BBs.insert(BB);
3525429c06bSJuergen Ributzka }
3535429c06bSJuergen Ributzka assert((BBs.size() == 1) && "Expected only one element.");
3545429c06bSJuergen Ributzka Instruction &FirstInst = (*BBs.begin())->front();
355337d4d95SWei Mi InsertPts.insert(findMatInsertPt(&FirstInst));
356337d4d95SWei Mi return InsertPts;
3575429c06bSJuergen Ributzka }
3585429c06bSJuergen Ributzka
3595f8f34e4SAdrian Prantl /// Record constant integer ConstInt for instruction Inst at operand
3605429c06bSJuergen Ributzka /// index Idx.
3615429c06bSJuergen Ributzka ///
362f0dff49aSJuergen Ributzka /// The operand at index Idx is not necessarily the constant integer itself. It
3635429c06bSJuergen Ributzka /// could also be a cast instruction or a constant expression that uses the
364a0aa41d7SZhaoshi Zheng /// constant integer.
collectConstantCandidates(ConstCandMapType & ConstCandMap,Instruction * Inst,unsigned Idx,ConstantInt * ConstInt)365071d8306SMichael Kuperstein void ConstantHoistingPass::collectConstantCandidates(
366071d8306SMichael Kuperstein ConstCandMapType &ConstCandMap, Instruction *Inst, unsigned Idx,
3675429c06bSJuergen Ributzka ConstantInt *ConstInt) {
368f9a50f04SSander de Smalen InstructionCost Cost;
3695429c06bSJuergen Ributzka // Ask the target about the cost of materializing the constant for the given
370f0dff49aSJuergen Ributzka // instruction and operand index.
3715429c06bSJuergen Ributzka if (auto IntrInst = dyn_cast<IntrinsicInst>(Inst))
37285ba5f63SReid Kleckner Cost = TTI->getIntImmCostIntrin(IntrInst->getIntrinsicID(), Idx,
37340574fefSSam Parker ConstInt->getValue(), ConstInt->getType(),
37440574fefSSam Parker TargetTransformInfo::TCK_SizeAndLatency);
3756dab520cSJuergen Ributzka else
376a3d0dce2SMeera Nakrani Cost = TTI->getIntImmCostInst(
377a3d0dce2SMeera Nakrani Inst->getOpcode(), Idx, ConstInt->getValue(), ConstInt->getType(),
378a3d0dce2SMeera Nakrani TargetTransformInfo::TCK_SizeAndLatency, Inst);
3796dab520cSJuergen Ributzka
380a29a5b84SJuergen Ributzka // Ignore cheap integer constants.
3816dab520cSJuergen Ributzka if (Cost > TargetTransformInfo::TCC_Basic) {
382a29a5b84SJuergen Ributzka ConstCandMapType::iterator Itr;
383a29a5b84SJuergen Ributzka bool Inserted;
384a0aa41d7SZhaoshi Zheng ConstPtrUnionType Cand = ConstInt;
385a0aa41d7SZhaoshi Zheng std::tie(Itr, Inserted) = ConstCandMap.insert(std::make_pair(Cand, 0));
386a29a5b84SJuergen Ributzka if (Inserted) {
387a0aa41d7SZhaoshi Zheng ConstIntCandVec.push_back(ConstantCandidate(ConstInt));
388a0aa41d7SZhaoshi Zheng Itr->second = ConstIntCandVec.size() - 1;
389a29a5b84SJuergen Ributzka }
390f9a50f04SSander de Smalen ConstIntCandVec[Itr->second].addUser(Inst, Idx, *Cost.getValue());
391d34e60caSNicola Zaghen LLVM_DEBUG(if (isa<ConstantInt>(Inst->getOperand(Idx))) dbgs()
392d34e60caSNicola Zaghen << "Collect constant " << *ConstInt << " from " << *Inst
3935429c06bSJuergen Ributzka << " with cost " << Cost << '\n';
394d34e60caSNicola Zaghen else dbgs() << "Collect constant " << *ConstInt
395d34e60caSNicola Zaghen << " indirectly from " << *Inst << " via "
396d34e60caSNicola Zaghen << *Inst->getOperand(Idx) << " with cost " << Cost
397d34e60caSNicola Zaghen << '\n';);
3986dab520cSJuergen Ributzka }
39946357931SJuergen Ributzka }
40046357931SJuergen Ributzka
401a0aa41d7SZhaoshi Zheng /// Record constant GEP expression for instruction Inst at operand index Idx.
collectConstantCandidates(ConstCandMapType & ConstCandMap,Instruction * Inst,unsigned Idx,ConstantExpr * ConstExpr)402a0aa41d7SZhaoshi Zheng void ConstantHoistingPass::collectConstantCandidates(
403a0aa41d7SZhaoshi Zheng ConstCandMapType &ConstCandMap, Instruction *Inst, unsigned Idx,
404a0aa41d7SZhaoshi Zheng ConstantExpr *ConstExpr) {
405a0aa41d7SZhaoshi Zheng // TODO: Handle vector GEPs
406a0aa41d7SZhaoshi Zheng if (ConstExpr->getType()->isVectorTy())
407a0aa41d7SZhaoshi Zheng return;
408a0aa41d7SZhaoshi Zheng
409a0aa41d7SZhaoshi Zheng GlobalVariable *BaseGV = dyn_cast<GlobalVariable>(ConstExpr->getOperand(0));
410a0aa41d7SZhaoshi Zheng if (!BaseGV)
411a0aa41d7SZhaoshi Zheng return;
412a0aa41d7SZhaoshi Zheng
413a0aa41d7SZhaoshi Zheng // Get offset from the base GV.
414db05a482SSimon Pilgrim PointerType *GVPtrTy = cast<PointerType>(BaseGV->getType());
415a0aa41d7SZhaoshi Zheng IntegerType *PtrIntTy = DL->getIntPtrType(*Ctx, GVPtrTy->getAddressSpace());
416a0aa41d7SZhaoshi Zheng APInt Offset(DL->getTypeSizeInBits(PtrIntTy), /*val*/0, /*isSigned*/true);
417a0aa41d7SZhaoshi Zheng auto *GEPO = cast<GEPOperator>(ConstExpr);
418d56b0ad4SNikita Popov
419d56b0ad4SNikita Popov // TODO: If we have a mix of inbounds and non-inbounds GEPs, then basing a
420d56b0ad4SNikita Popov // non-inbounds GEP on an inbounds GEP is potentially incorrect. Restrict to
421d56b0ad4SNikita Popov // inbounds GEP for now -- alternatively, we could drop inbounds from the
422d56b0ad4SNikita Popov // constant expression,
423d56b0ad4SNikita Popov if (!GEPO->isInBounds())
424d56b0ad4SNikita Popov return;
425d56b0ad4SNikita Popov
426a0aa41d7SZhaoshi Zheng if (!GEPO->accumulateConstantOffset(*DL, Offset))
427a0aa41d7SZhaoshi Zheng return;
428a0aa41d7SZhaoshi Zheng
429a0aa41d7SZhaoshi Zheng if (!Offset.isIntN(32))
430a0aa41d7SZhaoshi Zheng return;
431a0aa41d7SZhaoshi Zheng
432a0aa41d7SZhaoshi Zheng // A constant GEP expression that has a GlobalVariable as base pointer is
433a0aa41d7SZhaoshi Zheng // usually lowered to a load from constant pool. Such operation is unlikely
434a0aa41d7SZhaoshi Zheng // to be cheaper than compute it by <Base + Offset>, which can be lowered to
435a0aa41d7SZhaoshi Zheng // an ADD instruction or folded into Load/Store instruction.
436f9a50f04SSander de Smalen InstructionCost Cost =
437a3d0dce2SMeera Nakrani TTI->getIntImmCostInst(Instruction::Add, 1, Offset, PtrIntTy,
438a3d0dce2SMeera Nakrani TargetTransformInfo::TCK_SizeAndLatency, Inst);
439a0aa41d7SZhaoshi Zheng ConstCandVecType &ExprCandVec = ConstGEPCandMap[BaseGV];
440a0aa41d7SZhaoshi Zheng ConstCandMapType::iterator Itr;
441a0aa41d7SZhaoshi Zheng bool Inserted;
442a0aa41d7SZhaoshi Zheng ConstPtrUnionType Cand = ConstExpr;
443a0aa41d7SZhaoshi Zheng std::tie(Itr, Inserted) = ConstCandMap.insert(std::make_pair(Cand, 0));
444a0aa41d7SZhaoshi Zheng if (Inserted) {
445a0aa41d7SZhaoshi Zheng ExprCandVec.push_back(ConstantCandidate(
446a0aa41d7SZhaoshi Zheng ConstantInt::get(Type::getInt32Ty(*Ctx), Offset.getLimitedValue()),
447a0aa41d7SZhaoshi Zheng ConstExpr));
448a0aa41d7SZhaoshi Zheng Itr->second = ExprCandVec.size() - 1;
449a0aa41d7SZhaoshi Zheng }
450f9a50f04SSander de Smalen ExprCandVec[Itr->second].addUser(Inst, Idx, *Cost.getValue());
451a0aa41d7SZhaoshi Zheng }
452a0aa41d7SZhaoshi Zheng
4535f8f34e4SAdrian Prantl /// Check the operand for instruction Inst at index Idx.
collectConstantCandidates(ConstCandMapType & ConstCandMap,Instruction * Inst,unsigned Idx)45420fbad93SLeo Li void ConstantHoistingPass::collectConstantCandidates(
45520fbad93SLeo Li ConstCandMapType &ConstCandMap, Instruction *Inst, unsigned Idx) {
45620fbad93SLeo Li Value *Opnd = Inst->getOperand(Idx);
45720fbad93SLeo Li
45820fbad93SLeo Li // Visit constant integers.
45920fbad93SLeo Li if (auto ConstInt = dyn_cast<ConstantInt>(Opnd)) {
46020fbad93SLeo Li collectConstantCandidates(ConstCandMap, Inst, Idx, ConstInt);
46120fbad93SLeo Li return;
46220fbad93SLeo Li }
46320fbad93SLeo Li
46420fbad93SLeo Li // Visit cast instructions that have constant integers.
46520fbad93SLeo Li if (auto CastInst = dyn_cast<Instruction>(Opnd)) {
46620fbad93SLeo Li // Only visit cast instructions, which have been skipped. All other
46720fbad93SLeo Li // instructions should have already been visited.
46820fbad93SLeo Li if (!CastInst->isCast())
46920fbad93SLeo Li return;
47020fbad93SLeo Li
47120fbad93SLeo Li if (auto *ConstInt = dyn_cast<ConstantInt>(CastInst->getOperand(0))) {
47220fbad93SLeo Li // Pretend the constant is directly used by the instruction and ignore
47320fbad93SLeo Li // the cast instruction.
47420fbad93SLeo Li collectConstantCandidates(ConstCandMap, Inst, Idx, ConstInt);
47520fbad93SLeo Li return;
47620fbad93SLeo Li }
47720fbad93SLeo Li }
47820fbad93SLeo Li
47920fbad93SLeo Li // Visit constant expressions that have constant integers.
48020fbad93SLeo Li if (auto ConstExpr = dyn_cast<ConstantExpr>(Opnd)) {
481a0aa41d7SZhaoshi Zheng // Handle constant gep expressions.
482d56b0ad4SNikita Popov if (ConstHoistGEP && isa<GEPOperator>(ConstExpr))
483a0aa41d7SZhaoshi Zheng collectConstantCandidates(ConstCandMap, Inst, Idx, ConstExpr);
484a0aa41d7SZhaoshi Zheng
48520fbad93SLeo Li // Only visit constant cast expressions.
48620fbad93SLeo Li if (!ConstExpr->isCast())
48720fbad93SLeo Li return;
48820fbad93SLeo Li
48920fbad93SLeo Li if (auto ConstInt = dyn_cast<ConstantInt>(ConstExpr->getOperand(0))) {
49020fbad93SLeo Li // Pretend the constant is directly used by the instruction and ignore
49120fbad93SLeo Li // the constant expression.
49220fbad93SLeo Li collectConstantCandidates(ConstCandMap, Inst, Idx, ConstInt);
49320fbad93SLeo Li return;
49420fbad93SLeo Li }
49520fbad93SLeo Li }
49620fbad93SLeo Li }
49720fbad93SLeo Li
4985f8f34e4SAdrian Prantl /// Scan the instruction for expensive integer constants and record them
4995429c06bSJuergen Ributzka /// in the constant candidate vector.
collectConstantCandidates(ConstCandMapType & ConstCandMap,Instruction * Inst)500071d8306SMichael Kuperstein void ConstantHoistingPass::collectConstantCandidates(
501071d8306SMichael Kuperstein ConstCandMapType &ConstCandMap, Instruction *Inst) {
5025429c06bSJuergen Ributzka // Skip all cast instructions. They are visited indirectly later on.
5035429c06bSJuergen Ributzka if (Inst->isCast())
5045429c06bSJuergen Ributzka return;
5055429c06bSJuergen Ributzka
5066dab520cSJuergen Ributzka // Scan all operands.
5075429c06bSJuergen Ributzka for (unsigned Idx = 0, E = Inst->getNumOperands(); Idx != E; ++Idx) {
50893abd7d9SLeo Li // The cost of materializing the constants (defined in
50985ba5f63SReid Kleckner // `TargetTransformInfo::getIntImmCostInst`) for instructions which only
51085ba5f63SReid Kleckner // take constant variables is lower than `TargetTransformInfo::TCC_Basic`.
51185ba5f63SReid Kleckner // So it's safe for us to collect constant candidates from all
51285ba5f63SReid Kleckner // IntrinsicInsts.
51343d98a0eSMatt Arsenault if (canReplaceOperandWithVariable(Inst, Idx)) {
51420fbad93SLeo Li collectConstantCandidates(ConstCandMap, Inst, Idx);
51593abd7d9SLeo Li }
5165429c06bSJuergen Ributzka } // end of for all operands
5175429c06bSJuergen Ributzka }
5186dab520cSJuergen Ributzka
5195f8f34e4SAdrian Prantl /// Collect all integer constants in the function that cannot be folded
5206dab520cSJuergen Ributzka /// into an instruction itself.
collectConstantCandidates(Function & Fn)521071d8306SMichael Kuperstein void ConstantHoistingPass::collectConstantCandidates(Function &Fn) {
5227be410f5SJuergen Ributzka ConstCandMapType ConstCandMap;
52389e3bb45SBjorn Pettersson for (BasicBlock &BB : Fn) {
52489e3bb45SBjorn Pettersson // Ignore unreachable basic blocks.
52589e3bb45SBjorn Pettersson if (!DT->isReachableFromEntry(&BB))
52689e3bb45SBjorn Pettersson continue;
5273a9c9e3dSDuncan P. N. Exon Smith for (Instruction &Inst : BB)
5283a9c9e3dSDuncan P. N. Exon Smith collectConstantCandidates(ConstCandMap, &Inst);
5296dab520cSJuergen Ributzka }
53089e3bb45SBjorn Pettersson }
5316dab520cSJuergen Ributzka
53238c2cd0cSSjoerd Meijer // This helper function is necessary to deal with values that have different
53338c2cd0cSSjoerd Meijer // bit widths (APInt Operator- does not like that). If the value cannot be
53438c2cd0cSSjoerd Meijer // represented in uint64 we return an "empty" APInt. This is then interpreted
53538c2cd0cSSjoerd Meijer // as the value is not in range.
calculateOffsetDiff(const APInt & V1,const APInt & V2)5368002c504SEugene Zelenko static Optional<APInt> calculateOffsetDiff(const APInt &V1, const APInt &V2) {
5378002c504SEugene Zelenko Optional<APInt> Res = None;
53838c2cd0cSSjoerd Meijer unsigned BW = V1.getBitWidth() > V2.getBitWidth() ?
53938c2cd0cSSjoerd Meijer V1.getBitWidth() : V2.getBitWidth();
54038c2cd0cSSjoerd Meijer uint64_t LimVal1 = V1.getLimitedValue();
54138c2cd0cSSjoerd Meijer uint64_t LimVal2 = V2.getLimitedValue();
54238c2cd0cSSjoerd Meijer
54338c2cd0cSSjoerd Meijer if (LimVal1 == ~0ULL || LimVal2 == ~0ULL)
54438c2cd0cSSjoerd Meijer return Res;
54538c2cd0cSSjoerd Meijer
54638c2cd0cSSjoerd Meijer uint64_t Diff = LimVal1 - LimVal2;
54738c2cd0cSSjoerd Meijer return APInt(BW, Diff, true);
54838c2cd0cSSjoerd Meijer }
54938c2cd0cSSjoerd Meijer
55038c2cd0cSSjoerd Meijer // From a list of constants, one needs to picked as the base and the other
55138c2cd0cSSjoerd Meijer // constants will be transformed into an offset from that base constant. The
55238c2cd0cSSjoerd Meijer // question is which we can pick best? For example, consider these constants
55338c2cd0cSSjoerd Meijer // and their number of uses:
55438c2cd0cSSjoerd Meijer //
55538c2cd0cSSjoerd Meijer // Constants| 2 | 4 | 12 | 42 |
55638c2cd0cSSjoerd Meijer // NumUses | 3 | 2 | 8 | 7 |
55738c2cd0cSSjoerd Meijer //
55838c2cd0cSSjoerd Meijer // Selecting constant 12 because it has the most uses will generate negative
55938c2cd0cSSjoerd Meijer // offsets for constants 2 and 4 (i.e. -10 and -8 respectively). If negative
56038c2cd0cSSjoerd Meijer // offsets lead to less optimal code generation, then there might be better
56138c2cd0cSSjoerd Meijer // solutions. Suppose immediates in the range of 0..35 are most optimally
56238c2cd0cSSjoerd Meijer // supported by the architecture, then selecting constant 2 is most optimal
56338c2cd0cSSjoerd Meijer // because this will generate offsets: 0, 2, 10, 40. Offsets 0, 2 and 10 are in
56438c2cd0cSSjoerd Meijer // range 0..35, and thus 3 + 2 + 8 = 13 uses are in range. Selecting 12 would
56538c2cd0cSSjoerd Meijer // have only 8 uses in range, so choosing 2 as a base is more optimal. Thus, in
56638c2cd0cSSjoerd Meijer // selecting the base constant the range of the offsets is a very important
56738c2cd0cSSjoerd Meijer // factor too that we take into account here. This algorithm calculates a total
56838c2cd0cSSjoerd Meijer // costs for selecting a constant as the base and substract the costs if
56938c2cd0cSSjoerd Meijer // immediates are out of range. It has quadratic complexity, so we call this
57038c2cd0cSSjoerd Meijer // function only when we're optimising for size and there are less than 100
57138c2cd0cSSjoerd Meijer // constants, we fall back to the straightforward algorithm otherwise
57238c2cd0cSSjoerd Meijer // which does not do all the offset calculations.
57338c2cd0cSSjoerd Meijer unsigned
maximizeConstantsInRange(ConstCandVecType::iterator S,ConstCandVecType::iterator E,ConstCandVecType::iterator & MaxCostItr)57438c2cd0cSSjoerd Meijer ConstantHoistingPass::maximizeConstantsInRange(ConstCandVecType::iterator S,
57538c2cd0cSSjoerd Meijer ConstCandVecType::iterator E,
57638c2cd0cSSjoerd Meijer ConstCandVecType::iterator &MaxCostItr) {
5776dab520cSJuergen Ributzka unsigned NumUses = 0;
57838c2cd0cSSjoerd Meijer
57909e539fcSHiroshi Yamauchi bool OptForSize = Entry->getParent()->hasOptSize() ||
5808cdfdfeeSHiroshi Yamauchi llvm::shouldOptimizeForSize(Entry->getParent(), PSI, BFI,
5818cdfdfeeSHiroshi Yamauchi PGSOQueryType::IRPass);
58209e539fcSHiroshi Yamauchi if (!OptForSize || std::distance(S,E) > 100) {
5835429c06bSJuergen Ributzka for (auto ConstCand = S; ConstCand != E; ++ConstCand) {
5845429c06bSJuergen Ributzka NumUses += ConstCand->Uses.size();
5855429c06bSJuergen Ributzka if (ConstCand->CumulativeCost > MaxCostItr->CumulativeCost)
5865429c06bSJuergen Ributzka MaxCostItr = ConstCand;
5876dab520cSJuergen Ributzka }
58838c2cd0cSSjoerd Meijer return NumUses;
58938c2cd0cSSjoerd Meijer }
59038c2cd0cSSjoerd Meijer
591d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "== Maximize constants in range ==\n");
592f9a50f04SSander de Smalen InstructionCost MaxCost = -1;
59338c2cd0cSSjoerd Meijer for (auto ConstCand = S; ConstCand != E; ++ConstCand) {
59438c2cd0cSSjoerd Meijer auto Value = ConstCand->ConstInt->getValue();
59538c2cd0cSSjoerd Meijer Type *Ty = ConstCand->ConstInt->getType();
596f9a50f04SSander de Smalen InstructionCost Cost = 0;
59738c2cd0cSSjoerd Meijer NumUses += ConstCand->Uses.size();
598d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "= Constant: " << ConstCand->ConstInt->getValue()
599d34e60caSNicola Zaghen << "\n");
60038c2cd0cSSjoerd Meijer
60138c2cd0cSSjoerd Meijer for (auto User : ConstCand->Uses) {
60238c2cd0cSSjoerd Meijer unsigned Opcode = User.Inst->getOpcode();
60338c2cd0cSSjoerd Meijer unsigned OpndIdx = User.OpndIdx;
60440574fefSSam Parker Cost += TTI->getIntImmCostInst(Opcode, OpndIdx, Value, Ty,
60540574fefSSam Parker TargetTransformInfo::TCK_SizeAndLatency);
606d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "Cost: " << Cost << "\n");
60738c2cd0cSSjoerd Meijer
60838c2cd0cSSjoerd Meijer for (auto C2 = S; C2 != E; ++C2) {
6098002c504SEugene Zelenko Optional<APInt> Diff = calculateOffsetDiff(
61038c2cd0cSSjoerd Meijer C2->ConstInt->getValue(),
61138c2cd0cSSjoerd Meijer ConstCand->ConstInt->getValue());
61238c2cd0cSSjoerd Meijer if (Diff) {
613f9a50f04SSander de Smalen const InstructionCost ImmCosts =
614*611ffcf4SKazu Hirata TTI->getIntImmCodeSizeCost(Opcode, OpndIdx, Diff.value(), Ty);
61538c2cd0cSSjoerd Meijer Cost -= ImmCosts;
616*611ffcf4SKazu Hirata LLVM_DEBUG(dbgs() << "Offset " << Diff.value() << " "
61738c2cd0cSSjoerd Meijer << "has penalty: " << ImmCosts << "\n"
61838c2cd0cSSjoerd Meijer << "Adjusted cost: " << Cost << "\n");
61938c2cd0cSSjoerd Meijer }
62038c2cd0cSSjoerd Meijer }
62138c2cd0cSSjoerd Meijer }
622d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "Cumulative cost: " << Cost << "\n");
62338c2cd0cSSjoerd Meijer if (Cost > MaxCost) {
62438c2cd0cSSjoerd Meijer MaxCost = Cost;
62538c2cd0cSSjoerd Meijer MaxCostItr = ConstCand;
626d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "New candidate: " << MaxCostItr->ConstInt->getValue()
62738c2cd0cSSjoerd Meijer << "\n");
62838c2cd0cSSjoerd Meijer }
62938c2cd0cSSjoerd Meijer }
63038c2cd0cSSjoerd Meijer return NumUses;
63138c2cd0cSSjoerd Meijer }
63238c2cd0cSSjoerd Meijer
6335f8f34e4SAdrian Prantl /// Find the base constant within the given range and rebase all other
63438c2cd0cSSjoerd Meijer /// constants with respect to the base constant.
findAndMakeBaseConstant(ConstCandVecType::iterator S,ConstCandVecType::iterator E,SmallVectorImpl<consthoist::ConstantInfo> & ConstInfoVec)63538c2cd0cSSjoerd Meijer void ConstantHoistingPass::findAndMakeBaseConstant(
636a0aa41d7SZhaoshi Zheng ConstCandVecType::iterator S, ConstCandVecType::iterator E,
637a0aa41d7SZhaoshi Zheng SmallVectorImpl<consthoist::ConstantInfo> &ConstInfoVec) {
63838c2cd0cSSjoerd Meijer auto MaxCostItr = S;
63938c2cd0cSSjoerd Meijer unsigned NumUses = maximizeConstantsInRange(S, E, MaxCostItr);
6406dab520cSJuergen Ributzka
6416dab520cSJuergen Ributzka // Don't hoist constants that have only one use.
6426dab520cSJuergen Ributzka if (NumUses <= 1)
6436dab520cSJuergen Ributzka return;
6446dab520cSJuergen Ributzka
645a0aa41d7SZhaoshi Zheng ConstantInt *ConstInt = MaxCostItr->ConstInt;
646a0aa41d7SZhaoshi Zheng ConstantExpr *ConstExpr = MaxCostItr->ConstExpr;
6475429c06bSJuergen Ributzka ConstantInfo ConstInfo;
648a0aa41d7SZhaoshi Zheng ConstInfo.BaseInt = ConstInt;
649a0aa41d7SZhaoshi Zheng ConstInfo.BaseExpr = ConstExpr;
650a0aa41d7SZhaoshi Zheng Type *Ty = ConstInt->getType();
6515429c06bSJuergen Ributzka
6526dab520cSJuergen Ributzka // Rebase the constants with respect to the base constant.
6535429c06bSJuergen Ributzka for (auto ConstCand = S; ConstCand != E; ++ConstCand) {
654a0aa41d7SZhaoshi Zheng APInt Diff = ConstCand->ConstInt->getValue() - ConstInt->getValue();
6555429c06bSJuergen Ributzka Constant *Offset = Diff == 0 ? nullptr : ConstantInt::get(Ty, Diff);
656a0aa41d7SZhaoshi Zheng Type *ConstTy =
657a0aa41d7SZhaoshi Zheng ConstCand->ConstExpr ? ConstCand->ConstExpr->getType() : nullptr;
6585429c06bSJuergen Ributzka ConstInfo.RebasedConstants.push_back(
659a0aa41d7SZhaoshi Zheng RebasedConstantInfo(std::move(ConstCand->Uses), Offset, ConstTy));
6606dab520cSJuergen Ributzka }
661a0aa41d7SZhaoshi Zheng ConstInfoVec.push_back(std::move(ConstInfo));
6626dab520cSJuergen Ributzka }
6636dab520cSJuergen Ributzka
6645f8f34e4SAdrian Prantl /// Finds and combines constant candidates that can be easily
6655429c06bSJuergen Ributzka /// rematerialized with an add from a common base constant.
findBaseConstants(GlobalVariable * BaseGV)666a0aa41d7SZhaoshi Zheng void ConstantHoistingPass::findBaseConstants(GlobalVariable *BaseGV) {
667a0aa41d7SZhaoshi Zheng // If BaseGV is nullptr, find base among candidate constant integers;
668a0aa41d7SZhaoshi Zheng // Otherwise find base among constant GEPs that share the same BaseGV.
669a0aa41d7SZhaoshi Zheng ConstCandVecType &ConstCandVec = BaseGV ?
670a0aa41d7SZhaoshi Zheng ConstGEPCandMap[BaseGV] : ConstIntCandVec;
671a0aa41d7SZhaoshi Zheng ConstInfoVecType &ConstInfoVec = BaseGV ?
672a0aa41d7SZhaoshi Zheng ConstGEPInfoMap[BaseGV] : ConstIntInfoVec;
673a0aa41d7SZhaoshi Zheng
6745429c06bSJuergen Ributzka // Sort the constants by value and type. This invalidates the mapping!
675efd94c56SFangrui Song llvm::stable_sort(ConstCandVec, [](const ConstantCandidate &LHS,
676efd94c56SFangrui Song const ConstantCandidate &RHS) {
677a29a5b84SJuergen Ributzka if (LHS.ConstInt->getType() != RHS.ConstInt->getType())
678a29a5b84SJuergen Ributzka return LHS.ConstInt->getType()->getBitWidth() <
679a29a5b84SJuergen Ributzka RHS.ConstInt->getType()->getBitWidth();
680a29a5b84SJuergen Ributzka return LHS.ConstInt->getValue().ult(RHS.ConstInt->getValue());
6816dab520cSJuergen Ributzka });
6826dab520cSJuergen Ributzka
6835429c06bSJuergen Ributzka // Simple linear scan through the sorted constant candidate vector for viable
6845429c06bSJuergen Ributzka // merge candidates.
6855429c06bSJuergen Ributzka auto MinValItr = ConstCandVec.begin();
6865429c06bSJuergen Ributzka for (auto CC = std::next(ConstCandVec.begin()), E = ConstCandVec.end();
6875429c06bSJuergen Ributzka CC != E; ++CC) {
6885429c06bSJuergen Ributzka if (MinValItr->ConstInt->getType() == CC->ConstInt->getType()) {
68935818e27SZhaoshi Zheng Type *MemUseValTy = nullptr;
69035818e27SZhaoshi Zheng for (auto &U : CC->Uses) {
69135818e27SZhaoshi Zheng auto *UI = U.Inst;
69235818e27SZhaoshi Zheng if (LoadInst *LI = dyn_cast<LoadInst>(UI)) {
69335818e27SZhaoshi Zheng MemUseValTy = LI->getType();
69435818e27SZhaoshi Zheng break;
69535818e27SZhaoshi Zheng } else if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
69635818e27SZhaoshi Zheng // Make sure the constant is used as pointer operand of the StoreInst.
69735818e27SZhaoshi Zheng if (SI->getPointerOperand() == SI->getOperand(U.OpndIdx)) {
69835818e27SZhaoshi Zheng MemUseValTy = SI->getValueOperand()->getType();
69935818e27SZhaoshi Zheng break;
70035818e27SZhaoshi Zheng }
70135818e27SZhaoshi Zheng }
70235818e27SZhaoshi Zheng }
70335818e27SZhaoshi Zheng
7046dab520cSJuergen Ributzka // Check if the constant is in range of an add with immediate.
7055429c06bSJuergen Ributzka APInt Diff = CC->ConstInt->getValue() - MinValItr->ConstInt->getValue();
7066dab520cSJuergen Ributzka if ((Diff.getBitWidth() <= 64) &&
70735818e27SZhaoshi Zheng TTI->isLegalAddImmediate(Diff.getSExtValue()) &&
70835818e27SZhaoshi Zheng // Check if Diff can be used as offset in addressing mode of the user
70935818e27SZhaoshi Zheng // memory instruction.
71035818e27SZhaoshi Zheng (!MemUseValTy || TTI->isLegalAddressingMode(MemUseValTy,
71135818e27SZhaoshi Zheng /*BaseGV*/nullptr, /*BaseOffset*/Diff.getSExtValue(),
71235818e27SZhaoshi Zheng /*HasBaseReg*/true, /*Scale*/0)))
7136dab520cSJuergen Ributzka continue;
7146dab520cSJuergen Ributzka }
7156dab520cSJuergen Ributzka // We either have now a different constant type or the constant is not in
7166dab520cSJuergen Ributzka // range of an add with immediate anymore.
717a0aa41d7SZhaoshi Zheng findAndMakeBaseConstant(MinValItr, CC, ConstInfoVec);
7186dab520cSJuergen Ributzka // Start a new base constant search.
7195429c06bSJuergen Ributzka MinValItr = CC;
7206dab520cSJuergen Ributzka }
7216dab520cSJuergen Ributzka // Finalize the last base constant search.
722a0aa41d7SZhaoshi Zheng findAndMakeBaseConstant(MinValItr, ConstCandVec.end(), ConstInfoVec);
72346357931SJuergen Ributzka }
72446357931SJuergen Ributzka
7255f8f34e4SAdrian Prantl /// Updates the operand at Idx in instruction Inst with the result of
726e802d507SJuergen Ributzka /// instruction Mat. If the instruction is a PHI node then special
7277d18a70dSSimon Pilgrim /// handling for duplicate values form the same incoming basic block is
728e802d507SJuergen Ributzka /// required.
729e802d507SJuergen Ributzka /// \return The update will always succeed, but the return value indicated if
730e802d507SJuergen Ributzka /// Mat was used for the update or not.
updateOperand(Instruction * Inst,unsigned Idx,Instruction * Mat)731e802d507SJuergen Ributzka static bool updateOperand(Instruction *Inst, unsigned Idx, Instruction *Mat) {
732e802d507SJuergen Ributzka if (auto PHI = dyn_cast<PHINode>(Inst)) {
733e802d507SJuergen Ributzka // Check if any previous operand of the PHI node has the same incoming basic
734e802d507SJuergen Ributzka // block. This is a very odd case that happens when the incoming basic block
735e802d507SJuergen Ributzka // has a switch statement. In this case use the same value as the previous
736e802d507SJuergen Ributzka // operand(s), otherwise we will fail verification due to different values.
737e802d507SJuergen Ributzka // The values are actually the same, but the variable names are different
738e802d507SJuergen Ributzka // and the verifier doesn't like that.
739e802d507SJuergen Ributzka BasicBlock *IncomingBB = PHI->getIncomingBlock(Idx);
740e802d507SJuergen Ributzka for (unsigned i = 0; i < Idx; ++i) {
741e802d507SJuergen Ributzka if (PHI->getIncomingBlock(i) == IncomingBB) {
742e802d507SJuergen Ributzka Value *IncomingVal = PHI->getIncomingValue(i);
743e802d507SJuergen Ributzka Inst->setOperand(Idx, IncomingVal);
744e802d507SJuergen Ributzka return false;
745e802d507SJuergen Ributzka }
746e802d507SJuergen Ributzka }
747e802d507SJuergen Ributzka }
748e802d507SJuergen Ributzka
749e802d507SJuergen Ributzka Inst->setOperand(Idx, Mat);
750e802d507SJuergen Ributzka return true;
751e802d507SJuergen Ributzka }
752e802d507SJuergen Ributzka
7535f8f34e4SAdrian Prantl /// Emit materialization code for all rebased constants and update their
754f26beda7SJuergen Ributzka /// users.
emitBaseConstants(Instruction * Base,Constant * Offset,Type * Ty,const ConstantUser & ConstUser)755071d8306SMichael Kuperstein void ConstantHoistingPass::emitBaseConstants(Instruction *Base,
756071d8306SMichael Kuperstein Constant *Offset,
757a0aa41d7SZhaoshi Zheng Type *Ty,
7585429c06bSJuergen Ributzka const ConstantUser &ConstUser) {
759f26beda7SJuergen Ributzka Instruction *Mat = Base;
760a0aa41d7SZhaoshi Zheng
761a0aa41d7SZhaoshi Zheng // The same offset can be dereferenced to different types in nested struct.
762a0aa41d7SZhaoshi Zheng if (!Offset && Ty && Ty != Base->getType())
763a0aa41d7SZhaoshi Zheng Offset = ConstantInt::get(Type::getInt32Ty(*Ctx), 0);
764a0aa41d7SZhaoshi Zheng
7655429c06bSJuergen Ributzka if (Offset) {
7665429c06bSJuergen Ributzka Instruction *InsertionPt = findMatInsertPt(ConstUser.Inst,
7675429c06bSJuergen Ributzka ConstUser.OpndIdx);
768a0aa41d7SZhaoshi Zheng if (Ty) {
769a0aa41d7SZhaoshi Zheng // Constant being rebased is a ConstantExpr.
770a0aa41d7SZhaoshi Zheng PointerType *Int8PtrTy = Type::getInt8PtrTy(*Ctx,
771a0aa41d7SZhaoshi Zheng cast<PointerType>(Ty)->getAddressSpace());
772a0aa41d7SZhaoshi Zheng Base = new BitCastInst(Base, Int8PtrTy, "base_bitcast", InsertionPt);
7733e54de4dSNikita Popov Mat = GetElementPtrInst::Create(Type::getInt8Ty(*Ctx), Base,
774a0aa41d7SZhaoshi Zheng Offset, "mat_gep", InsertionPt);
775a0aa41d7SZhaoshi Zheng Mat = new BitCastInst(Mat, Ty, "mat_bitcast", InsertionPt);
776a0aa41d7SZhaoshi Zheng } else
777a0aa41d7SZhaoshi Zheng // Constant being rebased is a ConstantInt.
778f26beda7SJuergen Ributzka Mat = BinaryOperator::Create(Instruction::Add, Base, Offset,
7795429c06bSJuergen Ributzka "const_mat", InsertionPt);
780f26beda7SJuergen Ributzka
781d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "Materialize constant (" << *Base->getOperand(0)
782f26beda7SJuergen Ributzka << " + " << *Offset << ") in BB "
783d34e60caSNicola Zaghen << Mat->getParent()->getName() << '\n'
784d34e60caSNicola Zaghen << *Mat << '\n');
7855429c06bSJuergen Ributzka Mat->setDebugLoc(ConstUser.Inst->getDebugLoc());
786f26beda7SJuergen Ributzka }
7875429c06bSJuergen Ributzka Value *Opnd = ConstUser.Inst->getOperand(ConstUser.OpndIdx);
7885429c06bSJuergen Ributzka
7895429c06bSJuergen Ributzka // Visit constant integer.
7905429c06bSJuergen Ributzka if (isa<ConstantInt>(Opnd)) {
791d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "Update: " << *ConstUser.Inst << '\n');
792e802d507SJuergen Ributzka if (!updateOperand(ConstUser.Inst, ConstUser.OpndIdx, Mat) && Offset)
793e802d507SJuergen Ributzka Mat->eraseFromParent();
794d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "To : " << *ConstUser.Inst << '\n');
795f26beda7SJuergen Ributzka return;
796f26beda7SJuergen Ributzka }
7975429c06bSJuergen Ributzka
7985429c06bSJuergen Ributzka // Visit cast instruction.
7995429c06bSJuergen Ributzka if (auto CastInst = dyn_cast<Instruction>(Opnd)) {
8005429c06bSJuergen Ributzka assert(CastInst->isCast() && "Expected an cast instruction!");
8015429c06bSJuergen Ributzka // Check if we already have visited this cast instruction before to avoid
8025429c06bSJuergen Ributzka // unnecessary cloning.
8035429c06bSJuergen Ributzka Instruction *&ClonedCastInst = ClonedCastMap[CastInst];
8045429c06bSJuergen Ributzka if (!ClonedCastInst) {
8055429c06bSJuergen Ributzka ClonedCastInst = CastInst->clone();
8065429c06bSJuergen Ributzka ClonedCastInst->setOperand(0, Mat);
8075429c06bSJuergen Ributzka ClonedCastInst->insertAfter(CastInst);
8085429c06bSJuergen Ributzka // Use the same debug location as the original cast instruction.
8095429c06bSJuergen Ributzka ClonedCastInst->setDebugLoc(CastInst->getDebugLoc());
810d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "Clone instruction: " << *CastInst << '\n'
811a1444b39SJuergen Ributzka << "To : " << *ClonedCastInst << '\n');
8124c8a0252SJuergen Ributzka }
813f26beda7SJuergen Ributzka
814d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "Update: " << *ConstUser.Inst << '\n');
815e802d507SJuergen Ributzka updateOperand(ConstUser.Inst, ConstUser.OpndIdx, ClonedCastInst);
816d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "To : " << *ConstUser.Inst << '\n');
8175429c06bSJuergen Ributzka return;
81846357931SJuergen Ributzka }
8195429c06bSJuergen Ributzka
8205429c06bSJuergen Ributzka // Visit constant expression.
8215429c06bSJuergen Ributzka if (auto ConstExpr = dyn_cast<ConstantExpr>(Opnd)) {
822d56b0ad4SNikita Popov if (isa<GEPOperator>(ConstExpr)) {
823a0aa41d7SZhaoshi Zheng // Operand is a ConstantGEP, replace it.
824a0aa41d7SZhaoshi Zheng updateOperand(ConstUser.Inst, ConstUser.OpndIdx, Mat);
825a0aa41d7SZhaoshi Zheng return;
826a0aa41d7SZhaoshi Zheng }
827a0aa41d7SZhaoshi Zheng
828a0aa41d7SZhaoshi Zheng // Aside from constant GEPs, only constant cast expressions are collected.
829a0aa41d7SZhaoshi Zheng assert(ConstExpr->isCast() && "ConstExpr should be a cast");
8301b758925SJay Foad Instruction *ConstExprInst = ConstExpr->getAsInstruction(
8311b758925SJay Foad findMatInsertPt(ConstUser.Inst, ConstUser.OpndIdx));
8325429c06bSJuergen Ributzka ConstExprInst->setOperand(0, Mat);
833f26beda7SJuergen Ributzka
834f26beda7SJuergen Ributzka // Use the same debug location as the instruction we are about to update.
8355429c06bSJuergen Ributzka ConstExprInst->setDebugLoc(ConstUser.Inst->getDebugLoc());
836f26beda7SJuergen Ributzka
837d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "Create instruction: " << *ConstExprInst << '\n'
8385429c06bSJuergen Ributzka << "From : " << *ConstExpr << '\n');
839d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "Update: " << *ConstUser.Inst << '\n');
840e802d507SJuergen Ributzka if (!updateOperand(ConstUser.Inst, ConstUser.OpndIdx, ConstExprInst)) {
841e802d507SJuergen Ributzka ConstExprInst->eraseFromParent();
842e802d507SJuergen Ributzka if (Offset)
843e802d507SJuergen Ributzka Mat->eraseFromParent();
844e802d507SJuergen Ributzka }
845d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "To : " << *ConstUser.Inst << '\n');
8465429c06bSJuergen Ributzka return;
8474c8a0252SJuergen Ributzka }
848f26beda7SJuergen Ributzka }
849f26beda7SJuergen Ributzka
8505f8f34e4SAdrian Prantl /// Hoist and hide the base constant behind a bitcast and emit
851f26beda7SJuergen Ributzka /// materialization code for derived constants.
emitBaseConstants(GlobalVariable * BaseGV)852a0aa41d7SZhaoshi Zheng bool ConstantHoistingPass::emitBaseConstants(GlobalVariable *BaseGV) {
853f26beda7SJuergen Ributzka bool MadeChange = false;
854a0aa41d7SZhaoshi Zheng SmallVectorImpl<consthoist::ConstantInfo> &ConstInfoVec =
855a0aa41d7SZhaoshi Zheng BaseGV ? ConstGEPInfoMap[BaseGV] : ConstIntInfoVec;
856a0aa41d7SZhaoshi Zheng for (auto const &ConstInfo : ConstInfoVec) {
857403e08d4SEli Friedman SetVector<Instruction *> IPSet = findConstantInsertionPoint(ConstInfo);
8586e32b46bSSanjay Patel // We can have an empty set if the function contains unreachable blocks.
8596e32b46bSSanjay Patel if (IPSet.empty())
8606e32b46bSSanjay Patel continue;
861337d4d95SWei Mi
862337d4d95SWei Mi unsigned UsesNum = 0;
863337d4d95SWei Mi unsigned ReBasesNum = 0;
86495710337SZhaoshi Zheng unsigned NotRebasedNum = 0;
865337d4d95SWei Mi for (Instruction *IP : IPSet) {
86695710337SZhaoshi Zheng // First, collect constants depending on this IP of the base.
86795710337SZhaoshi Zheng unsigned Uses = 0;
86895710337SZhaoshi Zheng using RebasedUse = std::tuple<Constant *, Type *, ConstantUser>;
86995710337SZhaoshi Zheng SmallVector<RebasedUse, 4> ToBeRebased;
87095710337SZhaoshi Zheng for (auto const &RCI : ConstInfo.RebasedConstants) {
87195710337SZhaoshi Zheng for (auto const &U : RCI.Uses) {
87295710337SZhaoshi Zheng Uses++;
87395710337SZhaoshi Zheng BasicBlock *OrigMatInsertBB =
87495710337SZhaoshi Zheng findMatInsertPt(U.Inst, U.OpndIdx)->getParent();
87595710337SZhaoshi Zheng // If Base constant is to be inserted in multiple places,
87695710337SZhaoshi Zheng // generate rebase for U using the Base dominating U.
87795710337SZhaoshi Zheng if (IPSet.size() == 1 ||
87895710337SZhaoshi Zheng DT->dominates(IP->getParent(), OrigMatInsertBB))
87995710337SZhaoshi Zheng ToBeRebased.push_back(RebasedUse(RCI.Offset, RCI.Ty, U));
88095710337SZhaoshi Zheng }
88195710337SZhaoshi Zheng }
88295710337SZhaoshi Zheng UsesNum = Uses;
88395710337SZhaoshi Zheng
88495710337SZhaoshi Zheng // If only few constants depend on this IP of base, skip rebasing,
88595710337SZhaoshi Zheng // assuming the base and the rebased have the same materialization cost.
88695710337SZhaoshi Zheng if (ToBeRebased.size() < MinNumOfDependentToRebase) {
88795710337SZhaoshi Zheng NotRebasedNum += ToBeRebased.size();
88895710337SZhaoshi Zheng continue;
88995710337SZhaoshi Zheng }
89095710337SZhaoshi Zheng
89195710337SZhaoshi Zheng // Emit an instance of the base at this IP.
892a0aa41d7SZhaoshi Zheng Instruction *Base = nullptr;
893a0aa41d7SZhaoshi Zheng // Hoist and hide the base constant behind a bitcast.
894a0aa41d7SZhaoshi Zheng if (ConstInfo.BaseExpr) {
895a0aa41d7SZhaoshi Zheng assert(BaseGV && "A base constant expression must have an base GV");
896a0aa41d7SZhaoshi Zheng Type *Ty = ConstInfo.BaseExpr->getType();
897a0aa41d7SZhaoshi Zheng Base = new BitCastInst(ConstInfo.BaseExpr, Ty, "const", IP);
898a0aa41d7SZhaoshi Zheng } else {
899a0aa41d7SZhaoshi Zheng IntegerType *Ty = ConstInfo.BaseInt->getType();
900a0aa41d7SZhaoshi Zheng Base = new BitCastInst(ConstInfo.BaseInt, Ty, "const", IP);
901a0aa41d7SZhaoshi Zheng }
902b46256b0SPaul Robinson
903b46256b0SPaul Robinson Base->setDebugLoc(IP->getDebugLoc());
904b46256b0SPaul Robinson
905a0aa41d7SZhaoshi Zheng LLVM_DEBUG(dbgs() << "Hoist constant (" << *ConstInfo.BaseInt
906337d4d95SWei Mi << ") to BB " << IP->getParent()->getName() << '\n'
907337d4d95SWei Mi << *Base << '\n');
908f26beda7SJuergen Ributzka
90995710337SZhaoshi Zheng // Emit materialization code for rebased constants depending on this IP.
91095710337SZhaoshi Zheng for (auto const &R : ToBeRebased) {
91195710337SZhaoshi Zheng Constant *Off = std::get<0>(R);
91295710337SZhaoshi Zheng Type *Ty = std::get<1>(R);
91395710337SZhaoshi Zheng ConstantUser U = std::get<2>(R);
91495710337SZhaoshi Zheng emitBaseConstants(Base, Off, Ty, U);
915337d4d95SWei Mi ReBasesNum++;
91695710337SZhaoshi Zheng // Use the same debug location as the last user of the constant.
917a0aa41d7SZhaoshi Zheng Base->setDebugLoc(DILocation::getMergedLocation(
918a0aa41d7SZhaoshi Zheng Base->getDebugLoc(), U.Inst->getDebugLoc()));
919337d4d95SWei Mi }
920f26beda7SJuergen Ributzka assert(!Base->use_empty() && "The use list is empty!?");
921cdf47884SChandler Carruth assert(isa<Instruction>(Base->user_back()) &&
922f26beda7SJuergen Ributzka "All uses should be instructions.");
923337d4d95SWei Mi }
924337d4d95SWei Mi (void)UsesNum;
925337d4d95SWei Mi (void)ReBasesNum;
92695710337SZhaoshi Zheng (void)NotRebasedNum;
927337d4d95SWei Mi // Expect all uses are rebased after rebase is done.
92895710337SZhaoshi Zheng assert(UsesNum == (ReBasesNum + NotRebasedNum) &&
92995710337SZhaoshi Zheng "Not all uses are rebased");
930f26beda7SJuergen Ributzka
931337d4d95SWei Mi NumConstantsHoisted++;
932337d4d95SWei Mi
933337d4d95SWei Mi // Base constant is also included in ConstInfo.RebasedConstants, so
934337d4d95SWei Mi // deduct 1 from ConstInfo.RebasedConstants.size().
935a0aa41d7SZhaoshi Zheng NumConstantsRebased += ConstInfo.RebasedConstants.size() - 1;
936337d4d95SWei Mi
937f26beda7SJuergen Ributzka MadeChange = true;
938f26beda7SJuergen Ributzka }
939f26beda7SJuergen Ributzka return MadeChange;
940f26beda7SJuergen Ributzka }
941f26beda7SJuergen Ributzka
9425f8f34e4SAdrian Prantl /// Check all cast instructions we made a copy of and remove them if they
9435429c06bSJuergen Ributzka /// have no more users.
deleteDeadCastInst() const944071d8306SMichael Kuperstein void ConstantHoistingPass::deleteDeadCastInst() const {
9455429c06bSJuergen Ributzka for (auto const &I : ClonedCastMap)
9465429c06bSJuergen Ributzka if (I.first->use_empty())
947e474752fSJuergen Ributzka I.first->eraseFromParent();
9485429c06bSJuergen Ributzka }
949f26beda7SJuergen Ributzka
9505f8f34e4SAdrian Prantl /// Optimize expensive integer constants in the given function.
runImpl(Function & Fn,TargetTransformInfo & TTI,DominatorTree & DT,BlockFrequencyInfo * BFI,BasicBlock & Entry,ProfileSummaryInfo * PSI)951071d8306SMichael Kuperstein bool ConstantHoistingPass::runImpl(Function &Fn, TargetTransformInfo &TTI,
952337d4d95SWei Mi DominatorTree &DT, BlockFrequencyInfo *BFI,
95309e539fcSHiroshi Yamauchi BasicBlock &Entry, ProfileSummaryInfo *PSI) {
954071d8306SMichael Kuperstein this->TTI = &TTI;
955071d8306SMichael Kuperstein this->DT = &DT;
956337d4d95SWei Mi this->BFI = BFI;
957a0aa41d7SZhaoshi Zheng this->DL = &Fn.getParent()->getDataLayout();
958a0aa41d7SZhaoshi Zheng this->Ctx = &Fn.getContext();
959071d8306SMichael Kuperstein this->Entry = &Entry;
96009e539fcSHiroshi Yamauchi this->PSI = PSI;
96146357931SJuergen Ributzka // Collect all constant candidates.
9625429c06bSJuergen Ributzka collectConstantCandidates(Fn);
96346357931SJuergen Ributzka
964f26beda7SJuergen Ributzka // Combine constants that can be easily materialized with an add from a common
965f26beda7SJuergen Ributzka // base constant.
966a0aa41d7SZhaoshi Zheng if (!ConstIntCandVec.empty())
967a0aa41d7SZhaoshi Zheng findBaseConstants(nullptr);
96881a40880SSimon Pilgrim for (const auto &MapEntry : ConstGEPCandMap)
969a0aa41d7SZhaoshi Zheng if (!MapEntry.second.empty())
970a0aa41d7SZhaoshi Zheng findBaseConstants(MapEntry.first);
9715429c06bSJuergen Ributzka
972f0dff49aSJuergen Ributzka // Finally hoist the base constant and emit materialization code for dependent
973f26beda7SJuergen Ributzka // constants.
974a0aa41d7SZhaoshi Zheng bool MadeChange = false;
975a0aa41d7SZhaoshi Zheng if (!ConstIntInfoVec.empty())
976a0aa41d7SZhaoshi Zheng MadeChange = emitBaseConstants(nullptr);
97781a40880SSimon Pilgrim for (const auto &MapEntry : ConstGEPInfoMap)
978a0aa41d7SZhaoshi Zheng if (!MapEntry.second.empty())
979a0aa41d7SZhaoshi Zheng MadeChange |= emitBaseConstants(MapEntry.first);
980a0aa41d7SZhaoshi Zheng
981f26beda7SJuergen Ributzka
9825429c06bSJuergen Ributzka // Cleanup dead instructions.
9835429c06bSJuergen Ributzka deleteDeadCastInst();
984f26beda7SJuergen Ributzka
985f4b25f70SFangrui Song cleanup();
986f4b25f70SFangrui Song
987f26beda7SJuergen Ributzka return MadeChange;
988f26beda7SJuergen Ributzka }
989071d8306SMichael Kuperstein
run(Function & F,FunctionAnalysisManager & AM)990071d8306SMichael Kuperstein PreservedAnalyses ConstantHoistingPass::run(Function &F,
991071d8306SMichael Kuperstein FunctionAnalysisManager &AM) {
992071d8306SMichael Kuperstein auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
993071d8306SMichael Kuperstein auto &TTI = AM.getResult<TargetIRAnalysis>(F);
994337d4d95SWei Mi auto BFI = ConstHoistWithBlockFrequency
995337d4d95SWei Mi ? &AM.getResult<BlockFrequencyAnalysis>(F)
996337d4d95SWei Mi : nullptr;
997bd541b21SAlina Sbirlea auto &MAMProxy = AM.getResult<ModuleAnalysisManagerFunctionProxy>(F);
998bd541b21SAlina Sbirlea auto *PSI = MAMProxy.getCachedResult<ProfileSummaryAnalysis>(*F.getParent());
99909e539fcSHiroshi Yamauchi if (!runImpl(F, TTI, DT, BFI, F.getEntryBlock(), PSI))
1000071d8306SMichael Kuperstein return PreservedAnalyses::all();
1001071d8306SMichael Kuperstein
1002ca68a3ecSChandler Carruth PreservedAnalyses PA;
1003ca68a3ecSChandler Carruth PA.preserveSet<CFGAnalyses>();
1004ca68a3ecSChandler Carruth return PA;
1005071d8306SMichael Kuperstein }
1006