blob: 98243a23f1ef19efcaa46557d1110a078a2678f5 [file] [log] [blame]
Juergen Ributzkaf26beda2014-01-25 02:02:55 +00001//===- ConstantHoisting.cpp - Prepare code for expensive constants --------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Juergen Ributzkaf26beda2014-01-25 02:02:55 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This pass identifies expensive constants to hoist and coalesces them to
10// better prepare it for SelectionDAG-based code generation. This works around
11// the limitations of the basic-block-at-a-time approach.
12//
13// First it scans all instructions for integer constants and calculates its
14// cost. If the constant can be folded into the instruction (the cost is
15// TCC_Free) or the cost is just a simple operation (TCC_BASIC), then we don't
16// consider it expensive and leave it alone. This is the default behavior and
17// the default implementation of getIntImmCost will always return TCC_Free.
18//
19// If the cost is more than TCC_BASIC, then the integer constant can't be folded
20// into the instruction and it might be beneficial to hoist the constant.
21// Similar constants are coalesced to reduce register pressure and
22// materialization code.
23//
24// When a constant is hoisted, it is also hidden behind a bitcast to force it to
25// be live-out of the basic block. Otherwise the constant would be just
26// duplicated and each basic block would have its own copy in the SelectionDAG.
27// The SelectionDAG recognizes such constants as opaque and doesn't perform
28// certain transformations on them, which would create a new expensive constant.
29//
30// This optimization is only applied to integer constants in instructions and
Juergen Ributzkaf0dff492014-03-21 06:04:45 +000031// simple (this means not nested) constant cast expressions. For example:
Juergen Ributzkaf26beda2014-01-25 02:02:55 +000032// %0 = load i64* inttoptr (i64 big_constant to i64*)
33//===----------------------------------------------------------------------===//
34
Michael Kuperstein071d8302016-07-02 00:16:47 +000035#include "llvm/Transforms/Scalar/ConstantHoisting.h"
Eugene Zelenko8002c502017-09-13 21:43:53 +000036#include "llvm/ADT/APInt.h"
37#include "llvm/ADT/DenseMap.h"
38#include "llvm/ADT/None.h"
39#include "llvm/ADT/Optional.h"
40#include "llvm/ADT/SmallPtrSet.h"
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +000041#include "llvm/ADT/SmallVector.h"
Juergen Ributzkaf26beda2014-01-25 02:02:55 +000042#include "llvm/ADT/Statistic.h"
Eugene Zelenko8002c502017-09-13 21:43:53 +000043#include "llvm/Analysis/BlockFrequencyInfo.h"
Hiroshi Yamauchi09e539f2019-04-15 16:49:00 +000044#include "llvm/Analysis/ProfileSummaryInfo.h"
Eugene Zelenko8002c502017-09-13 21:43:53 +000045#include "llvm/Analysis/TargetTransformInfo.h"
David Blaikie31b98d22018-06-04 21:23:21 +000046#include "llvm/Transforms/Utils/Local.h"
Eugene Zelenko8002c502017-09-13 21:43:53 +000047#include "llvm/IR/BasicBlock.h"
Juergen Ributzkaf26beda2014-01-25 02:02:55 +000048#include "llvm/IR/Constants.h"
David Blaikie2be39222018-03-21 22:34:23 +000049#include "llvm/IR/DebugInfoMetadata.h"
Eugene Zelenko8002c502017-09-13 21:43:53 +000050#include "llvm/IR/Dominators.h"
51#include "llvm/IR/Function.h"
52#include "llvm/IR/InstrTypes.h"
53#include "llvm/IR/Instruction.h"
54#include "llvm/IR/Instructions.h"
Juergen Ributzkaf26beda2014-01-25 02:02:55 +000055#include "llvm/IR/IntrinsicInst.h"
Eugene Zelenko8002c502017-09-13 21:43:53 +000056#include "llvm/IR/Value.h"
Juergen Ributzkaf26beda2014-01-25 02:02:55 +000057#include "llvm/Pass.h"
Eugene Zelenko8002c502017-09-13 21:43:53 +000058#include "llvm/Support/BlockFrequency.h"
59#include "llvm/Support/Casting.h"
60#include "llvm/Support/CommandLine.h"
Juergen Ributzkaf26beda2014-01-25 02:02:55 +000061#include "llvm/Support/Debug.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000062#include "llvm/Support/raw_ostream.h"
Michael Kuperstein071d8302016-07-02 00:16:47 +000063#include "llvm/Transforms/Scalar.h"
Hiroshi Yamauchi09e539f2019-04-15 16:49:00 +000064#include "llvm/Transforms/Utils/SizeOpts.h"
Eugene Zelenko8002c502017-09-13 21:43:53 +000065#include <algorithm>
66#include <cassert>
67#include <cstdint>
68#include <iterator>
NAKAMURA Takumi99aa6e12014-04-30 06:44:50 +000069#include <tuple>
Eugene Zelenko8002c502017-09-13 21:43:53 +000070#include <utility>
Juergen Ributzkaf26beda2014-01-25 02:02:55 +000071
72using namespace llvm;
Michael Kuperstein071d8302016-07-02 00:16:47 +000073using namespace consthoist;
Juergen Ributzkaf26beda2014-01-25 02:02:55 +000074
Chandler Carruth964daaa2014-04-22 02:55:47 +000075#define DEBUG_TYPE "consthoist"
76
Juergen Ributzkaf26beda2014-01-25 02:02:55 +000077STATISTIC(NumConstantsHoisted, "Number of constants hoisted");
78STATISTIC(NumConstantsRebased, "Number of constants rebased");
79
Wei Mi337d4d92017-04-21 15:50:16 +000080static cl::opt<bool> ConstHoistWithBlockFrequency(
Wei Mi75867552017-07-07 00:11:05 +000081 "consthoist-with-block-frequency", cl::init(true), cl::Hidden,
Wei Mi337d4d92017-04-21 15:50:16 +000082 cl::desc("Enable the use of the block frequency analysis to reduce the "
83 "chance to execute const materialization more frequently than "
84 "without hoisting."));
85
Zhaoshi Zhenga0aa41d2018-09-04 22:17:03 +000086static cl::opt<bool> ConstHoistGEP(
87 "consthoist-gep", cl::init(false), cl::Hidden,
88 cl::desc("Try hoisting constant gep expressions"));
89
Zhaoshi Zheng95710332018-09-26 00:59:09 +000090static cl::opt<unsigned>
91MinNumOfDependentToRebase("consthoist-min-num-to-rebase",
92 cl::desc("Do not rebase if number of dependent constants of a Base is less "
93 "than this number."),
94 cl::init(0), cl::Hidden);
95
Juergen Ributzkaf26beda2014-01-25 02:02:55 +000096namespace {
Eugene Zelenko8002c502017-09-13 21:43:53 +000097
Adrian Prantl5f8f34e42018-05-01 15:54:18 +000098/// The constant hoisting pass.
Michael Kuperstein071d8302016-07-02 00:16:47 +000099class ConstantHoistingLegacyPass : public FunctionPass {
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000100public:
101 static char ID; // Pass identification, replacement for typeid
Eugene Zelenko8002c502017-09-13 21:43:53 +0000102
Michael Kuperstein071d8302016-07-02 00:16:47 +0000103 ConstantHoistingLegacyPass() : FunctionPass(ID) {
104 initializeConstantHoistingLegacyPassPass(*PassRegistry::getPassRegistry());
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000105 }
106
Juergen Ributzka5429c062014-03-21 06:04:36 +0000107 bool runOnFunction(Function &Fn) override;
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000108
Mehdi Amini117296c2016-10-01 02:56:57 +0000109 StringRef getPassName() const override { return "Constant Hoisting"; }
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000110
Craig Topper3e4c6972014-03-05 09:10:37 +0000111 void getAnalysisUsage(AnalysisUsage &AU) const override {
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000112 AU.setPreservesCFG();
Wei Mi337d4d92017-04-21 15:50:16 +0000113 if (ConstHoistWithBlockFrequency)
114 AU.addRequired<BlockFrequencyInfoWrapperPass>();
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000115 AU.addRequired<DominatorTreeWrapperPass>();
Hiroshi Yamauchi09e539f2019-04-15 16:49:00 +0000116 AU.addRequired<ProfileSummaryInfoWrapperPass>();
Chandler Carruth705b1852015-01-31 03:43:40 +0000117 AU.addRequired<TargetTransformInfoWrapperPass>();
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000118 }
119
120private:
Michael Kuperstein071d8302016-07-02 00:16:47 +0000121 ConstantHoistingPass Impl;
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000122};
Eugene Zelenko8002c502017-09-13 21:43:53 +0000123
124} // end anonymous namespace
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000125
Michael Kuperstein071d8302016-07-02 00:16:47 +0000126char ConstantHoistingLegacyPass::ID = 0;
Eugene Zelenko8002c502017-09-13 21:43:53 +0000127
Michael Kuperstein071d8302016-07-02 00:16:47 +0000128INITIALIZE_PASS_BEGIN(ConstantHoistingLegacyPass, "consthoist",
129 "Constant Hoisting", false, false)
Wei Mi337d4d92017-04-21 15:50:16 +0000130INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000131INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Hiroshi Yamauchi09e539f2019-04-15 16:49:00 +0000132INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
Chandler Carruth705b1852015-01-31 03:43:40 +0000133INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
Michael Kuperstein071d8302016-07-02 00:16:47 +0000134INITIALIZE_PASS_END(ConstantHoistingLegacyPass, "consthoist",
135 "Constant Hoisting", false, false)
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000136
137FunctionPass *llvm::createConstantHoistingPass() {
Michael Kuperstein071d8302016-07-02 00:16:47 +0000138 return new ConstantHoistingLegacyPass();
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000139}
140
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000141/// Perform the constant hoisting optimization for the given function.
Michael Kuperstein071d8302016-07-02 00:16:47 +0000142bool ConstantHoistingLegacyPass::runOnFunction(Function &Fn) {
Andrew Kayloraa641a52016-04-22 22:06:11 +0000143 if (skipFunction(Fn))
Andrea Di Biagiof54432382015-02-14 15:11:48 +0000144 return false;
145
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000146 LLVM_DEBUG(dbgs() << "********** Begin Constant Hoisting **********\n");
147 LLVM_DEBUG(dbgs() << "********** Function: " << Fn.getName() << '\n');
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000148
Wei Mi337d4d92017-04-21 15:50:16 +0000149 bool MadeChange =
150 Impl.runImpl(Fn, getAnalysis<TargetTransformInfoWrapperPass>().getTTI(Fn),
151 getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
152 ConstHoistWithBlockFrequency
153 ? &getAnalysis<BlockFrequencyInfoWrapperPass>().getBFI()
154 : nullptr,
Hiroshi Yamauchi09e539f2019-04-15 16:49:00 +0000155 Fn.getEntryBlock(),
156 &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI());
Juergen Ributzka5429c062014-03-21 06:04:36 +0000157
158 if (MadeChange) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000159 LLVM_DEBUG(dbgs() << "********** Function after Constant Hoisting: "
160 << Fn.getName() << '\n');
161 LLVM_DEBUG(dbgs() << Fn);
Juergen Ributzka5429c062014-03-21 06:04:36 +0000162 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000163 LLVM_DEBUG(dbgs() << "********** End Constant Hoisting **********\n");
Juergen Ributzka5429c062014-03-21 06:04:36 +0000164
Juergen Ributzka5429c062014-03-21 06:04:36 +0000165 return MadeChange;
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000166}
167
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000168/// Find the constant materialization insertion point.
Michael Kuperstein071d8302016-07-02 00:16:47 +0000169Instruction *ConstantHoistingPass::findMatInsertPt(Instruction *Inst,
170 unsigned Idx) const {
Juergen Ributzka575bcb72014-04-22 18:06:58 +0000171 // If the operand is a cast instruction, then we have to materialize the
172 // constant before the cast instruction.
173 if (Idx != ~0U) {
174 Value *Opnd = Inst->getOperand(Idx);
175 if (auto CastInst = dyn_cast<Instruction>(Opnd))
176 if (CastInst->isCast())
177 return CastInst;
178 }
179
180 // The simple and common case. This also includes constant expressions.
David Majnemerba275f92015-08-19 19:54:02 +0000181 if (!isa<PHINode>(Inst) && !Inst->isEHPad())
Juergen Ributzka5429c062014-03-21 06:04:36 +0000182 return Inst;
183
David Majnemerba275f92015-08-19 19:54:02 +0000184 // We can't insert directly before a phi node or an eh pad. Insert before
Juergen Ributzka5429c062014-03-21 06:04:36 +0000185 // the terminator of the incoming or dominating block.
186 assert(Entry != Inst->getParent() && "PHI or landing pad in entry block!");
187 if (Idx != ~0U && isa<PHINode>(Inst))
188 return cast<PHINode>(Inst)->getIncomingBlock(Idx)->getTerminator();
189
Reid Klecknerd80b69f2017-03-01 22:41:12 +0000190 // This must be an EH pad. Iterate over immediate dominators until we find a
191 // non-EH pad. We need to skip over catchswitch blocks, which are both EH pads
192 // and terminators.
193 auto IDom = DT->getNode(Inst->getParent())->getIDom();
194 while (IDom->getBlock()->isEHPad()) {
195 assert(Entry != IDom->getBlock() && "eh pad in entry block");
196 IDom = IDom->getIDom();
197 }
198
199 return IDom->getBlock()->getTerminator();
Juergen Ributzka5429c062014-03-21 06:04:36 +0000200}
201
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000202/// Given \p BBs as input, find another set of BBs which collectively
Wei Mi337d4d92017-04-21 15:50:16 +0000203/// dominates \p BBs and have the minimal sum of frequencies. Return the BB
204/// set found in \p BBs.
Benjamin Kramerdebb3c32017-05-26 20:09:00 +0000205static void findBestInsertionSet(DominatorTree &DT, BlockFrequencyInfo &BFI,
206 BasicBlock *Entry,
207 SmallPtrSet<BasicBlock *, 8> &BBs) {
Wei Mi337d4d92017-04-21 15:50:16 +0000208 assert(!BBs.count(Entry) && "Assume Entry is not in BBs");
209 // Nodes on the current path to the root.
210 SmallPtrSet<BasicBlock *, 8> Path;
211 // Candidates includes any block 'BB' in set 'BBs' that is not strictly
212 // dominated by any other blocks in set 'BBs', and all nodes in the path
213 // in the dominator tree from Entry to 'BB'.
214 SmallPtrSet<BasicBlock *, 16> Candidates;
215 for (auto BB : BBs) {
Sanjay Patel6e32b462019-03-04 20:57:14 +0000216 // Ignore unreachable basic blocks.
217 if (!DT.isReachableFromEntry(BB))
218 continue;
Wei Mi337d4d92017-04-21 15:50:16 +0000219 Path.clear();
220 // Walk up the dominator tree until Entry or another BB in BBs
221 // is reached. Insert the nodes on the way to the Path.
222 BasicBlock *Node = BB;
223 // The "Path" is a candidate path to be added into Candidates set.
224 bool isCandidate = false;
225 do {
226 Path.insert(Node);
227 if (Node == Entry || Candidates.count(Node)) {
228 isCandidate = true;
229 break;
230 }
231 assert(DT.getNode(Node)->getIDom() &&
232 "Entry doens't dominate current Node");
233 Node = DT.getNode(Node)->getIDom()->getBlock();
234 } while (!BBs.count(Node));
235
236 // If isCandidate is false, Node is another Block in BBs dominating
237 // current 'BB'. Drop the nodes on the Path.
238 if (!isCandidate)
239 continue;
240
241 // Add nodes on the Path into Candidates.
242 Candidates.insert(Path.begin(), Path.end());
243 }
244
245 // Sort the nodes in Candidates in top-down order and save the nodes
246 // in Orders.
247 unsigned Idx = 0;
248 SmallVector<BasicBlock *, 16> Orders;
249 Orders.push_back(Entry);
250 while (Idx != Orders.size()) {
251 BasicBlock *Node = Orders[Idx++];
252 for (auto ChildDomNode : DT.getNode(Node)->getChildren()) {
253 if (Candidates.count(ChildDomNode->getBlock()))
254 Orders.push_back(ChildDomNode->getBlock());
255 }
256 }
257
258 // Visit Orders in bottom-up order.
Eugene Zelenko8002c502017-09-13 21:43:53 +0000259 using InsertPtsCostPair =
260 std::pair<SmallPtrSet<BasicBlock *, 16>, BlockFrequency>;
261
Wei Mi337d4d92017-04-21 15:50:16 +0000262 // InsertPtsMap is a map from a BB to the best insertion points for the
263 // subtree of BB (subtree not including the BB itself).
264 DenseMap<BasicBlock *, InsertPtsCostPair> InsertPtsMap;
265 InsertPtsMap.reserve(Orders.size() + 1);
266 for (auto RIt = Orders.rbegin(); RIt != Orders.rend(); RIt++) {
267 BasicBlock *Node = *RIt;
268 bool NodeInBBs = BBs.count(Node);
269 SmallPtrSet<BasicBlock *, 16> &InsertPts = InsertPtsMap[Node].first;
270 BlockFrequency &InsertPtsFreq = InsertPtsMap[Node].second;
271
272 // Return the optimal insert points in BBs.
273 if (Node == Entry) {
274 BBs.clear();
Wei Mi20526b22017-07-06 22:32:27 +0000275 if (InsertPtsFreq > BFI.getBlockFreq(Node) ||
276 (InsertPtsFreq == BFI.getBlockFreq(Node) && InsertPts.size() > 1))
Wei Mi337d4d92017-04-21 15:50:16 +0000277 BBs.insert(Entry);
278 else
279 BBs.insert(InsertPts.begin(), InsertPts.end());
280 break;
281 }
282
283 BasicBlock *Parent = DT.getNode(Node)->getIDom()->getBlock();
284 // Initially, ParentInsertPts is empty and ParentPtsFreq is 0. Every child
285 // will update its parent's ParentInsertPts and ParentPtsFreq.
286 SmallPtrSet<BasicBlock *, 16> &ParentInsertPts = InsertPtsMap[Parent].first;
287 BlockFrequency &ParentPtsFreq = InsertPtsMap[Parent].second;
288 // Choose to insert in Node or in subtree of Node.
Wei Mi20526b22017-07-06 22:32:27 +0000289 // Don't hoist to EHPad because we may not find a proper place to insert
290 // in EHPad.
291 // If the total frequency of InsertPts is the same as the frequency of the
292 // target Node, and InsertPts contains more than one nodes, choose hoisting
293 // to reduce code size.
294 if (NodeInBBs ||
295 (!Node->isEHPad() &&
296 (InsertPtsFreq > BFI.getBlockFreq(Node) ||
297 (InsertPtsFreq == BFI.getBlockFreq(Node) && InsertPts.size() > 1)))) {
Wei Mi337d4d92017-04-21 15:50:16 +0000298 ParentInsertPts.insert(Node);
299 ParentPtsFreq += BFI.getBlockFreq(Node);
300 } else {
301 ParentInsertPts.insert(InsertPts.begin(), InsertPts.end());
302 ParentPtsFreq += InsertPtsFreq;
303 }
304 }
305}
306
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000307/// Find an insertion point that dominates all uses.
Wei Mi337d4d92017-04-21 15:50:16 +0000308SmallPtrSet<Instruction *, 8> ConstantHoistingPass::findConstantInsertionPoint(
Michael Kuperstein071d8302016-07-02 00:16:47 +0000309 const ConstantInfo &ConstInfo) const {
Juergen Ributzka5429c062014-03-21 06:04:36 +0000310 assert(!ConstInfo.RebasedConstants.empty() && "Invalid constant info entry.");
Juergen Ributzkac81000b2014-04-03 01:38:47 +0000311 // Collect all basic blocks.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000312 SmallPtrSet<BasicBlock *, 8> BBs;
Wei Mi337d4d92017-04-21 15:50:16 +0000313 SmallPtrSet<Instruction *, 8> InsertPts;
Juergen Ributzka5429c062014-03-21 06:04:36 +0000314 for (auto const &RCI : ConstInfo.RebasedConstants)
Juergen Ributzkac81000b2014-04-03 01:38:47 +0000315 for (auto const &U : RCI.Uses)
Juergen Ributzka575bcb72014-04-22 18:06:58 +0000316 BBs.insert(findMatInsertPt(U.Inst, U.OpndIdx)->getParent());
Juergen Ributzka5429c062014-03-21 06:04:36 +0000317
Wei Mi337d4d92017-04-21 15:50:16 +0000318 if (BBs.count(Entry)) {
319 InsertPts.insert(&Entry->front());
320 return InsertPts;
321 }
322
323 if (BFI) {
324 findBestInsertionSet(*DT, *BFI, Entry, BBs);
325 for (auto BB : BBs) {
326 BasicBlock::iterator InsertPt = BB->begin();
327 for (; isa<PHINode>(InsertPt) || InsertPt->isEHPad(); ++InsertPt)
328 ;
329 InsertPts.insert(&*InsertPt);
330 }
331 return InsertPts;
332 }
Juergen Ributzka5429c062014-03-21 06:04:36 +0000333
334 while (BBs.size() >= 2) {
335 BasicBlock *BB, *BB1, *BB2;
336 BB1 = *BBs.begin();
337 BB2 = *std::next(BBs.begin());
338 BB = DT->findNearestCommonDominator(BB1, BB2);
Wei Mi337d4d92017-04-21 15:50:16 +0000339 if (BB == Entry) {
340 InsertPts.insert(&Entry->front());
341 return InsertPts;
342 }
Juergen Ributzka5429c062014-03-21 06:04:36 +0000343 BBs.erase(BB1);
344 BBs.erase(BB2);
345 BBs.insert(BB);
346 }
347 assert((BBs.size() == 1) && "Expected only one element.");
348 Instruction &FirstInst = (*BBs.begin())->front();
Wei Mi337d4d92017-04-21 15:50:16 +0000349 InsertPts.insert(findMatInsertPt(&FirstInst));
350 return InsertPts;
Juergen Ributzka5429c062014-03-21 06:04:36 +0000351}
352
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000353/// Record constant integer ConstInt for instruction Inst at operand
Juergen Ributzka5429c062014-03-21 06:04:36 +0000354/// index Idx.
355///
Juergen Ributzkaf0dff492014-03-21 06:04:45 +0000356/// The operand at index Idx is not necessarily the constant integer itself. It
Juergen Ributzka5429c062014-03-21 06:04:36 +0000357/// could also be a cast instruction or a constant expression that uses the
Zhaoshi Zhenga0aa41d2018-09-04 22:17:03 +0000358/// constant integer.
Michael Kuperstein071d8302016-07-02 00:16:47 +0000359void ConstantHoistingPass::collectConstantCandidates(
360 ConstCandMapType &ConstCandMap, Instruction *Inst, unsigned Idx,
361 ConstantInt *ConstInt) {
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000362 unsigned Cost;
Juergen Ributzka5429c062014-03-21 06:04:36 +0000363 // Ask the target about the cost of materializing the constant for the given
Juergen Ributzkaf0dff492014-03-21 06:04:45 +0000364 // instruction and operand index.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000365 if (auto IntrInst = dyn_cast<IntrinsicInst>(Inst))
Juergen Ributzkaf0dff492014-03-21 06:04:45 +0000366 Cost = TTI->getIntImmCost(IntrInst->getIntrinsicID(), Idx,
Juergen Ributzka5429c062014-03-21 06:04:36 +0000367 ConstInt->getValue(), ConstInt->getType());
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000368 else
Juergen Ributzkaf0dff492014-03-21 06:04:45 +0000369 Cost = TTI->getIntImmCost(Inst->getOpcode(), Idx, ConstInt->getValue(),
Juergen Ributzka5429c062014-03-21 06:04:36 +0000370 ConstInt->getType());
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000371
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +0000372 // Ignore cheap integer constants.
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000373 if (Cost > TargetTransformInfo::TCC_Basic) {
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +0000374 ConstCandMapType::iterator Itr;
375 bool Inserted;
Zhaoshi Zhenga0aa41d2018-09-04 22:17:03 +0000376 ConstPtrUnionType Cand = ConstInt;
377 std::tie(Itr, Inserted) = ConstCandMap.insert(std::make_pair(Cand, 0));
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +0000378 if (Inserted) {
Zhaoshi Zhenga0aa41d2018-09-04 22:17:03 +0000379 ConstIntCandVec.push_back(ConstantCandidate(ConstInt));
380 Itr->second = ConstIntCandVec.size() - 1;
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +0000381 }
Zhaoshi Zhenga0aa41d2018-09-04 22:17:03 +0000382 ConstIntCandVec[Itr->second].addUser(Inst, Idx, Cost);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000383 LLVM_DEBUG(if (isa<ConstantInt>(Inst->getOperand(Idx))) dbgs()
384 << "Collect constant " << *ConstInt << " from " << *Inst
Juergen Ributzka5429c062014-03-21 06:04:36 +0000385 << " with cost " << Cost << '\n';
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000386 else dbgs() << "Collect constant " << *ConstInt
387 << " indirectly from " << *Inst << " via "
388 << *Inst->getOperand(Idx) << " with cost " << Cost
389 << '\n';);
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000390 }
391}
392
Zhaoshi Zhenga0aa41d2018-09-04 22:17:03 +0000393/// Record constant GEP expression for instruction Inst at operand index Idx.
394void ConstantHoistingPass::collectConstantCandidates(
395 ConstCandMapType &ConstCandMap, Instruction *Inst, unsigned Idx,
396 ConstantExpr *ConstExpr) {
397 // TODO: Handle vector GEPs
398 if (ConstExpr->getType()->isVectorTy())
399 return;
400
401 GlobalVariable *BaseGV = dyn_cast<GlobalVariable>(ConstExpr->getOperand(0));
402 if (!BaseGV)
403 return;
404
405 // Get offset from the base GV.
406 PointerType *GVPtrTy = dyn_cast<PointerType>(BaseGV->getType());
407 IntegerType *PtrIntTy = DL->getIntPtrType(*Ctx, GVPtrTy->getAddressSpace());
408 APInt Offset(DL->getTypeSizeInBits(PtrIntTy), /*val*/0, /*isSigned*/true);
409 auto *GEPO = cast<GEPOperator>(ConstExpr);
410 if (!GEPO->accumulateConstantOffset(*DL, Offset))
411 return;
412
413 if (!Offset.isIntN(32))
414 return;
415
416 // A constant GEP expression that has a GlobalVariable as base pointer is
417 // usually lowered to a load from constant pool. Such operation is unlikely
418 // to be cheaper than compute it by <Base + Offset>, which can be lowered to
419 // an ADD instruction or folded into Load/Store instruction.
420 int Cost = TTI->getIntImmCost(Instruction::Add, 1, Offset, PtrIntTy);
421 ConstCandVecType &ExprCandVec = ConstGEPCandMap[BaseGV];
422 ConstCandMapType::iterator Itr;
423 bool Inserted;
424 ConstPtrUnionType Cand = ConstExpr;
425 std::tie(Itr, Inserted) = ConstCandMap.insert(std::make_pair(Cand, 0));
426 if (Inserted) {
427 ExprCandVec.push_back(ConstantCandidate(
428 ConstantInt::get(Type::getInt32Ty(*Ctx), Offset.getLimitedValue()),
429 ConstExpr));
430 Itr->second = ExprCandVec.size() - 1;
431 }
432 ExprCandVec[Itr->second].addUser(Inst, Idx, Cost);
433}
434
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000435/// Check the operand for instruction Inst at index Idx.
Leo Li20fbad92017-06-29 17:03:34 +0000436void ConstantHoistingPass::collectConstantCandidates(
437 ConstCandMapType &ConstCandMap, Instruction *Inst, unsigned Idx) {
438 Value *Opnd = Inst->getOperand(Idx);
439
440 // Visit constant integers.
441 if (auto ConstInt = dyn_cast<ConstantInt>(Opnd)) {
442 collectConstantCandidates(ConstCandMap, Inst, Idx, ConstInt);
443 return;
444 }
445
446 // Visit cast instructions that have constant integers.
447 if (auto CastInst = dyn_cast<Instruction>(Opnd)) {
448 // Only visit cast instructions, which have been skipped. All other
449 // instructions should have already been visited.
450 if (!CastInst->isCast())
451 return;
452
453 if (auto *ConstInt = dyn_cast<ConstantInt>(CastInst->getOperand(0))) {
454 // Pretend the constant is directly used by the instruction and ignore
455 // the cast instruction.
456 collectConstantCandidates(ConstCandMap, Inst, Idx, ConstInt);
457 return;
458 }
459 }
460
461 // Visit constant expressions that have constant integers.
462 if (auto ConstExpr = dyn_cast<ConstantExpr>(Opnd)) {
Zhaoshi Zhenga0aa41d2018-09-04 22:17:03 +0000463 // Handle constant gep expressions.
464 if (ConstHoistGEP && ConstExpr->isGEPWithNoNotionalOverIndexing())
465 collectConstantCandidates(ConstCandMap, Inst, Idx, ConstExpr);
466
Leo Li20fbad92017-06-29 17:03:34 +0000467 // Only visit constant cast expressions.
468 if (!ConstExpr->isCast())
469 return;
470
471 if (auto ConstInt = dyn_cast<ConstantInt>(ConstExpr->getOperand(0))) {
472 // Pretend the constant is directly used by the instruction and ignore
473 // the constant expression.
474 collectConstantCandidates(ConstCandMap, Inst, Idx, ConstInt);
475 return;
476 }
477 }
478}
479
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000480/// Scan the instruction for expensive integer constants and record them
Juergen Ributzka5429c062014-03-21 06:04:36 +0000481/// in the constant candidate vector.
Michael Kuperstein071d8302016-07-02 00:16:47 +0000482void ConstantHoistingPass::collectConstantCandidates(
483 ConstCandMapType &ConstCandMap, Instruction *Inst) {
Juergen Ributzka5429c062014-03-21 06:04:36 +0000484 // Skip all cast instructions. They are visited indirectly later on.
485 if (Inst->isCast())
486 return;
487
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000488 // Scan all operands.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000489 for (unsigned Idx = 0, E = Inst->getNumOperands(); Idx != E; ++Idx) {
Leo Li93abd7d2017-07-10 20:45:34 +0000490 // The cost of materializing the constants (defined in
491 // `TargetTransformInfo::getIntImmCost`) for instructions which only take
492 // constant variables is lower than `TargetTransformInfo::TCC_Basic`. So
493 // it's safe for us to collect constant candidates from all IntrinsicInsts.
494 if (canReplaceOperandWithVariable(Inst, Idx) || isa<IntrinsicInst>(Inst)) {
495 collectConstantCandidates(ConstCandMap, Inst, Idx);
496 }
Juergen Ributzka5429c062014-03-21 06:04:36 +0000497 } // end of for all operands
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000498}
499
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000500/// Collect all integer constants in the function that cannot be folded
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000501/// into an instruction itself.
Michael Kuperstein071d8302016-07-02 00:16:47 +0000502void ConstantHoistingPass::collectConstantCandidates(Function &Fn) {
Juergen Ributzka7be410f2014-03-25 21:21:10 +0000503 ConstCandMapType ConstCandMap;
Duncan P. N. Exon Smith3a9c9e32015-10-13 18:26:00 +0000504 for (BasicBlock &BB : Fn)
505 for (Instruction &Inst : BB)
506 collectConstantCandidates(ConstCandMap, &Inst);
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000507}
508
Sjoerd Meijer38c2cd02016-07-14 07:44:20 +0000509// This helper function is necessary to deal with values that have different
510// bit widths (APInt Operator- does not like that). If the value cannot be
511// represented in uint64 we return an "empty" APInt. This is then interpreted
512// as the value is not in range.
Eugene Zelenko8002c502017-09-13 21:43:53 +0000513static Optional<APInt> calculateOffsetDiff(const APInt &V1, const APInt &V2) {
514 Optional<APInt> Res = None;
Sjoerd Meijer38c2cd02016-07-14 07:44:20 +0000515 unsigned BW = V1.getBitWidth() > V2.getBitWidth() ?
516 V1.getBitWidth() : V2.getBitWidth();
517 uint64_t LimVal1 = V1.getLimitedValue();
518 uint64_t LimVal2 = V2.getLimitedValue();
519
520 if (LimVal1 == ~0ULL || LimVal2 == ~0ULL)
521 return Res;
522
523 uint64_t Diff = LimVal1 - LimVal2;
524 return APInt(BW, Diff, true);
525}
526
527// From a list of constants, one needs to picked as the base and the other
528// constants will be transformed into an offset from that base constant. The
529// question is which we can pick best? For example, consider these constants
530// and their number of uses:
531//
532// Constants| 2 | 4 | 12 | 42 |
533// NumUses | 3 | 2 | 8 | 7 |
534//
535// Selecting constant 12 because it has the most uses will generate negative
536// offsets for constants 2 and 4 (i.e. -10 and -8 respectively). If negative
537// offsets lead to less optimal code generation, then there might be better
538// solutions. Suppose immediates in the range of 0..35 are most optimally
539// supported by the architecture, then selecting constant 2 is most optimal
540// because this will generate offsets: 0, 2, 10, 40. Offsets 0, 2 and 10 are in
541// range 0..35, and thus 3 + 2 + 8 = 13 uses are in range. Selecting 12 would
542// have only 8 uses in range, so choosing 2 as a base is more optimal. Thus, in
543// selecting the base constant the range of the offsets is a very important
544// factor too that we take into account here. This algorithm calculates a total
545// costs for selecting a constant as the base and substract the costs if
546// immediates are out of range. It has quadratic complexity, so we call this
547// function only when we're optimising for size and there are less than 100
548// constants, we fall back to the straightforward algorithm otherwise
549// which does not do all the offset calculations.
550unsigned
551ConstantHoistingPass::maximizeConstantsInRange(ConstCandVecType::iterator S,
552 ConstCandVecType::iterator E,
553 ConstCandVecType::iterator &MaxCostItr) {
554 unsigned NumUses = 0;
555
Hiroshi Yamauchi09e539f2019-04-15 16:49:00 +0000556 bool OptForSize = Entry->getParent()->hasOptSize() ||
557 llvm::shouldOptimizeForSize(Entry->getParent(), PSI, BFI);
558 if (!OptForSize || std::distance(S,E) > 100) {
Sjoerd Meijer38c2cd02016-07-14 07:44:20 +0000559 for (auto ConstCand = S; ConstCand != E; ++ConstCand) {
560 NumUses += ConstCand->Uses.size();
561 if (ConstCand->CumulativeCost > MaxCostItr->CumulativeCost)
562 MaxCostItr = ConstCand;
563 }
564 return NumUses;
565 }
566
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000567 LLVM_DEBUG(dbgs() << "== Maximize constants in range ==\n");
Sjoerd Meijer38c2cd02016-07-14 07:44:20 +0000568 int MaxCost = -1;
569 for (auto ConstCand = S; ConstCand != E; ++ConstCand) {
570 auto Value = ConstCand->ConstInt->getValue();
571 Type *Ty = ConstCand->ConstInt->getType();
572 int Cost = 0;
573 NumUses += ConstCand->Uses.size();
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000574 LLVM_DEBUG(dbgs() << "= Constant: " << ConstCand->ConstInt->getValue()
575 << "\n");
Sjoerd Meijer38c2cd02016-07-14 07:44:20 +0000576
577 for (auto User : ConstCand->Uses) {
578 unsigned Opcode = User.Inst->getOpcode();
579 unsigned OpndIdx = User.OpndIdx;
580 Cost += TTI->getIntImmCost(Opcode, OpndIdx, Value, Ty);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000581 LLVM_DEBUG(dbgs() << "Cost: " << Cost << "\n");
Sjoerd Meijer38c2cd02016-07-14 07:44:20 +0000582
583 for (auto C2 = S; C2 != E; ++C2) {
Eugene Zelenko8002c502017-09-13 21:43:53 +0000584 Optional<APInt> Diff = calculateOffsetDiff(
585 C2->ConstInt->getValue(),
586 ConstCand->ConstInt->getValue());
Sjoerd Meijer38c2cd02016-07-14 07:44:20 +0000587 if (Diff) {
588 const int ImmCosts =
589 TTI->getIntImmCodeSizeCost(Opcode, OpndIdx, Diff.getValue(), Ty);
590 Cost -= ImmCosts;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000591 LLVM_DEBUG(dbgs() << "Offset " << Diff.getValue() << " "
592 << "has penalty: " << ImmCosts << "\n"
593 << "Adjusted cost: " << Cost << "\n");
Sjoerd Meijer38c2cd02016-07-14 07:44:20 +0000594 }
595 }
596 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000597 LLVM_DEBUG(dbgs() << "Cumulative cost: " << Cost << "\n");
Sjoerd Meijer38c2cd02016-07-14 07:44:20 +0000598 if (Cost > MaxCost) {
599 MaxCost = Cost;
600 MaxCostItr = ConstCand;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000601 LLVM_DEBUG(dbgs() << "New candidate: " << MaxCostItr->ConstInt->getValue()
602 << "\n");
Sjoerd Meijer38c2cd02016-07-14 07:44:20 +0000603 }
604 }
605 return NumUses;
606}
607
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000608/// Find the base constant within the given range and rebase all other
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000609/// constants with respect to the base constant.
Michael Kuperstein071d8302016-07-02 00:16:47 +0000610void ConstantHoistingPass::findAndMakeBaseConstant(
Zhaoshi Zhenga0aa41d2018-09-04 22:17:03 +0000611 ConstCandVecType::iterator S, ConstCandVecType::iterator E,
612 SmallVectorImpl<consthoist::ConstantInfo> &ConstInfoVec) {
Juergen Ributzka5429c062014-03-21 06:04:36 +0000613 auto MaxCostItr = S;
Sjoerd Meijer38c2cd02016-07-14 07:44:20 +0000614 unsigned NumUses = maximizeConstantsInRange(S, E, MaxCostItr);
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000615
616 // Don't hoist constants that have only one use.
617 if (NumUses <= 1)
618 return;
619
Zhaoshi Zhenga0aa41d2018-09-04 22:17:03 +0000620 ConstantInt *ConstInt = MaxCostItr->ConstInt;
621 ConstantExpr *ConstExpr = MaxCostItr->ConstExpr;
Juergen Ributzka5429c062014-03-21 06:04:36 +0000622 ConstantInfo ConstInfo;
Zhaoshi Zhenga0aa41d2018-09-04 22:17:03 +0000623 ConstInfo.BaseInt = ConstInt;
624 ConstInfo.BaseExpr = ConstExpr;
625 Type *Ty = ConstInt->getType();
Juergen Ributzka5429c062014-03-21 06:04:36 +0000626
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000627 // Rebase the constants with respect to the base constant.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000628 for (auto ConstCand = S; ConstCand != E; ++ConstCand) {
Zhaoshi Zhenga0aa41d2018-09-04 22:17:03 +0000629 APInt Diff = ConstCand->ConstInt->getValue() - ConstInt->getValue();
Juergen Ributzka5429c062014-03-21 06:04:36 +0000630 Constant *Offset = Diff == 0 ? nullptr : ConstantInt::get(Ty, Diff);
Zhaoshi Zhenga0aa41d2018-09-04 22:17:03 +0000631 Type *ConstTy =
632 ConstCand->ConstExpr ? ConstCand->ConstExpr->getType() : nullptr;
Juergen Ributzka5429c062014-03-21 06:04:36 +0000633 ConstInfo.RebasedConstants.push_back(
Zhaoshi Zhenga0aa41d2018-09-04 22:17:03 +0000634 RebasedConstantInfo(std::move(ConstCand->Uses), Offset, ConstTy));
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000635 }
Zhaoshi Zhenga0aa41d2018-09-04 22:17:03 +0000636 ConstInfoVec.push_back(std::move(ConstInfo));
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000637}
638
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000639/// Finds and combines constant candidates that can be easily
Juergen Ributzka5429c062014-03-21 06:04:36 +0000640/// rematerialized with an add from a common base constant.
Zhaoshi Zhenga0aa41d2018-09-04 22:17:03 +0000641void ConstantHoistingPass::findBaseConstants(GlobalVariable *BaseGV) {
642 // If BaseGV is nullptr, find base among candidate constant integers;
643 // Otherwise find base among constant GEPs that share the same BaseGV.
644 ConstCandVecType &ConstCandVec = BaseGV ?
645 ConstGEPCandMap[BaseGV] : ConstIntCandVec;
646 ConstInfoVecType &ConstInfoVec = BaseGV ?
647 ConstGEPInfoMap[BaseGV] : ConstIntInfoVec;
648
Juergen Ributzka5429c062014-03-21 06:04:36 +0000649 // Sort the constants by value and type. This invalidates the mapping!
Fangrui Songefd94c52019-04-23 14:51:27 +0000650 llvm::stable_sort(ConstCandVec, [](const ConstantCandidate &LHS,
651 const ConstantCandidate &RHS) {
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +0000652 if (LHS.ConstInt->getType() != RHS.ConstInt->getType())
653 return LHS.ConstInt->getType()->getBitWidth() <
654 RHS.ConstInt->getType()->getBitWidth();
655 return LHS.ConstInt->getValue().ult(RHS.ConstInt->getValue());
Juergen Ributzka46357932014-03-20 20:17:13 +0000656 });
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000657
Juergen Ributzka5429c062014-03-21 06:04:36 +0000658 // Simple linear scan through the sorted constant candidate vector for viable
659 // merge candidates.
660 auto MinValItr = ConstCandVec.begin();
661 for (auto CC = std::next(ConstCandVec.begin()), E = ConstCandVec.end();
662 CC != E; ++CC) {
663 if (MinValItr->ConstInt->getType() == CC->ConstInt->getType()) {
Zhaoshi Zheng35818e22018-08-28 23:00:59 +0000664 Type *MemUseValTy = nullptr;
665 for (auto &U : CC->Uses) {
666 auto *UI = U.Inst;
667 if (LoadInst *LI = dyn_cast<LoadInst>(UI)) {
668 MemUseValTy = LI->getType();
669 break;
670 } else if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
671 // Make sure the constant is used as pointer operand of the StoreInst.
672 if (SI->getPointerOperand() == SI->getOperand(U.OpndIdx)) {
673 MemUseValTy = SI->getValueOperand()->getType();
674 break;
675 }
676 }
677 }
678
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000679 // Check if the constant is in range of an add with immediate.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000680 APInt Diff = CC->ConstInt->getValue() - MinValItr->ConstInt->getValue();
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000681 if ((Diff.getBitWidth() <= 64) &&
Zhaoshi Zheng35818e22018-08-28 23:00:59 +0000682 TTI->isLegalAddImmediate(Diff.getSExtValue()) &&
683 // Check if Diff can be used as offset in addressing mode of the user
684 // memory instruction.
685 (!MemUseValTy || TTI->isLegalAddressingMode(MemUseValTy,
686 /*BaseGV*/nullptr, /*BaseOffset*/Diff.getSExtValue(),
687 /*HasBaseReg*/true, /*Scale*/0)))
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000688 continue;
689 }
690 // We either have now a different constant type or the constant is not in
691 // range of an add with immediate anymore.
Zhaoshi Zhenga0aa41d2018-09-04 22:17:03 +0000692 findAndMakeBaseConstant(MinValItr, CC, ConstInfoVec);
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000693 // Start a new base constant search.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000694 MinValItr = CC;
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000695 }
696 // Finalize the last base constant search.
Zhaoshi Zhenga0aa41d2018-09-04 22:17:03 +0000697 findAndMakeBaseConstant(MinValItr, ConstCandVec.end(), ConstInfoVec);
Juergen Ributzka46357932014-03-20 20:17:13 +0000698}
699
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000700/// Updates the operand at Idx in instruction Inst with the result of
Juergen Ributzkae802d502014-03-22 01:49:27 +0000701/// instruction Mat. If the instruction is a PHI node then special
Simon Pilgrim7d18a702016-11-20 13:19:49 +0000702/// handling for duplicate values form the same incoming basic block is
Juergen Ributzkae802d502014-03-22 01:49:27 +0000703/// required.
704/// \return The update will always succeed, but the return value indicated if
705/// Mat was used for the update or not.
706static bool updateOperand(Instruction *Inst, unsigned Idx, Instruction *Mat) {
707 if (auto PHI = dyn_cast<PHINode>(Inst)) {
708 // Check if any previous operand of the PHI node has the same incoming basic
709 // block. This is a very odd case that happens when the incoming basic block
710 // has a switch statement. In this case use the same value as the previous
711 // operand(s), otherwise we will fail verification due to different values.
712 // The values are actually the same, but the variable names are different
713 // and the verifier doesn't like that.
714 BasicBlock *IncomingBB = PHI->getIncomingBlock(Idx);
715 for (unsigned i = 0; i < Idx; ++i) {
716 if (PHI->getIncomingBlock(i) == IncomingBB) {
717 Value *IncomingVal = PHI->getIncomingValue(i);
718 Inst->setOperand(Idx, IncomingVal);
719 return false;
720 }
721 }
722 }
723
724 Inst->setOperand(Idx, Mat);
725 return true;
726}
727
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000728/// Emit materialization code for all rebased constants and update their
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000729/// users.
Michael Kuperstein071d8302016-07-02 00:16:47 +0000730void ConstantHoistingPass::emitBaseConstants(Instruction *Base,
731 Constant *Offset,
Zhaoshi Zhenga0aa41d2018-09-04 22:17:03 +0000732 Type *Ty,
Michael Kuperstein071d8302016-07-02 00:16:47 +0000733 const ConstantUser &ConstUser) {
Juergen Ributzka5429c062014-03-21 06:04:36 +0000734 Instruction *Mat = Base;
Zhaoshi Zhenga0aa41d2018-09-04 22:17:03 +0000735
736 // The same offset can be dereferenced to different types in nested struct.
737 if (!Offset && Ty && Ty != Base->getType())
738 Offset = ConstantInt::get(Type::getInt32Ty(*Ctx), 0);
739
Juergen Ributzka5429c062014-03-21 06:04:36 +0000740 if (Offset) {
741 Instruction *InsertionPt = findMatInsertPt(ConstUser.Inst,
742 ConstUser.OpndIdx);
Zhaoshi Zhenga0aa41d2018-09-04 22:17:03 +0000743 if (Ty) {
744 // Constant being rebased is a ConstantExpr.
745 PointerType *Int8PtrTy = Type::getInt8PtrTy(*Ctx,
746 cast<PointerType>(Ty)->getAddressSpace());
747 Base = new BitCastInst(Base, Int8PtrTy, "base_bitcast", InsertionPt);
748 Mat = GetElementPtrInst::Create(Int8PtrTy->getElementType(), Base,
749 Offset, "mat_gep", InsertionPt);
750 Mat = new BitCastInst(Mat, Ty, "mat_bitcast", InsertionPt);
751 } else
752 // Constant being rebased is a ConstantInt.
753 Mat = BinaryOperator::Create(Instruction::Add, Base, Offset,
Juergen Ributzka5429c062014-03-21 06:04:36 +0000754 "const_mat", InsertionPt);
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000755
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000756 LLVM_DEBUG(dbgs() << "Materialize constant (" << *Base->getOperand(0)
757 << " + " << *Offset << ") in BB "
758 << Mat->getParent()->getName() << '\n'
759 << *Mat << '\n');
Juergen Ributzka5429c062014-03-21 06:04:36 +0000760 Mat->setDebugLoc(ConstUser.Inst->getDebugLoc());
761 }
762 Value *Opnd = ConstUser.Inst->getOperand(ConstUser.OpndIdx);
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000763
Juergen Ributzka5429c062014-03-21 06:04:36 +0000764 // Visit constant integer.
765 if (isa<ConstantInt>(Opnd)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000766 LLVM_DEBUG(dbgs() << "Update: " << *ConstUser.Inst << '\n');
Juergen Ributzkae802d502014-03-22 01:49:27 +0000767 if (!updateOperand(ConstUser.Inst, ConstUser.OpndIdx, Mat) && Offset)
768 Mat->eraseFromParent();
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000769 LLVM_DEBUG(dbgs() << "To : " << *ConstUser.Inst << '\n');
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000770 return;
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000771 }
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000772
Juergen Ributzka5429c062014-03-21 06:04:36 +0000773 // Visit cast instruction.
774 if (auto CastInst = dyn_cast<Instruction>(Opnd)) {
775 assert(CastInst->isCast() && "Expected an cast instruction!");
776 // Check if we already have visited this cast instruction before to avoid
777 // unnecessary cloning.
778 Instruction *&ClonedCastInst = ClonedCastMap[CastInst];
779 if (!ClonedCastInst) {
780 ClonedCastInst = CastInst->clone();
781 ClonedCastInst->setOperand(0, Mat);
782 ClonedCastInst->insertAfter(CastInst);
783 // Use the same debug location as the original cast instruction.
784 ClonedCastInst->setDebugLoc(CastInst->getDebugLoc());
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000785 LLVM_DEBUG(dbgs() << "Clone instruction: " << *CastInst << '\n'
786 << "To : " << *ClonedCastInst << '\n');
Juergen Ributzka46357932014-03-20 20:17:13 +0000787 }
Juergen Ributzka5429c062014-03-21 06:04:36 +0000788
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000789 LLVM_DEBUG(dbgs() << "Update: " << *ConstUser.Inst << '\n');
Juergen Ributzkae802d502014-03-22 01:49:27 +0000790 updateOperand(ConstUser.Inst, ConstUser.OpndIdx, ClonedCastInst);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000791 LLVM_DEBUG(dbgs() << "To : " << *ConstUser.Inst << '\n');
Juergen Ributzka5429c062014-03-21 06:04:36 +0000792 return;
Juergen Ributzka46357932014-03-20 20:17:13 +0000793 }
Juergen Ributzka5429c062014-03-21 06:04:36 +0000794
795 // Visit constant expression.
796 if (auto ConstExpr = dyn_cast<ConstantExpr>(Opnd)) {
Zhaoshi Zhenga0aa41d2018-09-04 22:17:03 +0000797 if (ConstExpr->isGEPWithNoNotionalOverIndexing()) {
798 // Operand is a ConstantGEP, replace it.
799 updateOperand(ConstUser.Inst, ConstUser.OpndIdx, Mat);
800 return;
801 }
802
803 // Aside from constant GEPs, only constant cast expressions are collected.
804 assert(ConstExpr->isCast() && "ConstExpr should be a cast");
Juergen Ributzka5429c062014-03-21 06:04:36 +0000805 Instruction *ConstExprInst = ConstExpr->getAsInstruction();
806 ConstExprInst->setOperand(0, Mat);
807 ConstExprInst->insertBefore(findMatInsertPt(ConstUser.Inst,
808 ConstUser.OpndIdx));
809
810 // Use the same debug location as the instruction we are about to update.
811 ConstExprInst->setDebugLoc(ConstUser.Inst->getDebugLoc());
812
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000813 LLVM_DEBUG(dbgs() << "Create instruction: " << *ConstExprInst << '\n'
814 << "From : " << *ConstExpr << '\n');
815 LLVM_DEBUG(dbgs() << "Update: " << *ConstUser.Inst << '\n');
Juergen Ributzkae802d502014-03-22 01:49:27 +0000816 if (!updateOperand(ConstUser.Inst, ConstUser.OpndIdx, ConstExprInst)) {
817 ConstExprInst->eraseFromParent();
818 if (Offset)
819 Mat->eraseFromParent();
820 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000821 LLVM_DEBUG(dbgs() << "To : " << *ConstUser.Inst << '\n');
Juergen Ributzka5429c062014-03-21 06:04:36 +0000822 return;
Juergen Ributzka4c8a0252014-02-08 00:20:45 +0000823 }
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000824}
825
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000826/// Hoist and hide the base constant behind a bitcast and emit
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000827/// materialization code for derived constants.
Zhaoshi Zhenga0aa41d2018-09-04 22:17:03 +0000828bool ConstantHoistingPass::emitBaseConstants(GlobalVariable *BaseGV) {
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000829 bool MadeChange = false;
Zhaoshi Zhenga0aa41d2018-09-04 22:17:03 +0000830 SmallVectorImpl<consthoist::ConstantInfo> &ConstInfoVec =
831 BaseGV ? ConstGEPInfoMap[BaseGV] : ConstIntInfoVec;
832 for (auto const &ConstInfo : ConstInfoVec) {
Wei Mi337d4d92017-04-21 15:50:16 +0000833 SmallPtrSet<Instruction *, 8> IPSet = findConstantInsertionPoint(ConstInfo);
Sanjay Patel6e32b462019-03-04 20:57:14 +0000834 // We can have an empty set if the function contains unreachable blocks.
835 if (IPSet.empty())
836 continue;
Wei Mi337d4d92017-04-21 15:50:16 +0000837
838 unsigned UsesNum = 0;
839 unsigned ReBasesNum = 0;
Zhaoshi Zheng95710332018-09-26 00:59:09 +0000840 unsigned NotRebasedNum = 0;
Wei Mi337d4d92017-04-21 15:50:16 +0000841 for (Instruction *IP : IPSet) {
Zhaoshi Zheng95710332018-09-26 00:59:09 +0000842 // First, collect constants depending on this IP of the base.
843 unsigned Uses = 0;
844 using RebasedUse = std::tuple<Constant *, Type *, ConstantUser>;
845 SmallVector<RebasedUse, 4> ToBeRebased;
846 for (auto const &RCI : ConstInfo.RebasedConstants) {
847 for (auto const &U : RCI.Uses) {
848 Uses++;
849 BasicBlock *OrigMatInsertBB =
850 findMatInsertPt(U.Inst, U.OpndIdx)->getParent();
851 // If Base constant is to be inserted in multiple places,
852 // generate rebase for U using the Base dominating U.
853 if (IPSet.size() == 1 ||
854 DT->dominates(IP->getParent(), OrigMatInsertBB))
855 ToBeRebased.push_back(RebasedUse(RCI.Offset, RCI.Ty, U));
856 }
857 }
858 UsesNum = Uses;
859
860 // If only few constants depend on this IP of base, skip rebasing,
861 // assuming the base and the rebased have the same materialization cost.
862 if (ToBeRebased.size() < MinNumOfDependentToRebase) {
863 NotRebasedNum += ToBeRebased.size();
864 continue;
865 }
866
867 // Emit an instance of the base at this IP.
Zhaoshi Zhenga0aa41d2018-09-04 22:17:03 +0000868 Instruction *Base = nullptr;
869 // Hoist and hide the base constant behind a bitcast.
870 if (ConstInfo.BaseExpr) {
871 assert(BaseGV && "A base constant expression must have an base GV");
872 Type *Ty = ConstInfo.BaseExpr->getType();
873 Base = new BitCastInst(ConstInfo.BaseExpr, Ty, "const", IP);
874 } else {
875 IntegerType *Ty = ConstInfo.BaseInt->getType();
876 Base = new BitCastInst(ConstInfo.BaseInt, Ty, "const", IP);
877 }
Paul Robinsonb46256b2017-11-09 20:01:31 +0000878
879 Base->setDebugLoc(IP->getDebugLoc());
880
Zhaoshi Zhenga0aa41d2018-09-04 22:17:03 +0000881 LLVM_DEBUG(dbgs() << "Hoist constant (" << *ConstInfo.BaseInt
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000882 << ") to BB " << IP->getParent()->getName() << '\n'
883 << *Base << '\n');
Wei Mi337d4d92017-04-21 15:50:16 +0000884
Zhaoshi Zheng95710332018-09-26 00:59:09 +0000885 // Emit materialization code for rebased constants depending on this IP.
886 for (auto const &R : ToBeRebased) {
887 Constant *Off = std::get<0>(R);
888 Type *Ty = std::get<1>(R);
889 ConstantUser U = std::get<2>(R);
890 emitBaseConstants(Base, Off, Ty, U);
891 ReBasesNum++;
892 // Use the same debug location as the last user of the constant.
893 Base->setDebugLoc(DILocation::getMergedLocation(
894 Base->getDebugLoc(), U.Inst->getDebugLoc()));
Wei Mi337d4d92017-04-21 15:50:16 +0000895 }
Wei Mi337d4d92017-04-21 15:50:16 +0000896 assert(!Base->use_empty() && "The use list is empty!?");
897 assert(isa<Instruction>(Base->user_back()) &&
898 "All uses should be instructions.");
Wei Mi337d4d92017-04-21 15:50:16 +0000899 }
900 (void)UsesNum;
901 (void)ReBasesNum;
Zhaoshi Zheng95710332018-09-26 00:59:09 +0000902 (void)NotRebasedNum;
Wei Mi337d4d92017-04-21 15:50:16 +0000903 // Expect all uses are rebased after rebase is done.
Zhaoshi Zheng95710332018-09-26 00:59:09 +0000904 assert(UsesNum == (ReBasesNum + NotRebasedNum) &&
905 "Not all uses are rebased");
Wei Mi337d4d92017-04-21 15:50:16 +0000906
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000907 NumConstantsHoisted++;
908
Wei Mi337d4d92017-04-21 15:50:16 +0000909 // Base constant is also included in ConstInfo.RebasedConstants, so
910 // deduct 1 from ConstInfo.RebasedConstants.size().
Zhaoshi Zhenga0aa41d2018-09-04 22:17:03 +0000911 NumConstantsRebased += ConstInfo.RebasedConstants.size() - 1;
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000912
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000913 MadeChange = true;
914 }
915 return MadeChange;
916}
917
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000918/// Check all cast instructions we made a copy of and remove them if they
Juergen Ributzka5429c062014-03-21 06:04:36 +0000919/// have no more users.
Michael Kuperstein071d8302016-07-02 00:16:47 +0000920void ConstantHoistingPass::deleteDeadCastInst() const {
Juergen Ributzka5429c062014-03-21 06:04:36 +0000921 for (auto const &I : ClonedCastMap)
922 if (I.first->use_empty())
Juergen Ributzkae4747522014-03-22 01:49:30 +0000923 I.first->eraseFromParent();
Juergen Ributzka5429c062014-03-21 06:04:36 +0000924}
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000925
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000926/// Optimize expensive integer constants in the given function.
Michael Kuperstein071d8302016-07-02 00:16:47 +0000927bool ConstantHoistingPass::runImpl(Function &Fn, TargetTransformInfo &TTI,
Wei Mi337d4d92017-04-21 15:50:16 +0000928 DominatorTree &DT, BlockFrequencyInfo *BFI,
Hiroshi Yamauchi09e539f2019-04-15 16:49:00 +0000929 BasicBlock &Entry, ProfileSummaryInfo *PSI) {
Michael Kuperstein071d8302016-07-02 00:16:47 +0000930 this->TTI = &TTI;
931 this->DT = &DT;
Wei Mi337d4d92017-04-21 15:50:16 +0000932 this->BFI = BFI;
Zhaoshi Zhenga0aa41d2018-09-04 22:17:03 +0000933 this->DL = &Fn.getParent()->getDataLayout();
934 this->Ctx = &Fn.getContext();
Fangrui Songf78650a2018-07-30 19:41:25 +0000935 this->Entry = &Entry;
Hiroshi Yamauchi09e539f2019-04-15 16:49:00 +0000936 this->PSI = PSI;
Juergen Ributzka46357932014-03-20 20:17:13 +0000937 // Collect all constant candidates.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000938 collectConstantCandidates(Fn);
Juergen Ributzka46357932014-03-20 20:17:13 +0000939
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000940 // Combine constants that can be easily materialized with an add from a common
941 // base constant.
Zhaoshi Zhenga0aa41d2018-09-04 22:17:03 +0000942 if (!ConstIntCandVec.empty())
943 findBaseConstants(nullptr);
944 for (auto &MapEntry : ConstGEPCandMap)
945 if (!MapEntry.second.empty())
946 findBaseConstants(MapEntry.first);
Juergen Ributzka5429c062014-03-21 06:04:36 +0000947
Juergen Ributzkaf0dff492014-03-21 06:04:45 +0000948 // Finally hoist the base constant and emit materialization code for dependent
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000949 // constants.
Zhaoshi Zhenga0aa41d2018-09-04 22:17:03 +0000950 bool MadeChange = false;
951 if (!ConstIntInfoVec.empty())
952 MadeChange = emitBaseConstants(nullptr);
953 for (auto MapEntry : ConstGEPInfoMap)
954 if (!MapEntry.second.empty())
955 MadeChange |= emitBaseConstants(MapEntry.first);
956
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000957
Juergen Ributzka5429c062014-03-21 06:04:36 +0000958 // Cleanup dead instructions.
959 deleteDeadCastInst();
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000960
Fangrui Songf4b25f72019-03-01 05:27:01 +0000961 cleanup();
962
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000963 return MadeChange;
964}
Michael Kuperstein071d8302016-07-02 00:16:47 +0000965
966PreservedAnalyses ConstantHoistingPass::run(Function &F,
967 FunctionAnalysisManager &AM) {
968 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
969 auto &TTI = AM.getResult<TargetIRAnalysis>(F);
Wei Mi337d4d92017-04-21 15:50:16 +0000970 auto BFI = ConstHoistWithBlockFrequency
971 ? &AM.getResult<BlockFrequencyAnalysis>(F)
972 : nullptr;
Hiroshi Yamauchi09e539f2019-04-15 16:49:00 +0000973 auto &MAM = AM.getResult<ModuleAnalysisManagerFunctionProxy>(F).getManager();
974 auto *PSI = MAM.getCachedResult<ProfileSummaryAnalysis>(*F.getParent());
975 if (!runImpl(F, TTI, DT, BFI, F.getEntryBlock(), PSI))
Michael Kuperstein071d8302016-07-02 00:16:47 +0000976 return PreservedAnalyses::all();
977
Chandler Carruthca68a3e2017-01-15 06:32:49 +0000978 PreservedAnalyses PA;
979 PA.preserveSet<CFGAnalyses>();
980 return PA;
Michael Kuperstein071d8302016-07-02 00:16:47 +0000981}