blob: 7acc85c3dd39da1a08123a7773056980dddd8737 [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
Juergen Ributzkaf26beda2014-01-25 02:02:55 +000089namespace {
Eugene Zelenko8002c502017-09-13 21:43:53 +000090
Adrian Prantl5f8f34e42018-05-01 15:54:18 +000091/// The constant hoisting pass.
Michael Kuperstein071d8302016-07-02 00:16:47 +000092class ConstantHoistingLegacyPass : public FunctionPass {
Juergen Ributzkaf26beda2014-01-25 02:02:55 +000093public:
94 static char ID; // Pass identification, replacement for typeid
Eugene Zelenko8002c502017-09-13 21:43:53 +000095
Michael Kuperstein071d8302016-07-02 00:16:47 +000096 ConstantHoistingLegacyPass() : FunctionPass(ID) {
97 initializeConstantHoistingLegacyPassPass(*PassRegistry::getPassRegistry());
Juergen Ributzkaf26beda2014-01-25 02:02:55 +000098 }
99
Juergen Ributzka5429c062014-03-21 06:04:36 +0000100 bool runOnFunction(Function &Fn) override;
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000101
Mehdi Amini117296c2016-10-01 02:56:57 +0000102 StringRef getPassName() const override { return "Constant Hoisting"; }
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000103
Craig Topper3e4c6972014-03-05 09:10:37 +0000104 void getAnalysisUsage(AnalysisUsage &AU) const override {
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000105 AU.setPreservesCFG();
Wei Mi337d4d92017-04-21 15:50:16 +0000106 if (ConstHoistWithBlockFrequency)
107 AU.addRequired<BlockFrequencyInfoWrapperPass>();
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000108 AU.addRequired<DominatorTreeWrapperPass>();
Chandler Carruth705b1852015-01-31 03:43:40 +0000109 AU.addRequired<TargetTransformInfoWrapperPass>();
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000110 }
111
Michael Kuperstein071d8302016-07-02 00:16:47 +0000112 void releaseMemory() override { Impl.releaseMemory(); }
113
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000114private:
Michael Kuperstein071d8302016-07-02 00:16:47 +0000115 ConstantHoistingPass Impl;
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000116};
Eugene Zelenko8002c502017-09-13 21:43:53 +0000117
118} // end anonymous namespace
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000119
Michael Kuperstein071d8302016-07-02 00:16:47 +0000120char ConstantHoistingLegacyPass::ID = 0;
Eugene Zelenko8002c502017-09-13 21:43:53 +0000121
Michael Kuperstein071d8302016-07-02 00:16:47 +0000122INITIALIZE_PASS_BEGIN(ConstantHoistingLegacyPass, "consthoist",
123 "Constant Hoisting", false, false)
Wei Mi337d4d92017-04-21 15:50:16 +0000124INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000125INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Chandler Carruth705b1852015-01-31 03:43:40 +0000126INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
Michael Kuperstein071d8302016-07-02 00:16:47 +0000127INITIALIZE_PASS_END(ConstantHoistingLegacyPass, "consthoist",
128 "Constant Hoisting", false, false)
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000129
130FunctionPass *llvm::createConstantHoistingPass() {
Michael Kuperstein071d8302016-07-02 00:16:47 +0000131 return new ConstantHoistingLegacyPass();
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000132}
133
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000134/// Perform the constant hoisting optimization for the given function.
Michael Kuperstein071d8302016-07-02 00:16:47 +0000135bool ConstantHoistingLegacyPass::runOnFunction(Function &Fn) {
Andrew Kayloraa641a52016-04-22 22:06:11 +0000136 if (skipFunction(Fn))
Andrea Di Biagiof54432382015-02-14 15:11:48 +0000137 return false;
138
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000139 LLVM_DEBUG(dbgs() << "********** Begin Constant Hoisting **********\n");
140 LLVM_DEBUG(dbgs() << "********** Function: " << Fn.getName() << '\n');
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000141
Wei Mi337d4d92017-04-21 15:50:16 +0000142 bool MadeChange =
143 Impl.runImpl(Fn, getAnalysis<TargetTransformInfoWrapperPass>().getTTI(Fn),
144 getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
145 ConstHoistWithBlockFrequency
146 ? &getAnalysis<BlockFrequencyInfoWrapperPass>().getBFI()
147 : nullptr,
148 Fn.getEntryBlock());
Juergen Ributzka5429c062014-03-21 06:04:36 +0000149
150 if (MadeChange) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000151 LLVM_DEBUG(dbgs() << "********** Function after Constant Hoisting: "
152 << Fn.getName() << '\n');
153 LLVM_DEBUG(dbgs() << Fn);
Juergen Ributzka5429c062014-03-21 06:04:36 +0000154 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000155 LLVM_DEBUG(dbgs() << "********** End Constant Hoisting **********\n");
Juergen Ributzka5429c062014-03-21 06:04:36 +0000156
Juergen Ributzka5429c062014-03-21 06:04:36 +0000157 return MadeChange;
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000158}
159
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000160/// Find the constant materialization insertion point.
Michael Kuperstein071d8302016-07-02 00:16:47 +0000161Instruction *ConstantHoistingPass::findMatInsertPt(Instruction *Inst,
162 unsigned Idx) const {
Juergen Ributzka575bcb72014-04-22 18:06:58 +0000163 // If the operand is a cast instruction, then we have to materialize the
164 // constant before the cast instruction.
165 if (Idx != ~0U) {
166 Value *Opnd = Inst->getOperand(Idx);
167 if (auto CastInst = dyn_cast<Instruction>(Opnd))
168 if (CastInst->isCast())
169 return CastInst;
170 }
171
172 // The simple and common case. This also includes constant expressions.
David Majnemerba275f92015-08-19 19:54:02 +0000173 if (!isa<PHINode>(Inst) && !Inst->isEHPad())
Juergen Ributzka5429c062014-03-21 06:04:36 +0000174 return Inst;
175
David Majnemerba275f92015-08-19 19:54:02 +0000176 // We can't insert directly before a phi node or an eh pad. Insert before
Juergen Ributzka5429c062014-03-21 06:04:36 +0000177 // the terminator of the incoming or dominating block.
178 assert(Entry != Inst->getParent() && "PHI or landing pad in entry block!");
179 if (Idx != ~0U && isa<PHINode>(Inst))
180 return cast<PHINode>(Inst)->getIncomingBlock(Idx)->getTerminator();
181
Reid Klecknerd80b69f2017-03-01 22:41:12 +0000182 // This must be an EH pad. Iterate over immediate dominators until we find a
183 // non-EH pad. We need to skip over catchswitch blocks, which are both EH pads
184 // and terminators.
185 auto IDom = DT->getNode(Inst->getParent())->getIDom();
186 while (IDom->getBlock()->isEHPad()) {
187 assert(Entry != IDom->getBlock() && "eh pad in entry block");
188 IDom = IDom->getIDom();
189 }
190
191 return IDom->getBlock()->getTerminator();
Juergen Ributzka5429c062014-03-21 06:04:36 +0000192}
193
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000194/// Given \p BBs as input, find another set of BBs which collectively
Wei Mi337d4d92017-04-21 15:50:16 +0000195/// dominates \p BBs and have the minimal sum of frequencies. Return the BB
196/// set found in \p BBs.
Benjamin Kramerdebb3c32017-05-26 20:09:00 +0000197static void findBestInsertionSet(DominatorTree &DT, BlockFrequencyInfo &BFI,
198 BasicBlock *Entry,
199 SmallPtrSet<BasicBlock *, 8> &BBs) {
Wei Mi337d4d92017-04-21 15:50:16 +0000200 assert(!BBs.count(Entry) && "Assume Entry is not in BBs");
201 // Nodes on the current path to the root.
202 SmallPtrSet<BasicBlock *, 8> Path;
203 // Candidates includes any block 'BB' in set 'BBs' that is not strictly
204 // dominated by any other blocks in set 'BBs', and all nodes in the path
205 // in the dominator tree from Entry to 'BB'.
206 SmallPtrSet<BasicBlock *, 16> Candidates;
207 for (auto BB : BBs) {
208 Path.clear();
209 // Walk up the dominator tree until Entry or another BB in BBs
210 // is reached. Insert the nodes on the way to the Path.
211 BasicBlock *Node = BB;
212 // The "Path" is a candidate path to be added into Candidates set.
213 bool isCandidate = false;
214 do {
215 Path.insert(Node);
216 if (Node == Entry || Candidates.count(Node)) {
217 isCandidate = true;
218 break;
219 }
220 assert(DT.getNode(Node)->getIDom() &&
221 "Entry doens't dominate current Node");
222 Node = DT.getNode(Node)->getIDom()->getBlock();
223 } while (!BBs.count(Node));
224
225 // If isCandidate is false, Node is another Block in BBs dominating
226 // current 'BB'. Drop the nodes on the Path.
227 if (!isCandidate)
228 continue;
229
230 // Add nodes on the Path into Candidates.
231 Candidates.insert(Path.begin(), Path.end());
232 }
233
234 // Sort the nodes in Candidates in top-down order and save the nodes
235 // in Orders.
236 unsigned Idx = 0;
237 SmallVector<BasicBlock *, 16> Orders;
238 Orders.push_back(Entry);
239 while (Idx != Orders.size()) {
240 BasicBlock *Node = Orders[Idx++];
241 for (auto ChildDomNode : DT.getNode(Node)->getChildren()) {
242 if (Candidates.count(ChildDomNode->getBlock()))
243 Orders.push_back(ChildDomNode->getBlock());
244 }
245 }
246
247 // Visit Orders in bottom-up order.
Eugene Zelenko8002c502017-09-13 21:43:53 +0000248 using InsertPtsCostPair =
249 std::pair<SmallPtrSet<BasicBlock *, 16>, BlockFrequency>;
250
Wei Mi337d4d92017-04-21 15:50:16 +0000251 // InsertPtsMap is a map from a BB to the best insertion points for the
252 // subtree of BB (subtree not including the BB itself).
253 DenseMap<BasicBlock *, InsertPtsCostPair> InsertPtsMap;
254 InsertPtsMap.reserve(Orders.size() + 1);
255 for (auto RIt = Orders.rbegin(); RIt != Orders.rend(); RIt++) {
256 BasicBlock *Node = *RIt;
257 bool NodeInBBs = BBs.count(Node);
258 SmallPtrSet<BasicBlock *, 16> &InsertPts = InsertPtsMap[Node].first;
259 BlockFrequency &InsertPtsFreq = InsertPtsMap[Node].second;
260
261 // Return the optimal insert points in BBs.
262 if (Node == Entry) {
263 BBs.clear();
Wei Mi20526b22017-07-06 22:32:27 +0000264 if (InsertPtsFreq > BFI.getBlockFreq(Node) ||
265 (InsertPtsFreq == BFI.getBlockFreq(Node) && InsertPts.size() > 1))
Wei Mi337d4d92017-04-21 15:50:16 +0000266 BBs.insert(Entry);
267 else
268 BBs.insert(InsertPts.begin(), InsertPts.end());
269 break;
270 }
271
272 BasicBlock *Parent = DT.getNode(Node)->getIDom()->getBlock();
273 // Initially, ParentInsertPts is empty and ParentPtsFreq is 0. Every child
274 // will update its parent's ParentInsertPts and ParentPtsFreq.
275 SmallPtrSet<BasicBlock *, 16> &ParentInsertPts = InsertPtsMap[Parent].first;
276 BlockFrequency &ParentPtsFreq = InsertPtsMap[Parent].second;
277 // Choose to insert in Node or in subtree of Node.
Wei Mi20526b22017-07-06 22:32:27 +0000278 // Don't hoist to EHPad because we may not find a proper place to insert
279 // in EHPad.
280 // If the total frequency of InsertPts is the same as the frequency of the
281 // target Node, and InsertPts contains more than one nodes, choose hoisting
282 // to reduce code size.
283 if (NodeInBBs ||
284 (!Node->isEHPad() &&
285 (InsertPtsFreq > BFI.getBlockFreq(Node) ||
286 (InsertPtsFreq == BFI.getBlockFreq(Node) && InsertPts.size() > 1)))) {
Wei Mi337d4d92017-04-21 15:50:16 +0000287 ParentInsertPts.insert(Node);
288 ParentPtsFreq += BFI.getBlockFreq(Node);
289 } else {
290 ParentInsertPts.insert(InsertPts.begin(), InsertPts.end());
291 ParentPtsFreq += InsertPtsFreq;
292 }
293 }
294}
295
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000296/// Find an insertion point that dominates all uses.
Wei Mi337d4d92017-04-21 15:50:16 +0000297SmallPtrSet<Instruction *, 8> ConstantHoistingPass::findConstantInsertionPoint(
Michael Kuperstein071d8302016-07-02 00:16:47 +0000298 const ConstantInfo &ConstInfo) const {
Juergen Ributzka5429c062014-03-21 06:04:36 +0000299 assert(!ConstInfo.RebasedConstants.empty() && "Invalid constant info entry.");
Juergen Ributzkac81000b2014-04-03 01:38:47 +0000300 // Collect all basic blocks.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000301 SmallPtrSet<BasicBlock *, 8> BBs;
Wei Mi337d4d92017-04-21 15:50:16 +0000302 SmallPtrSet<Instruction *, 8> InsertPts;
Juergen Ributzka5429c062014-03-21 06:04:36 +0000303 for (auto const &RCI : ConstInfo.RebasedConstants)
Juergen Ributzkac81000b2014-04-03 01:38:47 +0000304 for (auto const &U : RCI.Uses)
Juergen Ributzka575bcb72014-04-22 18:06:58 +0000305 BBs.insert(findMatInsertPt(U.Inst, U.OpndIdx)->getParent());
Juergen Ributzka5429c062014-03-21 06:04:36 +0000306
Wei Mi337d4d92017-04-21 15:50:16 +0000307 if (BBs.count(Entry)) {
308 InsertPts.insert(&Entry->front());
309 return InsertPts;
310 }
311
312 if (BFI) {
313 findBestInsertionSet(*DT, *BFI, Entry, BBs);
314 for (auto BB : BBs) {
315 BasicBlock::iterator InsertPt = BB->begin();
316 for (; isa<PHINode>(InsertPt) || InsertPt->isEHPad(); ++InsertPt)
317 ;
318 InsertPts.insert(&*InsertPt);
319 }
320 return InsertPts;
321 }
Juergen Ributzka5429c062014-03-21 06:04:36 +0000322
323 while (BBs.size() >= 2) {
324 BasicBlock *BB, *BB1, *BB2;
325 BB1 = *BBs.begin();
326 BB2 = *std::next(BBs.begin());
327 BB = DT->findNearestCommonDominator(BB1, BB2);
Wei Mi337d4d92017-04-21 15:50:16 +0000328 if (BB == Entry) {
329 InsertPts.insert(&Entry->front());
330 return InsertPts;
331 }
Juergen Ributzka5429c062014-03-21 06:04:36 +0000332 BBs.erase(BB1);
333 BBs.erase(BB2);
334 BBs.insert(BB);
335 }
336 assert((BBs.size() == 1) && "Expected only one element.");
337 Instruction &FirstInst = (*BBs.begin())->front();
Wei Mi337d4d92017-04-21 15:50:16 +0000338 InsertPts.insert(findMatInsertPt(&FirstInst));
339 return InsertPts;
Juergen Ributzka5429c062014-03-21 06:04:36 +0000340}
341
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000342/// Record constant integer ConstInt for instruction Inst at operand
Juergen Ributzka5429c062014-03-21 06:04:36 +0000343/// index Idx.
344///
Juergen Ributzkaf0dff492014-03-21 06:04:45 +0000345/// The operand at index Idx is not necessarily the constant integer itself. It
Juergen Ributzka5429c062014-03-21 06:04:36 +0000346/// could also be a cast instruction or a constant expression that uses the
Zhaoshi Zhenga0aa41d2018-09-04 22:17:03 +0000347/// constant integer.
Michael Kuperstein071d8302016-07-02 00:16:47 +0000348void ConstantHoistingPass::collectConstantCandidates(
349 ConstCandMapType &ConstCandMap, Instruction *Inst, unsigned Idx,
350 ConstantInt *ConstInt) {
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000351 unsigned Cost;
Juergen Ributzka5429c062014-03-21 06:04:36 +0000352 // Ask the target about the cost of materializing the constant for the given
Juergen Ributzkaf0dff492014-03-21 06:04:45 +0000353 // instruction and operand index.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000354 if (auto IntrInst = dyn_cast<IntrinsicInst>(Inst))
Juergen Ributzkaf0dff492014-03-21 06:04:45 +0000355 Cost = TTI->getIntImmCost(IntrInst->getIntrinsicID(), Idx,
Juergen Ributzka5429c062014-03-21 06:04:36 +0000356 ConstInt->getValue(), ConstInt->getType());
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000357 else
Juergen Ributzkaf0dff492014-03-21 06:04:45 +0000358 Cost = TTI->getIntImmCost(Inst->getOpcode(), Idx, ConstInt->getValue(),
Juergen Ributzka5429c062014-03-21 06:04:36 +0000359 ConstInt->getType());
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000360
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +0000361 // Ignore cheap integer constants.
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000362 if (Cost > TargetTransformInfo::TCC_Basic) {
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +0000363 ConstCandMapType::iterator Itr;
364 bool Inserted;
Zhaoshi Zhenga0aa41d2018-09-04 22:17:03 +0000365 ConstPtrUnionType Cand = ConstInt;
366 std::tie(Itr, Inserted) = ConstCandMap.insert(std::make_pair(Cand, 0));
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +0000367 if (Inserted) {
Zhaoshi Zhenga0aa41d2018-09-04 22:17:03 +0000368 ConstIntCandVec.push_back(ConstantCandidate(ConstInt));
369 Itr->second = ConstIntCandVec.size() - 1;
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +0000370 }
Zhaoshi Zhenga0aa41d2018-09-04 22:17:03 +0000371 ConstIntCandVec[Itr->second].addUser(Inst, Idx, Cost);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000372 LLVM_DEBUG(if (isa<ConstantInt>(Inst->getOperand(Idx))) dbgs()
373 << "Collect constant " << *ConstInt << " from " << *Inst
Juergen Ributzka5429c062014-03-21 06:04:36 +0000374 << " with cost " << Cost << '\n';
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000375 else dbgs() << "Collect constant " << *ConstInt
376 << " indirectly from " << *Inst << " via "
377 << *Inst->getOperand(Idx) << " with cost " << Cost
378 << '\n';);
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000379 }
380}
381
Zhaoshi Zhenga0aa41d2018-09-04 22:17:03 +0000382/// Record constant GEP expression for instruction Inst at operand index Idx.
383void ConstantHoistingPass::collectConstantCandidates(
384 ConstCandMapType &ConstCandMap, Instruction *Inst, unsigned Idx,
385 ConstantExpr *ConstExpr) {
386 // TODO: Handle vector GEPs
387 if (ConstExpr->getType()->isVectorTy())
388 return;
389
390 GlobalVariable *BaseGV = dyn_cast<GlobalVariable>(ConstExpr->getOperand(0));
391 if (!BaseGV)
392 return;
393
394 // Get offset from the base GV.
395 PointerType *GVPtrTy = dyn_cast<PointerType>(BaseGV->getType());
396 IntegerType *PtrIntTy = DL->getIntPtrType(*Ctx, GVPtrTy->getAddressSpace());
397 APInt Offset(DL->getTypeSizeInBits(PtrIntTy), /*val*/0, /*isSigned*/true);
398 auto *GEPO = cast<GEPOperator>(ConstExpr);
399 if (!GEPO->accumulateConstantOffset(*DL, Offset))
400 return;
401
402 if (!Offset.isIntN(32))
403 return;
404
405 // A constant GEP expression that has a GlobalVariable as base pointer is
406 // usually lowered to a load from constant pool. Such operation is unlikely
407 // to be cheaper than compute it by <Base + Offset>, which can be lowered to
408 // an ADD instruction or folded into Load/Store instruction.
409 int Cost = TTI->getIntImmCost(Instruction::Add, 1, Offset, PtrIntTy);
410 ConstCandVecType &ExprCandVec = ConstGEPCandMap[BaseGV];
411 ConstCandMapType::iterator Itr;
412 bool Inserted;
413 ConstPtrUnionType Cand = ConstExpr;
414 std::tie(Itr, Inserted) = ConstCandMap.insert(std::make_pair(Cand, 0));
415 if (Inserted) {
416 ExprCandVec.push_back(ConstantCandidate(
417 ConstantInt::get(Type::getInt32Ty(*Ctx), Offset.getLimitedValue()),
418 ConstExpr));
419 Itr->second = ExprCandVec.size() - 1;
420 }
421 ExprCandVec[Itr->second].addUser(Inst, Idx, Cost);
422}
423
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000424/// Check the operand for instruction Inst at index Idx.
Leo Li20fbad92017-06-29 17:03:34 +0000425void ConstantHoistingPass::collectConstantCandidates(
426 ConstCandMapType &ConstCandMap, Instruction *Inst, unsigned Idx) {
427 Value *Opnd = Inst->getOperand(Idx);
428
429 // Visit constant integers.
430 if (auto ConstInt = dyn_cast<ConstantInt>(Opnd)) {
431 collectConstantCandidates(ConstCandMap, Inst, Idx, ConstInt);
432 return;
433 }
434
435 // Visit cast instructions that have constant integers.
436 if (auto CastInst = dyn_cast<Instruction>(Opnd)) {
437 // Only visit cast instructions, which have been skipped. All other
438 // instructions should have already been visited.
439 if (!CastInst->isCast())
440 return;
441
442 if (auto *ConstInt = dyn_cast<ConstantInt>(CastInst->getOperand(0))) {
443 // Pretend the constant is directly used by the instruction and ignore
444 // the cast instruction.
445 collectConstantCandidates(ConstCandMap, Inst, Idx, ConstInt);
446 return;
447 }
448 }
449
450 // Visit constant expressions that have constant integers.
451 if (auto ConstExpr = dyn_cast<ConstantExpr>(Opnd)) {
Zhaoshi Zhenga0aa41d2018-09-04 22:17:03 +0000452 // Handle constant gep expressions.
453 if (ConstHoistGEP && ConstExpr->isGEPWithNoNotionalOverIndexing())
454 collectConstantCandidates(ConstCandMap, Inst, Idx, ConstExpr);
455
Leo Li20fbad92017-06-29 17:03:34 +0000456 // Only visit constant cast expressions.
457 if (!ConstExpr->isCast())
458 return;
459
460 if (auto ConstInt = dyn_cast<ConstantInt>(ConstExpr->getOperand(0))) {
461 // Pretend the constant is directly used by the instruction and ignore
462 // the constant expression.
463 collectConstantCandidates(ConstCandMap, Inst, Idx, ConstInt);
464 return;
465 }
466 }
467}
468
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000469/// Scan the instruction for expensive integer constants and record them
Juergen Ributzka5429c062014-03-21 06:04:36 +0000470/// in the constant candidate vector.
Michael Kuperstein071d8302016-07-02 00:16:47 +0000471void ConstantHoistingPass::collectConstantCandidates(
472 ConstCandMapType &ConstCandMap, Instruction *Inst) {
Juergen Ributzka5429c062014-03-21 06:04:36 +0000473 // Skip all cast instructions. They are visited indirectly later on.
474 if (Inst->isCast())
475 return;
476
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000477 // Scan all operands.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000478 for (unsigned Idx = 0, E = Inst->getNumOperands(); Idx != E; ++Idx) {
Leo Li93abd7d2017-07-10 20:45:34 +0000479 // The cost of materializing the constants (defined in
480 // `TargetTransformInfo::getIntImmCost`) for instructions which only take
481 // constant variables is lower than `TargetTransformInfo::TCC_Basic`. So
482 // it's safe for us to collect constant candidates from all IntrinsicInsts.
483 if (canReplaceOperandWithVariable(Inst, Idx) || isa<IntrinsicInst>(Inst)) {
484 collectConstantCandidates(ConstCandMap, Inst, Idx);
485 }
Juergen Ributzka5429c062014-03-21 06:04:36 +0000486 } // end of for all operands
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000487}
488
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000489/// Collect all integer constants in the function that cannot be folded
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000490/// into an instruction itself.
Michael Kuperstein071d8302016-07-02 00:16:47 +0000491void ConstantHoistingPass::collectConstantCandidates(Function &Fn) {
Juergen Ributzka7be410f2014-03-25 21:21:10 +0000492 ConstCandMapType ConstCandMap;
Duncan P. N. Exon Smith3a9c9e32015-10-13 18:26:00 +0000493 for (BasicBlock &BB : Fn)
494 for (Instruction &Inst : BB)
495 collectConstantCandidates(ConstCandMap, &Inst);
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000496}
497
Sjoerd Meijer38c2cd02016-07-14 07:44:20 +0000498// This helper function is necessary to deal with values that have different
499// bit widths (APInt Operator- does not like that). If the value cannot be
500// represented in uint64 we return an "empty" APInt. This is then interpreted
501// as the value is not in range.
Eugene Zelenko8002c502017-09-13 21:43:53 +0000502static Optional<APInt> calculateOffsetDiff(const APInt &V1, const APInt &V2) {
503 Optional<APInt> Res = None;
Sjoerd Meijer38c2cd02016-07-14 07:44:20 +0000504 unsigned BW = V1.getBitWidth() > V2.getBitWidth() ?
505 V1.getBitWidth() : V2.getBitWidth();
506 uint64_t LimVal1 = V1.getLimitedValue();
507 uint64_t LimVal2 = V2.getLimitedValue();
508
509 if (LimVal1 == ~0ULL || LimVal2 == ~0ULL)
510 return Res;
511
512 uint64_t Diff = LimVal1 - LimVal2;
513 return APInt(BW, Diff, true);
514}
515
516// From a list of constants, one needs to picked as the base and the other
517// constants will be transformed into an offset from that base constant. The
518// question is which we can pick best? For example, consider these constants
519// and their number of uses:
520//
521// Constants| 2 | 4 | 12 | 42 |
522// NumUses | 3 | 2 | 8 | 7 |
523//
524// Selecting constant 12 because it has the most uses will generate negative
525// offsets for constants 2 and 4 (i.e. -10 and -8 respectively). If negative
526// offsets lead to less optimal code generation, then there might be better
527// solutions. Suppose immediates in the range of 0..35 are most optimally
528// supported by the architecture, then selecting constant 2 is most optimal
529// because this will generate offsets: 0, 2, 10, 40. Offsets 0, 2 and 10 are in
530// range 0..35, and thus 3 + 2 + 8 = 13 uses are in range. Selecting 12 would
531// have only 8 uses in range, so choosing 2 as a base is more optimal. Thus, in
532// selecting the base constant the range of the offsets is a very important
533// factor too that we take into account here. This algorithm calculates a total
534// costs for selecting a constant as the base and substract the costs if
535// immediates are out of range. It has quadratic complexity, so we call this
536// function only when we're optimising for size and there are less than 100
537// constants, we fall back to the straightforward algorithm otherwise
538// which does not do all the offset calculations.
539unsigned
540ConstantHoistingPass::maximizeConstantsInRange(ConstCandVecType::iterator S,
541 ConstCandVecType::iterator E,
542 ConstCandVecType::iterator &MaxCostItr) {
543 unsigned NumUses = 0;
544
545 if(!Entry->getParent()->optForSize() || std::distance(S,E) > 100) {
546 for (auto ConstCand = S; ConstCand != E; ++ConstCand) {
547 NumUses += ConstCand->Uses.size();
548 if (ConstCand->CumulativeCost > MaxCostItr->CumulativeCost)
549 MaxCostItr = ConstCand;
550 }
551 return NumUses;
552 }
553
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000554 LLVM_DEBUG(dbgs() << "== Maximize constants in range ==\n");
Sjoerd Meijer38c2cd02016-07-14 07:44:20 +0000555 int MaxCost = -1;
556 for (auto ConstCand = S; ConstCand != E; ++ConstCand) {
557 auto Value = ConstCand->ConstInt->getValue();
558 Type *Ty = ConstCand->ConstInt->getType();
559 int Cost = 0;
560 NumUses += ConstCand->Uses.size();
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000561 LLVM_DEBUG(dbgs() << "= Constant: " << ConstCand->ConstInt->getValue()
562 << "\n");
Sjoerd Meijer38c2cd02016-07-14 07:44:20 +0000563
564 for (auto User : ConstCand->Uses) {
565 unsigned Opcode = User.Inst->getOpcode();
566 unsigned OpndIdx = User.OpndIdx;
567 Cost += TTI->getIntImmCost(Opcode, OpndIdx, Value, Ty);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000568 LLVM_DEBUG(dbgs() << "Cost: " << Cost << "\n");
Sjoerd Meijer38c2cd02016-07-14 07:44:20 +0000569
570 for (auto C2 = S; C2 != E; ++C2) {
Eugene Zelenko8002c502017-09-13 21:43:53 +0000571 Optional<APInt> Diff = calculateOffsetDiff(
572 C2->ConstInt->getValue(),
573 ConstCand->ConstInt->getValue());
Sjoerd Meijer38c2cd02016-07-14 07:44:20 +0000574 if (Diff) {
575 const int ImmCosts =
576 TTI->getIntImmCodeSizeCost(Opcode, OpndIdx, Diff.getValue(), Ty);
577 Cost -= ImmCosts;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000578 LLVM_DEBUG(dbgs() << "Offset " << Diff.getValue() << " "
579 << "has penalty: " << ImmCosts << "\n"
580 << "Adjusted cost: " << Cost << "\n");
Sjoerd Meijer38c2cd02016-07-14 07:44:20 +0000581 }
582 }
583 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000584 LLVM_DEBUG(dbgs() << "Cumulative cost: " << Cost << "\n");
Sjoerd Meijer38c2cd02016-07-14 07:44:20 +0000585 if (Cost > MaxCost) {
586 MaxCost = Cost;
587 MaxCostItr = ConstCand;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000588 LLVM_DEBUG(dbgs() << "New candidate: " << MaxCostItr->ConstInt->getValue()
589 << "\n");
Sjoerd Meijer38c2cd02016-07-14 07:44:20 +0000590 }
591 }
592 return NumUses;
593}
594
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000595/// Find the base constant within the given range and rebase all other
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000596/// constants with respect to the base constant.
Michael Kuperstein071d8302016-07-02 00:16:47 +0000597void ConstantHoistingPass::findAndMakeBaseConstant(
Zhaoshi Zhenga0aa41d2018-09-04 22:17:03 +0000598 ConstCandVecType::iterator S, ConstCandVecType::iterator E,
599 SmallVectorImpl<consthoist::ConstantInfo> &ConstInfoVec) {
Juergen Ributzka5429c062014-03-21 06:04:36 +0000600 auto MaxCostItr = S;
Sjoerd Meijer38c2cd02016-07-14 07:44:20 +0000601 unsigned NumUses = maximizeConstantsInRange(S, E, MaxCostItr);
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000602
603 // Don't hoist constants that have only one use.
604 if (NumUses <= 1)
605 return;
606
Zhaoshi Zhenga0aa41d2018-09-04 22:17:03 +0000607 ConstantInt *ConstInt = MaxCostItr->ConstInt;
608 ConstantExpr *ConstExpr = MaxCostItr->ConstExpr;
Juergen Ributzka5429c062014-03-21 06:04:36 +0000609 ConstantInfo ConstInfo;
Zhaoshi Zhenga0aa41d2018-09-04 22:17:03 +0000610 ConstInfo.BaseInt = ConstInt;
611 ConstInfo.BaseExpr = ConstExpr;
612 Type *Ty = ConstInt->getType();
Juergen Ributzka5429c062014-03-21 06:04:36 +0000613
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000614 // Rebase the constants with respect to the base constant.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000615 for (auto ConstCand = S; ConstCand != E; ++ConstCand) {
Zhaoshi Zhenga0aa41d2018-09-04 22:17:03 +0000616 APInt Diff = ConstCand->ConstInt->getValue() - ConstInt->getValue();
Juergen Ributzka5429c062014-03-21 06:04:36 +0000617 Constant *Offset = Diff == 0 ? nullptr : ConstantInt::get(Ty, Diff);
Zhaoshi Zhenga0aa41d2018-09-04 22:17:03 +0000618 Type *ConstTy =
619 ConstCand->ConstExpr ? ConstCand->ConstExpr->getType() : nullptr;
Juergen Ributzka5429c062014-03-21 06:04:36 +0000620 ConstInfo.RebasedConstants.push_back(
Zhaoshi Zhenga0aa41d2018-09-04 22:17:03 +0000621 RebasedConstantInfo(std::move(ConstCand->Uses), Offset, ConstTy));
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000622 }
Zhaoshi Zhenga0aa41d2018-09-04 22:17:03 +0000623 ConstInfoVec.push_back(std::move(ConstInfo));
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000624}
625
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000626/// Finds and combines constant candidates that can be easily
Juergen Ributzka5429c062014-03-21 06:04:36 +0000627/// rematerialized with an add from a common base constant.
Zhaoshi Zhenga0aa41d2018-09-04 22:17:03 +0000628void ConstantHoistingPass::findBaseConstants(GlobalVariable *BaseGV) {
629 // If BaseGV is nullptr, find base among candidate constant integers;
630 // Otherwise find base among constant GEPs that share the same BaseGV.
631 ConstCandVecType &ConstCandVec = BaseGV ?
632 ConstGEPCandMap[BaseGV] : ConstIntCandVec;
633 ConstInfoVecType &ConstInfoVec = BaseGV ?
634 ConstGEPInfoMap[BaseGV] : ConstIntInfoVec;
635
Juergen Ributzka5429c062014-03-21 06:04:36 +0000636 // Sort the constants by value and type. This invalidates the mapping!
Zhaoshi Zhenga0aa41d2018-09-04 22:17:03 +0000637 std::stable_sort(ConstCandVec.begin(), ConstCandVec.end(),
Mandeep Singh Grang636d94d2018-04-13 19:47:57 +0000638 [](const ConstantCandidate &LHS, const ConstantCandidate &RHS) {
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +0000639 if (LHS.ConstInt->getType() != RHS.ConstInt->getType())
640 return LHS.ConstInt->getType()->getBitWidth() <
641 RHS.ConstInt->getType()->getBitWidth();
642 return LHS.ConstInt->getValue().ult(RHS.ConstInt->getValue());
Juergen Ributzka46357932014-03-20 20:17:13 +0000643 });
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000644
Juergen Ributzka5429c062014-03-21 06:04:36 +0000645 // Simple linear scan through the sorted constant candidate vector for viable
646 // merge candidates.
647 auto MinValItr = ConstCandVec.begin();
648 for (auto CC = std::next(ConstCandVec.begin()), E = ConstCandVec.end();
649 CC != E; ++CC) {
650 if (MinValItr->ConstInt->getType() == CC->ConstInt->getType()) {
Zhaoshi Zheng35818e22018-08-28 23:00:59 +0000651 Type *MemUseValTy = nullptr;
652 for (auto &U : CC->Uses) {
653 auto *UI = U.Inst;
654 if (LoadInst *LI = dyn_cast<LoadInst>(UI)) {
655 MemUseValTy = LI->getType();
656 break;
657 } else if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
658 // Make sure the constant is used as pointer operand of the StoreInst.
659 if (SI->getPointerOperand() == SI->getOperand(U.OpndIdx)) {
660 MemUseValTy = SI->getValueOperand()->getType();
661 break;
662 }
663 }
664 }
665
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000666 // Check if the constant is in range of an add with immediate.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000667 APInt Diff = CC->ConstInt->getValue() - MinValItr->ConstInt->getValue();
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000668 if ((Diff.getBitWidth() <= 64) &&
Zhaoshi Zheng35818e22018-08-28 23:00:59 +0000669 TTI->isLegalAddImmediate(Diff.getSExtValue()) &&
670 // Check if Diff can be used as offset in addressing mode of the user
671 // memory instruction.
672 (!MemUseValTy || TTI->isLegalAddressingMode(MemUseValTy,
673 /*BaseGV*/nullptr, /*BaseOffset*/Diff.getSExtValue(),
674 /*HasBaseReg*/true, /*Scale*/0)))
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000675 continue;
676 }
677 // We either have now a different constant type or the constant is not in
678 // range of an add with immediate anymore.
Zhaoshi Zhenga0aa41d2018-09-04 22:17:03 +0000679 findAndMakeBaseConstant(MinValItr, CC, ConstInfoVec);
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000680 // Start a new base constant search.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000681 MinValItr = CC;
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000682 }
683 // Finalize the last base constant search.
Zhaoshi Zhenga0aa41d2018-09-04 22:17:03 +0000684 findAndMakeBaseConstant(MinValItr, ConstCandVec.end(), ConstInfoVec);
Juergen Ributzka46357932014-03-20 20:17:13 +0000685}
686
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000687/// Updates the operand at Idx in instruction Inst with the result of
Juergen Ributzkae802d502014-03-22 01:49:27 +0000688/// instruction Mat. If the instruction is a PHI node then special
Simon Pilgrim7d18a702016-11-20 13:19:49 +0000689/// handling for duplicate values form the same incoming basic block is
Juergen Ributzkae802d502014-03-22 01:49:27 +0000690/// required.
691/// \return The update will always succeed, but the return value indicated if
692/// Mat was used for the update or not.
693static bool updateOperand(Instruction *Inst, unsigned Idx, Instruction *Mat) {
694 if (auto PHI = dyn_cast<PHINode>(Inst)) {
695 // Check if any previous operand of the PHI node has the same incoming basic
696 // block. This is a very odd case that happens when the incoming basic block
697 // has a switch statement. In this case use the same value as the previous
698 // operand(s), otherwise we will fail verification due to different values.
699 // The values are actually the same, but the variable names are different
700 // and the verifier doesn't like that.
701 BasicBlock *IncomingBB = PHI->getIncomingBlock(Idx);
702 for (unsigned i = 0; i < Idx; ++i) {
703 if (PHI->getIncomingBlock(i) == IncomingBB) {
704 Value *IncomingVal = PHI->getIncomingValue(i);
705 Inst->setOperand(Idx, IncomingVal);
706 return false;
707 }
708 }
709 }
710
711 Inst->setOperand(Idx, Mat);
712 return true;
713}
714
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000715/// Emit materialization code for all rebased constants and update their
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000716/// users.
Michael Kuperstein071d8302016-07-02 00:16:47 +0000717void ConstantHoistingPass::emitBaseConstants(Instruction *Base,
718 Constant *Offset,
Zhaoshi Zhenga0aa41d2018-09-04 22:17:03 +0000719 Type *Ty,
Michael Kuperstein071d8302016-07-02 00:16:47 +0000720 const ConstantUser &ConstUser) {
Juergen Ributzka5429c062014-03-21 06:04:36 +0000721 Instruction *Mat = Base;
Zhaoshi Zhenga0aa41d2018-09-04 22:17:03 +0000722
723 // The same offset can be dereferenced to different types in nested struct.
724 if (!Offset && Ty && Ty != Base->getType())
725 Offset = ConstantInt::get(Type::getInt32Ty(*Ctx), 0);
726
Juergen Ributzka5429c062014-03-21 06:04:36 +0000727 if (Offset) {
728 Instruction *InsertionPt = findMatInsertPt(ConstUser.Inst,
729 ConstUser.OpndIdx);
Zhaoshi Zhenga0aa41d2018-09-04 22:17:03 +0000730 if (Ty) {
731 // Constant being rebased is a ConstantExpr.
732 PointerType *Int8PtrTy = Type::getInt8PtrTy(*Ctx,
733 cast<PointerType>(Ty)->getAddressSpace());
734 Base = new BitCastInst(Base, Int8PtrTy, "base_bitcast", InsertionPt);
735 Mat = GetElementPtrInst::Create(Int8PtrTy->getElementType(), Base,
736 Offset, "mat_gep", InsertionPt);
737 Mat = new BitCastInst(Mat, Ty, "mat_bitcast", InsertionPt);
738 } else
739 // Constant being rebased is a ConstantInt.
740 Mat = BinaryOperator::Create(Instruction::Add, Base, Offset,
Juergen Ributzka5429c062014-03-21 06:04:36 +0000741 "const_mat", InsertionPt);
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000742
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000743 LLVM_DEBUG(dbgs() << "Materialize constant (" << *Base->getOperand(0)
744 << " + " << *Offset << ") in BB "
745 << Mat->getParent()->getName() << '\n'
746 << *Mat << '\n');
Juergen Ributzka5429c062014-03-21 06:04:36 +0000747 Mat->setDebugLoc(ConstUser.Inst->getDebugLoc());
748 }
749 Value *Opnd = ConstUser.Inst->getOperand(ConstUser.OpndIdx);
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000750
Juergen Ributzka5429c062014-03-21 06:04:36 +0000751 // Visit constant integer.
752 if (isa<ConstantInt>(Opnd)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000753 LLVM_DEBUG(dbgs() << "Update: " << *ConstUser.Inst << '\n');
Juergen Ributzkae802d502014-03-22 01:49:27 +0000754 if (!updateOperand(ConstUser.Inst, ConstUser.OpndIdx, Mat) && Offset)
755 Mat->eraseFromParent();
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000756 LLVM_DEBUG(dbgs() << "To : " << *ConstUser.Inst << '\n');
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000757 return;
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000758 }
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000759
Juergen Ributzka5429c062014-03-21 06:04:36 +0000760 // Visit cast instruction.
761 if (auto CastInst = dyn_cast<Instruction>(Opnd)) {
762 assert(CastInst->isCast() && "Expected an cast instruction!");
763 // Check if we already have visited this cast instruction before to avoid
764 // unnecessary cloning.
765 Instruction *&ClonedCastInst = ClonedCastMap[CastInst];
766 if (!ClonedCastInst) {
767 ClonedCastInst = CastInst->clone();
768 ClonedCastInst->setOperand(0, Mat);
769 ClonedCastInst->insertAfter(CastInst);
770 // Use the same debug location as the original cast instruction.
771 ClonedCastInst->setDebugLoc(CastInst->getDebugLoc());
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000772 LLVM_DEBUG(dbgs() << "Clone instruction: " << *CastInst << '\n'
773 << "To : " << *ClonedCastInst << '\n');
Juergen Ributzka46357932014-03-20 20:17:13 +0000774 }
Juergen Ributzka5429c062014-03-21 06:04:36 +0000775
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000776 LLVM_DEBUG(dbgs() << "Update: " << *ConstUser.Inst << '\n');
Juergen Ributzkae802d502014-03-22 01:49:27 +0000777 updateOperand(ConstUser.Inst, ConstUser.OpndIdx, ClonedCastInst);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000778 LLVM_DEBUG(dbgs() << "To : " << *ConstUser.Inst << '\n');
Juergen Ributzka5429c062014-03-21 06:04:36 +0000779 return;
Juergen Ributzka46357932014-03-20 20:17:13 +0000780 }
Juergen Ributzka5429c062014-03-21 06:04:36 +0000781
782 // Visit constant expression.
783 if (auto ConstExpr = dyn_cast<ConstantExpr>(Opnd)) {
Zhaoshi Zhenga0aa41d2018-09-04 22:17:03 +0000784 if (ConstExpr->isGEPWithNoNotionalOverIndexing()) {
785 // Operand is a ConstantGEP, replace it.
786 updateOperand(ConstUser.Inst, ConstUser.OpndIdx, Mat);
787 return;
788 }
789
790 // Aside from constant GEPs, only constant cast expressions are collected.
791 assert(ConstExpr->isCast() && "ConstExpr should be a cast");
Juergen Ributzka5429c062014-03-21 06:04:36 +0000792 Instruction *ConstExprInst = ConstExpr->getAsInstruction();
793 ConstExprInst->setOperand(0, Mat);
794 ConstExprInst->insertBefore(findMatInsertPt(ConstUser.Inst,
795 ConstUser.OpndIdx));
796
797 // Use the same debug location as the instruction we are about to update.
798 ConstExprInst->setDebugLoc(ConstUser.Inst->getDebugLoc());
799
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000800 LLVM_DEBUG(dbgs() << "Create instruction: " << *ConstExprInst << '\n'
801 << "From : " << *ConstExpr << '\n');
802 LLVM_DEBUG(dbgs() << "Update: " << *ConstUser.Inst << '\n');
Juergen Ributzkae802d502014-03-22 01:49:27 +0000803 if (!updateOperand(ConstUser.Inst, ConstUser.OpndIdx, ConstExprInst)) {
804 ConstExprInst->eraseFromParent();
805 if (Offset)
806 Mat->eraseFromParent();
807 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000808 LLVM_DEBUG(dbgs() << "To : " << *ConstUser.Inst << '\n');
Juergen Ributzka5429c062014-03-21 06:04:36 +0000809 return;
Juergen Ributzka4c8a0252014-02-08 00:20:45 +0000810 }
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000811}
812
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000813/// Hoist and hide the base constant behind a bitcast and emit
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000814/// materialization code for derived constants.
Zhaoshi Zhenga0aa41d2018-09-04 22:17:03 +0000815bool ConstantHoistingPass::emitBaseConstants(GlobalVariable *BaseGV) {
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000816 bool MadeChange = false;
Zhaoshi Zhenga0aa41d2018-09-04 22:17:03 +0000817 SmallVectorImpl<consthoist::ConstantInfo> &ConstInfoVec =
818 BaseGV ? ConstGEPInfoMap[BaseGV] : ConstIntInfoVec;
819 for (auto const &ConstInfo : ConstInfoVec) {
Wei Mi337d4d92017-04-21 15:50:16 +0000820 SmallPtrSet<Instruction *, 8> IPSet = findConstantInsertionPoint(ConstInfo);
821 assert(!IPSet.empty() && "IPSet is empty");
822
823 unsigned UsesNum = 0;
824 unsigned ReBasesNum = 0;
825 for (Instruction *IP : IPSet) {
Zhaoshi Zhenga0aa41d2018-09-04 22:17:03 +0000826 Instruction *Base = nullptr;
827 // Hoist and hide the base constant behind a bitcast.
828 if (ConstInfo.BaseExpr) {
829 assert(BaseGV && "A base constant expression must have an base GV");
830 Type *Ty = ConstInfo.BaseExpr->getType();
831 Base = new BitCastInst(ConstInfo.BaseExpr, Ty, "const", IP);
832 } else {
833 IntegerType *Ty = ConstInfo.BaseInt->getType();
834 Base = new BitCastInst(ConstInfo.BaseInt, Ty, "const", IP);
835 }
Paul Robinsonb46256b2017-11-09 20:01:31 +0000836
837 Base->setDebugLoc(IP->getDebugLoc());
838
Zhaoshi Zhenga0aa41d2018-09-04 22:17:03 +0000839 LLVM_DEBUG(dbgs() << "Hoist constant (" << *ConstInfo.BaseInt
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000840 << ") to BB " << IP->getParent()->getName() << '\n'
841 << *Base << '\n');
Wei Mi337d4d92017-04-21 15:50:16 +0000842
Jessica Paquettee02de052018-09-25 18:41:40 +0000843 // Emit materialization code for all rebased constants.
844 unsigned Uses = 0;
845 for (auto const &RCI : ConstInfo.RebasedConstants) {
846 for (auto const &U : RCI.Uses) {
847 Uses++;
848 BasicBlock *OrigMatInsertBB =
849 findMatInsertPt(U.Inst, U.OpndIdx)->getParent();
850 // If Base constant is to be inserted in multiple places,
851 // generate rebase for U using the Base dominating U.
852 if (IPSet.size() == 1 ||
853 DT->dominates(Base->getParent(), OrigMatInsertBB)) {
854 emitBaseConstants(Base, RCI.Offset, RCI.Ty, U);
855 ReBasesNum++;
856 }
857
858 Base->setDebugLoc(DILocation::getMergedLocation(
859 Base->getDebugLoc(), U.Inst->getDebugLoc()));
860 }
Wei Mi337d4d92017-04-21 15:50:16 +0000861 }
Jessica Paquettee02de052018-09-25 18:41:40 +0000862 UsesNum = Uses;
863
864 // Use the same debug location as the last user of the constant.
Wei Mi337d4d92017-04-21 15:50:16 +0000865 assert(!Base->use_empty() && "The use list is empty!?");
866 assert(isa<Instruction>(Base->user_back()) &&
867 "All uses should be instructions.");
Wei Mi337d4d92017-04-21 15:50:16 +0000868 }
869 (void)UsesNum;
870 (void)ReBasesNum;
871 // Expect all uses are rebased after rebase is done.
Jessica Paquettee02de052018-09-25 18:41:40 +0000872 assert(UsesNum == ReBasesNum && "Not all uses are rebased");
Wei Mi337d4d92017-04-21 15:50:16 +0000873
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000874 NumConstantsHoisted++;
875
Wei Mi337d4d92017-04-21 15:50:16 +0000876 // Base constant is also included in ConstInfo.RebasedConstants, so
877 // deduct 1 from ConstInfo.RebasedConstants.size().
Zhaoshi Zhenga0aa41d2018-09-04 22:17:03 +0000878 NumConstantsRebased += ConstInfo.RebasedConstants.size() - 1;
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000879
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000880 MadeChange = true;
881 }
882 return MadeChange;
883}
884
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000885/// Check all cast instructions we made a copy of and remove them if they
Juergen Ributzka5429c062014-03-21 06:04:36 +0000886/// have no more users.
Michael Kuperstein071d8302016-07-02 00:16:47 +0000887void ConstantHoistingPass::deleteDeadCastInst() const {
Juergen Ributzka5429c062014-03-21 06:04:36 +0000888 for (auto const &I : ClonedCastMap)
889 if (I.first->use_empty())
Juergen Ributzkae4747522014-03-22 01:49:30 +0000890 I.first->eraseFromParent();
Juergen Ributzka5429c062014-03-21 06:04:36 +0000891}
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000892
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000893/// Optimize expensive integer constants in the given function.
Michael Kuperstein071d8302016-07-02 00:16:47 +0000894bool ConstantHoistingPass::runImpl(Function &Fn, TargetTransformInfo &TTI,
Wei Mi337d4d92017-04-21 15:50:16 +0000895 DominatorTree &DT, BlockFrequencyInfo *BFI,
896 BasicBlock &Entry) {
Michael Kuperstein071d8302016-07-02 00:16:47 +0000897 this->TTI = &TTI;
898 this->DT = &DT;
Wei Mi337d4d92017-04-21 15:50:16 +0000899 this->BFI = BFI;
Zhaoshi Zhenga0aa41d2018-09-04 22:17:03 +0000900 this->DL = &Fn.getParent()->getDataLayout();
901 this->Ctx = &Fn.getContext();
Fangrui Songf78650a2018-07-30 19:41:25 +0000902 this->Entry = &Entry;
Juergen Ributzka46357932014-03-20 20:17:13 +0000903 // Collect all constant candidates.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000904 collectConstantCandidates(Fn);
Juergen Ributzka46357932014-03-20 20:17:13 +0000905
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000906 // Combine constants that can be easily materialized with an add from a common
907 // base constant.
Zhaoshi Zhenga0aa41d2018-09-04 22:17:03 +0000908 if (!ConstIntCandVec.empty())
909 findBaseConstants(nullptr);
910 for (auto &MapEntry : ConstGEPCandMap)
911 if (!MapEntry.second.empty())
912 findBaseConstants(MapEntry.first);
Juergen Ributzka5429c062014-03-21 06:04:36 +0000913
Juergen Ributzkaf0dff492014-03-21 06:04:45 +0000914 // Finally hoist the base constant and emit materialization code for dependent
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000915 // constants.
Zhaoshi Zhenga0aa41d2018-09-04 22:17:03 +0000916 bool MadeChange = false;
917 if (!ConstIntInfoVec.empty())
918 MadeChange = emitBaseConstants(nullptr);
919 for (auto MapEntry : ConstGEPInfoMap)
920 if (!MapEntry.second.empty())
921 MadeChange |= emitBaseConstants(MapEntry.first);
922
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000923
Juergen Ributzka5429c062014-03-21 06:04:36 +0000924 // Cleanup dead instructions.
925 deleteDeadCastInst();
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000926
927 return MadeChange;
928}
Michael Kuperstein071d8302016-07-02 00:16:47 +0000929
930PreservedAnalyses ConstantHoistingPass::run(Function &F,
931 FunctionAnalysisManager &AM) {
932 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
933 auto &TTI = AM.getResult<TargetIRAnalysis>(F);
Wei Mi337d4d92017-04-21 15:50:16 +0000934 auto BFI = ConstHoistWithBlockFrequency
935 ? &AM.getResult<BlockFrequencyAnalysis>(F)
936 : nullptr;
937 if (!runImpl(F, TTI, DT, BFI, F.getEntryBlock()))
Michael Kuperstein071d8302016-07-02 00:16:47 +0000938 return PreservedAnalyses::all();
939
Chandler Carruthca68a3e2017-01-15 06:32:49 +0000940 PreservedAnalyses PA;
941 PA.preserveSet<CFGAnalyses>();
942 return PA;
Michael Kuperstein071d8302016-07-02 00:16:47 +0000943}