1 //=- AArch64PromoteConstant.cpp --- Promote constant to global for AArch64 -==// 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 file implements the AArch64PromoteConstant pass which promotes constants 11 // to global variables when this is likely to be more efficient. Currently only 12 // types related to constant vector (i.e., constant vector, array of constant 13 // vectors, constant structure with a constant vector field, etc.) are promoted 14 // to global variables. Constant vectors are likely to be lowered in target 15 // constant pool during instruction selection already; therefore, the access 16 // will remain the same (memory load), but the structure types are not split 17 // into different constant pool accesses for each field. A bonus side effect is 18 // that created globals may be merged by the global merge pass. 19 // 20 // FIXME: This pass may be useful for other targets too. 21 //===----------------------------------------------------------------------===// 22 23 #include "AArch64.h" 24 #include "llvm/ADT/DenseMap.h" 25 #include "llvm/ADT/SmallPtrSet.h" 26 #include "llvm/ADT/SmallVector.h" 27 #include "llvm/ADT/Statistic.h" 28 #include "llvm/IR/Constants.h" 29 #include "llvm/IR/Dominators.h" 30 #include "llvm/IR/Function.h" 31 #include "llvm/IR/GlobalVariable.h" 32 #include "llvm/IR/IRBuilder.h" 33 #include "llvm/IR/InlineAsm.h" 34 #include "llvm/IR/InstIterator.h" 35 #include "llvm/IR/Instructions.h" 36 #include "llvm/IR/IntrinsicInst.h" 37 #include "llvm/IR/Module.h" 38 #include "llvm/Pass.h" 39 #include "llvm/Support/CommandLine.h" 40 #include "llvm/Support/Debug.h" 41 #include "llvm/Support/raw_ostream.h" 42 43 using namespace llvm; 44 45 #define DEBUG_TYPE "aarch64-promote-const" 46 47 // Stress testing mode - disable heuristics. 48 static cl::opt<bool> Stress("aarch64-stress-promote-const", cl::Hidden, 49 cl::desc("Promote all vector constants")); 50 51 STATISTIC(NumPromoted, "Number of promoted constants"); 52 STATISTIC(NumPromotedUses, "Number of promoted constants uses"); 53 54 //===----------------------------------------------------------------------===// 55 // AArch64PromoteConstant 56 //===----------------------------------------------------------------------===// 57 58 namespace { 59 /// Promotes interesting constant into global variables. 60 /// The motivating example is: 61 /// static const uint16_t TableA[32] = { 62 /// 41944, 40330, 38837, 37450, 36158, 34953, 33826, 32768, 63 /// 31776, 30841, 29960, 29128, 28340, 27595, 26887, 26215, 64 /// 25576, 24967, 24386, 23832, 23302, 22796, 22311, 21846, 65 /// 21400, 20972, 20561, 20165, 19785, 19419, 19066, 18725, 66 /// }; 67 /// 68 /// uint8x16x4_t LoadStatic(void) { 69 /// uint8x16x4_t ret; 70 /// ret.val[0] = vld1q_u16(TableA + 0); 71 /// ret.val[1] = vld1q_u16(TableA + 8); 72 /// ret.val[2] = vld1q_u16(TableA + 16); 73 /// ret.val[3] = vld1q_u16(TableA + 24); 74 /// return ret; 75 /// } 76 /// 77 /// The constants in this example are folded into the uses. Thus, 4 different 78 /// constants are created. 79 /// 80 /// As their type is vector the cheapest way to create them is to load them 81 /// for the memory. 82 /// 83 /// Therefore the final assembly final has 4 different loads. With this pass 84 /// enabled, only one load is issued for the constants. 85 class AArch64PromoteConstant : public ModulePass { 86 87 public: 88 struct PromotedConstant { 89 bool ShouldConvert = false; 90 GlobalVariable *GV = nullptr; 91 }; 92 typedef SmallDenseMap<Constant *, PromotedConstant, 16> PromotionCacheTy; 93 94 struct UpdateRecord { 95 Constant *C; 96 Instruction *User; 97 unsigned Op; 98 99 UpdateRecord(Constant *C, Instruction *User, unsigned Op) 100 : C(C), User(User), Op(Op) {} 101 }; 102 103 static char ID; 104 AArch64PromoteConstant() : ModulePass(ID) {} 105 106 const char *getPassName() const override { return "AArch64 Promote Constant"; } 107 108 /// Iterate over the functions and promote the interesting constants into 109 /// global variables with module scope. 110 bool runOnModule(Module &M) override { 111 DEBUG(dbgs() << getPassName() << '\n'); 112 if (skipModule(M)) 113 return false; 114 bool Changed = false; 115 PromotionCacheTy PromotionCache; 116 for (auto &MF : M) { 117 Changed |= runOnFunction(MF, PromotionCache); 118 } 119 return Changed; 120 } 121 122 private: 123 /// Look for interesting constants used within the given function. 124 /// Promote them into global variables, load these global variables within 125 /// the related function, so that the number of inserted load is minimal. 126 bool runOnFunction(Function &F, PromotionCacheTy &PromotionCache); 127 128 // This transformation requires dominator info 129 void getAnalysisUsage(AnalysisUsage &AU) const override { 130 AU.setPreservesCFG(); 131 AU.addRequired<DominatorTreeWrapperPass>(); 132 AU.addPreserved<DominatorTreeWrapperPass>(); 133 } 134 135 /// Type to store a list of Uses. 136 typedef SmallVector<std::pair<Instruction *, unsigned>, 4> Uses; 137 /// Map an insertion point to all the uses it dominates. 138 typedef DenseMap<Instruction *, Uses> InsertionPoints; 139 140 /// Find the closest point that dominates the given Use. 141 Instruction *findInsertionPoint(Instruction &User, unsigned OpNo); 142 143 /// Check if the given insertion point is dominated by an existing 144 /// insertion point. 145 /// If true, the given use is added to the list of dominated uses for 146 /// the related existing point. 147 /// \param NewPt the insertion point to be checked 148 /// \param User the user of the constant 149 /// \param OpNo the operand number of the use 150 /// \param InsertPts existing insertion points 151 /// \pre NewPt and all instruction in InsertPts belong to the same function 152 /// \return true if one of the insertion point in InsertPts dominates NewPt, 153 /// false otherwise 154 bool isDominated(Instruction *NewPt, Instruction *User, unsigned OpNo, 155 InsertionPoints &InsertPts); 156 157 /// Check if the given insertion point can be merged with an existing 158 /// insertion point in a common dominator. 159 /// If true, the given use is added to the list of the created insertion 160 /// point. 161 /// \param NewPt the insertion point to be checked 162 /// \param User the user of the constant 163 /// \param OpNo the operand number of the use 164 /// \param InsertPts existing insertion points 165 /// \pre NewPt and all instruction in InsertPts belong to the same function 166 /// \pre isDominated returns false for the exact same parameters. 167 /// \return true if it exists an insertion point in InsertPts that could 168 /// have been merged with NewPt in a common dominator, 169 /// false otherwise 170 bool tryAndMerge(Instruction *NewPt, Instruction *User, unsigned OpNo, 171 InsertionPoints &InsertPts); 172 173 /// Compute the minimal insertion points to dominates all the interesting 174 /// uses of value. 175 /// Insertion points are group per function and each insertion point 176 /// contains a list of all the uses it dominates within the related function 177 /// \param User the user of the constant 178 /// \param OpNo the operand number of the constant 179 /// \param[out] InsertPts output storage of the analysis 180 void computeInsertionPoint(Instruction *User, unsigned OpNo, 181 InsertionPoints &InsertPts); 182 183 /// Insert a definition of a new global variable at each point contained in 184 /// InsPtsPerFunc and update the related uses (also contained in 185 /// InsPtsPerFunc). 186 void insertDefinitions(Function &F, GlobalVariable &GV, 187 InsertionPoints &InsertPts); 188 189 /// Sort the updates in a deterministic way. 190 void sortUpdates(SmallVectorImpl<UpdateRecord> &Updates); 191 192 /// Do the constant promotion indicated by the Updates records, keeping track 193 /// of globals in PromotionCache. 194 void promoteConstants(Function &F, SmallVectorImpl<UpdateRecord> &Updates, 195 PromotionCacheTy &PromotionCache); 196 197 /// Transfer the list of dominated uses of IPI to NewPt in InsertPts. 198 /// Append Use to this list and delete the entry of IPI in InsertPts. 199 static void appendAndTransferDominatedUses(Instruction *NewPt, 200 Instruction *User, unsigned OpNo, 201 InsertionPoints::iterator &IPI, 202 InsertionPoints &InsertPts) { 203 // Record the dominated use. 204 IPI->second.emplace_back(User, OpNo); 205 // Transfer the dominated uses of IPI to NewPt 206 // Inserting into the DenseMap may invalidate existing iterator. 207 // Keep a copy of the key to find the iterator to erase. Keep a copy of the 208 // value so that we don't have to dereference IPI->second. 209 Instruction *OldInstr = IPI->first; 210 Uses OldUses = std::move(IPI->second); 211 InsertPts[NewPt] = std::move(OldUses); 212 // Erase IPI. 213 InsertPts.erase(OldInstr); 214 } 215 }; 216 } // end anonymous namespace 217 218 char AArch64PromoteConstant::ID = 0; 219 220 namespace llvm { 221 void initializeAArch64PromoteConstantPass(PassRegistry &); 222 } 223 224 INITIALIZE_PASS_BEGIN(AArch64PromoteConstant, "aarch64-promote-const", 225 "AArch64 Promote Constant Pass", false, false) 226 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 227 INITIALIZE_PASS_END(AArch64PromoteConstant, "aarch64-promote-const", 228 "AArch64 Promote Constant Pass", false, false) 229 230 ModulePass *llvm::createAArch64PromoteConstantPass() { 231 return new AArch64PromoteConstant(); 232 } 233 234 /// Check if the given type uses a vector type. 235 static bool isConstantUsingVectorTy(const Type *CstTy) { 236 if (CstTy->isVectorTy()) 237 return true; 238 if (CstTy->isStructTy()) { 239 for (unsigned EltIdx = 0, EndEltIdx = CstTy->getStructNumElements(); 240 EltIdx < EndEltIdx; ++EltIdx) 241 if (isConstantUsingVectorTy(CstTy->getStructElementType(EltIdx))) 242 return true; 243 } else if (CstTy->isArrayTy()) 244 return isConstantUsingVectorTy(CstTy->getArrayElementType()); 245 return false; 246 } 247 248 /// Check if the given use (Instruction + OpIdx) of Cst should be converted into 249 /// a load of a global variable initialized with Cst. 250 /// A use should be converted if it is legal to do so. 251 /// For instance, it is not legal to turn the mask operand of a shuffle vector 252 /// into a load of a global variable. 253 static bool shouldConvertUse(const Constant *Cst, const Instruction *Instr, 254 unsigned OpIdx) { 255 // shufflevector instruction expects a const for the mask argument, i.e., the 256 // third argument. Do not promote this use in that case. 257 if (isa<const ShuffleVectorInst>(Instr) && OpIdx == 2) 258 return false; 259 260 // extractvalue instruction expects a const idx. 261 if (isa<const ExtractValueInst>(Instr) && OpIdx > 0) 262 return false; 263 264 // extractvalue instruction expects a const idx. 265 if (isa<const InsertValueInst>(Instr) && OpIdx > 1) 266 return false; 267 268 if (isa<const AllocaInst>(Instr) && OpIdx > 0) 269 return false; 270 271 // Alignment argument must be constant. 272 if (isa<const LoadInst>(Instr) && OpIdx > 0) 273 return false; 274 275 // Alignment argument must be constant. 276 if (isa<const StoreInst>(Instr) && OpIdx > 1) 277 return false; 278 279 // Index must be constant. 280 if (isa<const GetElementPtrInst>(Instr) && OpIdx > 0) 281 return false; 282 283 // Personality function and filters must be constant. 284 // Give up on that instruction. 285 if (isa<const LandingPadInst>(Instr)) 286 return false; 287 288 // Switch instruction expects constants to compare to. 289 if (isa<const SwitchInst>(Instr)) 290 return false; 291 292 // Expected address must be a constant. 293 if (isa<const IndirectBrInst>(Instr)) 294 return false; 295 296 // Do not mess with intrinsics. 297 if (isa<const IntrinsicInst>(Instr)) 298 return false; 299 300 // Do not mess with inline asm. 301 const CallInst *CI = dyn_cast<const CallInst>(Instr); 302 return !(CI && isa<const InlineAsm>(CI->getCalledValue())); 303 } 304 305 /// Check if the given Cst should be converted into 306 /// a load of a global variable initialized with Cst. 307 /// A constant should be converted if it is likely that the materialization of 308 /// the constant will be tricky. Thus, we give up on zero or undef values. 309 /// 310 /// \todo Currently, accept only vector related types. 311 /// Also we give up on all simple vector type to keep the existing 312 /// behavior. Otherwise, we should push here all the check of the lowering of 313 /// BUILD_VECTOR. By giving up, we lose the potential benefit of merging 314 /// constant via global merge and the fact that the same constant is stored 315 /// only once with this method (versus, as many function that uses the constant 316 /// for the regular approach, even for float). 317 /// Again, the simplest solution would be to promote every 318 /// constant and rematerialize them when they are actually cheap to create. 319 static bool shouldConvertImpl(const Constant *Cst) { 320 if (isa<const UndefValue>(Cst)) 321 return false; 322 323 // FIXME: In some cases, it may be interesting to promote in memory 324 // a zero initialized constant. 325 // E.g., when the type of Cst require more instructions than the 326 // adrp/add/load sequence or when this sequence can be shared by several 327 // instances of Cst. 328 // Ideally, we could promote this into a global and rematerialize the constant 329 // when it was a bad idea. 330 if (Cst->isZeroValue()) 331 return false; 332 333 if (Stress) 334 return true; 335 336 // FIXME: see function \todo 337 if (Cst->getType()->isVectorTy()) 338 return false; 339 return isConstantUsingVectorTy(Cst->getType()); 340 } 341 342 static bool 343 shouldConvert(Constant &C, 344 AArch64PromoteConstant::PromotionCacheTy &PromotionCache) { 345 auto Converted = PromotionCache.insert( 346 std::make_pair(&C, AArch64PromoteConstant::PromotedConstant())); 347 if (Converted.second) 348 Converted.first->second.ShouldConvert = shouldConvertImpl(&C); 349 return Converted.first->second.ShouldConvert; 350 } 351 352 Instruction *AArch64PromoteConstant::findInsertionPoint(Instruction &User, 353 unsigned OpNo) { 354 // If this user is a phi, the insertion point is in the related 355 // incoming basic block. 356 if (PHINode *PhiInst = dyn_cast<PHINode>(&User)) 357 return PhiInst->getIncomingBlock(OpNo)->getTerminator(); 358 359 return &User; 360 } 361 362 bool AArch64PromoteConstant::isDominated(Instruction *NewPt, Instruction *User, 363 unsigned OpNo, 364 InsertionPoints &InsertPts) { 365 366 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>( 367 *NewPt->getParent()->getParent()).getDomTree(); 368 369 // Traverse all the existing insertion points and check if one is dominating 370 // NewPt. If it is, remember that. 371 for (auto &IPI : InsertPts) { 372 if (NewPt == IPI.first || DT.dominates(IPI.first, NewPt) || 373 // When IPI.first is a terminator instruction, DT may think that 374 // the result is defined on the edge. 375 // Here we are testing the insertion point, not the definition. 376 (IPI.first->getParent() != NewPt->getParent() && 377 DT.dominates(IPI.first->getParent(), NewPt->getParent()))) { 378 // No need to insert this point. Just record the dominated use. 379 DEBUG(dbgs() << "Insertion point dominated by:\n"); 380 DEBUG(IPI.first->print(dbgs())); 381 DEBUG(dbgs() << '\n'); 382 IPI.second.emplace_back(User, OpNo); 383 return true; 384 } 385 } 386 return false; 387 } 388 389 bool AArch64PromoteConstant::tryAndMerge(Instruction *NewPt, Instruction *User, 390 unsigned OpNo, 391 InsertionPoints &InsertPts) { 392 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>( 393 *NewPt->getParent()->getParent()).getDomTree(); 394 BasicBlock *NewBB = NewPt->getParent(); 395 396 // Traverse all the existing insertion point and check if one is dominated by 397 // NewPt and thus useless or can be combined with NewPt into a common 398 // dominator. 399 for (InsertionPoints::iterator IPI = InsertPts.begin(), 400 EndIPI = InsertPts.end(); 401 IPI != EndIPI; ++IPI) { 402 BasicBlock *CurBB = IPI->first->getParent(); 403 if (NewBB == CurBB) { 404 // Instructions are in the same block. 405 // By construction, NewPt is dominating the other. 406 // Indeed, isDominated returned false with the exact same arguments. 407 DEBUG(dbgs() << "Merge insertion point with:\n"); 408 DEBUG(IPI->first->print(dbgs())); 409 DEBUG(dbgs() << "\nat considered insertion point.\n"); 410 appendAndTransferDominatedUses(NewPt, User, OpNo, IPI, InsertPts); 411 return true; 412 } 413 414 // Look for a common dominator 415 BasicBlock *CommonDominator = DT.findNearestCommonDominator(NewBB, CurBB); 416 // If none exists, we cannot merge these two points. 417 if (!CommonDominator) 418 continue; 419 420 if (CommonDominator != NewBB) { 421 // By construction, the CommonDominator cannot be CurBB. 422 assert(CommonDominator != CurBB && 423 "Instruction has not been rejected during isDominated check!"); 424 // Take the last instruction of the CommonDominator as insertion point 425 NewPt = CommonDominator->getTerminator(); 426 } 427 // else, CommonDominator is the block of NewBB, hence NewBB is the last 428 // possible insertion point in that block. 429 DEBUG(dbgs() << "Merge insertion point with:\n"); 430 DEBUG(IPI->first->print(dbgs())); 431 DEBUG(dbgs() << '\n'); 432 DEBUG(NewPt->print(dbgs())); 433 DEBUG(dbgs() << '\n'); 434 appendAndTransferDominatedUses(NewPt, User, OpNo, IPI, InsertPts); 435 return true; 436 } 437 return false; 438 } 439 440 void AArch64PromoteConstant::computeInsertionPoint( 441 Instruction *User, unsigned OpNo, InsertionPoints &InsertPts) { 442 DEBUG(dbgs() << "Considered use, opidx " << OpNo << ":\n"); 443 DEBUG(User->print(dbgs())); 444 DEBUG(dbgs() << '\n'); 445 446 Instruction *InsertionPoint = findInsertionPoint(*User, OpNo); 447 448 DEBUG(dbgs() << "Considered insertion point:\n"); 449 DEBUG(InsertionPoint->print(dbgs())); 450 DEBUG(dbgs() << '\n'); 451 452 if (isDominated(InsertionPoint, User, OpNo, InsertPts)) 453 return; 454 // This insertion point is useful, check if we can merge some insertion 455 // point in a common dominator or if NewPt dominates an existing one. 456 if (tryAndMerge(InsertionPoint, User, OpNo, InsertPts)) 457 return; 458 459 DEBUG(dbgs() << "Keep considered insertion point\n"); 460 461 // It is definitely useful by its own 462 InsertPts[InsertionPoint].emplace_back(User, OpNo); 463 } 464 465 static void ensurePromotedGV(Function &F, Constant &C, 466 AArch64PromoteConstant::PromotedConstant &PC) { 467 assert(PC.ShouldConvert && 468 "Expected that we should convert this to a global"); 469 if (PC.GV) 470 return; 471 PC.GV = new GlobalVariable( 472 *F.getParent(), C.getType(), true, GlobalValue::InternalLinkage, nullptr, 473 "_PromotedConst", nullptr, GlobalVariable::NotThreadLocal); 474 PC.GV->setInitializer(&C); 475 DEBUG(dbgs() << "Global replacement: "); 476 DEBUG(PC.GV->print(dbgs())); 477 DEBUG(dbgs() << '\n'); 478 ++NumPromoted; 479 } 480 481 void AArch64PromoteConstant::insertDefinitions(Function &F, 482 GlobalVariable &PromotedGV, 483 InsertionPoints &InsertPts) { 484 #ifndef NDEBUG 485 // Do more checking for debug purposes. 486 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>(F).getDomTree(); 487 #endif 488 assert(!InsertPts.empty() && "Empty uses does not need a definition"); 489 490 for (const auto &IPI : InsertPts) { 491 // Create the load of the global variable. 492 IRBuilder<> Builder(IPI.first); 493 LoadInst *LoadedCst = Builder.CreateLoad(&PromotedGV); 494 DEBUG(dbgs() << "**********\n"); 495 DEBUG(dbgs() << "New def: "); 496 DEBUG(LoadedCst->print(dbgs())); 497 DEBUG(dbgs() << '\n'); 498 499 // Update the dominated uses. 500 for (auto Use : IPI.second) { 501 #ifndef NDEBUG 502 assert(DT.dominates(LoadedCst, 503 findInsertionPoint(*Use.first, Use.second)) && 504 "Inserted definition does not dominate all its uses!"); 505 #endif 506 DEBUG({ 507 dbgs() << "Use to update " << Use.second << ":"; 508 Use.first->print(dbgs()); 509 dbgs() << '\n'; 510 }); 511 Use.first->setOperand(Use.second, LoadedCst); 512 ++NumPromotedUses; 513 } 514 } 515 } 516 517 void AArch64PromoteConstant::sortUpdates( 518 SmallVectorImpl<UpdateRecord> &Updates) { 519 // The order the constants were inserted is deterministic (unlike their 520 // address). 521 SmallDenseMap<const Constant *, unsigned, 128> InsertionOrder; 522 for (const auto &Record : Updates) 523 InsertionOrder.insert(std::make_pair(Record.C, InsertionOrder.size())); 524 525 // This is already sorted by Instruction ordering in the function and operand 526 // number, which is a good first step. Now reorder by constant. 527 std::stable_sort( 528 Updates.begin(), Updates.end(), 529 [&InsertionOrder](const UpdateRecord &L, const UpdateRecord &R) { 530 return InsertionOrder.lookup(L.C) < InsertionOrder.lookup(R.C); 531 }); 532 } 533 534 void AArch64PromoteConstant::promoteConstants( 535 Function &F, SmallVectorImpl<UpdateRecord> &Updates, 536 PromotionCacheTy &PromotionCache) { 537 // Promote the constants. 538 for (auto U = Updates.begin(), E = Updates.end(); U != E;) { 539 DEBUG(dbgs() << "** Compute insertion points **\n"); 540 auto First = U; 541 Constant *C = First->C; 542 InsertionPoints InsertPts; 543 do { 544 computeInsertionPoint(U->User, U->Op, InsertPts); 545 } while (++U != E && U->C == C); 546 547 auto &Promotion = PromotionCache[C]; 548 ensurePromotedGV(F, *C, Promotion); 549 insertDefinitions(F, *Promotion.GV, InsertPts); 550 } 551 } 552 553 bool AArch64PromoteConstant::runOnFunction(Function &F, 554 PromotionCacheTy &PromotionCache) { 555 // Look for instructions using constant vector. Promote that constant to a 556 // global variable. Create as few loads of this variable as possible and 557 // update the uses accordingly. 558 SmallVector<UpdateRecord, 64> Updates; 559 for (Instruction &I : instructions(&F)) { 560 // Traverse the operand, looking for constant vectors. Replace them by a 561 // load of a global variable of constant vector type. 562 for (Use &U : I.operands()) { 563 Constant *Cst = dyn_cast<Constant>(U); 564 // There is no point in promoting global values as they are already 565 // global. Do not promote constant expressions either, as they may 566 // require some code expansion. 567 if (!Cst || isa<GlobalValue>(Cst) || isa<ConstantExpr>(Cst)) 568 continue; 569 570 // Check if this constant is worth promoting. 571 if (!shouldConvert(*Cst, PromotionCache)) 572 continue; 573 574 // Check if this use should be promoted. 575 unsigned OpNo = &U - I.op_begin(); 576 if (!shouldConvertUse(Cst, &I, OpNo)) 577 continue; 578 579 Updates.emplace_back(Cst, &I, OpNo); 580 } 581 } 582 583 if (Updates.empty()) 584 return false; 585 586 promoteConstants(F, Updates, PromotionCache); 587 return true; 588 } 589