blob: 1da95bfb9a8d6f9ed56bb7f7b3e33927c06d85d6 [file] [log] [blame]
Eugene Zelenko96d933d2017-07-25 23:51:02 +00001//==- AArch64PromoteConstant.cpp - Promote constant to global for AArch64 --==//
Tim Northover3b0846e2014-05-24 12:50:23 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Tim Northover3b0846e2014-05-24 12:50:23 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the AArch64PromoteConstant pass which promotes constants
10// to global variables when this is likely to be more efficient. Currently only
11// types related to constant vector (i.e., constant vector, array of constant
12// vectors, constant structure with a constant vector field, etc.) are promoted
13// to global variables. Constant vectors are likely to be lowered in target
14// constant pool during instruction selection already; therefore, the access
15// will remain the same (memory load), but the structure types are not split
16// into different constant pool accesses for each field. A bonus side effect is
17// that created globals may be merged by the global merge pass.
18//
19// FIXME: This pass may be useful for other targets too.
20//===----------------------------------------------------------------------===//
21
22#include "AArch64.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000023#include "llvm/ADT/DenseMap.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000024#include "llvm/ADT/SmallVector.h"
Benjamin Kramer1f8930e2014-07-25 11:42:14 +000025#include "llvm/ADT/Statistic.h"
Eugene Zelenko96d933d2017-07-25 23:51:02 +000026#include "llvm/IR/BasicBlock.h"
27#include "llvm/IR/Constant.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000028#include "llvm/IR/Constants.h"
29#include "llvm/IR/Dominators.h"
30#include "llvm/IR/Function.h"
Eugene Zelenko96d933d2017-07-25 23:51:02 +000031#include "llvm/IR/GlobalValue.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000032#include "llvm/IR/GlobalVariable.h"
Benjamin Kramer1f8930e2014-07-25 11:42:14 +000033#include "llvm/IR/IRBuilder.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000034#include "llvm/IR/InlineAsm.h"
Benjamin Kramer69b4ad22015-02-06 14:43:55 +000035#include "llvm/IR/InstIterator.h"
Eugene Zelenko96d933d2017-07-25 23:51:02 +000036#include "llvm/IR/Instruction.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000037#include "llvm/IR/Instructions.h"
38#include "llvm/IR/IntrinsicInst.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000039#include "llvm/IR/Module.h"
Eugene Zelenko96d933d2017-07-25 23:51:02 +000040#include "llvm/IR/Type.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000041#include "llvm/Pass.h"
Eugene Zelenko96d933d2017-07-25 23:51:02 +000042#include "llvm/Support/Casting.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000043#include "llvm/Support/CommandLine.h"
44#include "llvm/Support/Debug.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000045#include "llvm/Support/raw_ostream.h"
Eugene Zelenko96d933d2017-07-25 23:51:02 +000046#include <algorithm>
47#include <cassert>
48#include <utility>
Tim Northover3b0846e2014-05-24 12:50:23 +000049
50using namespace llvm;
51
52#define DEBUG_TYPE "aarch64-promote-const"
53
54// Stress testing mode - disable heuristics.
55static cl::opt<bool> Stress("aarch64-stress-promote-const", cl::Hidden,
56 cl::desc("Promote all vector constants"));
57
58STATISTIC(NumPromoted, "Number of promoted constants");
59STATISTIC(NumPromotedUses, "Number of promoted constants uses");
60
61//===----------------------------------------------------------------------===//
62// AArch64PromoteConstant
63//===----------------------------------------------------------------------===//
64
65namespace {
Eugene Zelenko96d933d2017-07-25 23:51:02 +000066
Tim Northover3b0846e2014-05-24 12:50:23 +000067/// Promotes interesting constant into global variables.
68/// The motivating example is:
69/// static const uint16_t TableA[32] = {
70/// 41944, 40330, 38837, 37450, 36158, 34953, 33826, 32768,
71/// 31776, 30841, 29960, 29128, 28340, 27595, 26887, 26215,
72/// 25576, 24967, 24386, 23832, 23302, 22796, 22311, 21846,
73/// 21400, 20972, 20561, 20165, 19785, 19419, 19066, 18725,
74/// };
75///
76/// uint8x16x4_t LoadStatic(void) {
77/// uint8x16x4_t ret;
78/// ret.val[0] = vld1q_u16(TableA + 0);
79/// ret.val[1] = vld1q_u16(TableA + 8);
80/// ret.val[2] = vld1q_u16(TableA + 16);
81/// ret.val[3] = vld1q_u16(TableA + 24);
82/// return ret;
83/// }
84///
85/// The constants in this example are folded into the uses. Thus, 4 different
86/// constants are created.
87///
88/// As their type is vector the cheapest way to create them is to load them
89/// for the memory.
90///
91/// Therefore the final assembly final has 4 different loads. With this pass
92/// enabled, only one load is issued for the constants.
93class AArch64PromoteConstant : public ModulePass {
Tim Northover3b0846e2014-05-24 12:50:23 +000094public:
Duncan P. N. Exon Smithc3fa1ed2016-03-18 23:30:54 +000095 struct PromotedConstant {
96 bool ShouldConvert = false;
97 GlobalVariable *GV = nullptr;
98 };
Eugene Zelenko96d933d2017-07-25 23:51:02 +000099 using PromotionCacheTy = SmallDenseMap<Constant *, PromotedConstant, 16>;
Duncan P. N. Exon Smithc3fa1ed2016-03-18 23:30:54 +0000100
101 struct UpdateRecord {
102 Constant *C;
103 Instruction *User;
104 unsigned Op;
105
106 UpdateRecord(Constant *C, Instruction *User, unsigned Op)
107 : C(C), User(User), Op(Op) {}
108 };
109
Tim Northover3b0846e2014-05-24 12:50:23 +0000110 static char ID;
Eugene Zelenko96d933d2017-07-25 23:51:02 +0000111
Diana Picus850043b2016-08-01 05:56:57 +0000112 AArch64PromoteConstant() : ModulePass(ID) {
113 initializeAArch64PromoteConstantPass(*PassRegistry::getPassRegistry());
114 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000115
Mehdi Amini117296c2016-10-01 02:56:57 +0000116 StringRef getPassName() const override { return "AArch64 Promote Constant"; }
Tim Northover3b0846e2014-05-24 12:50:23 +0000117
118 /// Iterate over the functions and promote the interesting constants into
119 /// global variables with module scope.
120 bool runOnModule(Module &M) override {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000121 LLVM_DEBUG(dbgs() << getPassName() << '\n');
Andrew Kaylor1ac98bb2016-04-25 21:58:52 +0000122 if (skipModule(M))
123 return false;
Tim Northover3b0846e2014-05-24 12:50:23 +0000124 bool Changed = false;
Duncan P. N. Exon Smithc3fa1ed2016-03-18 23:30:54 +0000125 PromotionCacheTy PromotionCache;
Tim Northover3b0846e2014-05-24 12:50:23 +0000126 for (auto &MF : M) {
Duncan P. N. Exon Smithc3fa1ed2016-03-18 23:30:54 +0000127 Changed |= runOnFunction(MF, PromotionCache);
Tim Northover3b0846e2014-05-24 12:50:23 +0000128 }
129 return Changed;
130 }
131
132private:
133 /// Look for interesting constants used within the given function.
134 /// Promote them into global variables, load these global variables within
135 /// the related function, so that the number of inserted load is minimal.
Duncan P. N. Exon Smithc3fa1ed2016-03-18 23:30:54 +0000136 bool runOnFunction(Function &F, PromotionCacheTy &PromotionCache);
Tim Northover3b0846e2014-05-24 12:50:23 +0000137
138 // This transformation requires dominator info
139 void getAnalysisUsage(AnalysisUsage &AU) const override {
140 AU.setPreservesCFG();
141 AU.addRequired<DominatorTreeWrapperPass>();
142 AU.addPreserved<DominatorTreeWrapperPass>();
143 }
144
Benjamin Kramer69b4ad22015-02-06 14:43:55 +0000145 /// Type to store a list of Uses.
Eugene Zelenko96d933d2017-07-25 23:51:02 +0000146 using Uses = SmallVector<std::pair<Instruction *, unsigned>, 4>;
Tim Northover3b0846e2014-05-24 12:50:23 +0000147 /// Map an insertion point to all the uses it dominates.
Eugene Zelenko96d933d2017-07-25 23:51:02 +0000148 using InsertionPoints = DenseMap<Instruction *, Uses>;
Tim Northover3b0846e2014-05-24 12:50:23 +0000149
150 /// Find the closest point that dominates the given Use.
Duncan P. N. Exon Smithc3fa1ed2016-03-18 23:30:54 +0000151 Instruction *findInsertionPoint(Instruction &User, unsigned OpNo);
Tim Northover3b0846e2014-05-24 12:50:23 +0000152
153 /// Check if the given insertion point is dominated by an existing
154 /// insertion point.
155 /// If true, the given use is added to the list of dominated uses for
156 /// the related existing point.
157 /// \param NewPt the insertion point to be checked
Duncan P. N. Exon Smith20be8762016-03-21 22:13:44 +0000158 /// \param User the user of the constant
159 /// \param OpNo the operand number of the use
Tim Northover3b0846e2014-05-24 12:50:23 +0000160 /// \param InsertPts existing insertion points
161 /// \pre NewPt and all instruction in InsertPts belong to the same function
162 /// \return true if one of the insertion point in InsertPts dominates NewPt,
163 /// false otherwise
Duncan P. N. Exon Smithc3fa1ed2016-03-18 23:30:54 +0000164 bool isDominated(Instruction *NewPt, Instruction *User, unsigned OpNo,
165 InsertionPoints &InsertPts);
Tim Northover3b0846e2014-05-24 12:50:23 +0000166
167 /// Check if the given insertion point can be merged with an existing
168 /// insertion point in a common dominator.
169 /// If true, the given use is added to the list of the created insertion
170 /// point.
171 /// \param NewPt the insertion point to be checked
Duncan P. N. Exon Smith20be8762016-03-21 22:13:44 +0000172 /// \param User the user of the constant
173 /// \param OpNo the operand number of the use
Tim Northover3b0846e2014-05-24 12:50:23 +0000174 /// \param InsertPts existing insertion points
175 /// \pre NewPt and all instruction in InsertPts belong to the same function
176 /// \pre isDominated returns false for the exact same parameters.
177 /// \return true if it exists an insertion point in InsertPts that could
178 /// have been merged with NewPt in a common dominator,
179 /// false otherwise
Duncan P. N. Exon Smithc3fa1ed2016-03-18 23:30:54 +0000180 bool tryAndMerge(Instruction *NewPt, Instruction *User, unsigned OpNo,
181 InsertionPoints &InsertPts);
Tim Northover3b0846e2014-05-24 12:50:23 +0000182
183 /// Compute the minimal insertion points to dominates all the interesting
184 /// uses of value.
185 /// Insertion points are group per function and each insertion point
186 /// contains a list of all the uses it dominates within the related function
Duncan P. N. Exon Smith20be8762016-03-21 22:13:44 +0000187 /// \param User the user of the constant
188 /// \param OpNo the operand number of the constant
189 /// \param[out] InsertPts output storage of the analysis
Duncan P. N. Exon Smithc3fa1ed2016-03-18 23:30:54 +0000190 void computeInsertionPoint(Instruction *User, unsigned OpNo,
191 InsertionPoints &InsertPts);
Tim Northover3b0846e2014-05-24 12:50:23 +0000192
193 /// Insert a definition of a new global variable at each point contained in
194 /// InsPtsPerFunc and update the related uses (also contained in
195 /// InsPtsPerFunc).
Duncan P. N. Exon Smithc3fa1ed2016-03-18 23:30:54 +0000196 void insertDefinitions(Function &F, GlobalVariable &GV,
197 InsertionPoints &InsertPts);
Tim Northover3b0846e2014-05-24 12:50:23 +0000198
Duncan P. N. Exon Smithc3fa1ed2016-03-18 23:30:54 +0000199 /// Do the constant promotion indicated by the Updates records, keeping track
200 /// of globals in PromotionCache.
201 void promoteConstants(Function &F, SmallVectorImpl<UpdateRecord> &Updates,
202 PromotionCacheTy &PromotionCache);
Tim Northover3b0846e2014-05-24 12:50:23 +0000203
204 /// Transfer the list of dominated uses of IPI to NewPt in InsertPts.
Benjamin Kramer69b4ad22015-02-06 14:43:55 +0000205 /// Append Use to this list and delete the entry of IPI in InsertPts.
Duncan P. N. Exon Smithc3fa1ed2016-03-18 23:30:54 +0000206 static void appendAndTransferDominatedUses(Instruction *NewPt,
207 Instruction *User, unsigned OpNo,
Tim Northover3b0846e2014-05-24 12:50:23 +0000208 InsertionPoints::iterator &IPI,
209 InsertionPoints &InsertPts) {
210 // Record the dominated use.
Duncan P. N. Exon Smithc3fa1ed2016-03-18 23:30:54 +0000211 IPI->second.emplace_back(User, OpNo);
Tim Northover3b0846e2014-05-24 12:50:23 +0000212 // Transfer the dominated uses of IPI to NewPt
213 // Inserting into the DenseMap may invalidate existing iterator.
Sanjoy Dase5d14662015-03-02 00:17:18 +0000214 // Keep a copy of the key to find the iterator to erase. Keep a copy of the
215 // value so that we don't have to dereference IPI->second.
Tim Northover3b0846e2014-05-24 12:50:23 +0000216 Instruction *OldInstr = IPI->first;
Sanjoy Dase5d14662015-03-02 00:17:18 +0000217 Uses OldUses = std::move(IPI->second);
218 InsertPts[NewPt] = std::move(OldUses);
Tim Northover3b0846e2014-05-24 12:50:23 +0000219 // Erase IPI.
Benjamin Kramer69b4ad22015-02-06 14:43:55 +0000220 InsertPts.erase(OldInstr);
Tim Northover3b0846e2014-05-24 12:50:23 +0000221 }
222};
Eugene Zelenko96d933d2017-07-25 23:51:02 +0000223
Tim Northover3b0846e2014-05-24 12:50:23 +0000224} // end anonymous namespace
225
226char AArch64PromoteConstant::ID = 0;
227
Tim Northover3b0846e2014-05-24 12:50:23 +0000228INITIALIZE_PASS_BEGIN(AArch64PromoteConstant, "aarch64-promote-const",
229 "AArch64 Promote Constant Pass", false, false)
230INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
231INITIALIZE_PASS_END(AArch64PromoteConstant, "aarch64-promote-const",
232 "AArch64 Promote Constant Pass", false, false)
233
234ModulePass *llvm::createAArch64PromoteConstantPass() {
235 return new AArch64PromoteConstant();
236}
237
238/// Check if the given type uses a vector type.
239static bool isConstantUsingVectorTy(const Type *CstTy) {
240 if (CstTy->isVectorTy())
241 return true;
242 if (CstTy->isStructTy()) {
243 for (unsigned EltIdx = 0, EndEltIdx = CstTy->getStructNumElements();
244 EltIdx < EndEltIdx; ++EltIdx)
245 if (isConstantUsingVectorTy(CstTy->getStructElementType(EltIdx)))
246 return true;
247 } else if (CstTy->isArrayTy())
248 return isConstantUsingVectorTy(CstTy->getArrayElementType());
249 return false;
250}
251
252/// Check if the given use (Instruction + OpIdx) of Cst should be converted into
253/// a load of a global variable initialized with Cst.
254/// A use should be converted if it is legal to do so.
255/// For instance, it is not legal to turn the mask operand of a shuffle vector
256/// into a load of a global variable.
257static bool shouldConvertUse(const Constant *Cst, const Instruction *Instr,
258 unsigned OpIdx) {
259 // shufflevector instruction expects a const for the mask argument, i.e., the
260 // third argument. Do not promote this use in that case.
261 if (isa<const ShuffleVectorInst>(Instr) && OpIdx == 2)
262 return false;
263
264 // extractvalue instruction expects a const idx.
265 if (isa<const ExtractValueInst>(Instr) && OpIdx > 0)
266 return false;
267
268 // extractvalue instruction expects a const idx.
269 if (isa<const InsertValueInst>(Instr) && OpIdx > 1)
270 return false;
271
272 if (isa<const AllocaInst>(Instr) && OpIdx > 0)
273 return false;
274
275 // Alignment argument must be constant.
276 if (isa<const LoadInst>(Instr) && OpIdx > 0)
277 return false;
278
279 // Alignment argument must be constant.
280 if (isa<const StoreInst>(Instr) && OpIdx > 1)
281 return false;
282
283 // Index must be constant.
284 if (isa<const GetElementPtrInst>(Instr) && OpIdx > 0)
285 return false;
286
287 // Personality function and filters must be constant.
288 // Give up on that instruction.
289 if (isa<const LandingPadInst>(Instr))
290 return false;
291
292 // Switch instruction expects constants to compare to.
293 if (isa<const SwitchInst>(Instr))
294 return false;
295
296 // Expected address must be a constant.
297 if (isa<const IndirectBrInst>(Instr))
298 return false;
299
300 // Do not mess with intrinsics.
301 if (isa<const IntrinsicInst>(Instr))
302 return false;
303
304 // Do not mess with inline asm.
305 const CallInst *CI = dyn_cast<const CallInst>(Instr);
Eric Christopher114fa1c2016-02-29 22:50:49 +0000306 return !(CI && isa<const InlineAsm>(CI->getCalledValue()));
Tim Northover3b0846e2014-05-24 12:50:23 +0000307}
308
309/// Check if the given Cst should be converted into
310/// a load of a global variable initialized with Cst.
311/// A constant should be converted if it is likely that the materialization of
312/// the constant will be tricky. Thus, we give up on zero or undef values.
313///
314/// \todo Currently, accept only vector related types.
315/// Also we give up on all simple vector type to keep the existing
316/// behavior. Otherwise, we should push here all the check of the lowering of
317/// BUILD_VECTOR. By giving up, we lose the potential benefit of merging
318/// constant via global merge and the fact that the same constant is stored
319/// only once with this method (versus, as many function that uses the constant
320/// for the regular approach, even for float).
321/// Again, the simplest solution would be to promote every
322/// constant and rematerialize them when they are actually cheap to create.
Duncan P. N. Exon Smithc3fa1ed2016-03-18 23:30:54 +0000323static bool shouldConvertImpl(const Constant *Cst) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000324 if (isa<const UndefValue>(Cst))
325 return false;
326
327 // FIXME: In some cases, it may be interesting to promote in memory
328 // a zero initialized constant.
329 // E.g., when the type of Cst require more instructions than the
330 // adrp/add/load sequence or when this sequence can be shared by several
331 // instances of Cst.
332 // Ideally, we could promote this into a global and rematerialize the constant
333 // when it was a bad idea.
334 if (Cst->isZeroValue())
335 return false;
336
337 if (Stress)
338 return true;
339
340 // FIXME: see function \todo
341 if (Cst->getType()->isVectorTy())
342 return false;
343 return isConstantUsingVectorTy(Cst->getType());
344}
345
Duncan P. N. Exon Smithc3fa1ed2016-03-18 23:30:54 +0000346static bool
347shouldConvert(Constant &C,
348 AArch64PromoteConstant::PromotionCacheTy &PromotionCache) {
349 auto Converted = PromotionCache.insert(
350 std::make_pair(&C, AArch64PromoteConstant::PromotedConstant()));
351 if (Converted.second)
352 Converted.first->second.ShouldConvert = shouldConvertImpl(&C);
353 return Converted.first->second.ShouldConvert;
Tim Northover3b0846e2014-05-24 12:50:23 +0000354}
355
Duncan P. N. Exon Smithc3fa1ed2016-03-18 23:30:54 +0000356Instruction *AArch64PromoteConstant::findInsertionPoint(Instruction &User,
357 unsigned OpNo) {
358 // If this user is a phi, the insertion point is in the related
359 // incoming basic block.
360 if (PHINode *PhiInst = dyn_cast<PHINode>(&User))
361 return PhiInst->getIncomingBlock(OpNo)->getTerminator();
362
363 return &User;
364}
365
366bool AArch64PromoteConstant::isDominated(Instruction *NewPt, Instruction *User,
367 unsigned OpNo,
Tim Northover3b0846e2014-05-24 12:50:23 +0000368 InsertionPoints &InsertPts) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000369 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>(
370 *NewPt->getParent()->getParent()).getDomTree();
371
372 // Traverse all the existing insertion points and check if one is dominating
373 // NewPt. If it is, remember that.
374 for (auto &IPI : InsertPts) {
375 if (NewPt == IPI.first || DT.dominates(IPI.first, NewPt) ||
376 // When IPI.first is a terminator instruction, DT may think that
377 // the result is defined on the edge.
378 // Here we are testing the insertion point, not the definition.
379 (IPI.first->getParent() != NewPt->getParent() &&
380 DT.dominates(IPI.first->getParent(), NewPt->getParent()))) {
381 // No need to insert this point. Just record the dominated use.
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000382 LLVM_DEBUG(dbgs() << "Insertion point dominated by:\n");
383 LLVM_DEBUG(IPI.first->print(dbgs()));
384 LLVM_DEBUG(dbgs() << '\n');
Duncan P. N. Exon Smithc3fa1ed2016-03-18 23:30:54 +0000385 IPI.second.emplace_back(User, OpNo);
Tim Northover3b0846e2014-05-24 12:50:23 +0000386 return true;
387 }
388 }
389 return false;
390}
391
Duncan P. N. Exon Smithc3fa1ed2016-03-18 23:30:54 +0000392bool AArch64PromoteConstant::tryAndMerge(Instruction *NewPt, Instruction *User,
393 unsigned OpNo,
Tim Northover3b0846e2014-05-24 12:50:23 +0000394 InsertionPoints &InsertPts) {
395 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>(
396 *NewPt->getParent()->getParent()).getDomTree();
397 BasicBlock *NewBB = NewPt->getParent();
398
399 // Traverse all the existing insertion point and check if one is dominated by
400 // NewPt and thus useless or can be combined with NewPt into a common
401 // dominator.
402 for (InsertionPoints::iterator IPI = InsertPts.begin(),
403 EndIPI = InsertPts.end();
404 IPI != EndIPI; ++IPI) {
405 BasicBlock *CurBB = IPI->first->getParent();
406 if (NewBB == CurBB) {
407 // Instructions are in the same block.
408 // By construction, NewPt is dominating the other.
409 // Indeed, isDominated returned false with the exact same arguments.
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000410 LLVM_DEBUG(dbgs() << "Merge insertion point with:\n");
411 LLVM_DEBUG(IPI->first->print(dbgs()));
412 LLVM_DEBUG(dbgs() << "\nat considered insertion point.\n");
Duncan P. N. Exon Smithc3fa1ed2016-03-18 23:30:54 +0000413 appendAndTransferDominatedUses(NewPt, User, OpNo, IPI, InsertPts);
Tim Northover3b0846e2014-05-24 12:50:23 +0000414 return true;
415 }
416
417 // Look for a common dominator
418 BasicBlock *CommonDominator = DT.findNearestCommonDominator(NewBB, CurBB);
419 // If none exists, we cannot merge these two points.
420 if (!CommonDominator)
421 continue;
422
423 if (CommonDominator != NewBB) {
424 // By construction, the CommonDominator cannot be CurBB.
425 assert(CommonDominator != CurBB &&
426 "Instruction has not been rejected during isDominated check!");
427 // Take the last instruction of the CommonDominator as insertion point
428 NewPt = CommonDominator->getTerminator();
429 }
430 // else, CommonDominator is the block of NewBB, hence NewBB is the last
431 // possible insertion point in that block.
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000432 LLVM_DEBUG(dbgs() << "Merge insertion point with:\n");
433 LLVM_DEBUG(IPI->first->print(dbgs()));
434 LLVM_DEBUG(dbgs() << '\n');
435 LLVM_DEBUG(NewPt->print(dbgs()));
436 LLVM_DEBUG(dbgs() << '\n');
Duncan P. N. Exon Smithc3fa1ed2016-03-18 23:30:54 +0000437 appendAndTransferDominatedUses(NewPt, User, OpNo, IPI, InsertPts);
Tim Northover3b0846e2014-05-24 12:50:23 +0000438 return true;
439 }
440 return false;
441}
442
Duncan P. N. Exon Smithc3fa1ed2016-03-18 23:30:54 +0000443void AArch64PromoteConstant::computeInsertionPoint(
444 Instruction *User, unsigned OpNo, InsertionPoints &InsertPts) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000445 LLVM_DEBUG(dbgs() << "Considered use, opidx " << OpNo << ":\n");
446 LLVM_DEBUG(User->print(dbgs()));
447 LLVM_DEBUG(dbgs() << '\n');
Tim Northover3b0846e2014-05-24 12:50:23 +0000448
Duncan P. N. Exon Smithc3fa1ed2016-03-18 23:30:54 +0000449 Instruction *InsertionPoint = findInsertionPoint(*User, OpNo);
450
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000451 LLVM_DEBUG(dbgs() << "Considered insertion point:\n");
452 LLVM_DEBUG(InsertionPoint->print(dbgs()));
453 LLVM_DEBUG(dbgs() << '\n');
Duncan P. N. Exon Smithc3fa1ed2016-03-18 23:30:54 +0000454
455 if (isDominated(InsertionPoint, User, OpNo, InsertPts))
456 return;
457 // This insertion point is useful, check if we can merge some insertion
458 // point in a common dominator or if NewPt dominates an existing one.
459 if (tryAndMerge(InsertionPoint, User, OpNo, InsertPts))
460 return;
461
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000462 LLVM_DEBUG(dbgs() << "Keep considered insertion point\n");
Duncan P. N. Exon Smithc3fa1ed2016-03-18 23:30:54 +0000463
464 // It is definitely useful by its own
465 InsertPts[InsertionPoint].emplace_back(User, OpNo);
Tim Northover3b0846e2014-05-24 12:50:23 +0000466}
467
Duncan P. N. Exon Smithc3fa1ed2016-03-18 23:30:54 +0000468static void ensurePromotedGV(Function &F, Constant &C,
469 AArch64PromoteConstant::PromotedConstant &PC) {
470 assert(PC.ShouldConvert &&
471 "Expected that we should convert this to a global");
472 if (PC.GV)
473 return;
474 PC.GV = new GlobalVariable(
475 *F.getParent(), C.getType(), true, GlobalValue::InternalLinkage, nullptr,
476 "_PromotedConst", nullptr, GlobalVariable::NotThreadLocal);
477 PC.GV->setInitializer(&C);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000478 LLVM_DEBUG(dbgs() << "Global replacement: ");
479 LLVM_DEBUG(PC.GV->print(dbgs()));
480 LLVM_DEBUG(dbgs() << '\n');
Duncan P. N. Exon Smithc3fa1ed2016-03-18 23:30:54 +0000481 ++NumPromoted;
482}
483
484void AArch64PromoteConstant::insertDefinitions(Function &F,
485 GlobalVariable &PromotedGV,
486 InsertionPoints &InsertPts) {
487#ifndef NDEBUG
488 // Do more checking for debug purposes.
489 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
490#endif
491 assert(!InsertPts.empty() && "Empty uses does not need a definition");
492
493 for (const auto &IPI : InsertPts) {
494 // Create the load of the global variable.
495 IRBuilder<> Builder(IPI.first);
496 LoadInst *LoadedCst = Builder.CreateLoad(&PromotedGV);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000497 LLVM_DEBUG(dbgs() << "**********\n");
498 LLVM_DEBUG(dbgs() << "New def: ");
499 LLVM_DEBUG(LoadedCst->print(dbgs()));
500 LLVM_DEBUG(dbgs() << '\n');
Duncan P. N. Exon Smithc3fa1ed2016-03-18 23:30:54 +0000501
502 // Update the dominated uses.
503 for (auto Use : IPI.second) {
504#ifndef NDEBUG
505 assert(DT.dominates(LoadedCst,
506 findInsertionPoint(*Use.first, Use.second)) &&
507 "Inserted definition does not dominate all its uses!");
508#endif
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000509 LLVM_DEBUG({
510 dbgs() << "Use to update " << Use.second << ":";
511 Use.first->print(dbgs());
512 dbgs() << '\n';
513 });
Duncan P. N. Exon Smithc3fa1ed2016-03-18 23:30:54 +0000514 Use.first->setOperand(Use.second, LoadedCst);
515 ++NumPromotedUses;
516 }
517 }
518}
519
Duncan P. N. Exon Smithc3fa1ed2016-03-18 23:30:54 +0000520void AArch64PromoteConstant::promoteConstants(
521 Function &F, SmallVectorImpl<UpdateRecord> &Updates,
522 PromotionCacheTy &PromotionCache) {
523 // Promote the constants.
524 for (auto U = Updates.begin(), E = Updates.end(); U != E;) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000525 LLVM_DEBUG(dbgs() << "** Compute insertion points **\n");
Duncan P. N. Exon Smithc3fa1ed2016-03-18 23:30:54 +0000526 auto First = U;
527 Constant *C = First->C;
528 InsertionPoints InsertPts;
529 do {
530 computeInsertionPoint(U->User, U->Op, InsertPts);
531 } while (++U != E && U->C == C);
532
533 auto &Promotion = PromotionCache[C];
534 ensurePromotedGV(F, *C, Promotion);
535 insertDefinitions(F, *Promotion.GV, InsertPts);
536 }
537}
538
539bool AArch64PromoteConstant::runOnFunction(Function &F,
540 PromotionCacheTy &PromotionCache) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000541 // Look for instructions using constant vector. Promote that constant to a
542 // global variable. Create as few loads of this variable as possible and
543 // update the uses accordingly.
Duncan P. N. Exon Smithc3fa1ed2016-03-18 23:30:54 +0000544 SmallVector<UpdateRecord, 64> Updates;
Nico Rieck78199512015-08-06 19:10:45 +0000545 for (Instruction &I : instructions(&F)) {
Benjamin Kramer69b4ad22015-02-06 14:43:55 +0000546 // Traverse the operand, looking for constant vectors. Replace them by a
547 // load of a global variable of constant vector type.
Duncan P. N. Exon Smithc3fa1ed2016-03-18 23:30:54 +0000548 for (Use &U : I.operands()) {
549 Constant *Cst = dyn_cast<Constant>(U);
Benjamin Kramer69b4ad22015-02-06 14:43:55 +0000550 // There is no point in promoting global values as they are already
551 // global. Do not promote constant expressions either, as they may
552 // require some code expansion.
Duncan P. N. Exon Smithc3fa1ed2016-03-18 23:30:54 +0000553 if (!Cst || isa<GlobalValue>(Cst) || isa<ConstantExpr>(Cst))
554 continue;
555
556 // Check if this constant is worth promoting.
557 if (!shouldConvert(*Cst, PromotionCache))
558 continue;
559
560 // Check if this use should be promoted.
561 unsigned OpNo = &U - I.op_begin();
562 if (!shouldConvertUse(Cst, &I, OpNo))
563 continue;
564
565 Updates.emplace_back(Cst, &I, OpNo);
Tim Northover3b0846e2014-05-24 12:50:23 +0000566 }
567 }
Duncan P. N. Exon Smithc3fa1ed2016-03-18 23:30:54 +0000568
569 if (Updates.empty())
570 return false;
571
572 promoteConstants(F, Updates, PromotionCache);
573 return true;
Tim Northover3b0846e2014-05-24 12:50:23 +0000574}