2 //===-- ARM64PromoteConstant.cpp --- Promote constant to global for ARM64 -===//
4 // The LLVM Compiler Infrastructure
6 // This file is distributed under the University of Illinois Open Source
7 // License. See LICENSE.TXT for details.
9 //===----------------------------------------------------------------------===//
11 // This file implements the ARM64PromoteConstant pass which promotes constants
12 // to global variables when this is likely to be more efficient. Currently only
13 // types related to constant vector (i.e., constant vector, array of constant
14 // vectors, constant structure with a constant vector field, etc.) are promoted
15 // to global variables. Constant vectors are likely to be lowered in target
16 // constant pool during instruction selection already; therefore, the access
17 // will remain the same (memory load), but the structure types are not split
18 // into different constant pool accesses for each field. A bonus side effect is
19 // that created globals may be merged by the global merge pass.
21 // FIXME: This pass may be useful for other targets too.
22 //===----------------------------------------------------------------------===//
24 #define DEBUG_TYPE "arm64-promote-const"
26 #include "llvm/ADT/Statistic.h"
27 #include "llvm/ADT/DenseMap.h"
28 #include "llvm/ADT/SmallSet.h"
29 #include "llvm/ADT/SmallVector.h"
30 #include "llvm/IR/Constants.h"
31 #include "llvm/IR/Dominators.h"
32 #include "llvm/IR/Function.h"
33 #include "llvm/IR/GlobalVariable.h"
34 #include "llvm/IR/InlineAsm.h"
35 #include "llvm/IR/Instructions.h"
36 #include "llvm/IR/IntrinsicInst.h"
37 #include "llvm/IR/IRBuilder.h"
38 #include "llvm/IR/Module.h"
39 #include "llvm/Pass.h"
40 #include "llvm/Support/CommandLine.h"
41 #include "llvm/Support/Debug.h"
45 // Stress testing mode - disable heuristics.
46 static cl::opt<bool> Stress("arm64-stress-promote-const", cl::Hidden,
47 cl::desc("Promote all vector constants"));
49 STATISTIC(NumPromoted, "Number of promoted constants");
50 STATISTIC(NumPromotedUses, "Number of promoted constants uses");
52 //===----------------------------------------------------------------------===//
53 // ARM64PromoteConstant
54 //===----------------------------------------------------------------------===//
57 /// Promotes interesting constant into global variables.
58 /// The motivating example is:
59 /// static const uint16_t TableA[32] = {
60 /// 41944, 40330, 38837, 37450, 36158, 34953, 33826, 32768,
61 /// 31776, 30841, 29960, 29128, 28340, 27595, 26887, 26215,
62 /// 25576, 24967, 24386, 23832, 23302, 22796, 22311, 21846,
63 /// 21400, 20972, 20561, 20165, 19785, 19419, 19066, 18725,
66 /// uint8x16x4_t LoadStatic(void) {
68 /// ret.val[0] = vld1q_u16(TableA + 0);
69 /// ret.val[1] = vld1q_u16(TableA + 8);
70 /// ret.val[2] = vld1q_u16(TableA + 16);
71 /// ret.val[3] = vld1q_u16(TableA + 24);
75 /// The constants in that example are folded into the uses. Thus, 4 different
76 /// constants are created.
77 /// As their type is vector the cheapest way to create them is to load them
79 /// Therefore the final assembly final has 4 different load.
80 /// With this pass enabled, only one load is issued for the constants.
81 class ARM64PromoteConstant : public ModulePass {
85 ARM64PromoteConstant() : ModulePass(ID) {}
87 virtual const char *getPassName() const { return "ARM64 Promote Constant"; }
89 /// Iterate over the functions and promote the interesting constants into
90 /// global variables with module scope.
91 bool runOnModule(Module &M) {
92 DEBUG(dbgs() << getPassName() << '\n');
95 Changed |= runOnFunction(MF);
101 /// Look for interesting constants used within the given function.
102 /// Promote them into global variables, load these global variables within
103 /// the related function, so that the number of inserted load is minimal.
104 bool runOnFunction(Function &F);
106 // This transformation requires dominator info
107 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
108 AU.setPreservesCFG();
109 AU.addRequired<DominatorTreeWrapperPass>();
110 AU.addPreserved<DominatorTreeWrapperPass>();
113 /// Type to store a list of User
114 typedef SmallVector<Value::user_iterator, 4> Users;
115 /// Map an insertion point to all the uses it dominates.
116 typedef DenseMap<Instruction *, Users> InsertionPoints;
117 /// Map a function to the required insertion point of load for a
119 typedef DenseMap<Function *, InsertionPoints> InsertionPointsPerFunc;
121 /// Find the closest point that dominates the given Use.
122 Instruction *findInsertionPoint(Value::user_iterator &Use);
124 /// Check if the given insertion point is dominated by an existing
126 /// If true, the given use is added to the list of dominated uses for
127 /// the related existing point.
128 /// \param NewPt the insertion point to be checked
129 /// \param UseIt the use to be added into the list of dominated uses
130 /// \param InsertPts existing insertion points
131 /// \pre NewPt and all instruction in InsertPts belong to the same function
132 /// \return true if one of the insertion point in InsertPts dominates NewPt,
134 bool isDominated(Instruction *NewPt, Value::user_iterator &UseIt,
135 InsertionPoints &InsertPts);
137 /// Check if the given insertion point can be merged with an existing
138 /// insertion point in a common dominator.
139 /// If true, the given use is added to the list of the created insertion
141 /// \param NewPt the insertion point to be checked
142 /// \param UseIt the use to be added into the list of dominated uses
143 /// \param InsertPts existing insertion points
144 /// \pre NewPt and all instruction in InsertPts belong to the same function
145 /// \pre isDominated returns false for the exact same parameters.
146 /// \return true if it exists an insertion point in InsertPts that could
147 /// have been merged with NewPt in a common dominator,
149 bool tryAndMerge(Instruction *NewPt, Value::user_iterator &UseIt,
150 InsertionPoints &InsertPts);
152 /// Compute the minimal insertion points to dominates all the interesting
154 /// Insertion points are group per function and each insertion point
155 /// contains a list of all the uses it dominates within the related function
156 /// \param Val constant to be examined
157 /// \param[out] InsPtsPerFunc output storage of the analysis
158 void computeInsertionPoints(Constant *Val,
159 InsertionPointsPerFunc &InsPtsPerFunc);
161 /// Insert a definition of a new global variable at each point contained in
162 /// InsPtsPerFunc and update the related uses (also contained in
164 bool insertDefinitions(Constant *Cst, InsertionPointsPerFunc &InsPtsPerFunc);
166 /// Compute the minimal insertion points to dominate all the interesting
167 /// uses of Val and insert a definition of a new global variable
169 /// Also update the uses of Val accordingly.
170 /// Currently a use of Val is considered interesting if:
171 /// - Val is not UndefValue
172 /// - Val is not zeroinitialized
173 /// - Replacing Val per a load of a global variable is valid.
174 /// \see shouldConvert for more details
175 bool computeAndInsertDefinitions(Constant *Val);
177 /// Promote the given constant into a global variable if it is expected to
179 /// \return true if Cst has been promoted
180 bool promoteConstant(Constant *Cst);
182 /// Transfer the list of dominated uses of IPI to NewPt in InsertPts.
183 /// Append UseIt to this list and delete the entry of IPI in InsertPts.
184 static void appendAndTransferDominatedUses(Instruction *NewPt,
185 Value::user_iterator &UseIt,
186 InsertionPoints::iterator &IPI,
187 InsertionPoints &InsertPts) {
188 // Record the dominated use
189 IPI->second.push_back(UseIt);
190 // Transfer the dominated uses of IPI to NewPt
191 // Inserting into the DenseMap may invalidate existing iterator.
192 // Keep a copy of the key to find the iterator to erase.
193 Instruction *OldInstr = IPI->first;
194 InsertPts.insert(InsertionPoints::value_type(NewPt, IPI->second));
196 IPI = InsertPts.find(OldInstr);
197 InsertPts.erase(IPI);
200 } // end anonymous namespace
202 char ARM64PromoteConstant::ID = 0;
205 void initializeARM64PromoteConstantPass(PassRegistry &);
208 INITIALIZE_PASS_BEGIN(ARM64PromoteConstant, "arm64-promote-const",
209 "ARM64 Promote Constant Pass", false, false)
210 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
211 INITIALIZE_PASS_END(ARM64PromoteConstant, "arm64-promote-const",
212 "ARM64 Promote Constant Pass", false, false)
214 ModulePass *llvm::createARM64PromoteConstantPass() {
215 return new ARM64PromoteConstant();
218 /// Check if the given type uses a vector type.
219 static bool isConstantUsingVectorTy(const Type *CstTy) {
220 if (CstTy->isVectorTy())
222 if (CstTy->isStructTy()) {
223 for (unsigned EltIdx = 0, EndEltIdx = CstTy->getStructNumElements();
224 EltIdx < EndEltIdx; ++EltIdx)
225 if (isConstantUsingVectorTy(CstTy->getStructElementType(EltIdx)))
227 } else if (CstTy->isArrayTy())
228 return isConstantUsingVectorTy(CstTy->getArrayElementType());
232 /// Check if the given use (Instruction + OpIdx) of Cst should be converted into
233 /// a load of a global variable initialized with Cst.
234 /// A use should be converted if it is legal to do so.
235 /// For instance, it is not legal to turn the mask operand of a shuffle vector
236 /// into a load of a global variable.
237 static bool shouldConvertUse(const Constant *Cst, const Instruction *Instr,
239 // shufflevector instruction expects a const for the mask argument, i.e., the
240 // third argument. Do not promote this use in that case.
241 if (isa<const ShuffleVectorInst>(Instr) && OpIdx == 2)
244 // extractvalue instruction expects a const idx
245 if (isa<const ExtractValueInst>(Instr) && OpIdx > 0)
248 // extractvalue instruction expects a const idx
249 if (isa<const InsertValueInst>(Instr) && OpIdx > 1)
252 if (isa<const AllocaInst>(Instr) && OpIdx > 0)
255 // Alignment argument must be constant
256 if (isa<const LoadInst>(Instr) && OpIdx > 0)
259 // Alignment argument must be constant
260 if (isa<const StoreInst>(Instr) && OpIdx > 1)
263 // Index must be constant
264 if (isa<const GetElementPtrInst>(Instr) && OpIdx > 0)
267 // Personality function and filters must be constant.
268 // Give up on that instruction.
269 if (isa<const LandingPadInst>(Instr))
272 // switch instruction expects constants to compare to
273 if (isa<const SwitchInst>(Instr))
276 // Expected address must be a constant
277 if (isa<const IndirectBrInst>(Instr))
280 // Do not mess with intrinsic
281 if (isa<const IntrinsicInst>(Instr))
284 // Do not mess with inline asm
285 const CallInst *CI = dyn_cast<const CallInst>(Instr);
286 if (CI && isa<const InlineAsm>(CI->getCalledValue()))
292 /// Check if the given Cst should be converted into
293 /// a load of a global variable initialized with Cst.
294 /// A constant should be converted if it is likely that the materialization of
295 /// the constant will be tricky. Thus, we give up on zero or undef values.
297 /// \todo Currently, accept only vector related types.
298 /// Also we give up on all simple vector type to keep the existing
299 /// behavior. Otherwise, we should push here all the check of the lowering of
300 /// BUILD_VECTOR. By giving up, we lose the potential benefit of merging
301 /// constant via global merge and the fact that the same constant is stored
302 /// only once with this method (versus, as many function that uses the constant
303 /// for the regular approach, even for float).
304 /// Again, the simplest solution would be to promote every
305 /// constant and rematerialize them when they are actually cheap to create.
306 static bool shouldConvert(const Constant *Cst) {
307 if (isa<const UndefValue>(Cst))
310 // FIXME: In some cases, it may be interesting to promote in memory
311 // a zero initialized constant.
312 // E.g., when the type of Cst require more instructions than the
313 // adrp/add/load sequence or when this sequence can be shared by several
315 // Ideally, we could promote this into a global and rematerialize the constant
316 // when it was a bad idea.
317 if (Cst->isZeroValue())
323 // FIXME: see function \todo
324 if (Cst->getType()->isVectorTy())
326 return isConstantUsingVectorTy(Cst->getType());
330 ARM64PromoteConstant::findInsertionPoint(Value::user_iterator &Use) {
331 // If this user is a phi, the insertion point is in the related
332 // incoming basic block
333 PHINode *PhiInst = dyn_cast<PHINode>(*Use);
334 Instruction *InsertionPoint;
337 PhiInst->getIncomingBlock(Use.getOperandNo())->getTerminator();
339 InsertionPoint = dyn_cast<Instruction>(*Use);
340 assert(InsertionPoint && "User is not an instruction!");
341 return InsertionPoint;
344 bool ARM64PromoteConstant::isDominated(Instruction *NewPt,
345 Value::user_iterator &UseIt,
346 InsertionPoints &InsertPts) {
348 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>(
349 *NewPt->getParent()->getParent()).getDomTree();
351 // Traverse all the existing insertion point and check if one is dominating
353 for (InsertionPoints::iterator IPI = InsertPts.begin(),
354 EndIPI = InsertPts.end();
355 IPI != EndIPI; ++IPI) {
356 if (NewPt == IPI->first || DT.dominates(IPI->first, NewPt) ||
357 // When IPI->first is a terminator instruction, DT may think that
358 // the result is defined on the edge.
359 // Here we are testing the insertion point, not the definition.
360 (IPI->first->getParent() != NewPt->getParent() &&
361 DT.dominates(IPI->first->getParent(), NewPt->getParent()))) {
362 // No need to insert this point
363 // Record the dominated use
364 DEBUG(dbgs() << "Insertion point dominated by:\n");
365 DEBUG(IPI->first->print(dbgs()));
366 DEBUG(dbgs() << '\n');
367 IPI->second.push_back(UseIt);
374 bool ARM64PromoteConstant::tryAndMerge(Instruction *NewPt,
375 Value::user_iterator &UseIt,
376 InsertionPoints &InsertPts) {
377 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>(
378 *NewPt->getParent()->getParent()).getDomTree();
379 BasicBlock *NewBB = NewPt->getParent();
381 // Traverse all the existing insertion point and check if one is dominated by
382 // NewPt and thus useless or can be combined with NewPt into a common
384 for (InsertionPoints::iterator IPI = InsertPts.begin(),
385 EndIPI = InsertPts.end();
386 IPI != EndIPI; ++IPI) {
387 BasicBlock *CurBB = IPI->first->getParent();
388 if (NewBB == CurBB) {
389 // Instructions are in the same block.
390 // By construction, NewPt is dominating the other.
391 // Indeed, isDominated returned false with the exact same arguments.
392 DEBUG(dbgs() << "Merge insertion point with:\n");
393 DEBUG(IPI->first->print(dbgs()));
394 DEBUG(dbgs() << "\nat considered insertion point.\n");
395 appendAndTransferDominatedUses(NewPt, UseIt, IPI, InsertPts);
399 // Look for a common dominator
400 BasicBlock *CommonDominator = DT.findNearestCommonDominator(NewBB, CurBB);
401 // If none exists, we cannot merge these two points
402 if (!CommonDominator)
405 if (CommonDominator != NewBB) {
406 // By construction, the CommonDominator cannot be CurBB
407 assert(CommonDominator != CurBB &&
408 "Instruction has not been rejected during isDominated check!");
409 // Take the last instruction of the CommonDominator as insertion point
410 NewPt = CommonDominator->getTerminator();
412 // else, CommonDominator is the block of NewBB, hence NewBB is the last
413 // possible insertion point in that block
414 DEBUG(dbgs() << "Merge insertion point with:\n");
415 DEBUG(IPI->first->print(dbgs()));
416 DEBUG(dbgs() << '\n');
417 DEBUG(NewPt->print(dbgs()));
418 DEBUG(dbgs() << '\n');
419 appendAndTransferDominatedUses(NewPt, UseIt, IPI, InsertPts);
425 void ARM64PromoteConstant::computeInsertionPoints(
426 Constant *Val, InsertionPointsPerFunc &InsPtsPerFunc) {
427 DEBUG(dbgs() << "** Compute insertion points **\n");
428 for (Value::user_iterator UseIt = Val->user_begin(),
429 EndUseIt = Val->user_end();
430 UseIt != EndUseIt; ++UseIt) {
431 // If the user is not an Instruction, we cannot modify it
432 if (!isa<Instruction>(*UseIt))
435 // Filter out uses that should not be converted
436 if (!shouldConvertUse(Val, cast<Instruction>(*UseIt), UseIt.getOperandNo()))
439 DEBUG(dbgs() << "Considered use, opidx " << UseIt.getOperandNo() << ":\n");
440 DEBUG((*UseIt)->print(dbgs()));
441 DEBUG(dbgs() << '\n');
443 Instruction *InsertionPoint = findInsertionPoint(UseIt);
445 DEBUG(dbgs() << "Considered insertion point:\n");
446 DEBUG(InsertionPoint->print(dbgs()));
447 DEBUG(dbgs() << '\n');
449 // Check if the current insertion point is useless, i.e., it is dominated
451 InsertionPoints &InsertPts =
452 InsPtsPerFunc[InsertionPoint->getParent()->getParent()];
453 if (isDominated(InsertionPoint, UseIt, InsertPts))
455 // This insertion point is useful, check if we can merge some insertion
456 // point in a common dominator or if NewPt dominates an existing one.
457 if (tryAndMerge(InsertionPoint, UseIt, InsertPts))
460 DEBUG(dbgs() << "Keep considered insertion point\n");
462 // It is definitely useful by its own
463 InsertPts[InsertionPoint].push_back(UseIt);
468 ARM64PromoteConstant::insertDefinitions(Constant *Cst,
469 InsertionPointsPerFunc &InsPtsPerFunc) {
470 // We will create one global variable per Module
471 DenseMap<Module *, GlobalVariable *> ModuleToMergedGV;
472 bool HasChanged = false;
474 // Traverse all insertion points in all the function
475 for (InsertionPointsPerFunc::iterator FctToInstPtsIt = InsPtsPerFunc.begin(),
476 EndIt = InsPtsPerFunc.end();
477 FctToInstPtsIt != EndIt; ++FctToInstPtsIt) {
478 InsertionPoints &InsertPts = FctToInstPtsIt->second;
479 // Do more check for debug purposes
481 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>(
482 *FctToInstPtsIt->first).getDomTree();
484 GlobalVariable *PromotedGV;
485 assert(!InsertPts.empty() && "Empty uses does not need a definition");
487 Module *M = FctToInstPtsIt->first->getParent();
488 DenseMap<Module *, GlobalVariable *>::iterator MapIt =
489 ModuleToMergedGV.find(M);
490 if (MapIt == ModuleToMergedGV.end()) {
491 PromotedGV = new GlobalVariable(
492 *M, Cst->getType(), true, GlobalValue::InternalLinkage, 0,
493 "_PromotedConst", 0, GlobalVariable::NotThreadLocal);
494 PromotedGV->setInitializer(Cst);
495 ModuleToMergedGV[M] = PromotedGV;
496 DEBUG(dbgs() << "Global replacement: ");
497 DEBUG(PromotedGV->print(dbgs()));
498 DEBUG(dbgs() << '\n');
502 PromotedGV = MapIt->second;
505 for (InsertionPoints::iterator IPI = InsertPts.begin(),
506 EndIPI = InsertPts.end();
507 IPI != EndIPI; ++IPI) {
508 // Create the load of the global variable
509 IRBuilder<> Builder(IPI->first->getParent(), IPI->first);
510 LoadInst *LoadedCst = Builder.CreateLoad(PromotedGV);
511 DEBUG(dbgs() << "**********\n");
512 DEBUG(dbgs() << "New def: ");
513 DEBUG(LoadedCst->print(dbgs()));
514 DEBUG(dbgs() << '\n');
516 // Update the dominated uses
517 Users &DominatedUsers = IPI->second;
518 for (Users::iterator UseIt = DominatedUsers.begin(),
519 EndIt = DominatedUsers.end();
520 UseIt != EndIt; ++UseIt) {
522 assert((DT.dominates(LoadedCst, cast<Instruction>(**UseIt)) ||
523 (isa<PHINode>(**UseIt) &&
524 DT.dominates(LoadedCst, findInsertionPoint(*UseIt)))) &&
525 "Inserted definition does not dominate all its uses!");
527 DEBUG(dbgs() << "Use to update " << UseIt->getOperandNo() << ":");
528 DEBUG((*UseIt)->print(dbgs()));
529 DEBUG(dbgs() << '\n');
530 (*UseIt)->setOperand(UseIt->getOperandNo(), LoadedCst);
538 bool ARM64PromoteConstant::computeAndInsertDefinitions(Constant *Val) {
539 InsertionPointsPerFunc InsertPtsPerFunc;
540 computeInsertionPoints(Val, InsertPtsPerFunc);
541 return insertDefinitions(Val, InsertPtsPerFunc);
544 bool ARM64PromoteConstant::promoteConstant(Constant *Cst) {
545 assert(Cst && "Given variable is not a valid constant.");
547 if (!shouldConvert(Cst))
550 DEBUG(dbgs() << "******************************\n");
551 DEBUG(dbgs() << "Candidate constant: ");
552 DEBUG(Cst->print(dbgs()));
553 DEBUG(dbgs() << '\n');
555 return computeAndInsertDefinitions(Cst);
558 bool ARM64PromoteConstant::runOnFunction(Function &F) {
559 // Look for instructions using constant vector
560 // Promote that constant to a global variable.
561 // Create as few load of this variable as possible and update the uses
563 bool LocalChange = false;
564 SmallSet<Constant *, 8> AlreadyChecked;
566 for (auto &MBB : F) {
567 for (auto &MI : MBB) {
568 // Traverse the operand, looking for constant vectors
569 // Replace them by a load of a global variable of type constant vector
570 for (unsigned OpIdx = 0, EndOpIdx = MI.getNumOperands();
571 OpIdx != EndOpIdx; ++OpIdx) {
572 Constant *Cst = dyn_cast<Constant>(MI.getOperand(OpIdx));
573 // There is no point is promoting global value, they are already global.
574 // Do not promote constant expression, as they may require some code
576 if (Cst && !isa<GlobalValue>(Cst) && !isa<ConstantExpr>(Cst) &&
577 AlreadyChecked.insert(Cst))
578 LocalChange |= promoteConstant(Cst);