blob: beac0d967a980609e9d3c28bfe1f1d2dbcde1c2d [file] [log] [blame]
Juergen Ributzkaf26beda2014-01-25 02:02:55 +00001//===- ConstantHoisting.cpp - Prepare code for expensive constants --------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This pass identifies expensive constants to hoist and coalesces them to
11// better prepare it for SelectionDAG-based code generation. This works around
12// the limitations of the basic-block-at-a-time approach.
13//
14// First it scans all instructions for integer constants and calculates its
15// cost. If the constant can be folded into the instruction (the cost is
16// TCC_Free) or the cost is just a simple operation (TCC_BASIC), then we don't
17// consider it expensive and leave it alone. This is the default behavior and
18// the default implementation of getIntImmCost will always return TCC_Free.
19//
20// If the cost is more than TCC_BASIC, then the integer constant can't be folded
21// into the instruction and it might be beneficial to hoist the constant.
22// Similar constants are coalesced to reduce register pressure and
23// materialization code.
24//
25// When a constant is hoisted, it is also hidden behind a bitcast to force it to
26// be live-out of the basic block. Otherwise the constant would be just
27// duplicated and each basic block would have its own copy in the SelectionDAG.
28// The SelectionDAG recognizes such constants as opaque and doesn't perform
29// certain transformations on them, which would create a new expensive constant.
30//
31// This optimization is only applied to integer constants in instructions and
Juergen Ributzkaf0dff492014-03-21 06:04:45 +000032// simple (this means not nested) constant cast expressions. For example:
Juergen Ributzkaf26beda2014-01-25 02:02:55 +000033// %0 = load i64* inttoptr (i64 big_constant to i64*)
34//===----------------------------------------------------------------------===//
35
Michael Kuperstein071d8302016-07-02 00:16:47 +000036#include "llvm/Transforms/Scalar/ConstantHoisting.h"
Eugene Zelenko8002c502017-09-13 21:43:53 +000037#include "llvm/ADT/APInt.h"
38#include "llvm/ADT/DenseMap.h"
39#include "llvm/ADT/None.h"
40#include "llvm/ADT/Optional.h"
41#include "llvm/ADT/SmallPtrSet.h"
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +000042#include "llvm/ADT/SmallVector.h"
Juergen Ributzkaf26beda2014-01-25 02:02:55 +000043#include "llvm/ADT/Statistic.h"
Eugene Zelenko8002c502017-09-13 21:43:53 +000044#include "llvm/Analysis/BlockFrequencyInfo.h"
45#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"
Eugene Zelenko8002c502017-09-13 21:43:53 +000064#include <algorithm>
65#include <cassert>
66#include <cstdint>
67#include <iterator>
NAKAMURA Takumi99aa6e12014-04-30 06:44:50 +000068#include <tuple>
Eugene Zelenko8002c502017-09-13 21:43:53 +000069#include <utility>
Juergen Ributzkaf26beda2014-01-25 02:02:55 +000070
71using namespace llvm;
Michael Kuperstein071d8302016-07-02 00:16:47 +000072using namespace consthoist;
Juergen Ributzkaf26beda2014-01-25 02:02:55 +000073
Chandler Carruth964daaa2014-04-22 02:55:47 +000074#define DEBUG_TYPE "consthoist"
75
Juergen Ributzkaf26beda2014-01-25 02:02:55 +000076STATISTIC(NumConstantsHoisted, "Number of constants hoisted");
77STATISTIC(NumConstantsRebased, "Number of constants rebased");
78
Wei Mi337d4d92017-04-21 15:50:16 +000079static cl::opt<bool> ConstHoistWithBlockFrequency(
Wei Mi75867552017-07-07 00:11:05 +000080 "consthoist-with-block-frequency", cl::init(true), cl::Hidden,
Wei Mi337d4d92017-04-21 15:50:16 +000081 cl::desc("Enable the use of the block frequency analysis to reduce the "
82 "chance to execute const materialization more frequently than "
83 "without hoisting."));
84
Zhaoshi Zhenga0aa41d2018-09-04 22:17:03 +000085static cl::opt<bool> ConstHoistGEP(
86 "consthoist-gep", cl::init(false), cl::Hidden,
87 cl::desc("Try hoisting constant gep expressions"));
88
Zhaoshi Zheng95710332018-09-26 00:59:09 +000089static cl::opt<unsigned>
90MinNumOfDependentToRebase("consthoist-min-num-to-rebase",
91 cl::desc("Do not rebase if number of dependent constants of a Base is less "
92 "than this number."),
93 cl::init(0), cl::Hidden);
94
Juergen Ributzkaf26beda2014-01-25 02:02:55 +000095namespace {
Eugene Zelenko8002c502017-09-13 21:43:53 +000096
Adrian Prantl5f8f34e42018-05-01 15:54:18 +000097/// The constant hoisting pass.
Michael Kuperstein071d8302016-07-02 00:16:47 +000098class ConstantHoistingLegacyPass : public FunctionPass {
Juergen Ributzkaf26beda2014-01-25 02:02:55 +000099public:
100 static char ID; // Pass identification, replacement for typeid
Eugene Zelenko8002c502017-09-13 21:43:53 +0000101
Michael Kuperstein071d8302016-07-02 00:16:47 +0000102 ConstantHoistingLegacyPass() : FunctionPass(ID) {
103 initializeConstantHoistingLegacyPassPass(*PassRegistry::getPassRegistry());
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000104 }
105
Juergen Ributzka5429c062014-03-21 06:04:36 +0000106 bool runOnFunction(Function &Fn) override;
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000107
Mehdi Amini117296c2016-10-01 02:56:57 +0000108 StringRef getPassName() const override { return "Constant Hoisting"; }
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000109
Craig Topper3e4c6972014-03-05 09:10:37 +0000110 void getAnalysisUsage(AnalysisUsage &AU) const override {
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000111 AU.setPreservesCFG();
Wei Mi337d4d92017-04-21 15:50:16 +0000112 if (ConstHoistWithBlockFrequency)
113 AU.addRequired<BlockFrequencyInfoWrapperPass>();
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000114 AU.addRequired<DominatorTreeWrapperPass>();
Chandler Carruth705b1852015-01-31 03:43:40 +0000115 AU.addRequired<TargetTransformInfoWrapperPass>();
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000116 }
117
Michael Kuperstein071d8302016-07-02 00:16:47 +0000118 void releaseMemory() override { Impl.releaseMemory(); }
119
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000120private:
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)
Chandler Carruth705b1852015-01-31 03:43:40 +0000132INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
Michael Kuperstein071d8302016-07-02 00:16:47 +0000133INITIALIZE_PASS_END(ConstantHoistingLegacyPass, "consthoist",
134 "Constant Hoisting", false, false)
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000135
136FunctionPass *llvm::createConstantHoistingPass() {
Michael Kuperstein071d8302016-07-02 00:16:47 +0000137 return new ConstantHoistingLegacyPass();
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000138}
139
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000140/// Perform the constant hoisting optimization for the given function.
Michael Kuperstein071d8302016-07-02 00:16:47 +0000141bool ConstantHoistingLegacyPass::runOnFunction(Function &Fn) {
Andrew Kayloraa641a52016-04-22 22:06:11 +0000142 if (skipFunction(Fn))
Andrea Di Biagiof54432382015-02-14 15:11:48 +0000143 return false;
144
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000145 LLVM_DEBUG(dbgs() << "********** Begin Constant Hoisting **********\n");
146 LLVM_DEBUG(dbgs() << "********** Function: " << Fn.getName() << '\n');
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000147
Wei Mi337d4d92017-04-21 15:50:16 +0000148 bool MadeChange =
149 Impl.runImpl(Fn, getAnalysis<TargetTransformInfoWrapperPass>().getTTI(Fn),
150 getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
151 ConstHoistWithBlockFrequency
152 ? &getAnalysis<BlockFrequencyInfoWrapperPass>().getBFI()
153 : nullptr,
154 Fn.getEntryBlock());
Juergen Ributzka5429c062014-03-21 06:04:36 +0000155
156 if (MadeChange) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000157 LLVM_DEBUG(dbgs() << "********** Function after Constant Hoisting: "
158 << Fn.getName() << '\n');
159 LLVM_DEBUG(dbgs() << Fn);
Juergen Ributzka5429c062014-03-21 06:04:36 +0000160 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000161 LLVM_DEBUG(dbgs() << "********** End Constant Hoisting **********\n");
Juergen Ributzka5429c062014-03-21 06:04:36 +0000162
Juergen Ributzka5429c062014-03-21 06:04:36 +0000163 return MadeChange;
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000164}
165
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000166/// Find the constant materialization insertion point.
Michael Kuperstein071d8302016-07-02 00:16:47 +0000167Instruction *ConstantHoistingPass::findMatInsertPt(Instruction *Inst,
168 unsigned Idx) const {
Juergen Ributzka575bcb72014-04-22 18:06:58 +0000169 // If the operand is a cast instruction, then we have to materialize the
170 // constant before the cast instruction.
171 if (Idx != ~0U) {
172 Value *Opnd = Inst->getOperand(Idx);
173 if (auto CastInst = dyn_cast<Instruction>(Opnd))
174 if (CastInst->isCast())
175 return CastInst;
176 }
177
178 // The simple and common case. This also includes constant expressions.
David Majnemerba275f92015-08-19 19:54:02 +0000179 if (!isa<PHINode>(Inst) && !Inst->isEHPad())
Juergen Ributzka5429c062014-03-21 06:04:36 +0000180 return Inst;
181
David Majnemerba275f92015-08-19 19:54:02 +0000182 // We can't insert directly before a phi node or an eh pad. Insert before
Juergen Ributzka5429c062014-03-21 06:04:36 +0000183 // the terminator of the incoming or dominating block.
184 assert(Entry != Inst->getParent() && "PHI or landing pad in entry block!");
185 if (Idx != ~0U && isa<PHINode>(Inst))
186 return cast<PHINode>(Inst)->getIncomingBlock(Idx)->getTerminator();
187
Reid Klecknerd80b69f2017-03-01 22:41:12 +0000188 // This must be an EH pad. Iterate over immediate dominators until we find a
189 // non-EH pad. We need to skip over catchswitch blocks, which are both EH pads
190 // and terminators.
191 auto IDom = DT->getNode(Inst->getParent())->getIDom();
192 while (IDom->getBlock()->isEHPad()) {
193 assert(Entry != IDom->getBlock() && "eh pad in entry block");
194 IDom = IDom->getIDom();
195 }
196
197 return IDom->getBlock()->getTerminator();
Juergen Ributzka5429c062014-03-21 06:04:36 +0000198}
199
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000200/// Given \p BBs as input, find another set of BBs which collectively
Wei Mi337d4d92017-04-21 15:50:16 +0000201/// dominates \p BBs and have the minimal sum of frequencies. Return the BB
202/// set found in \p BBs.
Benjamin Kramerdebb3c32017-05-26 20:09:00 +0000203static void findBestInsertionSet(DominatorTree &DT, BlockFrequencyInfo &BFI,
204 BasicBlock *Entry,
205 SmallPtrSet<BasicBlock *, 8> &BBs) {
Wei Mi337d4d92017-04-21 15:50:16 +0000206 assert(!BBs.count(Entry) && "Assume Entry is not in BBs");
207 // Nodes on the current path to the root.
208 SmallPtrSet<BasicBlock *, 8> Path;
209 // Candidates includes any block 'BB' in set 'BBs' that is not strictly
210 // dominated by any other blocks in set 'BBs', and all nodes in the path
211 // in the dominator tree from Entry to 'BB'.
212 SmallPtrSet<BasicBlock *, 16> Candidates;
213 for (auto BB : BBs) {
214 Path.clear();
215 // Walk up the dominator tree until Entry or another BB in BBs
216 // is reached. Insert the nodes on the way to the Path.
217 BasicBlock *Node = BB;
218 // The "Path" is a candidate path to be added into Candidates set.
219 bool isCandidate = false;
220 do {
221 Path.insert(Node);
222 if (Node == Entry || Candidates.count(Node)) {
223 isCandidate = true;
224 break;
225 }
226 assert(DT.getNode(Node)->getIDom() &&
227 "Entry doens't dominate current Node");
228 Node = DT.getNode(Node)->getIDom()->getBlock();
229 } while (!BBs.count(Node));
230
231 // If isCandidate is false, Node is another Block in BBs dominating
232 // current 'BB'. Drop the nodes on the Path.
233 if (!isCandidate)
234 continue;
235
236 // Add nodes on the Path into Candidates.
237 Candidates.insert(Path.begin(), Path.end());
238 }
239
240 // Sort the nodes in Candidates in top-down order and save the nodes
241 // in Orders.
242 unsigned Idx = 0;
243 SmallVector<BasicBlock *, 16> Orders;
244 Orders.push_back(Entry);
245 while (Idx != Orders.size()) {
246 BasicBlock *Node = Orders[Idx++];
247 for (auto ChildDomNode : DT.getNode(Node)->getChildren()) {
248 if (Candidates.count(ChildDomNode->getBlock()))
249 Orders.push_back(ChildDomNode->getBlock());
250 }
251 }
252
253 // Visit Orders in bottom-up order.
Eugene Zelenko8002c502017-09-13 21:43:53 +0000254 using InsertPtsCostPair =
255 std::pair<SmallPtrSet<BasicBlock *, 16>, BlockFrequency>;
256
Wei Mi337d4d92017-04-21 15:50:16 +0000257 // InsertPtsMap is a map from a BB to the best insertion points for the
258 // subtree of BB (subtree not including the BB itself).
259 DenseMap<BasicBlock *, InsertPtsCostPair> InsertPtsMap;
260 InsertPtsMap.reserve(Orders.size() + 1);
261 for (auto RIt = Orders.rbegin(); RIt != Orders.rend(); RIt++) {
262 BasicBlock *Node = *RIt;
263 bool NodeInBBs = BBs.count(Node);
264 SmallPtrSet<BasicBlock *, 16> &InsertPts = InsertPtsMap[Node].first;
265 BlockFrequency &InsertPtsFreq = InsertPtsMap[Node].second;
266
267 // Return the optimal insert points in BBs.
268 if (Node == Entry) {
269 BBs.clear();
Wei Mi20526b22017-07-06 22:32:27 +0000270 if (InsertPtsFreq > BFI.getBlockFreq(Node) ||
271 (InsertPtsFreq == BFI.getBlockFreq(Node) && InsertPts.size() > 1))
Wei Mi337d4d92017-04-21 15:50:16 +0000272 BBs.insert(Entry);
273 else
274 BBs.insert(InsertPts.begin(), InsertPts.end());
275 break;
276 }
277
278 BasicBlock *Parent = DT.getNode(Node)->getIDom()->getBlock();
279 // Initially, ParentInsertPts is empty and ParentPtsFreq is 0. Every child
280 // will update its parent's ParentInsertPts and ParentPtsFreq.
281 SmallPtrSet<BasicBlock *, 16> &ParentInsertPts = InsertPtsMap[Parent].first;
282 BlockFrequency &ParentPtsFreq = InsertPtsMap[Parent].second;
283 // Choose to insert in Node or in subtree of Node.
Wei Mi20526b22017-07-06 22:32:27 +0000284 // Don't hoist to EHPad because we may not find a proper place to insert
285 // in EHPad.
286 // If the total frequency of InsertPts is the same as the frequency of the
287 // target Node, and InsertPts contains more than one nodes, choose hoisting
288 // to reduce code size.
289 if (NodeInBBs ||
290 (!Node->isEHPad() &&
291 (InsertPtsFreq > BFI.getBlockFreq(Node) ||
292 (InsertPtsFreq == BFI.getBlockFreq(Node) && InsertPts.size() > 1)))) {
Wei Mi337d4d92017-04-21 15:50:16 +0000293 ParentInsertPts.insert(Node);
294 ParentPtsFreq += BFI.getBlockFreq(Node);
295 } else {
296 ParentInsertPts.insert(InsertPts.begin(), InsertPts.end());
297 ParentPtsFreq += InsertPtsFreq;
298 }
299 }
300}
301
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000302/// Find an insertion point that dominates all uses.
Wei Mi337d4d92017-04-21 15:50:16 +0000303SmallPtrSet<Instruction *, 8> ConstantHoistingPass::findConstantInsertionPoint(
Michael Kuperstein071d8302016-07-02 00:16:47 +0000304 const ConstantInfo &ConstInfo) const {
Juergen Ributzka5429c062014-03-21 06:04:36 +0000305 assert(!ConstInfo.RebasedConstants.empty() && "Invalid constant info entry.");
Juergen Ributzkac81000b2014-04-03 01:38:47 +0000306 // Collect all basic blocks.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000307 SmallPtrSet<BasicBlock *, 8> BBs;
Wei Mi337d4d92017-04-21 15:50:16 +0000308 SmallPtrSet<Instruction *, 8> InsertPts;
Juergen Ributzka5429c062014-03-21 06:04:36 +0000309 for (auto const &RCI : ConstInfo.RebasedConstants)
Juergen Ributzkac81000b2014-04-03 01:38:47 +0000310 for (auto const &U : RCI.Uses)
Juergen Ributzka575bcb72014-04-22 18:06:58 +0000311 BBs.insert(findMatInsertPt(U.Inst, U.OpndIdx)->getParent());
Juergen Ributzka5429c062014-03-21 06:04:36 +0000312
Wei Mi337d4d92017-04-21 15:50:16 +0000313 if (BBs.count(Entry)) {
314 InsertPts.insert(&Entry->front());
315 return InsertPts;
316 }
317
318 if (BFI) {
319 findBestInsertionSet(*DT, *BFI, Entry, BBs);
320 for (auto BB : BBs) {
321 BasicBlock::iterator InsertPt = BB->begin();
322 for (; isa<PHINode>(InsertPt) || InsertPt->isEHPad(); ++InsertPt)
323 ;
324 InsertPts.insert(&*InsertPt);
325 }
326 return InsertPts;
327 }
Juergen Ributzka5429c062014-03-21 06:04:36 +0000328
329 while (BBs.size() >= 2) {
330 BasicBlock *BB, *BB1, *BB2;
331 BB1 = *BBs.begin();
332 BB2 = *std::next(BBs.begin());
333 BB = DT->findNearestCommonDominator(BB1, BB2);
Wei Mi337d4d92017-04-21 15:50:16 +0000334 if (BB == Entry) {
335 InsertPts.insert(&Entry->front());
336 return InsertPts;
337 }
Juergen Ributzka5429c062014-03-21 06:04:36 +0000338 BBs.erase(BB1);
339 BBs.erase(BB2);
340 BBs.insert(BB);
341 }
342 assert((BBs.size() == 1) && "Expected only one element.");
343 Instruction &FirstInst = (*BBs.begin())->front();
Wei Mi337d4d92017-04-21 15:50:16 +0000344 InsertPts.insert(findMatInsertPt(&FirstInst));
345 return InsertPts;
Juergen Ributzka5429c062014-03-21 06:04:36 +0000346}
347
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000348/// Record constant integer ConstInt for instruction Inst at operand
Juergen Ributzka5429c062014-03-21 06:04:36 +0000349/// index Idx.
350///
Juergen Ributzkaf0dff492014-03-21 06:04:45 +0000351/// The operand at index Idx is not necessarily the constant integer itself. It
Juergen Ributzka5429c062014-03-21 06:04:36 +0000352/// could also be a cast instruction or a constant expression that uses the
Zhaoshi Zhenga0aa41d2018-09-04 22:17:03 +0000353/// constant integer.
Michael Kuperstein071d8302016-07-02 00:16:47 +0000354void ConstantHoistingPass::collectConstantCandidates(
355 ConstCandMapType &ConstCandMap, Instruction *Inst, unsigned Idx,
356 ConstantInt *ConstInt) {
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000357 unsigned Cost;
Juergen Ributzka5429c062014-03-21 06:04:36 +0000358 // Ask the target about the cost of materializing the constant for the given
Juergen Ributzkaf0dff492014-03-21 06:04:45 +0000359 // instruction and operand index.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000360 if (auto IntrInst = dyn_cast<IntrinsicInst>(Inst))
Juergen Ributzkaf0dff492014-03-21 06:04:45 +0000361 Cost = TTI->getIntImmCost(IntrInst->getIntrinsicID(), Idx,
Juergen Ributzka5429c062014-03-21 06:04:36 +0000362 ConstInt->getValue(), ConstInt->getType());
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000363 else
Juergen Ributzkaf0dff492014-03-21 06:04:45 +0000364 Cost = TTI->getIntImmCost(Inst->getOpcode(), Idx, ConstInt->getValue(),
Juergen Ributzka5429c062014-03-21 06:04:36 +0000365 ConstInt->getType());
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000366
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +0000367 // Ignore cheap integer constants.
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000368 if (Cost > TargetTransformInfo::TCC_Basic) {
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +0000369 ConstCandMapType::iterator Itr;
370 bool Inserted;
Zhaoshi Zhenga0aa41d2018-09-04 22:17:03 +0000371 ConstPtrUnionType Cand = ConstInt;
372 std::tie(Itr, Inserted) = ConstCandMap.insert(std::make_pair(Cand, 0));
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +0000373 if (Inserted) {
Zhaoshi Zhenga0aa41d2018-09-04 22:17:03 +0000374 ConstIntCandVec.push_back(ConstantCandidate(ConstInt));
375 Itr->second = ConstIntCandVec.size() - 1;
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +0000376 }
Zhaoshi Zhenga0aa41d2018-09-04 22:17:03 +0000377 ConstIntCandVec[Itr->second].addUser(Inst, Idx, Cost);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000378 LLVM_DEBUG(if (isa<ConstantInt>(Inst->getOperand(Idx))) dbgs()
379 << "Collect constant " << *ConstInt << " from " << *Inst
Juergen Ributzka5429c062014-03-21 06:04:36 +0000380 << " with cost " << Cost << '\n';
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000381 else dbgs() << "Collect constant " << *ConstInt
382 << " indirectly from " << *Inst << " via "
383 << *Inst->getOperand(Idx) << " with cost " << Cost
384 << '\n';);
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000385 }
386}
387
Zhaoshi Zhenga0aa41d2018-09-04 22:17:03 +0000388/// Record constant GEP expression for instruction Inst at operand index Idx.
389void ConstantHoistingPass::collectConstantCandidates(
390 ConstCandMapType &ConstCandMap, Instruction *Inst, unsigned Idx,
391 ConstantExpr *ConstExpr) {
392 // TODO: Handle vector GEPs
393 if (ConstExpr->getType()->isVectorTy())
394 return;
395
396 GlobalVariable *BaseGV = dyn_cast<GlobalVariable>(ConstExpr->getOperand(0));
397 if (!BaseGV)
398 return;
399
400 // Get offset from the base GV.
401 PointerType *GVPtrTy = dyn_cast<PointerType>(BaseGV->getType());
402 IntegerType *PtrIntTy = DL->getIntPtrType(*Ctx, GVPtrTy->getAddressSpace());
403 APInt Offset(DL->getTypeSizeInBits(PtrIntTy), /*val*/0, /*isSigned*/true);
404 auto *GEPO = cast<GEPOperator>(ConstExpr);
405 if (!GEPO->accumulateConstantOffset(*DL, Offset))
406 return;
407
408 if (!Offset.isIntN(32))
409 return;
410
411 // A constant GEP expression that has a GlobalVariable as base pointer is
412 // usually lowered to a load from constant pool. Such operation is unlikely
413 // to be cheaper than compute it by <Base + Offset>, which can be lowered to
414 // an ADD instruction or folded into Load/Store instruction.
415 int Cost = TTI->getIntImmCost(Instruction::Add, 1, Offset, PtrIntTy);
416 ConstCandVecType &ExprCandVec = ConstGEPCandMap[BaseGV];
417 ConstCandMapType::iterator Itr;
418 bool Inserted;
419 ConstPtrUnionType Cand = ConstExpr;
420 std::tie(Itr, Inserted) = ConstCandMap.insert(std::make_pair(Cand, 0));
421 if (Inserted) {
422 ExprCandVec.push_back(ConstantCandidate(
423 ConstantInt::get(Type::getInt32Ty(*Ctx), Offset.getLimitedValue()),
424 ConstExpr));
425 Itr->second = ExprCandVec.size() - 1;
426 }
427 ExprCandVec[Itr->second].addUser(Inst, Idx, Cost);
428}
429
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000430/// Check the operand for instruction Inst at index Idx.
Leo Li20fbad92017-06-29 17:03:34 +0000431void ConstantHoistingPass::collectConstantCandidates(
432 ConstCandMapType &ConstCandMap, Instruction *Inst, unsigned Idx) {
433 Value *Opnd = Inst->getOperand(Idx);
434
435 // Visit constant integers.
436 if (auto ConstInt = dyn_cast<ConstantInt>(Opnd)) {
437 collectConstantCandidates(ConstCandMap, Inst, Idx, ConstInt);
438 return;
439 }
440
441 // Visit cast instructions that have constant integers.
442 if (auto CastInst = dyn_cast<Instruction>(Opnd)) {
443 // Only visit cast instructions, which have been skipped. All other
444 // instructions should have already been visited.
445 if (!CastInst->isCast())
446 return;
447
448 if (auto *ConstInt = dyn_cast<ConstantInt>(CastInst->getOperand(0))) {
449 // Pretend the constant is directly used by the instruction and ignore
450 // the cast instruction.
451 collectConstantCandidates(ConstCandMap, Inst, Idx, ConstInt);
452 return;
453 }
454 }
455
456 // Visit constant expressions that have constant integers.
457 if (auto ConstExpr = dyn_cast<ConstantExpr>(Opnd)) {
Zhaoshi Zhenga0aa41d2018-09-04 22:17:03 +0000458 // Handle constant gep expressions.
459 if (ConstHoistGEP && ConstExpr->isGEPWithNoNotionalOverIndexing())
460 collectConstantCandidates(ConstCandMap, Inst, Idx, ConstExpr);
461
Leo Li20fbad92017-06-29 17:03:34 +0000462 // Only visit constant cast expressions.
463 if (!ConstExpr->isCast())
464 return;
465
466 if (auto ConstInt = dyn_cast<ConstantInt>(ConstExpr->getOperand(0))) {
467 // Pretend the constant is directly used by the instruction and ignore
468 // the constant expression.
469 collectConstantCandidates(ConstCandMap, Inst, Idx, ConstInt);
470 return;
471 }
472 }
473}
474
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000475/// Scan the instruction for expensive integer constants and record them
Juergen Ributzka5429c062014-03-21 06:04:36 +0000476/// in the constant candidate vector.
Michael Kuperstein071d8302016-07-02 00:16:47 +0000477void ConstantHoistingPass::collectConstantCandidates(
478 ConstCandMapType &ConstCandMap, Instruction *Inst) {
Juergen Ributzka5429c062014-03-21 06:04:36 +0000479 // Skip all cast instructions. They are visited indirectly later on.
480 if (Inst->isCast())
481 return;
482
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000483 // Scan all operands.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000484 for (unsigned Idx = 0, E = Inst->getNumOperands(); Idx != E; ++Idx) {
Leo Li93abd7d2017-07-10 20:45:34 +0000485 // The cost of materializing the constants (defined in
486 // `TargetTransformInfo::getIntImmCost`) for instructions which only take
487 // constant variables is lower than `TargetTransformInfo::TCC_Basic`. So
488 // it's safe for us to collect constant candidates from all IntrinsicInsts.
489 if (canReplaceOperandWithVariable(Inst, Idx) || isa<IntrinsicInst>(Inst)) {
490 collectConstantCandidates(ConstCandMap, Inst, Idx);
491 }
Juergen Ributzka5429c062014-03-21 06:04:36 +0000492 } // end of for all operands
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000493}
494
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000495/// Collect all integer constants in the function that cannot be folded
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000496/// into an instruction itself.
Michael Kuperstein071d8302016-07-02 00:16:47 +0000497void ConstantHoistingPass::collectConstantCandidates(Function &Fn) {
Juergen Ributzka7be410f2014-03-25 21:21:10 +0000498 ConstCandMapType ConstCandMap;
Duncan P. N. Exon Smith3a9c9e32015-10-13 18:26:00 +0000499 for (BasicBlock &BB : Fn)
500 for (Instruction &Inst : BB)
501 collectConstantCandidates(ConstCandMap, &Inst);
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000502}
503
Sjoerd Meijer38c2cd02016-07-14 07:44:20 +0000504// This helper function is necessary to deal with values that have different
505// bit widths (APInt Operator- does not like that). If the value cannot be
506// represented in uint64 we return an "empty" APInt. This is then interpreted
507// as the value is not in range.
Eugene Zelenko8002c502017-09-13 21:43:53 +0000508static Optional<APInt> calculateOffsetDiff(const APInt &V1, const APInt &V2) {
509 Optional<APInt> Res = None;
Sjoerd Meijer38c2cd02016-07-14 07:44:20 +0000510 unsigned BW = V1.getBitWidth() > V2.getBitWidth() ?
511 V1.getBitWidth() : V2.getBitWidth();
512 uint64_t LimVal1 = V1.getLimitedValue();
513 uint64_t LimVal2 = V2.getLimitedValue();
514
515 if (LimVal1 == ~0ULL || LimVal2 == ~0ULL)
516 return Res;
517
518 uint64_t Diff = LimVal1 - LimVal2;
519 return APInt(BW, Diff, true);
520}
521
522// From a list of constants, one needs to picked as the base and the other
523// constants will be transformed into an offset from that base constant. The
524// question is which we can pick best? For example, consider these constants
525// and their number of uses:
526//
527// Constants| 2 | 4 | 12 | 42 |
528// NumUses | 3 | 2 | 8 | 7 |
529//
530// Selecting constant 12 because it has the most uses will generate negative
531// offsets for constants 2 and 4 (i.e. -10 and -8 respectively). If negative
532// offsets lead to less optimal code generation, then there might be better
533// solutions. Suppose immediates in the range of 0..35 are most optimally
534// supported by the architecture, then selecting constant 2 is most optimal
535// because this will generate offsets: 0, 2, 10, 40. Offsets 0, 2 and 10 are in
536// range 0..35, and thus 3 + 2 + 8 = 13 uses are in range. Selecting 12 would
537// have only 8 uses in range, so choosing 2 as a base is more optimal. Thus, in
538// selecting the base constant the range of the offsets is a very important
539// factor too that we take into account here. This algorithm calculates a total
540// costs for selecting a constant as the base and substract the costs if
541// immediates are out of range. It has quadratic complexity, so we call this
542// function only when we're optimising for size and there are less than 100
543// constants, we fall back to the straightforward algorithm otherwise
544// which does not do all the offset calculations.
545unsigned
546ConstantHoistingPass::maximizeConstantsInRange(ConstCandVecType::iterator S,
547 ConstCandVecType::iterator E,
548 ConstCandVecType::iterator &MaxCostItr) {
549 unsigned NumUses = 0;
550
551 if(!Entry->getParent()->optForSize() || std::distance(S,E) > 100) {
552 for (auto ConstCand = S; ConstCand != E; ++ConstCand) {
553 NumUses += ConstCand->Uses.size();
554 if (ConstCand->CumulativeCost > MaxCostItr->CumulativeCost)
555 MaxCostItr = ConstCand;
556 }
557 return NumUses;
558 }
559
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000560 LLVM_DEBUG(dbgs() << "== Maximize constants in range ==\n");
Sjoerd Meijer38c2cd02016-07-14 07:44:20 +0000561 int MaxCost = -1;
562 for (auto ConstCand = S; ConstCand != E; ++ConstCand) {
563 auto Value = ConstCand->ConstInt->getValue();
564 Type *Ty = ConstCand->ConstInt->getType();
565 int Cost = 0;
566 NumUses += ConstCand->Uses.size();
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000567 LLVM_DEBUG(dbgs() << "= Constant: " << ConstCand->ConstInt->getValue()
568 << "\n");
Sjoerd Meijer38c2cd02016-07-14 07:44:20 +0000569
570 for (auto User : ConstCand->Uses) {
571 unsigned Opcode = User.Inst->getOpcode();
572 unsigned OpndIdx = User.OpndIdx;
573 Cost += TTI->getIntImmCost(Opcode, OpndIdx, Value, Ty);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000574 LLVM_DEBUG(dbgs() << "Cost: " << Cost << "\n");
Sjoerd Meijer38c2cd02016-07-14 07:44:20 +0000575
576 for (auto C2 = S; C2 != E; ++C2) {
Eugene Zelenko8002c502017-09-13 21:43:53 +0000577 Optional<APInt> Diff = calculateOffsetDiff(
578 C2->ConstInt->getValue(),
579 ConstCand->ConstInt->getValue());
Sjoerd Meijer38c2cd02016-07-14 07:44:20 +0000580 if (Diff) {
581 const int ImmCosts =
582 TTI->getIntImmCodeSizeCost(Opcode, OpndIdx, Diff.getValue(), Ty);
583 Cost -= ImmCosts;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000584 LLVM_DEBUG(dbgs() << "Offset " << Diff.getValue() << " "
585 << "has penalty: " << ImmCosts << "\n"
586 << "Adjusted cost: " << Cost << "\n");
Sjoerd Meijer38c2cd02016-07-14 07:44:20 +0000587 }
588 }
589 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000590 LLVM_DEBUG(dbgs() << "Cumulative cost: " << Cost << "\n");
Sjoerd Meijer38c2cd02016-07-14 07:44:20 +0000591 if (Cost > MaxCost) {
592 MaxCost = Cost;
593 MaxCostItr = ConstCand;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000594 LLVM_DEBUG(dbgs() << "New candidate: " << MaxCostItr->ConstInt->getValue()
595 << "\n");
Sjoerd Meijer38c2cd02016-07-14 07:44:20 +0000596 }
597 }
598 return NumUses;
599}
600
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000601/// Find the base constant within the given range and rebase all other
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000602/// constants with respect to the base constant.
Michael Kuperstein071d8302016-07-02 00:16:47 +0000603void ConstantHoistingPass::findAndMakeBaseConstant(
Zhaoshi Zhenga0aa41d2018-09-04 22:17:03 +0000604 ConstCandVecType::iterator S, ConstCandVecType::iterator E,
605 SmallVectorImpl<consthoist::ConstantInfo> &ConstInfoVec) {
Juergen Ributzka5429c062014-03-21 06:04:36 +0000606 auto MaxCostItr = S;
Sjoerd Meijer38c2cd02016-07-14 07:44:20 +0000607 unsigned NumUses = maximizeConstantsInRange(S, E, MaxCostItr);
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000608
609 // Don't hoist constants that have only one use.
610 if (NumUses <= 1)
611 return;
612
Zhaoshi Zhenga0aa41d2018-09-04 22:17:03 +0000613 ConstantInt *ConstInt = MaxCostItr->ConstInt;
614 ConstantExpr *ConstExpr = MaxCostItr->ConstExpr;
Juergen Ributzka5429c062014-03-21 06:04:36 +0000615 ConstantInfo ConstInfo;
Zhaoshi Zhenga0aa41d2018-09-04 22:17:03 +0000616 ConstInfo.BaseInt = ConstInt;
617 ConstInfo.BaseExpr = ConstExpr;
618 Type *Ty = ConstInt->getType();
Juergen Ributzka5429c062014-03-21 06:04:36 +0000619
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000620 // Rebase the constants with respect to the base constant.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000621 for (auto ConstCand = S; ConstCand != E; ++ConstCand) {
Zhaoshi Zhenga0aa41d2018-09-04 22:17:03 +0000622 APInt Diff = ConstCand->ConstInt->getValue() - ConstInt->getValue();
Juergen Ributzka5429c062014-03-21 06:04:36 +0000623 Constant *Offset = Diff == 0 ? nullptr : ConstantInt::get(Ty, Diff);
Zhaoshi Zhenga0aa41d2018-09-04 22:17:03 +0000624 Type *ConstTy =
625 ConstCand->ConstExpr ? ConstCand->ConstExpr->getType() : nullptr;
Juergen Ributzka5429c062014-03-21 06:04:36 +0000626 ConstInfo.RebasedConstants.push_back(
Zhaoshi Zhenga0aa41d2018-09-04 22:17:03 +0000627 RebasedConstantInfo(std::move(ConstCand->Uses), Offset, ConstTy));
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000628 }
Zhaoshi Zhenga0aa41d2018-09-04 22:17:03 +0000629 ConstInfoVec.push_back(std::move(ConstInfo));
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000630}
631
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000632/// Finds and combines constant candidates that can be easily
Juergen Ributzka5429c062014-03-21 06:04:36 +0000633/// rematerialized with an add from a common base constant.
Zhaoshi Zhenga0aa41d2018-09-04 22:17:03 +0000634void ConstantHoistingPass::findBaseConstants(GlobalVariable *BaseGV) {
635 // If BaseGV is nullptr, find base among candidate constant integers;
636 // Otherwise find base among constant GEPs that share the same BaseGV.
637 ConstCandVecType &ConstCandVec = BaseGV ?
638 ConstGEPCandMap[BaseGV] : ConstIntCandVec;
639 ConstInfoVecType &ConstInfoVec = BaseGV ?
640 ConstGEPInfoMap[BaseGV] : ConstIntInfoVec;
641
Juergen Ributzka5429c062014-03-21 06:04:36 +0000642 // Sort the constants by value and type. This invalidates the mapping!
Zhaoshi Zhenga0aa41d2018-09-04 22:17:03 +0000643 std::stable_sort(ConstCandVec.begin(), ConstCandVec.end(),
Mandeep Singh Grang636d94d2018-04-13 19:47:57 +0000644 [](const ConstantCandidate &LHS, const ConstantCandidate &RHS) {
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +0000645 if (LHS.ConstInt->getType() != RHS.ConstInt->getType())
646 return LHS.ConstInt->getType()->getBitWidth() <
647 RHS.ConstInt->getType()->getBitWidth();
648 return LHS.ConstInt->getValue().ult(RHS.ConstInt->getValue());
Juergen Ributzka46357932014-03-20 20:17:13 +0000649 });
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000650
Juergen Ributzka5429c062014-03-21 06:04:36 +0000651 // Simple linear scan through the sorted constant candidate vector for viable
652 // merge candidates.
653 auto MinValItr = ConstCandVec.begin();
654 for (auto CC = std::next(ConstCandVec.begin()), E = ConstCandVec.end();
655 CC != E; ++CC) {
656 if (MinValItr->ConstInt->getType() == CC->ConstInt->getType()) {
Zhaoshi Zheng35818e22018-08-28 23:00:59 +0000657 Type *MemUseValTy = nullptr;
658 for (auto &U : CC->Uses) {
659 auto *UI = U.Inst;
660 if (LoadInst *LI = dyn_cast<LoadInst>(UI)) {
661 MemUseValTy = LI->getType();
662 break;
663 } else if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
664 // Make sure the constant is used as pointer operand of the StoreInst.
665 if (SI->getPointerOperand() == SI->getOperand(U.OpndIdx)) {
666 MemUseValTy = SI->getValueOperand()->getType();
667 break;
668 }
669 }
670 }
671
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000672 // Check if the constant is in range of an add with immediate.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000673 APInt Diff = CC->ConstInt->getValue() - MinValItr->ConstInt->getValue();
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000674 if ((Diff.getBitWidth() <= 64) &&
Zhaoshi Zheng35818e22018-08-28 23:00:59 +0000675 TTI->isLegalAddImmediate(Diff.getSExtValue()) &&
676 // Check if Diff can be used as offset in addressing mode of the user
677 // memory instruction.
678 (!MemUseValTy || TTI->isLegalAddressingMode(MemUseValTy,
679 /*BaseGV*/nullptr, /*BaseOffset*/Diff.getSExtValue(),
680 /*HasBaseReg*/true, /*Scale*/0)))
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000681 continue;
682 }
683 // We either have now a different constant type or the constant is not in
684 // range of an add with immediate anymore.
Zhaoshi Zhenga0aa41d2018-09-04 22:17:03 +0000685 findAndMakeBaseConstant(MinValItr, CC, ConstInfoVec);
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000686 // Start a new base constant search.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000687 MinValItr = CC;
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000688 }
689 // Finalize the last base constant search.
Zhaoshi Zhenga0aa41d2018-09-04 22:17:03 +0000690 findAndMakeBaseConstant(MinValItr, ConstCandVec.end(), ConstInfoVec);
Juergen Ributzka46357932014-03-20 20:17:13 +0000691}
692
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000693/// Updates the operand at Idx in instruction Inst with the result of
Juergen Ributzkae802d502014-03-22 01:49:27 +0000694/// instruction Mat. If the instruction is a PHI node then special
Simon Pilgrim7d18a702016-11-20 13:19:49 +0000695/// handling for duplicate values form the same incoming basic block is
Juergen Ributzkae802d502014-03-22 01:49:27 +0000696/// required.
697/// \return The update will always succeed, but the return value indicated if
698/// Mat was used for the update or not.
699static bool updateOperand(Instruction *Inst, unsigned Idx, Instruction *Mat) {
700 if (auto PHI = dyn_cast<PHINode>(Inst)) {
701 // Check if any previous operand of the PHI node has the same incoming basic
702 // block. This is a very odd case that happens when the incoming basic block
703 // has a switch statement. In this case use the same value as the previous
704 // operand(s), otherwise we will fail verification due to different values.
705 // The values are actually the same, but the variable names are different
706 // and the verifier doesn't like that.
707 BasicBlock *IncomingBB = PHI->getIncomingBlock(Idx);
708 for (unsigned i = 0; i < Idx; ++i) {
709 if (PHI->getIncomingBlock(i) == IncomingBB) {
710 Value *IncomingVal = PHI->getIncomingValue(i);
711 Inst->setOperand(Idx, IncomingVal);
712 return false;
713 }
714 }
715 }
716
717 Inst->setOperand(Idx, Mat);
718 return true;
719}
720
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000721/// Emit materialization code for all rebased constants and update their
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000722/// users.
Michael Kuperstein071d8302016-07-02 00:16:47 +0000723void ConstantHoistingPass::emitBaseConstants(Instruction *Base,
724 Constant *Offset,
Zhaoshi Zhenga0aa41d2018-09-04 22:17:03 +0000725 Type *Ty,
Michael Kuperstein071d8302016-07-02 00:16:47 +0000726 const ConstantUser &ConstUser) {
Juergen Ributzka5429c062014-03-21 06:04:36 +0000727 Instruction *Mat = Base;
Zhaoshi Zhenga0aa41d2018-09-04 22:17:03 +0000728
729 // The same offset can be dereferenced to different types in nested struct.
730 if (!Offset && Ty && Ty != Base->getType())
731 Offset = ConstantInt::get(Type::getInt32Ty(*Ctx), 0);
732
Juergen Ributzka5429c062014-03-21 06:04:36 +0000733 if (Offset) {
734 Instruction *InsertionPt = findMatInsertPt(ConstUser.Inst,
735 ConstUser.OpndIdx);
Zhaoshi Zhenga0aa41d2018-09-04 22:17:03 +0000736 if (Ty) {
737 // Constant being rebased is a ConstantExpr.
738 PointerType *Int8PtrTy = Type::getInt8PtrTy(*Ctx,
739 cast<PointerType>(Ty)->getAddressSpace());
740 Base = new BitCastInst(Base, Int8PtrTy, "base_bitcast", InsertionPt);
741 Mat = GetElementPtrInst::Create(Int8PtrTy->getElementType(), Base,
742 Offset, "mat_gep", InsertionPt);
743 Mat = new BitCastInst(Mat, Ty, "mat_bitcast", InsertionPt);
744 } else
745 // Constant being rebased is a ConstantInt.
746 Mat = BinaryOperator::Create(Instruction::Add, Base, Offset,
Juergen Ributzka5429c062014-03-21 06:04:36 +0000747 "const_mat", InsertionPt);
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000748
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000749 LLVM_DEBUG(dbgs() << "Materialize constant (" << *Base->getOperand(0)
750 << " + " << *Offset << ") in BB "
751 << Mat->getParent()->getName() << '\n'
752 << *Mat << '\n');
Juergen Ributzka5429c062014-03-21 06:04:36 +0000753 Mat->setDebugLoc(ConstUser.Inst->getDebugLoc());
754 }
755 Value *Opnd = ConstUser.Inst->getOperand(ConstUser.OpndIdx);
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000756
Juergen Ributzka5429c062014-03-21 06:04:36 +0000757 // Visit constant integer.
758 if (isa<ConstantInt>(Opnd)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000759 LLVM_DEBUG(dbgs() << "Update: " << *ConstUser.Inst << '\n');
Juergen Ributzkae802d502014-03-22 01:49:27 +0000760 if (!updateOperand(ConstUser.Inst, ConstUser.OpndIdx, Mat) && Offset)
761 Mat->eraseFromParent();
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000762 LLVM_DEBUG(dbgs() << "To : " << *ConstUser.Inst << '\n');
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000763 return;
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000764 }
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000765
Juergen Ributzka5429c062014-03-21 06:04:36 +0000766 // Visit cast instruction.
767 if (auto CastInst = dyn_cast<Instruction>(Opnd)) {
768 assert(CastInst->isCast() && "Expected an cast instruction!");
769 // Check if we already have visited this cast instruction before to avoid
770 // unnecessary cloning.
771 Instruction *&ClonedCastInst = ClonedCastMap[CastInst];
772 if (!ClonedCastInst) {
773 ClonedCastInst = CastInst->clone();
774 ClonedCastInst->setOperand(0, Mat);
775 ClonedCastInst->insertAfter(CastInst);
776 // Use the same debug location as the original cast instruction.
777 ClonedCastInst->setDebugLoc(CastInst->getDebugLoc());
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000778 LLVM_DEBUG(dbgs() << "Clone instruction: " << *CastInst << '\n'
779 << "To : " << *ClonedCastInst << '\n');
Juergen Ributzka46357932014-03-20 20:17:13 +0000780 }
Juergen Ributzka5429c062014-03-21 06:04:36 +0000781
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000782 LLVM_DEBUG(dbgs() << "Update: " << *ConstUser.Inst << '\n');
Juergen Ributzkae802d502014-03-22 01:49:27 +0000783 updateOperand(ConstUser.Inst, ConstUser.OpndIdx, ClonedCastInst);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000784 LLVM_DEBUG(dbgs() << "To : " << *ConstUser.Inst << '\n');
Juergen Ributzka5429c062014-03-21 06:04:36 +0000785 return;
Juergen Ributzka46357932014-03-20 20:17:13 +0000786 }
Juergen Ributzka5429c062014-03-21 06:04:36 +0000787
788 // Visit constant expression.
789 if (auto ConstExpr = dyn_cast<ConstantExpr>(Opnd)) {
Zhaoshi Zhenga0aa41d2018-09-04 22:17:03 +0000790 if (ConstExpr->isGEPWithNoNotionalOverIndexing()) {
791 // Operand is a ConstantGEP, replace it.
792 updateOperand(ConstUser.Inst, ConstUser.OpndIdx, Mat);
793 return;
794 }
795
796 // Aside from constant GEPs, only constant cast expressions are collected.
797 assert(ConstExpr->isCast() && "ConstExpr should be a cast");
Juergen Ributzka5429c062014-03-21 06:04:36 +0000798 Instruction *ConstExprInst = ConstExpr->getAsInstruction();
799 ConstExprInst->setOperand(0, Mat);
800 ConstExprInst->insertBefore(findMatInsertPt(ConstUser.Inst,
801 ConstUser.OpndIdx));
802
803 // Use the same debug location as the instruction we are about to update.
804 ConstExprInst->setDebugLoc(ConstUser.Inst->getDebugLoc());
805
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000806 LLVM_DEBUG(dbgs() << "Create instruction: " << *ConstExprInst << '\n'
807 << "From : " << *ConstExpr << '\n');
808 LLVM_DEBUG(dbgs() << "Update: " << *ConstUser.Inst << '\n');
Juergen Ributzkae802d502014-03-22 01:49:27 +0000809 if (!updateOperand(ConstUser.Inst, ConstUser.OpndIdx, ConstExprInst)) {
810 ConstExprInst->eraseFromParent();
811 if (Offset)
812 Mat->eraseFromParent();
813 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000814 LLVM_DEBUG(dbgs() << "To : " << *ConstUser.Inst << '\n');
Juergen Ributzka5429c062014-03-21 06:04:36 +0000815 return;
Juergen Ributzka4c8a0252014-02-08 00:20:45 +0000816 }
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000817}
818
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000819/// Hoist and hide the base constant behind a bitcast and emit
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000820/// materialization code for derived constants.
Zhaoshi Zhenga0aa41d2018-09-04 22:17:03 +0000821bool ConstantHoistingPass::emitBaseConstants(GlobalVariable *BaseGV) {
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000822 bool MadeChange = false;
Zhaoshi Zhenga0aa41d2018-09-04 22:17:03 +0000823 SmallVectorImpl<consthoist::ConstantInfo> &ConstInfoVec =
824 BaseGV ? ConstGEPInfoMap[BaseGV] : ConstIntInfoVec;
825 for (auto const &ConstInfo : ConstInfoVec) {
Wei Mi337d4d92017-04-21 15:50:16 +0000826 SmallPtrSet<Instruction *, 8> IPSet = findConstantInsertionPoint(ConstInfo);
827 assert(!IPSet.empty() && "IPSet is empty");
828
829 unsigned UsesNum = 0;
830 unsigned ReBasesNum = 0;
Zhaoshi Zheng95710332018-09-26 00:59:09 +0000831 unsigned NotRebasedNum = 0;
Wei Mi337d4d92017-04-21 15:50:16 +0000832 for (Instruction *IP : IPSet) {
Zhaoshi Zheng95710332018-09-26 00:59:09 +0000833 // First, collect constants depending on this IP of the base.
834 unsigned Uses = 0;
835 using RebasedUse = std::tuple<Constant *, Type *, ConstantUser>;
836 SmallVector<RebasedUse, 4> ToBeRebased;
837 for (auto const &RCI : ConstInfo.RebasedConstants) {
838 for (auto const &U : RCI.Uses) {
839 Uses++;
840 BasicBlock *OrigMatInsertBB =
841 findMatInsertPt(U.Inst, U.OpndIdx)->getParent();
842 // If Base constant is to be inserted in multiple places,
843 // generate rebase for U using the Base dominating U.
844 if (IPSet.size() == 1 ||
845 DT->dominates(IP->getParent(), OrigMatInsertBB))
846 ToBeRebased.push_back(RebasedUse(RCI.Offset, RCI.Ty, U));
847 }
848 }
849 UsesNum = Uses;
850
851 // If only few constants depend on this IP of base, skip rebasing,
852 // assuming the base and the rebased have the same materialization cost.
853 if (ToBeRebased.size() < MinNumOfDependentToRebase) {
854 NotRebasedNum += ToBeRebased.size();
855 continue;
856 }
857
858 // Emit an instance of the base at this IP.
Zhaoshi Zhenga0aa41d2018-09-04 22:17:03 +0000859 Instruction *Base = nullptr;
860 // Hoist and hide the base constant behind a bitcast.
861 if (ConstInfo.BaseExpr) {
862 assert(BaseGV && "A base constant expression must have an base GV");
863 Type *Ty = ConstInfo.BaseExpr->getType();
864 Base = new BitCastInst(ConstInfo.BaseExpr, Ty, "const", IP);
865 } else {
866 IntegerType *Ty = ConstInfo.BaseInt->getType();
867 Base = new BitCastInst(ConstInfo.BaseInt, Ty, "const", IP);
868 }
Paul Robinsonb46256b2017-11-09 20:01:31 +0000869
870 Base->setDebugLoc(IP->getDebugLoc());
871
Zhaoshi Zhenga0aa41d2018-09-04 22:17:03 +0000872 LLVM_DEBUG(dbgs() << "Hoist constant (" << *ConstInfo.BaseInt
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000873 << ") to BB " << IP->getParent()->getName() << '\n'
874 << *Base << '\n');
Wei Mi337d4d92017-04-21 15:50:16 +0000875
Zhaoshi Zheng95710332018-09-26 00:59:09 +0000876 // Emit materialization code for rebased constants depending on this IP.
877 for (auto const &R : ToBeRebased) {
878 Constant *Off = std::get<0>(R);
879 Type *Ty = std::get<1>(R);
880 ConstantUser U = std::get<2>(R);
881 emitBaseConstants(Base, Off, Ty, U);
882 ReBasesNum++;
883 // Use the same debug location as the last user of the constant.
884 Base->setDebugLoc(DILocation::getMergedLocation(
885 Base->getDebugLoc(), U.Inst->getDebugLoc()));
Wei Mi337d4d92017-04-21 15:50:16 +0000886 }
Wei Mi337d4d92017-04-21 15:50:16 +0000887 assert(!Base->use_empty() && "The use list is empty!?");
888 assert(isa<Instruction>(Base->user_back()) &&
889 "All uses should be instructions.");
Wei Mi337d4d92017-04-21 15:50:16 +0000890 }
891 (void)UsesNum;
892 (void)ReBasesNum;
Zhaoshi Zheng95710332018-09-26 00:59:09 +0000893 (void)NotRebasedNum;
Wei Mi337d4d92017-04-21 15:50:16 +0000894 // Expect all uses are rebased after rebase is done.
Zhaoshi Zheng95710332018-09-26 00:59:09 +0000895 assert(UsesNum == (ReBasesNum + NotRebasedNum) &&
896 "Not all uses are rebased");
Wei Mi337d4d92017-04-21 15:50:16 +0000897
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000898 NumConstantsHoisted++;
899
Wei Mi337d4d92017-04-21 15:50:16 +0000900 // Base constant is also included in ConstInfo.RebasedConstants, so
901 // deduct 1 from ConstInfo.RebasedConstants.size().
Zhaoshi Zhenga0aa41d2018-09-04 22:17:03 +0000902 NumConstantsRebased += ConstInfo.RebasedConstants.size() - 1;
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000903
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000904 MadeChange = true;
905 }
906 return MadeChange;
907}
908
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000909/// Check all cast instructions we made a copy of and remove them if they
Juergen Ributzka5429c062014-03-21 06:04:36 +0000910/// have no more users.
Michael Kuperstein071d8302016-07-02 00:16:47 +0000911void ConstantHoistingPass::deleteDeadCastInst() const {
Juergen Ributzka5429c062014-03-21 06:04:36 +0000912 for (auto const &I : ClonedCastMap)
913 if (I.first->use_empty())
Juergen Ributzkae4747522014-03-22 01:49:30 +0000914 I.first->eraseFromParent();
Juergen Ributzka5429c062014-03-21 06:04:36 +0000915}
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000916
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000917/// Optimize expensive integer constants in the given function.
Michael Kuperstein071d8302016-07-02 00:16:47 +0000918bool ConstantHoistingPass::runImpl(Function &Fn, TargetTransformInfo &TTI,
Wei Mi337d4d92017-04-21 15:50:16 +0000919 DominatorTree &DT, BlockFrequencyInfo *BFI,
920 BasicBlock &Entry) {
Michael Kuperstein071d8302016-07-02 00:16:47 +0000921 this->TTI = &TTI;
922 this->DT = &DT;
Wei Mi337d4d92017-04-21 15:50:16 +0000923 this->BFI = BFI;
Zhaoshi Zhenga0aa41d2018-09-04 22:17:03 +0000924 this->DL = &Fn.getParent()->getDataLayout();
925 this->Ctx = &Fn.getContext();
Fangrui Songf78650a2018-07-30 19:41:25 +0000926 this->Entry = &Entry;
Juergen Ributzka46357932014-03-20 20:17:13 +0000927 // Collect all constant candidates.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000928 collectConstantCandidates(Fn);
Juergen Ributzka46357932014-03-20 20:17:13 +0000929
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000930 // Combine constants that can be easily materialized with an add from a common
931 // base constant.
Zhaoshi Zhenga0aa41d2018-09-04 22:17:03 +0000932 if (!ConstIntCandVec.empty())
933 findBaseConstants(nullptr);
934 for (auto &MapEntry : ConstGEPCandMap)
935 if (!MapEntry.second.empty())
936 findBaseConstants(MapEntry.first);
Juergen Ributzka5429c062014-03-21 06:04:36 +0000937
Juergen Ributzkaf0dff492014-03-21 06:04:45 +0000938 // Finally hoist the base constant and emit materialization code for dependent
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000939 // constants.
Zhaoshi Zhenga0aa41d2018-09-04 22:17:03 +0000940 bool MadeChange = false;
941 if (!ConstIntInfoVec.empty())
942 MadeChange = emitBaseConstants(nullptr);
943 for (auto MapEntry : ConstGEPInfoMap)
944 if (!MapEntry.second.empty())
945 MadeChange |= emitBaseConstants(MapEntry.first);
946
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000947
Juergen Ributzka5429c062014-03-21 06:04:36 +0000948 // Cleanup dead instructions.
949 deleteDeadCastInst();
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000950
951 return MadeChange;
952}
Michael Kuperstein071d8302016-07-02 00:16:47 +0000953
954PreservedAnalyses ConstantHoistingPass::run(Function &F,
955 FunctionAnalysisManager &AM) {
956 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
957 auto &TTI = AM.getResult<TargetIRAnalysis>(F);
Wei Mi337d4d92017-04-21 15:50:16 +0000958 auto BFI = ConstHoistWithBlockFrequency
959 ? &AM.getResult<BlockFrequencyAnalysis>(F)
960 : nullptr;
961 if (!runImpl(F, TTI, DT, BFI, F.getEntryBlock()))
Michael Kuperstein071d8302016-07-02 00:16:47 +0000962 return PreservedAnalyses::all();
963
Chandler Carruthca68a3e2017-01-15 06:32:49 +0000964 PreservedAnalyses PA;
965 PA.preserveSet<CFGAnalyses>();
966 return PA;
Michael Kuperstein071d8302016-07-02 00:16:47 +0000967}