1 //===- CodeGenRegisters.cpp - Register and RegisterClass Info -------------===// 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 defines structures to encapsulate information gleaned from the 11 // target register and register class definitions. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "CodeGenRegisters.h" 16 #include "CodeGenTarget.h" 17 #include "llvm/ADT/IntEqClasses.h" 18 #include "llvm/ADT/STLExtras.h" 19 #include "llvm/ADT/SmallVector.h" 20 #include "llvm/ADT/StringExtras.h" 21 #include "llvm/ADT/Twine.h" 22 #include "llvm/Support/Debug.h" 23 #include "llvm/TableGen/Error.h" 24 25 using namespace llvm; 26 27 #define DEBUG_TYPE "regalloc-emitter" 28 29 //===----------------------------------------------------------------------===// 30 // CodeGenSubRegIndex 31 //===----------------------------------------------------------------------===// 32 33 CodeGenSubRegIndex::CodeGenSubRegIndex(Record *R, unsigned Enum) 34 : TheDef(R), EnumValue(Enum), LaneMask(0), AllSuperRegsCovered(true) { 35 Name = R->getName(); 36 if (R->getValue("Namespace")) 37 Namespace = R->getValueAsString("Namespace"); 38 Size = R->getValueAsInt("Size"); 39 Offset = R->getValueAsInt("Offset"); 40 } 41 42 CodeGenSubRegIndex::CodeGenSubRegIndex(StringRef N, StringRef Nspace, 43 unsigned Enum) 44 : TheDef(nullptr), Name(N), Namespace(Nspace), Size(-1), Offset(-1), 45 EnumValue(Enum), LaneMask(0), AllSuperRegsCovered(true) { 46 } 47 48 std::string CodeGenSubRegIndex::getQualifiedName() const { 49 std::string N = getNamespace(); 50 if (!N.empty()) 51 N += "::"; 52 N += getName(); 53 return N; 54 } 55 56 void CodeGenSubRegIndex::updateComponents(CodeGenRegBank &RegBank) { 57 if (!TheDef) 58 return; 59 60 std::vector<Record*> Comps = TheDef->getValueAsListOfDefs("ComposedOf"); 61 if (!Comps.empty()) { 62 if (Comps.size() != 2) 63 PrintFatalError(TheDef->getLoc(), 64 "ComposedOf must have exactly two entries"); 65 CodeGenSubRegIndex *A = RegBank.getSubRegIdx(Comps[0]); 66 CodeGenSubRegIndex *B = RegBank.getSubRegIdx(Comps[1]); 67 CodeGenSubRegIndex *X = A->addComposite(B, this); 68 if (X) 69 PrintFatalError(TheDef->getLoc(), "Ambiguous ComposedOf entries"); 70 } 71 72 std::vector<Record*> Parts = 73 TheDef->getValueAsListOfDefs("CoveringSubRegIndices"); 74 if (!Parts.empty()) { 75 if (Parts.size() < 2) 76 PrintFatalError(TheDef->getLoc(), 77 "CoveredBySubRegs must have two or more entries"); 78 SmallVector<CodeGenSubRegIndex*, 8> IdxParts; 79 for (unsigned i = 0, e = Parts.size(); i != e; ++i) 80 IdxParts.push_back(RegBank.getSubRegIdx(Parts[i])); 81 RegBank.addConcatSubRegIndex(IdxParts, this); 82 } 83 } 84 85 unsigned CodeGenSubRegIndex::computeLaneMask() const { 86 // Already computed? 87 if (LaneMask) 88 return LaneMask; 89 90 // Recursion guard, shouldn't be required. 91 LaneMask = ~0u; 92 93 // The lane mask is simply the union of all sub-indices. 94 unsigned M = 0; 95 for (const auto &C : Composed) 96 M |= C.second->computeLaneMask(); 97 assert(M && "Missing lane mask, sub-register cycle?"); 98 LaneMask = M; 99 return LaneMask; 100 } 101 102 //===----------------------------------------------------------------------===// 103 // CodeGenRegister 104 //===----------------------------------------------------------------------===// 105 106 CodeGenRegister::CodeGenRegister(Record *R, unsigned Enum) 107 : TheDef(R), 108 EnumValue(Enum), 109 CostPerUse(R->getValueAsInt("CostPerUse")), 110 CoveredBySubRegs(R->getValueAsBit("CoveredBySubRegs")), 111 NumNativeRegUnits(0), 112 SubRegsComplete(false), 113 SuperRegsComplete(false), 114 TopoSig(~0u) 115 {} 116 117 void CodeGenRegister::buildObjectGraph(CodeGenRegBank &RegBank) { 118 std::vector<Record*> SRIs = TheDef->getValueAsListOfDefs("SubRegIndices"); 119 std::vector<Record*> SRs = TheDef->getValueAsListOfDefs("SubRegs"); 120 121 if (SRIs.size() != SRs.size()) 122 PrintFatalError(TheDef->getLoc(), 123 "SubRegs and SubRegIndices must have the same size"); 124 125 for (unsigned i = 0, e = SRIs.size(); i != e; ++i) { 126 ExplicitSubRegIndices.push_back(RegBank.getSubRegIdx(SRIs[i])); 127 ExplicitSubRegs.push_back(RegBank.getReg(SRs[i])); 128 } 129 130 // Also compute leading super-registers. Each register has a list of 131 // covered-by-subregs super-registers where it appears as the first explicit 132 // sub-register. 133 // 134 // This is used by computeSecondarySubRegs() to find candidates. 135 if (CoveredBySubRegs && !ExplicitSubRegs.empty()) 136 ExplicitSubRegs.front()->LeadingSuperRegs.push_back(this); 137 138 // Add ad hoc alias links. This is a symmetric relationship between two 139 // registers, so build a symmetric graph by adding links in both ends. 140 std::vector<Record*> Aliases = TheDef->getValueAsListOfDefs("Aliases"); 141 for (unsigned i = 0, e = Aliases.size(); i != e; ++i) { 142 CodeGenRegister *Reg = RegBank.getReg(Aliases[i]); 143 ExplicitAliases.push_back(Reg); 144 Reg->ExplicitAliases.push_back(this); 145 } 146 } 147 148 const std::string &CodeGenRegister::getName() const { 149 return TheDef->getName(); 150 } 151 152 namespace { 153 // Iterate over all register units in a set of registers. 154 class RegUnitIterator { 155 CodeGenRegister::Set::const_iterator RegI, RegE; 156 CodeGenRegister::RegUnitList::const_iterator UnitI, UnitE; 157 158 public: 159 RegUnitIterator(const CodeGenRegister::Set &Regs): 160 RegI(Regs.begin()), RegE(Regs.end()), UnitI(), UnitE() { 161 162 if (RegI != RegE) { 163 UnitI = (*RegI)->getRegUnits().begin(); 164 UnitE = (*RegI)->getRegUnits().end(); 165 advance(); 166 } 167 } 168 169 bool isValid() const { return UnitI != UnitE; } 170 171 unsigned operator* () const { assert(isValid()); return *UnitI; } 172 173 const CodeGenRegister *getReg() const { assert(isValid()); return *RegI; } 174 175 /// Preincrement. Move to the next unit. 176 void operator++() { 177 assert(isValid() && "Cannot advance beyond the last operand"); 178 ++UnitI; 179 advance(); 180 } 181 182 protected: 183 void advance() { 184 while (UnitI == UnitE) { 185 if (++RegI == RegE) 186 break; 187 UnitI = (*RegI)->getRegUnits().begin(); 188 UnitE = (*RegI)->getRegUnits().end(); 189 } 190 } 191 }; 192 } // namespace 193 194 // Merge two RegUnitLists maintaining the order and removing duplicates. 195 // Overwrites MergedRU in the process. 196 static void mergeRegUnits(CodeGenRegister::RegUnitList &MergedRU, 197 const CodeGenRegister::RegUnitList &RRU) { 198 CodeGenRegister::RegUnitList LRU = MergedRU; 199 MergedRU.clear(); 200 std::set_union(LRU.begin(), LRU.end(), RRU.begin(), RRU.end(), 201 std::back_inserter(MergedRU)); 202 } 203 204 // Return true of this unit appears in RegUnits. 205 static bool hasRegUnit(CodeGenRegister::RegUnitList &RegUnits, unsigned Unit) { 206 return std::count(RegUnits.begin(), RegUnits.end(), Unit); 207 } 208 209 // Inherit register units from subregisters. 210 // Return true if the RegUnits changed. 211 bool CodeGenRegister::inheritRegUnits(CodeGenRegBank &RegBank) { 212 unsigned OldNumUnits = RegUnits.size(); 213 for (SubRegMap::const_iterator I = SubRegs.begin(), E = SubRegs.end(); 214 I != E; ++I) { 215 CodeGenRegister *SR = I->second; 216 // Merge the subregister's units into this register's RegUnits. 217 mergeRegUnits(RegUnits, SR->RegUnits); 218 } 219 return OldNumUnits != RegUnits.size(); 220 } 221 222 const CodeGenRegister::SubRegMap & 223 CodeGenRegister::computeSubRegs(CodeGenRegBank &RegBank) { 224 // Only compute this map once. 225 if (SubRegsComplete) 226 return SubRegs; 227 SubRegsComplete = true; 228 229 // First insert the explicit subregs and make sure they are fully indexed. 230 for (unsigned i = 0, e = ExplicitSubRegs.size(); i != e; ++i) { 231 CodeGenRegister *SR = ExplicitSubRegs[i]; 232 CodeGenSubRegIndex *Idx = ExplicitSubRegIndices[i]; 233 if (!SubRegs.insert(std::make_pair(Idx, SR)).second) 234 PrintFatalError(TheDef->getLoc(), "SubRegIndex " + Idx->getName() + 235 " appears twice in Register " + getName()); 236 // Map explicit sub-registers first, so the names take precedence. 237 // The inherited sub-registers are mapped below. 238 SubReg2Idx.insert(std::make_pair(SR, Idx)); 239 } 240 241 // Keep track of inherited subregs and how they can be reached. 242 SmallPtrSet<CodeGenRegister*, 8> Orphans; 243 244 // Clone inherited subregs and place duplicate entries in Orphans. 245 // Here the order is important - earlier subregs take precedence. 246 for (unsigned i = 0, e = ExplicitSubRegs.size(); i != e; ++i) { 247 CodeGenRegister *SR = ExplicitSubRegs[i]; 248 const SubRegMap &Map = SR->computeSubRegs(RegBank); 249 250 for (SubRegMap::const_iterator SI = Map.begin(), SE = Map.end(); SI != SE; 251 ++SI) { 252 if (!SubRegs.insert(*SI).second) 253 Orphans.insert(SI->second); 254 } 255 } 256 257 // Expand any composed subreg indices. 258 // If dsub_2 has ComposedOf = [qsub_1, dsub_0], and this register has a 259 // qsub_1 subreg, add a dsub_2 subreg. Keep growing Indices and process 260 // expanded subreg indices recursively. 261 SmallVector<CodeGenSubRegIndex*, 8> Indices = ExplicitSubRegIndices; 262 for (unsigned i = 0; i != Indices.size(); ++i) { 263 CodeGenSubRegIndex *Idx = Indices[i]; 264 const CodeGenSubRegIndex::CompMap &Comps = Idx->getComposites(); 265 CodeGenRegister *SR = SubRegs[Idx]; 266 const SubRegMap &Map = SR->computeSubRegs(RegBank); 267 268 // Look at the possible compositions of Idx. 269 // They may not all be supported by SR. 270 for (CodeGenSubRegIndex::CompMap::const_iterator I = Comps.begin(), 271 E = Comps.end(); I != E; ++I) { 272 SubRegMap::const_iterator SRI = Map.find(I->first); 273 if (SRI == Map.end()) 274 continue; // Idx + I->first doesn't exist in SR. 275 // Add I->second as a name for the subreg SRI->second, assuming it is 276 // orphaned, and the name isn't already used for something else. 277 if (SubRegs.count(I->second) || !Orphans.erase(SRI->second)) 278 continue; 279 // We found a new name for the orphaned sub-register. 280 SubRegs.insert(std::make_pair(I->second, SRI->second)); 281 Indices.push_back(I->second); 282 } 283 } 284 285 // Now Orphans contains the inherited subregisters without a direct index. 286 // Create inferred indexes for all missing entries. 287 // Work backwards in the Indices vector in order to compose subregs bottom-up. 288 // Consider this subreg sequence: 289 // 290 // qsub_1 -> dsub_0 -> ssub_0 291 // 292 // The qsub_1 -> dsub_0 composition becomes dsub_2, so the ssub_0 register 293 // can be reached in two different ways: 294 // 295 // qsub_1 -> ssub_0 296 // dsub_2 -> ssub_0 297 // 298 // We pick the latter composition because another register may have [dsub_0, 299 // dsub_1, dsub_2] subregs without necessarily having a qsub_1 subreg. The 300 // dsub_2 -> ssub_0 composition can be shared. 301 while (!Indices.empty() && !Orphans.empty()) { 302 CodeGenSubRegIndex *Idx = Indices.pop_back_val(); 303 CodeGenRegister *SR = SubRegs[Idx]; 304 const SubRegMap &Map = SR->computeSubRegs(RegBank); 305 for (SubRegMap::const_iterator SI = Map.begin(), SE = Map.end(); SI != SE; 306 ++SI) 307 if (Orphans.erase(SI->second)) 308 SubRegs[RegBank.getCompositeSubRegIndex(Idx, SI->first)] = SI->second; 309 } 310 311 // Compute the inverse SubReg -> Idx map. 312 for (SubRegMap::const_iterator SI = SubRegs.begin(), SE = SubRegs.end(); 313 SI != SE; ++SI) { 314 if (SI->second == this) { 315 ArrayRef<SMLoc> Loc; 316 if (TheDef) 317 Loc = TheDef->getLoc(); 318 PrintFatalError(Loc, "Register " + getName() + 319 " has itself as a sub-register"); 320 } 321 322 // Compute AllSuperRegsCovered. 323 if (!CoveredBySubRegs) 324 SI->first->AllSuperRegsCovered = false; 325 326 // Ensure that every sub-register has a unique name. 327 DenseMap<const CodeGenRegister*, CodeGenSubRegIndex*>::iterator Ins = 328 SubReg2Idx.insert(std::make_pair(SI->second, SI->first)).first; 329 if (Ins->second == SI->first) 330 continue; 331 // Trouble: Two different names for SI->second. 332 ArrayRef<SMLoc> Loc; 333 if (TheDef) 334 Loc = TheDef->getLoc(); 335 PrintFatalError(Loc, "Sub-register can't have two names: " + 336 SI->second->getName() + " available as " + 337 SI->first->getName() + " and " + Ins->second->getName()); 338 } 339 340 // Derive possible names for sub-register concatenations from any explicit 341 // sub-registers. By doing this before computeSecondarySubRegs(), we ensure 342 // that getConcatSubRegIndex() won't invent any concatenated indices that the 343 // user already specified. 344 for (unsigned i = 0, e = ExplicitSubRegs.size(); i != e; ++i) { 345 CodeGenRegister *SR = ExplicitSubRegs[i]; 346 if (!SR->CoveredBySubRegs || SR->ExplicitSubRegs.size() <= 1) 347 continue; 348 349 // SR is composed of multiple sub-regs. Find their names in this register. 350 SmallVector<CodeGenSubRegIndex*, 8> Parts; 351 for (unsigned j = 0, e = SR->ExplicitSubRegs.size(); j != e; ++j) 352 Parts.push_back(getSubRegIndex(SR->ExplicitSubRegs[j])); 353 354 // Offer this as an existing spelling for the concatenation of Parts. 355 RegBank.addConcatSubRegIndex(Parts, ExplicitSubRegIndices[i]); 356 } 357 358 // Initialize RegUnitList. Because getSubRegs is called recursively, this 359 // processes the register hierarchy in postorder. 360 // 361 // Inherit all sub-register units. It is good enough to look at the explicit 362 // sub-registers, the other registers won't contribute any more units. 363 for (unsigned i = 0, e = ExplicitSubRegs.size(); i != e; ++i) { 364 CodeGenRegister *SR = ExplicitSubRegs[i]; 365 // Explicit sub-registers are usually disjoint, so this is a good way of 366 // computing the union. We may pick up a few duplicates that will be 367 // eliminated below. 368 unsigned N = RegUnits.size(); 369 RegUnits.append(SR->RegUnits.begin(), SR->RegUnits.end()); 370 std::inplace_merge(RegUnits.begin(), RegUnits.begin() + N, RegUnits.end()); 371 } 372 RegUnits.erase(std::unique(RegUnits.begin(), RegUnits.end()), RegUnits.end()); 373 374 // Absent any ad hoc aliasing, we create one register unit per leaf register. 375 // These units correspond to the maximal cliques in the register overlap 376 // graph which is optimal. 377 // 378 // When there is ad hoc aliasing, we simply create one unit per edge in the 379 // undirected ad hoc aliasing graph. Technically, we could do better by 380 // identifying maximal cliques in the ad hoc graph, but cliques larger than 2 381 // are extremely rare anyway (I've never seen one), so we don't bother with 382 // the added complexity. 383 for (unsigned i = 0, e = ExplicitAliases.size(); i != e; ++i) { 384 CodeGenRegister *AR = ExplicitAliases[i]; 385 // Only visit each edge once. 386 if (AR->SubRegsComplete) 387 continue; 388 // Create a RegUnit representing this alias edge, and add it to both 389 // registers. 390 unsigned Unit = RegBank.newRegUnit(this, AR); 391 RegUnits.push_back(Unit); 392 AR->RegUnits.push_back(Unit); 393 } 394 395 // Finally, create units for leaf registers without ad hoc aliases. Note that 396 // a leaf register with ad hoc aliases doesn't get its own unit - it isn't 397 // necessary. This means the aliasing leaf registers can share a single unit. 398 if (RegUnits.empty()) 399 RegUnits.push_back(RegBank.newRegUnit(this)); 400 401 // We have now computed the native register units. More may be adopted later 402 // for balancing purposes. 403 NumNativeRegUnits = RegUnits.size(); 404 405 return SubRegs; 406 } 407 408 // In a register that is covered by its sub-registers, try to find redundant 409 // sub-registers. For example: 410 // 411 // QQ0 = {Q0, Q1} 412 // Q0 = {D0, D1} 413 // Q1 = {D2, D3} 414 // 415 // We can infer that D1_D2 is also a sub-register, even if it wasn't named in 416 // the register definition. 417 // 418 // The explicitly specified registers form a tree. This function discovers 419 // sub-register relationships that would force a DAG. 420 // 421 void CodeGenRegister::computeSecondarySubRegs(CodeGenRegBank &RegBank) { 422 // Collect new sub-registers first, add them later. 423 SmallVector<SubRegMap::value_type, 8> NewSubRegs; 424 425 // Look at the leading super-registers of each sub-register. Those are the 426 // candidates for new sub-registers, assuming they are fully contained in 427 // this register. 428 for (SubRegMap::iterator I = SubRegs.begin(), E = SubRegs.end(); I != E; ++I){ 429 const CodeGenRegister *SubReg = I->second; 430 const CodeGenRegister::SuperRegList &Leads = SubReg->LeadingSuperRegs; 431 for (unsigned i = 0, e = Leads.size(); i != e; ++i) { 432 CodeGenRegister *Cand = const_cast<CodeGenRegister*>(Leads[i]); 433 // Already got this sub-register? 434 if (Cand == this || getSubRegIndex(Cand)) 435 continue; 436 // Check if each component of Cand is already a sub-register. 437 // We know that the first component is I->second, and is present with the 438 // name I->first. 439 SmallVector<CodeGenSubRegIndex*, 8> Parts(1, I->first); 440 assert(!Cand->ExplicitSubRegs.empty() && 441 "Super-register has no sub-registers"); 442 for (unsigned j = 1, e = Cand->ExplicitSubRegs.size(); j != e; ++j) { 443 if (CodeGenSubRegIndex *Idx = getSubRegIndex(Cand->ExplicitSubRegs[j])) 444 Parts.push_back(Idx); 445 else { 446 // Sub-register doesn't exist. 447 Parts.clear(); 448 break; 449 } 450 } 451 // If some Cand sub-register is not part of this register, or if Cand only 452 // has one sub-register, there is nothing to do. 453 if (Parts.size() <= 1) 454 continue; 455 456 // Each part of Cand is a sub-register of this. Make the full Cand also 457 // a sub-register with a concatenated sub-register index. 458 CodeGenSubRegIndex *Concat= RegBank.getConcatSubRegIndex(Parts); 459 NewSubRegs.push_back(std::make_pair(Concat, Cand)); 460 } 461 } 462 463 // Now add all the new sub-registers. 464 for (unsigned i = 0, e = NewSubRegs.size(); i != e; ++i) { 465 // Don't add Cand if another sub-register is already using the index. 466 if (!SubRegs.insert(NewSubRegs[i]).second) 467 continue; 468 469 CodeGenSubRegIndex *NewIdx = NewSubRegs[i].first; 470 CodeGenRegister *NewSubReg = NewSubRegs[i].second; 471 SubReg2Idx.insert(std::make_pair(NewSubReg, NewIdx)); 472 } 473 474 // Create sub-register index composition maps for the synthesized indices. 475 for (unsigned i = 0, e = NewSubRegs.size(); i != e; ++i) { 476 CodeGenSubRegIndex *NewIdx = NewSubRegs[i].first; 477 CodeGenRegister *NewSubReg = NewSubRegs[i].second; 478 for (SubRegMap::const_iterator SI = NewSubReg->SubRegs.begin(), 479 SE = NewSubReg->SubRegs.end(); SI != SE; ++SI) { 480 CodeGenSubRegIndex *SubIdx = getSubRegIndex(SI->second); 481 if (!SubIdx) 482 PrintFatalError(TheDef->getLoc(), "No SubRegIndex for " + 483 SI->second->getName() + " in " + getName()); 484 NewIdx->addComposite(SI->first, SubIdx); 485 } 486 } 487 } 488 489 void CodeGenRegister::computeSuperRegs(CodeGenRegBank &RegBank) { 490 // Only visit each register once. 491 if (SuperRegsComplete) 492 return; 493 SuperRegsComplete = true; 494 495 // Make sure all sub-registers have been visited first, so the super-reg 496 // lists will be topologically ordered. 497 for (SubRegMap::const_iterator I = SubRegs.begin(), E = SubRegs.end(); 498 I != E; ++I) 499 I->second->computeSuperRegs(RegBank); 500 501 // Now add this as a super-register on all sub-registers. 502 // Also compute the TopoSigId in post-order. 503 TopoSigId Id; 504 for (SubRegMap::const_iterator I = SubRegs.begin(), E = SubRegs.end(); 505 I != E; ++I) { 506 // Topological signature computed from SubIdx, TopoId(SubReg). 507 // Loops and idempotent indices have TopoSig = ~0u. 508 Id.push_back(I->first->EnumValue); 509 Id.push_back(I->second->TopoSig); 510 511 // Don't add duplicate entries. 512 if (!I->second->SuperRegs.empty() && I->second->SuperRegs.back() == this) 513 continue; 514 I->second->SuperRegs.push_back(this); 515 } 516 TopoSig = RegBank.getTopoSig(Id); 517 } 518 519 void 520 CodeGenRegister::addSubRegsPreOrder(SetVector<const CodeGenRegister*> &OSet, 521 CodeGenRegBank &RegBank) const { 522 assert(SubRegsComplete && "Must precompute sub-registers"); 523 for (unsigned i = 0, e = ExplicitSubRegs.size(); i != e; ++i) { 524 CodeGenRegister *SR = ExplicitSubRegs[i]; 525 if (OSet.insert(SR)) 526 SR->addSubRegsPreOrder(OSet, RegBank); 527 } 528 // Add any secondary sub-registers that weren't part of the explicit tree. 529 for (SubRegMap::const_iterator I = SubRegs.begin(), E = SubRegs.end(); 530 I != E; ++I) 531 OSet.insert(I->second); 532 } 533 534 // Get the sum of this register's unit weights. 535 unsigned CodeGenRegister::getWeight(const CodeGenRegBank &RegBank) const { 536 unsigned Weight = 0; 537 for (RegUnitList::const_iterator I = RegUnits.begin(), E = RegUnits.end(); 538 I != E; ++I) { 539 Weight += RegBank.getRegUnit(*I).Weight; 540 } 541 return Weight; 542 } 543 544 //===----------------------------------------------------------------------===// 545 // RegisterTuples 546 //===----------------------------------------------------------------------===// 547 548 // A RegisterTuples def is used to generate pseudo-registers from lists of 549 // sub-registers. We provide a SetTheory expander class that returns the new 550 // registers. 551 namespace { 552 struct TupleExpander : SetTheory::Expander { 553 void expand(SetTheory &ST, Record *Def, SetTheory::RecSet &Elts) override { 554 std::vector<Record*> Indices = Def->getValueAsListOfDefs("SubRegIndices"); 555 unsigned Dim = Indices.size(); 556 ListInit *SubRegs = Def->getValueAsListInit("SubRegs"); 557 if (Dim != SubRegs->getSize()) 558 PrintFatalError(Def->getLoc(), "SubRegIndices and SubRegs size mismatch"); 559 if (Dim < 2) 560 PrintFatalError(Def->getLoc(), 561 "Tuples must have at least 2 sub-registers"); 562 563 // Evaluate the sub-register lists to be zipped. 564 unsigned Length = ~0u; 565 SmallVector<SetTheory::RecSet, 4> Lists(Dim); 566 for (unsigned i = 0; i != Dim; ++i) { 567 ST.evaluate(SubRegs->getElement(i), Lists[i], Def->getLoc()); 568 Length = std::min(Length, unsigned(Lists[i].size())); 569 } 570 571 if (Length == 0) 572 return; 573 574 // Precompute some types. 575 Record *RegisterCl = Def->getRecords().getClass("Register"); 576 RecTy *RegisterRecTy = RecordRecTy::get(RegisterCl); 577 StringInit *BlankName = StringInit::get(""); 578 579 // Zip them up. 580 for (unsigned n = 0; n != Length; ++n) { 581 std::string Name; 582 Record *Proto = Lists[0][n]; 583 std::vector<Init*> Tuple; 584 unsigned CostPerUse = 0; 585 for (unsigned i = 0; i != Dim; ++i) { 586 Record *Reg = Lists[i][n]; 587 if (i) Name += '_'; 588 Name += Reg->getName(); 589 Tuple.push_back(DefInit::get(Reg)); 590 CostPerUse = std::max(CostPerUse, 591 unsigned(Reg->getValueAsInt("CostPerUse"))); 592 } 593 594 // Create a new Record representing the synthesized register. This record 595 // is only for consumption by CodeGenRegister, it is not added to the 596 // RecordKeeper. 597 Record *NewReg = new Record(Name, Def->getLoc(), Def->getRecords()); 598 Elts.insert(NewReg); 599 600 // Copy Proto super-classes. 601 ArrayRef<Record *> Supers = Proto->getSuperClasses(); 602 ArrayRef<SMRange> Ranges = Proto->getSuperClassRanges(); 603 for (unsigned i = 0, e = Supers.size(); i != e; ++i) 604 NewReg->addSuperClass(Supers[i], Ranges[i]); 605 606 // Copy Proto fields. 607 for (unsigned i = 0, e = Proto->getValues().size(); i != e; ++i) { 608 RecordVal RV = Proto->getValues()[i]; 609 610 // Skip existing fields, like NAME. 611 if (NewReg->getValue(RV.getNameInit())) 612 continue; 613 614 StringRef Field = RV.getName(); 615 616 // Replace the sub-register list with Tuple. 617 if (Field == "SubRegs") 618 RV.setValue(ListInit::get(Tuple, RegisterRecTy)); 619 620 // Provide a blank AsmName. MC hacks are required anyway. 621 if (Field == "AsmName") 622 RV.setValue(BlankName); 623 624 // CostPerUse is aggregated from all Tuple members. 625 if (Field == "CostPerUse") 626 RV.setValue(IntInit::get(CostPerUse)); 627 628 // Composite registers are always covered by sub-registers. 629 if (Field == "CoveredBySubRegs") 630 RV.setValue(BitInit::get(true)); 631 632 // Copy fields from the RegisterTuples def. 633 if (Field == "SubRegIndices" || 634 Field == "CompositeIndices") { 635 NewReg->addValue(*Def->getValue(Field)); 636 continue; 637 } 638 639 // Some fields get their default uninitialized value. 640 if (Field == "DwarfNumbers" || 641 Field == "DwarfAlias" || 642 Field == "Aliases") { 643 if (const RecordVal *DefRV = RegisterCl->getValue(Field)) 644 NewReg->addValue(*DefRV); 645 continue; 646 } 647 648 // Everything else is copied from Proto. 649 NewReg->addValue(RV); 650 } 651 } 652 } 653 }; 654 } 655 656 //===----------------------------------------------------------------------===// 657 // CodeGenRegisterClass 658 //===----------------------------------------------------------------------===// 659 660 CodeGenRegisterClass::CodeGenRegisterClass(CodeGenRegBank &RegBank, Record *R) 661 : TheDef(R), 662 Name(R->getName()), 663 TopoSigs(RegBank.getNumTopoSigs()), 664 EnumValue(-1), 665 LaneMask(0) { 666 // Rename anonymous register classes. 667 if (R->getName().size() > 9 && R->getName()[9] == '.') { 668 static unsigned AnonCounter = 0; 669 R->setName("AnonRegClass_" + utostr(AnonCounter)); 670 // MSVC2012 ICEs if AnonCounter++ is directly passed to utostr. 671 ++AnonCounter; 672 } 673 674 std::vector<Record*> TypeList = R->getValueAsListOfDefs("RegTypes"); 675 for (unsigned i = 0, e = TypeList.size(); i != e; ++i) { 676 Record *Type = TypeList[i]; 677 if (!Type->isSubClassOf("ValueType")) 678 PrintFatalError("RegTypes list member '" + Type->getName() + 679 "' does not derive from the ValueType class!"); 680 VTs.push_back(getValueType(Type)); 681 } 682 assert(!VTs.empty() && "RegisterClass must contain at least one ValueType!"); 683 684 // Allocation order 0 is the full set. AltOrders provides others. 685 const SetTheory::RecVec *Elements = RegBank.getSets().expand(R); 686 ListInit *AltOrders = R->getValueAsListInit("AltOrders"); 687 Orders.resize(1 + AltOrders->size()); 688 689 // Default allocation order always contains all registers. 690 for (unsigned i = 0, e = Elements->size(); i != e; ++i) { 691 Orders[0].push_back((*Elements)[i]); 692 const CodeGenRegister *Reg = RegBank.getReg((*Elements)[i]); 693 Members.insert(Reg); 694 TopoSigs.set(Reg->getTopoSig()); 695 } 696 697 // Alternative allocation orders may be subsets. 698 SetTheory::RecSet Order; 699 for (unsigned i = 0, e = AltOrders->size(); i != e; ++i) { 700 RegBank.getSets().evaluate(AltOrders->getElement(i), Order, R->getLoc()); 701 Orders[1 + i].append(Order.begin(), Order.end()); 702 // Verify that all altorder members are regclass members. 703 while (!Order.empty()) { 704 CodeGenRegister *Reg = RegBank.getReg(Order.back()); 705 Order.pop_back(); 706 if (!contains(Reg)) 707 PrintFatalError(R->getLoc(), " AltOrder register " + Reg->getName() + 708 " is not a class member"); 709 } 710 } 711 712 // Allow targets to override the size in bits of the RegisterClass. 713 unsigned Size = R->getValueAsInt("Size"); 714 715 Namespace = R->getValueAsString("Namespace"); 716 SpillSize = Size ? Size : MVT(VTs[0]).getSizeInBits(); 717 SpillAlignment = R->getValueAsInt("Alignment"); 718 CopyCost = R->getValueAsInt("CopyCost"); 719 Allocatable = R->getValueAsBit("isAllocatable"); 720 AltOrderSelect = R->getValueAsString("AltOrderSelect"); 721 } 722 723 // Create an inferred register class that was missing from the .td files. 724 // Most properties will be inherited from the closest super-class after the 725 // class structure has been computed. 726 CodeGenRegisterClass::CodeGenRegisterClass(CodeGenRegBank &RegBank, 727 StringRef Name, Key Props) 728 : Members(*Props.Members), 729 TheDef(nullptr), 730 Name(Name), 731 TopoSigs(RegBank.getNumTopoSigs()), 732 EnumValue(-1), 733 SpillSize(Props.SpillSize), 734 SpillAlignment(Props.SpillAlignment), 735 CopyCost(0), 736 Allocatable(true) { 737 for (CodeGenRegister::Set::iterator I = Members.begin(), E = Members.end(); 738 I != E; ++I) 739 TopoSigs.set((*I)->getTopoSig()); 740 } 741 742 // Compute inherited propertied for a synthesized register class. 743 void CodeGenRegisterClass::inheritProperties(CodeGenRegBank &RegBank) { 744 assert(!getDef() && "Only synthesized classes can inherit properties"); 745 assert(!SuperClasses.empty() && "Synthesized class without super class"); 746 747 // The last super-class is the smallest one. 748 CodeGenRegisterClass &Super = *SuperClasses.back(); 749 750 // Most properties are copied directly. 751 // Exceptions are members, size, and alignment 752 Namespace = Super.Namespace; 753 VTs = Super.VTs; 754 CopyCost = Super.CopyCost; 755 Allocatable = Super.Allocatable; 756 AltOrderSelect = Super.AltOrderSelect; 757 758 // Copy all allocation orders, filter out foreign registers from the larger 759 // super-class. 760 Orders.resize(Super.Orders.size()); 761 for (unsigned i = 0, ie = Super.Orders.size(); i != ie; ++i) 762 for (unsigned j = 0, je = Super.Orders[i].size(); j != je; ++j) 763 if (contains(RegBank.getReg(Super.Orders[i][j]))) 764 Orders[i].push_back(Super.Orders[i][j]); 765 } 766 767 bool CodeGenRegisterClass::contains(const CodeGenRegister *Reg) const { 768 return Members.count(Reg); 769 } 770 771 namespace llvm { 772 raw_ostream &operator<<(raw_ostream &OS, const CodeGenRegisterClass::Key &K) { 773 OS << "{ S=" << K.SpillSize << ", A=" << K.SpillAlignment; 774 for (CodeGenRegister::Set::const_iterator I = K.Members->begin(), 775 E = K.Members->end(); I != E; ++I) 776 OS << ", " << (*I)->getName(); 777 return OS << " }"; 778 } 779 } 780 781 // This is a simple lexicographical order that can be used to search for sets. 782 // It is not the same as the topological order provided by TopoOrderRC. 783 bool CodeGenRegisterClass::Key:: 784 operator<(const CodeGenRegisterClass::Key &B) const { 785 assert(Members && B.Members); 786 return std::tie(*Members, SpillSize, SpillAlignment) < 787 std::tie(*B.Members, B.SpillSize, B.SpillAlignment); 788 } 789 790 // Returns true if RC is a strict subclass. 791 // RC is a sub-class of this class if it is a valid replacement for any 792 // instruction operand where a register of this classis required. It must 793 // satisfy these conditions: 794 // 795 // 1. All RC registers are also in this. 796 // 2. The RC spill size must not be smaller than our spill size. 797 // 3. RC spill alignment must be compatible with ours. 798 // 799 static bool testSubClass(const CodeGenRegisterClass *A, 800 const CodeGenRegisterClass *B) { 801 return A->SpillAlignment && B->SpillAlignment % A->SpillAlignment == 0 && 802 A->SpillSize <= B->SpillSize && 803 std::includes(A->getMembers().begin(), A->getMembers().end(), 804 B->getMembers().begin(), B->getMembers().end(), 805 CodeGenRegister::Less()); 806 } 807 808 /// Sorting predicate for register classes. This provides a topological 809 /// ordering that arranges all register classes before their sub-classes. 810 /// 811 /// Register classes with the same registers, spill size, and alignment form a 812 /// clique. They will be ordered alphabetically. 813 /// 814 static bool TopoOrderRC(const CodeGenRegisterClass &PA, 815 const CodeGenRegisterClass &PB) { 816 auto *A = &PA; 817 auto *B = &PB; 818 if (A == B) 819 return 0; 820 821 // Order by ascending spill size. 822 if (A->SpillSize < B->SpillSize) 823 return true; 824 if (A->SpillSize > B->SpillSize) 825 return false; 826 827 // Order by ascending spill alignment. 828 if (A->SpillAlignment < B->SpillAlignment) 829 return true; 830 if (A->SpillAlignment > B->SpillAlignment) 831 return false; 832 833 // Order by descending set size. Note that the classes' allocation order may 834 // not have been computed yet. The Members set is always vaild. 835 if (A->getMembers().size() > B->getMembers().size()) 836 return true; 837 if (A->getMembers().size() < B->getMembers().size()) 838 return false; 839 840 // Finally order by name as a tie breaker. 841 return StringRef(A->getName()) < B->getName(); 842 } 843 844 std::string CodeGenRegisterClass::getQualifiedName() const { 845 if (Namespace.empty()) 846 return getName(); 847 else 848 return Namespace + "::" + getName(); 849 } 850 851 // Compute sub-classes of all register classes. 852 // Assume the classes are ordered topologically. 853 void CodeGenRegisterClass::computeSubClasses(CodeGenRegBank &RegBank) { 854 auto &RegClasses = RegBank.getRegClasses(); 855 856 // Visit backwards so sub-classes are seen first. 857 for (auto I = RegClasses.rbegin(), E = RegClasses.rend(); I != E; ++I) { 858 CodeGenRegisterClass &RC = *I; 859 RC.SubClasses.resize(RegClasses.size()); 860 RC.SubClasses.set(RC.EnumValue); 861 862 // Normally, all subclasses have IDs >= rci, unless RC is part of a clique. 863 for (auto I2 = I.base(), E2 = RegClasses.end(); I2 != E2; ++I2) { 864 CodeGenRegisterClass &SubRC = *I2; 865 if (RC.SubClasses.test(SubRC.EnumValue)) 866 continue; 867 if (!testSubClass(&RC, &SubRC)) 868 continue; 869 // SubRC is a sub-class. Grap all its sub-classes so we won't have to 870 // check them again. 871 RC.SubClasses |= SubRC.SubClasses; 872 } 873 874 // Sweep up missed clique members. They will be immediately preceding RC. 875 for (auto I2 = std::next(I); I2 != E && testSubClass(&RC, &*I2); ++I2) 876 RC.SubClasses.set(I2->EnumValue); 877 } 878 879 // Compute the SuperClasses lists from the SubClasses vectors. 880 for (auto &RC : RegClasses) { 881 const BitVector &SC = RC.getSubClasses(); 882 auto I = RegClasses.begin(); 883 for (int s = 0, next_s = SC.find_first(); next_s != -1; 884 next_s = SC.find_next(s)) { 885 std::advance(I, next_s - s); 886 s = next_s; 887 if (&*I == &RC) 888 continue; 889 I->SuperClasses.push_back(&RC); 890 } 891 } 892 893 // With the class hierarchy in place, let synthesized register classes inherit 894 // properties from their closest super-class. The iteration order here can 895 // propagate properties down multiple levels. 896 for (auto &RC : RegClasses) 897 if (!RC.getDef()) 898 RC.inheritProperties(RegBank); 899 } 900 901 void CodeGenRegisterClass::getSuperRegClasses(const CodeGenSubRegIndex *SubIdx, 902 BitVector &Out) const { 903 auto FindI = SuperRegClasses.find(SubIdx); 904 if (FindI == SuperRegClasses.end()) 905 return; 906 for (CodeGenRegisterClass *RC : FindI->second) 907 Out.set(RC->EnumValue); 908 } 909 910 // Populate a unique sorted list of units from a register set. 911 void CodeGenRegisterClass::buildRegUnitSet( 912 std::vector<unsigned> &RegUnits) const { 913 std::vector<unsigned> TmpUnits; 914 for (RegUnitIterator UnitI(Members); UnitI.isValid(); ++UnitI) 915 TmpUnits.push_back(*UnitI); 916 std::sort(TmpUnits.begin(), TmpUnits.end()); 917 std::unique_copy(TmpUnits.begin(), TmpUnits.end(), 918 std::back_inserter(RegUnits)); 919 } 920 921 //===----------------------------------------------------------------------===// 922 // CodeGenRegBank 923 //===----------------------------------------------------------------------===// 924 925 CodeGenRegBank::CodeGenRegBank(RecordKeeper &Records) { 926 // Configure register Sets to understand register classes and tuples. 927 Sets.addFieldExpander("RegisterClass", "MemberList"); 928 Sets.addFieldExpander("CalleeSavedRegs", "SaveList"); 929 Sets.addExpander("RegisterTuples", new TupleExpander()); 930 931 // Read in the user-defined (named) sub-register indices. 932 // More indices will be synthesized later. 933 std::vector<Record*> SRIs = Records.getAllDerivedDefinitions("SubRegIndex"); 934 std::sort(SRIs.begin(), SRIs.end(), LessRecord()); 935 for (unsigned i = 0, e = SRIs.size(); i != e; ++i) 936 getSubRegIdx(SRIs[i]); 937 // Build composite maps from ComposedOf fields. 938 for (auto &Idx : SubRegIndices) 939 Idx.updateComponents(*this); 940 941 // Read in the register definitions. 942 std::vector<Record*> Regs = Records.getAllDerivedDefinitions("Register"); 943 std::sort(Regs.begin(), Regs.end(), LessRecordRegister()); 944 // Assign the enumeration values. 945 for (unsigned i = 0, e = Regs.size(); i != e; ++i) 946 getReg(Regs[i]); 947 948 // Expand tuples and number the new registers. 949 std::vector<Record*> Tups = 950 Records.getAllDerivedDefinitions("RegisterTuples"); 951 952 for (Record *R : Tups) { 953 std::vector<Record *> TupRegs = *Sets.expand(R); 954 std::sort(TupRegs.begin(), TupRegs.end(), LessRecordRegister()); 955 for (Record *RC : TupRegs) 956 getReg(RC); 957 } 958 959 // Now all the registers are known. Build the object graph of explicit 960 // register-register references. 961 for (auto &Reg : Registers) 962 Reg.buildObjectGraph(*this); 963 964 // Compute register name map. 965 for (auto &Reg : Registers) 966 // FIXME: This could just be RegistersByName[name] = register, except that 967 // causes some failures in MIPS - perhaps they have duplicate register name 968 // entries? (or maybe there's a reason for it - I don't know much about this 969 // code, just drive-by refactoring) 970 RegistersByName.insert( 971 std::make_pair(Reg.TheDef->getValueAsString("AsmName"), &Reg)); 972 973 // Precompute all sub-register maps. 974 // This will create Composite entries for all inferred sub-register indices. 975 for (auto &Reg : Registers) 976 Reg.computeSubRegs(*this); 977 978 // Infer even more sub-registers by combining leading super-registers. 979 for (auto &Reg : Registers) 980 if (Reg.CoveredBySubRegs) 981 Reg.computeSecondarySubRegs(*this); 982 983 // After the sub-register graph is complete, compute the topologically 984 // ordered SuperRegs list. 985 for (auto &Reg : Registers) 986 Reg.computeSuperRegs(*this); 987 988 // Native register units are associated with a leaf register. They've all been 989 // discovered now. 990 NumNativeRegUnits = RegUnits.size(); 991 992 // Read in register class definitions. 993 std::vector<Record*> RCs = Records.getAllDerivedDefinitions("RegisterClass"); 994 if (RCs.empty()) 995 PrintFatalError("No 'RegisterClass' subclasses defined!"); 996 997 // Allocate user-defined register classes. 998 for (auto *RC : RCs) { 999 RegClasses.push_back(CodeGenRegisterClass(*this, RC)); 1000 addToMaps(&RegClasses.back()); 1001 } 1002 1003 // Infer missing classes to create a full algebra. 1004 computeInferredRegisterClasses(); 1005 1006 // Order register classes topologically and assign enum values. 1007 RegClasses.sort(TopoOrderRC); 1008 unsigned i = 0; 1009 for (auto &RC : RegClasses) 1010 RC.EnumValue = i++; 1011 CodeGenRegisterClass::computeSubClasses(*this); 1012 } 1013 1014 // Create a synthetic CodeGenSubRegIndex without a corresponding Record. 1015 CodeGenSubRegIndex* 1016 CodeGenRegBank::createSubRegIndex(StringRef Name, StringRef Namespace) { 1017 SubRegIndices.emplace_back(Name, Namespace, SubRegIndices.size() + 1); 1018 return &SubRegIndices.back(); 1019 } 1020 1021 CodeGenSubRegIndex *CodeGenRegBank::getSubRegIdx(Record *Def) { 1022 CodeGenSubRegIndex *&Idx = Def2SubRegIdx[Def]; 1023 if (Idx) 1024 return Idx; 1025 SubRegIndices.emplace_back(Def, SubRegIndices.size() + 1); 1026 Idx = &SubRegIndices.back(); 1027 return Idx; 1028 } 1029 1030 CodeGenRegister *CodeGenRegBank::getReg(Record *Def) { 1031 CodeGenRegister *&Reg = Def2Reg[Def]; 1032 if (Reg) 1033 return Reg; 1034 Registers.emplace_back(Def, Registers.size() + 1); 1035 Reg = &Registers.back(); 1036 return Reg; 1037 } 1038 1039 void CodeGenRegBank::addToMaps(CodeGenRegisterClass *RC) { 1040 if (Record *Def = RC->getDef()) 1041 Def2RC.insert(std::make_pair(Def, RC)); 1042 1043 // Duplicate classes are rejected by insert(). 1044 // That's OK, we only care about the properties handled by CGRC::Key. 1045 CodeGenRegisterClass::Key K(*RC); 1046 Key2RC.insert(std::make_pair(K, RC)); 1047 } 1048 1049 // Create a synthetic sub-class if it is missing. 1050 CodeGenRegisterClass* 1051 CodeGenRegBank::getOrCreateSubClass(const CodeGenRegisterClass *RC, 1052 const CodeGenRegister::Set *Members, 1053 StringRef Name) { 1054 // Synthetic sub-class has the same size and alignment as RC. 1055 CodeGenRegisterClass::Key K(Members, RC->SpillSize, RC->SpillAlignment); 1056 RCKeyMap::const_iterator FoundI = Key2RC.find(K); 1057 if (FoundI != Key2RC.end()) 1058 return FoundI->second; 1059 1060 // Sub-class doesn't exist, create a new one. 1061 RegClasses.push_back(CodeGenRegisterClass(*this, Name, K)); 1062 addToMaps(&RegClasses.back()); 1063 return &RegClasses.back(); 1064 } 1065 1066 CodeGenRegisterClass *CodeGenRegBank::getRegClass(Record *Def) { 1067 if (CodeGenRegisterClass *RC = Def2RC[Def]) 1068 return RC; 1069 1070 PrintFatalError(Def->getLoc(), "Not a known RegisterClass!"); 1071 } 1072 1073 CodeGenSubRegIndex* 1074 CodeGenRegBank::getCompositeSubRegIndex(CodeGenSubRegIndex *A, 1075 CodeGenSubRegIndex *B) { 1076 // Look for an existing entry. 1077 CodeGenSubRegIndex *Comp = A->compose(B); 1078 if (Comp) 1079 return Comp; 1080 1081 // None exists, synthesize one. 1082 std::string Name = A->getName() + "_then_" + B->getName(); 1083 Comp = createSubRegIndex(Name, A->getNamespace()); 1084 A->addComposite(B, Comp); 1085 return Comp; 1086 } 1087 1088 CodeGenSubRegIndex *CodeGenRegBank:: 1089 getConcatSubRegIndex(const SmallVector<CodeGenSubRegIndex *, 8> &Parts) { 1090 assert(Parts.size() > 1 && "Need two parts to concatenate"); 1091 1092 // Look for an existing entry. 1093 CodeGenSubRegIndex *&Idx = ConcatIdx[Parts]; 1094 if (Idx) 1095 return Idx; 1096 1097 // None exists, synthesize one. 1098 std::string Name = Parts.front()->getName(); 1099 // Determine whether all parts are contiguous. 1100 bool isContinuous = true; 1101 unsigned Size = Parts.front()->Size; 1102 unsigned LastOffset = Parts.front()->Offset; 1103 unsigned LastSize = Parts.front()->Size; 1104 for (unsigned i = 1, e = Parts.size(); i != e; ++i) { 1105 Name += '_'; 1106 Name += Parts[i]->getName(); 1107 Size += Parts[i]->Size; 1108 if (Parts[i]->Offset != (LastOffset + LastSize)) 1109 isContinuous = false; 1110 LastOffset = Parts[i]->Offset; 1111 LastSize = Parts[i]->Size; 1112 } 1113 Idx = createSubRegIndex(Name, Parts.front()->getNamespace()); 1114 Idx->Size = Size; 1115 Idx->Offset = isContinuous ? Parts.front()->Offset : -1; 1116 return Idx; 1117 } 1118 1119 void CodeGenRegBank::computeComposites() { 1120 // Keep track of TopoSigs visited. We only need to visit each TopoSig once, 1121 // and many registers will share TopoSigs on regular architectures. 1122 BitVector TopoSigs(getNumTopoSigs()); 1123 1124 for (const auto &Reg1 : Registers) { 1125 // Skip identical subreg structures already processed. 1126 if (TopoSigs.test(Reg1.getTopoSig())) 1127 continue; 1128 TopoSigs.set(Reg1.getTopoSig()); 1129 1130 const CodeGenRegister::SubRegMap &SRM1 = Reg1.getSubRegs(); 1131 for (CodeGenRegister::SubRegMap::const_iterator i1 = SRM1.begin(), 1132 e1 = SRM1.end(); i1 != e1; ++i1) { 1133 CodeGenSubRegIndex *Idx1 = i1->first; 1134 CodeGenRegister *Reg2 = i1->second; 1135 // Ignore identity compositions. 1136 if (&Reg1 == Reg2) 1137 continue; 1138 const CodeGenRegister::SubRegMap &SRM2 = Reg2->getSubRegs(); 1139 // Try composing Idx1 with another SubRegIndex. 1140 for (CodeGenRegister::SubRegMap::const_iterator i2 = SRM2.begin(), 1141 e2 = SRM2.end(); i2 != e2; ++i2) { 1142 CodeGenSubRegIndex *Idx2 = i2->first; 1143 CodeGenRegister *Reg3 = i2->second; 1144 // Ignore identity compositions. 1145 if (Reg2 == Reg3) 1146 continue; 1147 // OK Reg1:IdxPair == Reg3. Find the index with Reg:Idx == Reg3. 1148 CodeGenSubRegIndex *Idx3 = Reg1.getSubRegIndex(Reg3); 1149 assert(Idx3 && "Sub-register doesn't have an index"); 1150 1151 // Conflicting composition? Emit a warning but allow it. 1152 if (CodeGenSubRegIndex *Prev = Idx1->addComposite(Idx2, Idx3)) 1153 PrintWarning(Twine("SubRegIndex ") + Idx1->getQualifiedName() + 1154 " and " + Idx2->getQualifiedName() + 1155 " compose ambiguously as " + Prev->getQualifiedName() + 1156 " or " + Idx3->getQualifiedName()); 1157 } 1158 } 1159 } 1160 } 1161 1162 // Compute lane masks. This is similar to register units, but at the 1163 // sub-register index level. Each bit in the lane mask is like a register unit 1164 // class, and two lane masks will have a bit in common if two sub-register 1165 // indices overlap in some register. 1166 // 1167 // Conservatively share a lane mask bit if two sub-register indices overlap in 1168 // some registers, but not in others. That shouldn't happen a lot. 1169 void CodeGenRegBank::computeSubRegLaneMasks() { 1170 // First assign individual bits to all the leaf indices. 1171 unsigned Bit = 0; 1172 // Determine mask of lanes that cover their registers. 1173 CoveringLanes = ~0u; 1174 for (auto &Idx : SubRegIndices) { 1175 if (Idx.getComposites().empty()) { 1176 Idx.LaneMask = 1u << Bit; 1177 // Share bit 31 in the unlikely case there are more than 32 leafs. 1178 // 1179 // Sharing bits is harmless; it allows graceful degradation in targets 1180 // with more than 32 vector lanes. They simply get a limited resolution 1181 // view of lanes beyond the 32nd. 1182 // 1183 // See also the comment for getSubRegIndexLaneMask(). 1184 if (Bit < 31) 1185 ++Bit; 1186 else 1187 // Once bit 31 is shared among multiple leafs, the 'lane' it represents 1188 // is no longer covering its registers. 1189 CoveringLanes &= ~(1u << Bit); 1190 } else { 1191 Idx.LaneMask = 0; 1192 } 1193 } 1194 1195 // Compute transformation sequences for composeSubRegIndexLaneMask. The idea 1196 // here is that for each possible target subregister we look at the leafs 1197 // in the subregister graph that compose for this target and create 1198 // transformation sequences for the lanemasks. Each step in the sequence 1199 // consists of a bitmask and a bitrotate operation. As the rotation amounts 1200 // are usually the same for many subregisters we can easily combine the steps 1201 // by combining the masks. 1202 for (const auto &Idx : SubRegIndices) { 1203 const auto &Composites = Idx.getComposites(); 1204 auto &LaneTransforms = Idx.CompositionLaneMaskTransform; 1205 // Go through all leaf subregisters and find the ones that compose with Idx. 1206 // These make out all possible valid bits in the lane mask we want to 1207 // transform. Looking only at the leafs ensure that only a single bit in 1208 // the mask is set. 1209 unsigned NextBit = 0; 1210 for (auto &Idx2 : SubRegIndices) { 1211 // Skip non-leaf subregisters. 1212 if (!Idx2.getComposites().empty()) 1213 continue; 1214 // Replicate the behaviour from the lane mask generation loop above. 1215 unsigned SrcBit = NextBit; 1216 unsigned SrcMask = 1u << SrcBit; 1217 if (NextBit < 31) 1218 ++NextBit; 1219 assert(Idx2.LaneMask == SrcMask); 1220 1221 // Get the composed subregister if there is any. 1222 auto C = Composites.find(&Idx2); 1223 if (C == Composites.end()) 1224 continue; 1225 const CodeGenSubRegIndex *Composite = C->second; 1226 // The Composed subreg should be a leaf subreg too 1227 assert(Composite->getComposites().empty()); 1228 1229 // Create Mask+Rotate operation and merge with existing ops if possible. 1230 unsigned DstBit = Log2_32(Composite->LaneMask); 1231 int Shift = DstBit - SrcBit; 1232 uint8_t RotateLeft = Shift >= 0 ? (uint8_t)Shift : 32+Shift; 1233 for (auto &I : LaneTransforms) { 1234 if (I.RotateLeft == RotateLeft) { 1235 I.Mask |= SrcMask; 1236 SrcMask = 0; 1237 } 1238 } 1239 if (SrcMask != 0) { 1240 MaskRolPair MaskRol = { SrcMask, RotateLeft }; 1241 LaneTransforms.push_back(MaskRol); 1242 } 1243 } 1244 // Optimize if the transformation consists of one step only: Set mask to 1245 // 0xffffffff (including some irrelevant invalid bits) so that it should 1246 // merge with more entries later while compressing the table. 1247 if (LaneTransforms.size() == 1) 1248 LaneTransforms[0].Mask = ~0u; 1249 1250 // Further compression optimization: For invalid compositions resulting 1251 // in a sequence with 0 entries we can just pick any other. Choose 1252 // Mask 0xffffffff with Rotation 0. 1253 if (LaneTransforms.size() == 0) { 1254 MaskRolPair P = { ~0u, 0 }; 1255 LaneTransforms.push_back(P); 1256 } 1257 } 1258 1259 // FIXME: What if ad-hoc aliasing introduces overlaps that aren't represented 1260 // by the sub-register graph? This doesn't occur in any known targets. 1261 1262 // Inherit lanes from composites. 1263 for (const auto &Idx : SubRegIndices) { 1264 unsigned Mask = Idx.computeLaneMask(); 1265 // If some super-registers without CoveredBySubRegs use this index, we can 1266 // no longer assume that the lanes are covering their registers. 1267 if (!Idx.AllSuperRegsCovered) 1268 CoveringLanes &= ~Mask; 1269 } 1270 1271 // Compute lane mask combinations for register classes. 1272 for (auto &RegClass : RegClasses) { 1273 unsigned LaneMask = 0; 1274 for (const auto &SubRegIndex : SubRegIndices) { 1275 if (RegClass.getSubClassWithSubReg(&SubRegIndex) != &RegClass) 1276 continue; 1277 LaneMask |= SubRegIndex.LaneMask; 1278 } 1279 RegClass.LaneMask = LaneMask; 1280 } 1281 } 1282 1283 namespace { 1284 // UberRegSet is a helper class for computeRegUnitWeights. Each UberRegSet is 1285 // the transitive closure of the union of overlapping register 1286 // classes. Together, the UberRegSets form a partition of the registers. If we 1287 // consider overlapping register classes to be connected, then each UberRegSet 1288 // is a set of connected components. 1289 // 1290 // An UberRegSet will likely be a horizontal slice of register names of 1291 // the same width. Nontrivial subregisters should then be in a separate 1292 // UberRegSet. But this property isn't required for valid computation of 1293 // register unit weights. 1294 // 1295 // A Weight field caches the max per-register unit weight in each UberRegSet. 1296 // 1297 // A set of SingularDeterminants flags single units of some register in this set 1298 // for which the unit weight equals the set weight. These units should not have 1299 // their weight increased. 1300 struct UberRegSet { 1301 CodeGenRegister::Set Regs; 1302 unsigned Weight; 1303 CodeGenRegister::RegUnitList SingularDeterminants; 1304 1305 UberRegSet(): Weight(0) {} 1306 }; 1307 } // namespace 1308 1309 // Partition registers into UberRegSets, where each set is the transitive 1310 // closure of the union of overlapping register classes. 1311 // 1312 // UberRegSets[0] is a special non-allocatable set. 1313 static void computeUberSets(std::vector<UberRegSet> &UberSets, 1314 std::vector<UberRegSet*> &RegSets, 1315 CodeGenRegBank &RegBank) { 1316 1317 const auto &Registers = RegBank.getRegisters(); 1318 1319 // The Register EnumValue is one greater than its index into Registers. 1320 assert(Registers.size() == Registers.back().EnumValue && 1321 "register enum value mismatch"); 1322 1323 // For simplicitly make the SetID the same as EnumValue. 1324 IntEqClasses UberSetIDs(Registers.size()+1); 1325 std::set<unsigned> AllocatableRegs; 1326 for (auto &RegClass : RegBank.getRegClasses()) { 1327 if (!RegClass.Allocatable) 1328 continue; 1329 1330 const CodeGenRegister::Set &Regs = RegClass.getMembers(); 1331 if (Regs.empty()) 1332 continue; 1333 1334 unsigned USetID = UberSetIDs.findLeader((*Regs.begin())->EnumValue); 1335 assert(USetID && "register number 0 is invalid"); 1336 1337 AllocatableRegs.insert((*Regs.begin())->EnumValue); 1338 for (CodeGenRegister::Set::const_iterator I = std::next(Regs.begin()), 1339 E = Regs.end(); I != E; ++I) { 1340 AllocatableRegs.insert((*I)->EnumValue); 1341 UberSetIDs.join(USetID, (*I)->EnumValue); 1342 } 1343 } 1344 // Combine non-allocatable regs. 1345 for (const auto &Reg : Registers) { 1346 unsigned RegNum = Reg.EnumValue; 1347 if (AllocatableRegs.count(RegNum)) 1348 continue; 1349 1350 UberSetIDs.join(0, RegNum); 1351 } 1352 UberSetIDs.compress(); 1353 1354 // Make the first UberSet a special unallocatable set. 1355 unsigned ZeroID = UberSetIDs[0]; 1356 1357 // Insert Registers into the UberSets formed by union-find. 1358 // Do not resize after this. 1359 UberSets.resize(UberSetIDs.getNumClasses()); 1360 unsigned i = 0; 1361 for (const CodeGenRegister &Reg : Registers) { 1362 unsigned USetID = UberSetIDs[Reg.EnumValue]; 1363 if (!USetID) 1364 USetID = ZeroID; 1365 else if (USetID == ZeroID) 1366 USetID = 0; 1367 1368 UberRegSet *USet = &UberSets[USetID]; 1369 USet->Regs.insert(&Reg); 1370 RegSets[i++] = USet; 1371 } 1372 } 1373 1374 // Recompute each UberSet weight after changing unit weights. 1375 static void computeUberWeights(std::vector<UberRegSet> &UberSets, 1376 CodeGenRegBank &RegBank) { 1377 // Skip the first unallocatable set. 1378 for (std::vector<UberRegSet>::iterator I = std::next(UberSets.begin()), 1379 E = UberSets.end(); I != E; ++I) { 1380 1381 // Initialize all unit weights in this set, and remember the max units/reg. 1382 const CodeGenRegister *Reg = nullptr; 1383 unsigned MaxWeight = 0, Weight = 0; 1384 for (RegUnitIterator UnitI(I->Regs); UnitI.isValid(); ++UnitI) { 1385 if (Reg != UnitI.getReg()) { 1386 if (Weight > MaxWeight) 1387 MaxWeight = Weight; 1388 Reg = UnitI.getReg(); 1389 Weight = 0; 1390 } 1391 unsigned UWeight = RegBank.getRegUnit(*UnitI).Weight; 1392 if (!UWeight) { 1393 UWeight = 1; 1394 RegBank.increaseRegUnitWeight(*UnitI, UWeight); 1395 } 1396 Weight += UWeight; 1397 } 1398 if (Weight > MaxWeight) 1399 MaxWeight = Weight; 1400 if (I->Weight != MaxWeight) { 1401 DEBUG( 1402 dbgs() << "UberSet " << I - UberSets.begin() << " Weight " << MaxWeight; 1403 for (auto &Unit : I->Regs) 1404 dbgs() << " " << Unit->getName(); 1405 dbgs() << "\n"); 1406 // Update the set weight. 1407 I->Weight = MaxWeight; 1408 } 1409 1410 // Find singular determinants. 1411 for (CodeGenRegister::Set::iterator RegI = I->Regs.begin(), 1412 RegE = I->Regs.end(); RegI != RegE; ++RegI) { 1413 if ((*RegI)->getRegUnits().size() == 1 1414 && (*RegI)->getWeight(RegBank) == I->Weight) 1415 mergeRegUnits(I->SingularDeterminants, (*RegI)->getRegUnits()); 1416 } 1417 } 1418 } 1419 1420 // normalizeWeight is a computeRegUnitWeights helper that adjusts the weight of 1421 // a register and its subregisters so that they have the same weight as their 1422 // UberSet. Self-recursion processes the subregister tree in postorder so 1423 // subregisters are normalized first. 1424 // 1425 // Side effects: 1426 // - creates new adopted register units 1427 // - causes superregisters to inherit adopted units 1428 // - increases the weight of "singular" units 1429 // - induces recomputation of UberWeights. 1430 static bool normalizeWeight(CodeGenRegister *Reg, 1431 std::vector<UberRegSet> &UberSets, 1432 std::vector<UberRegSet*> &RegSets, 1433 std::set<unsigned> &NormalRegs, 1434 CodeGenRegister::RegUnitList &NormalUnits, 1435 CodeGenRegBank &RegBank) { 1436 bool Changed = false; 1437 if (!NormalRegs.insert(Reg->EnumValue).second) 1438 return Changed; 1439 1440 const CodeGenRegister::SubRegMap &SRM = Reg->getSubRegs(); 1441 for (CodeGenRegister::SubRegMap::const_iterator SRI = SRM.begin(), 1442 SRE = SRM.end(); SRI != SRE; ++SRI) { 1443 if (SRI->second == Reg) 1444 continue; // self-cycles happen 1445 1446 Changed |= normalizeWeight(SRI->second, UberSets, RegSets, 1447 NormalRegs, NormalUnits, RegBank); 1448 } 1449 // Postorder register normalization. 1450 1451 // Inherit register units newly adopted by subregisters. 1452 if (Reg->inheritRegUnits(RegBank)) 1453 computeUberWeights(UberSets, RegBank); 1454 1455 // Check if this register is too skinny for its UberRegSet. 1456 UberRegSet *UberSet = RegSets[RegBank.getRegIndex(Reg)]; 1457 1458 unsigned RegWeight = Reg->getWeight(RegBank); 1459 if (UberSet->Weight > RegWeight) { 1460 // A register unit's weight can be adjusted only if it is the singular unit 1461 // for this register, has not been used to normalize a subregister's set, 1462 // and has not already been used to singularly determine this UberRegSet. 1463 unsigned AdjustUnit = Reg->getRegUnits().front(); 1464 if (Reg->getRegUnits().size() != 1 1465 || hasRegUnit(NormalUnits, AdjustUnit) 1466 || hasRegUnit(UberSet->SingularDeterminants, AdjustUnit)) { 1467 // We don't have an adjustable unit, so adopt a new one. 1468 AdjustUnit = RegBank.newRegUnit(UberSet->Weight - RegWeight); 1469 Reg->adoptRegUnit(AdjustUnit); 1470 // Adopting a unit does not immediately require recomputing set weights. 1471 } 1472 else { 1473 // Adjust the existing single unit. 1474 RegBank.increaseRegUnitWeight(AdjustUnit, UberSet->Weight - RegWeight); 1475 // The unit may be shared among sets and registers within this set. 1476 computeUberWeights(UberSets, RegBank); 1477 } 1478 Changed = true; 1479 } 1480 1481 // Mark these units normalized so superregisters can't change their weights. 1482 mergeRegUnits(NormalUnits, Reg->getRegUnits()); 1483 1484 return Changed; 1485 } 1486 1487 // Compute a weight for each register unit created during getSubRegs. 1488 // 1489 // The goal is that two registers in the same class will have the same weight, 1490 // where each register's weight is defined as sum of its units' weights. 1491 void CodeGenRegBank::computeRegUnitWeights() { 1492 std::vector<UberRegSet> UberSets; 1493 std::vector<UberRegSet*> RegSets(Registers.size()); 1494 computeUberSets(UberSets, RegSets, *this); 1495 // UberSets and RegSets are now immutable. 1496 1497 computeUberWeights(UberSets, *this); 1498 1499 // Iterate over each Register, normalizing the unit weights until reaching 1500 // a fix point. 1501 unsigned NumIters = 0; 1502 for (bool Changed = true; Changed; ++NumIters) { 1503 assert(NumIters <= NumNativeRegUnits && "Runaway register unit weights"); 1504 Changed = false; 1505 for (auto &Reg : Registers) { 1506 CodeGenRegister::RegUnitList NormalUnits; 1507 std::set<unsigned> NormalRegs; 1508 Changed |= normalizeWeight(&Reg, UberSets, RegSets, NormalRegs, 1509 NormalUnits, *this); 1510 } 1511 } 1512 } 1513 1514 // Find a set in UniqueSets with the same elements as Set. 1515 // Return an iterator into UniqueSets. 1516 static std::vector<RegUnitSet>::const_iterator 1517 findRegUnitSet(const std::vector<RegUnitSet> &UniqueSets, 1518 const RegUnitSet &Set) { 1519 std::vector<RegUnitSet>::const_iterator 1520 I = UniqueSets.begin(), E = UniqueSets.end(); 1521 for(;I != E; ++I) { 1522 if (I->Units == Set.Units) 1523 break; 1524 } 1525 return I; 1526 } 1527 1528 // Return true if the RUSubSet is a subset of RUSuperSet. 1529 static bool isRegUnitSubSet(const std::vector<unsigned> &RUSubSet, 1530 const std::vector<unsigned> &RUSuperSet) { 1531 return std::includes(RUSuperSet.begin(), RUSuperSet.end(), 1532 RUSubSet.begin(), RUSubSet.end()); 1533 } 1534 1535 /// Iteratively prune unit sets. Prune subsets that are close to the superset, 1536 /// but with one or two registers removed. We occasionally have registers like 1537 /// APSR and PC thrown in with the general registers. We also see many 1538 /// special-purpose register subsets, such as tail-call and Thumb 1539 /// encodings. Generating all possible overlapping sets is combinatorial and 1540 /// overkill for modeling pressure. Ideally we could fix this statically in 1541 /// tablegen by (1) having the target define register classes that only include 1542 /// the allocatable registers and marking other classes as non-allocatable and 1543 /// (2) having a way to mark special purpose classes as "don't-care" classes for 1544 /// the purpose of pressure. However, we make an attempt to handle targets that 1545 /// are not nicely defined by merging nearly identical register unit sets 1546 /// statically. This generates smaller tables. Then, dynamically, we adjust the 1547 /// set limit by filtering the reserved registers. 1548 /// 1549 /// Merge sets only if the units have the same weight. For example, on ARM, 1550 /// Q-tuples with ssub index 0 include all S regs but also include D16+. We 1551 /// should not expand the S set to include D regs. 1552 void CodeGenRegBank::pruneUnitSets() { 1553 assert(RegClassUnitSets.empty() && "this invalidates RegClassUnitSets"); 1554 1555 // Form an equivalence class of UnitSets with no significant difference. 1556 std::vector<unsigned> SuperSetIDs; 1557 for (unsigned SubIdx = 0, EndIdx = RegUnitSets.size(); 1558 SubIdx != EndIdx; ++SubIdx) { 1559 const RegUnitSet &SubSet = RegUnitSets[SubIdx]; 1560 unsigned SuperIdx = 0; 1561 for (; SuperIdx != EndIdx; ++SuperIdx) { 1562 if (SuperIdx == SubIdx) 1563 continue; 1564 1565 unsigned UnitWeight = RegUnits[SubSet.Units[0]].Weight; 1566 const RegUnitSet &SuperSet = RegUnitSets[SuperIdx]; 1567 if (isRegUnitSubSet(SubSet.Units, SuperSet.Units) 1568 && (SubSet.Units.size() + 3 > SuperSet.Units.size()) 1569 && UnitWeight == RegUnits[SuperSet.Units[0]].Weight 1570 && UnitWeight == RegUnits[SuperSet.Units.back()].Weight) { 1571 DEBUG(dbgs() << "UnitSet " << SubIdx << " subsumed by " << SuperIdx 1572 << "\n"); 1573 break; 1574 } 1575 } 1576 if (SuperIdx == EndIdx) 1577 SuperSetIDs.push_back(SubIdx); 1578 } 1579 // Populate PrunedUnitSets with each equivalence class's superset. 1580 std::vector<RegUnitSet> PrunedUnitSets(SuperSetIDs.size()); 1581 for (unsigned i = 0, e = SuperSetIDs.size(); i != e; ++i) { 1582 unsigned SuperIdx = SuperSetIDs[i]; 1583 PrunedUnitSets[i].Name = RegUnitSets[SuperIdx].Name; 1584 PrunedUnitSets[i].Units.swap(RegUnitSets[SuperIdx].Units); 1585 } 1586 RegUnitSets.swap(PrunedUnitSets); 1587 } 1588 1589 // Create a RegUnitSet for each RegClass that contains all units in the class 1590 // including adopted units that are necessary to model register pressure. Then 1591 // iteratively compute RegUnitSets such that the union of any two overlapping 1592 // RegUnitSets is repreresented. 1593 // 1594 // RegisterInfoEmitter will map each RegClass to its RegUnitClass and any 1595 // RegUnitSet that is a superset of that RegUnitClass. 1596 void CodeGenRegBank::computeRegUnitSets() { 1597 assert(RegUnitSets.empty() && "dirty RegUnitSets"); 1598 1599 // Compute a unique RegUnitSet for each RegClass. 1600 auto &RegClasses = getRegClasses(); 1601 for (auto &RC : RegClasses) { 1602 if (!RC.Allocatable) 1603 continue; 1604 1605 // Speculatively grow the RegUnitSets to hold the new set. 1606 RegUnitSets.resize(RegUnitSets.size() + 1); 1607 RegUnitSets.back().Name = RC.getName(); 1608 1609 // Compute a sorted list of units in this class. 1610 RC.buildRegUnitSet(RegUnitSets.back().Units); 1611 1612 // Find an existing RegUnitSet. 1613 std::vector<RegUnitSet>::const_iterator SetI = 1614 findRegUnitSet(RegUnitSets, RegUnitSets.back()); 1615 if (SetI != std::prev(RegUnitSets.end())) 1616 RegUnitSets.pop_back(); 1617 } 1618 1619 DEBUG(dbgs() << "\nBefore pruning:\n"; 1620 for (unsigned USIdx = 0, USEnd = RegUnitSets.size(); 1621 USIdx < USEnd; ++USIdx) { 1622 dbgs() << "UnitSet " << USIdx << " " << RegUnitSets[USIdx].Name 1623 << ":"; 1624 for (auto &U : RegUnitSets[USIdx].Units) 1625 dbgs() << " " << RegUnits[U].Roots[0]->getName(); 1626 dbgs() << "\n"; 1627 }); 1628 1629 // Iteratively prune unit sets. 1630 pruneUnitSets(); 1631 1632 DEBUG(dbgs() << "\nBefore union:\n"; 1633 for (unsigned USIdx = 0, USEnd = RegUnitSets.size(); 1634 USIdx < USEnd; ++USIdx) { 1635 dbgs() << "UnitSet " << USIdx << " " << RegUnitSets[USIdx].Name 1636 << ":"; 1637 for (auto &U : RegUnitSets[USIdx].Units) 1638 dbgs() << " " << RegUnits[U].Roots[0]->getName(); 1639 dbgs() << "\n"; 1640 } 1641 dbgs() << "\nUnion sets:\n"); 1642 1643 // Iterate over all unit sets, including new ones added by this loop. 1644 unsigned NumRegUnitSubSets = RegUnitSets.size(); 1645 for (unsigned Idx = 0, EndIdx = RegUnitSets.size(); Idx != EndIdx; ++Idx) { 1646 // In theory, this is combinatorial. In practice, it needs to be bounded 1647 // by a small number of sets for regpressure to be efficient. 1648 // If the assert is hit, we need to implement pruning. 1649 assert(Idx < (2*NumRegUnitSubSets) && "runaway unit set inference"); 1650 1651 // Compare new sets with all original classes. 1652 for (unsigned SearchIdx = (Idx >= NumRegUnitSubSets) ? 0 : Idx+1; 1653 SearchIdx != EndIdx; ++SearchIdx) { 1654 std::set<unsigned> Intersection; 1655 std::set_intersection(RegUnitSets[Idx].Units.begin(), 1656 RegUnitSets[Idx].Units.end(), 1657 RegUnitSets[SearchIdx].Units.begin(), 1658 RegUnitSets[SearchIdx].Units.end(), 1659 std::inserter(Intersection, Intersection.begin())); 1660 if (Intersection.empty()) 1661 continue; 1662 1663 // Speculatively grow the RegUnitSets to hold the new set. 1664 RegUnitSets.resize(RegUnitSets.size() + 1); 1665 RegUnitSets.back().Name = 1666 RegUnitSets[Idx].Name + "+" + RegUnitSets[SearchIdx].Name; 1667 1668 std::set_union(RegUnitSets[Idx].Units.begin(), 1669 RegUnitSets[Idx].Units.end(), 1670 RegUnitSets[SearchIdx].Units.begin(), 1671 RegUnitSets[SearchIdx].Units.end(), 1672 std::inserter(RegUnitSets.back().Units, 1673 RegUnitSets.back().Units.begin())); 1674 1675 // Find an existing RegUnitSet, or add the union to the unique sets. 1676 std::vector<RegUnitSet>::const_iterator SetI = 1677 findRegUnitSet(RegUnitSets, RegUnitSets.back()); 1678 if (SetI != std::prev(RegUnitSets.end())) 1679 RegUnitSets.pop_back(); 1680 else { 1681 DEBUG(dbgs() << "UnitSet " << RegUnitSets.size()-1 1682 << " " << RegUnitSets.back().Name << ":"; 1683 for (auto &U : RegUnitSets.back().Units) 1684 dbgs() << " " << RegUnits[U].Roots[0]->getName(); 1685 dbgs() << "\n";); 1686 } 1687 } 1688 } 1689 1690 // Iteratively prune unit sets after inferring supersets. 1691 pruneUnitSets(); 1692 1693 DEBUG(dbgs() << "\n"; 1694 for (unsigned USIdx = 0, USEnd = RegUnitSets.size(); 1695 USIdx < USEnd; ++USIdx) { 1696 dbgs() << "UnitSet " << USIdx << " " << RegUnitSets[USIdx].Name 1697 << ":"; 1698 for (auto &U : RegUnitSets[USIdx].Units) 1699 dbgs() << " " << RegUnits[U].Roots[0]->getName(); 1700 dbgs() << "\n"; 1701 }); 1702 1703 // For each register class, list the UnitSets that are supersets. 1704 RegClassUnitSets.resize(RegClasses.size()); 1705 int RCIdx = -1; 1706 for (auto &RC : RegClasses) { 1707 ++RCIdx; 1708 if (!RC.Allocatable) 1709 continue; 1710 1711 // Recompute the sorted list of units in this class. 1712 std::vector<unsigned> RCRegUnits; 1713 RC.buildRegUnitSet(RCRegUnits); 1714 1715 // Don't increase pressure for unallocatable regclasses. 1716 if (RCRegUnits.empty()) 1717 continue; 1718 1719 DEBUG(dbgs() << "RC " << RC.getName() << " Units: \n"; 1720 for (auto &U : RCRegUnits) 1721 dbgs() << RegUnits[U].getRoots()[0]->getName() << " "; 1722 dbgs() << "\n UnitSetIDs:"); 1723 1724 // Find all supersets. 1725 for (unsigned USIdx = 0, USEnd = RegUnitSets.size(); 1726 USIdx != USEnd; ++USIdx) { 1727 if (isRegUnitSubSet(RCRegUnits, RegUnitSets[USIdx].Units)) { 1728 DEBUG(dbgs() << " " << USIdx); 1729 RegClassUnitSets[RCIdx].push_back(USIdx); 1730 } 1731 } 1732 DEBUG(dbgs() << "\n"); 1733 assert(!RegClassUnitSets[RCIdx].empty() && "missing unit set for regclass"); 1734 } 1735 1736 // For each register unit, ensure that we have the list of UnitSets that 1737 // contain the unit. Normally, this matches an existing list of UnitSets for a 1738 // register class. If not, we create a new entry in RegClassUnitSets as a 1739 // "fake" register class. 1740 for (unsigned UnitIdx = 0, UnitEnd = NumNativeRegUnits; 1741 UnitIdx < UnitEnd; ++UnitIdx) { 1742 std::vector<unsigned> RUSets; 1743 for (unsigned i = 0, e = RegUnitSets.size(); i != e; ++i) { 1744 RegUnitSet &RUSet = RegUnitSets[i]; 1745 if (std::find(RUSet.Units.begin(), RUSet.Units.end(), UnitIdx) 1746 == RUSet.Units.end()) 1747 continue; 1748 RUSets.push_back(i); 1749 } 1750 unsigned RCUnitSetsIdx = 0; 1751 for (unsigned e = RegClassUnitSets.size(); 1752 RCUnitSetsIdx != e; ++RCUnitSetsIdx) { 1753 if (RegClassUnitSets[RCUnitSetsIdx] == RUSets) { 1754 break; 1755 } 1756 } 1757 RegUnits[UnitIdx].RegClassUnitSetsIdx = RCUnitSetsIdx; 1758 if (RCUnitSetsIdx == RegClassUnitSets.size()) { 1759 // Create a new list of UnitSets as a "fake" register class. 1760 RegClassUnitSets.resize(RCUnitSetsIdx + 1); 1761 RegClassUnitSets[RCUnitSetsIdx].swap(RUSets); 1762 } 1763 } 1764 } 1765 1766 void CodeGenRegBank::computeRegUnitLaneMasks() { 1767 for (auto &Register : Registers) { 1768 // Create an initial lane mask for all register units. 1769 const auto &RegUnits = Register.getRegUnits(); 1770 CodeGenRegister::RegUnitLaneMaskList RegUnitLaneMasks(RegUnits.size(), 0); 1771 // Iterate through SubRegisters. 1772 typedef CodeGenRegister::SubRegMap SubRegMap; 1773 const SubRegMap &SubRegs = Register.getSubRegs(); 1774 for (SubRegMap::const_iterator S = SubRegs.begin(), 1775 SE = SubRegs.end(); S != SE; ++S) { 1776 CodeGenRegister *SubReg = S->second; 1777 // Ignore non-leaf subregisters, their lane masks are fully covered by 1778 // the leaf subregisters anyway. 1779 if (SubReg->getSubRegs().size() != 0) 1780 continue; 1781 CodeGenSubRegIndex *SubRegIndex = S->first; 1782 const CodeGenRegister *SubRegister = S->second; 1783 unsigned LaneMask = SubRegIndex->LaneMask; 1784 // Distribute LaneMask to Register Units touched. 1785 for (const auto &SUI : SubRegister->getRegUnits()) { 1786 bool Found = false; 1787 for (size_t u = 0, ue = RegUnits.size(); u < ue; ++u) { 1788 if (SUI == RegUnits[u]) { 1789 RegUnitLaneMasks[u] |= LaneMask; 1790 assert(!Found); 1791 Found = true; 1792 } 1793 } 1794 assert(Found); 1795 } 1796 } 1797 Register.setRegUnitLaneMasks(RegUnitLaneMasks); 1798 } 1799 } 1800 1801 void CodeGenRegBank::computeDerivedInfo() { 1802 computeComposites(); 1803 computeSubRegLaneMasks(); 1804 1805 // Compute a weight for each register unit created during getSubRegs. 1806 // This may create adopted register units (with unit # >= NumNativeRegUnits). 1807 computeRegUnitWeights(); 1808 1809 // Compute a unique set of RegUnitSets. One for each RegClass and inferred 1810 // supersets for the union of overlapping sets. 1811 computeRegUnitSets(); 1812 1813 computeRegUnitLaneMasks(); 1814 1815 // Get the weight of each set. 1816 for (unsigned Idx = 0, EndIdx = RegUnitSets.size(); Idx != EndIdx; ++Idx) 1817 RegUnitSets[Idx].Weight = getRegUnitSetWeight(RegUnitSets[Idx].Units); 1818 1819 // Find the order of each set. 1820 RegUnitSetOrder.reserve(RegUnitSets.size()); 1821 for (unsigned Idx = 0, EndIdx = RegUnitSets.size(); Idx != EndIdx; ++Idx) 1822 RegUnitSetOrder.push_back(Idx); 1823 1824 std::stable_sort(RegUnitSetOrder.begin(), RegUnitSetOrder.end(), 1825 [this](unsigned ID1, unsigned ID2) { 1826 return getRegPressureSet(ID1).Units.size() < 1827 getRegPressureSet(ID2).Units.size(); 1828 }); 1829 for (unsigned Idx = 0, EndIdx = RegUnitSets.size(); Idx != EndIdx; ++Idx) { 1830 RegUnitSets[RegUnitSetOrder[Idx]].Order = Idx; 1831 } 1832 } 1833 1834 // 1835 // Synthesize missing register class intersections. 1836 // 1837 // Make sure that sub-classes of RC exists such that getCommonSubClass(RC, X) 1838 // returns a maximal register class for all X. 1839 // 1840 void CodeGenRegBank::inferCommonSubClass(CodeGenRegisterClass *RC) { 1841 assert(!RegClasses.empty()); 1842 // Stash the iterator to the last element so that this loop doesn't visit 1843 // elements added by the getOrCreateSubClass call within it. 1844 for (auto I = RegClasses.begin(), E = std::prev(RegClasses.end()); 1845 I != std::next(E); ++I) { 1846 CodeGenRegisterClass *RC1 = RC; 1847 CodeGenRegisterClass *RC2 = &*I; 1848 if (RC1 == RC2) 1849 continue; 1850 1851 // Compute the set intersection of RC1 and RC2. 1852 const CodeGenRegister::Set &Memb1 = RC1->getMembers(); 1853 const CodeGenRegister::Set &Memb2 = RC2->getMembers(); 1854 CodeGenRegister::Set Intersection; 1855 std::set_intersection(Memb1.begin(), Memb1.end(), 1856 Memb2.begin(), Memb2.end(), 1857 std::inserter(Intersection, Intersection.begin()), 1858 CodeGenRegister::Less()); 1859 1860 // Skip disjoint class pairs. 1861 if (Intersection.empty()) 1862 continue; 1863 1864 // If RC1 and RC2 have different spill sizes or alignments, use the 1865 // larger size for sub-classing. If they are equal, prefer RC1. 1866 if (RC2->SpillSize > RC1->SpillSize || 1867 (RC2->SpillSize == RC1->SpillSize && 1868 RC2->SpillAlignment > RC1->SpillAlignment)) 1869 std::swap(RC1, RC2); 1870 1871 getOrCreateSubClass(RC1, &Intersection, 1872 RC1->getName() + "_and_" + RC2->getName()); 1873 } 1874 } 1875 1876 // 1877 // Synthesize missing sub-classes for getSubClassWithSubReg(). 1878 // 1879 // Make sure that the set of registers in RC with a given SubIdx sub-register 1880 // form a register class. Update RC->SubClassWithSubReg. 1881 // 1882 void CodeGenRegBank::inferSubClassWithSubReg(CodeGenRegisterClass *RC) { 1883 // Map SubRegIndex to set of registers in RC supporting that SubRegIndex. 1884 typedef std::map<const CodeGenSubRegIndex *, CodeGenRegister::Set, 1885 CodeGenSubRegIndex::Less> SubReg2SetMap; 1886 1887 // Compute the set of registers supporting each SubRegIndex. 1888 SubReg2SetMap SRSets; 1889 for (CodeGenRegister::Set::const_iterator RI = RC->getMembers().begin(), 1890 RE = RC->getMembers().end(); RI != RE; ++RI) { 1891 const CodeGenRegister::SubRegMap &SRM = (*RI)->getSubRegs(); 1892 for (CodeGenRegister::SubRegMap::const_iterator I = SRM.begin(), 1893 E = SRM.end(); I != E; ++I) 1894 SRSets[I->first].insert(*RI); 1895 } 1896 1897 // Find matching classes for all SRSets entries. Iterate in SubRegIndex 1898 // numerical order to visit synthetic indices last. 1899 for (const auto &SubIdx : SubRegIndices) { 1900 SubReg2SetMap::const_iterator I = SRSets.find(&SubIdx); 1901 // Unsupported SubRegIndex. Skip it. 1902 if (I == SRSets.end()) 1903 continue; 1904 // In most cases, all RC registers support the SubRegIndex. 1905 if (I->second.size() == RC->getMembers().size()) { 1906 RC->setSubClassWithSubReg(&SubIdx, RC); 1907 continue; 1908 } 1909 // This is a real subset. See if we have a matching class. 1910 CodeGenRegisterClass *SubRC = 1911 getOrCreateSubClass(RC, &I->second, 1912 RC->getName() + "_with_" + I->first->getName()); 1913 RC->setSubClassWithSubReg(&SubIdx, SubRC); 1914 } 1915 } 1916 1917 // 1918 // Synthesize missing sub-classes of RC for getMatchingSuperRegClass(). 1919 // 1920 // Create sub-classes of RC such that getMatchingSuperRegClass(RC, SubIdx, X) 1921 // has a maximal result for any SubIdx and any X >= FirstSubRegRC. 1922 // 1923 1924 void CodeGenRegBank::inferMatchingSuperRegClass(CodeGenRegisterClass *RC, 1925 std::list<CodeGenRegisterClass>::iterator FirstSubRegRC) { 1926 SmallVector<std::pair<const CodeGenRegister*, 1927 const CodeGenRegister*>, 16> SSPairs; 1928 BitVector TopoSigs(getNumTopoSigs()); 1929 1930 // Iterate in SubRegIndex numerical order to visit synthetic indices last. 1931 for (auto &SubIdx : SubRegIndices) { 1932 // Skip indexes that aren't fully supported by RC's registers. This was 1933 // computed by inferSubClassWithSubReg() above which should have been 1934 // called first. 1935 if (RC->getSubClassWithSubReg(&SubIdx) != RC) 1936 continue; 1937 1938 // Build list of (Super, Sub) pairs for this SubIdx. 1939 SSPairs.clear(); 1940 TopoSigs.reset(); 1941 for (CodeGenRegister::Set::const_iterator RI = RC->getMembers().begin(), 1942 RE = RC->getMembers().end(); RI != RE; ++RI) { 1943 const CodeGenRegister *Super = *RI; 1944 const CodeGenRegister *Sub = Super->getSubRegs().find(&SubIdx)->second; 1945 assert(Sub && "Missing sub-register"); 1946 SSPairs.push_back(std::make_pair(Super, Sub)); 1947 TopoSigs.set(Sub->getTopoSig()); 1948 } 1949 1950 // Iterate over sub-register class candidates. Ignore classes created by 1951 // this loop. They will never be useful. 1952 // Store an iterator to the last element (not end) so that this loop doesn't 1953 // visit newly inserted elements. 1954 assert(!RegClasses.empty()); 1955 for (auto I = FirstSubRegRC, E = std::prev(RegClasses.end()); 1956 I != std::next(E); ++I) { 1957 CodeGenRegisterClass &SubRC = *I; 1958 // Topological shortcut: SubRC members have the wrong shape. 1959 if (!TopoSigs.anyCommon(SubRC.getTopoSigs())) 1960 continue; 1961 // Compute the subset of RC that maps into SubRC. 1962 CodeGenRegister::Set SubSet; 1963 for (unsigned i = 0, e = SSPairs.size(); i != e; ++i) 1964 if (SubRC.contains(SSPairs[i].second)) 1965 SubSet.insert(SSPairs[i].first); 1966 if (SubSet.empty()) 1967 continue; 1968 // RC injects completely into SubRC. 1969 if (SubSet.size() == SSPairs.size()) { 1970 SubRC.addSuperRegClass(&SubIdx, RC); 1971 continue; 1972 } 1973 // Only a subset of RC maps into SubRC. Make sure it is represented by a 1974 // class. 1975 getOrCreateSubClass(RC, &SubSet, RC->getName() + "_with_" + 1976 SubIdx.getName() + "_in_" + 1977 SubRC.getName()); 1978 } 1979 } 1980 } 1981 1982 1983 // 1984 // Infer missing register classes. 1985 // 1986 void CodeGenRegBank::computeInferredRegisterClasses() { 1987 assert(!RegClasses.empty()); 1988 // When this function is called, the register classes have not been sorted 1989 // and assigned EnumValues yet. That means getSubClasses(), 1990 // getSuperClasses(), and hasSubClass() functions are defunct. 1991 1992 // Use one-before-the-end so it doesn't move forward when new elements are 1993 // added. 1994 auto FirstNewRC = std::prev(RegClasses.end()); 1995 1996 // Visit all register classes, including the ones being added by the loop. 1997 // Watch out for iterator invalidation here. 1998 for (auto I = RegClasses.begin(), E = RegClasses.end(); I != E; ++I) { 1999 CodeGenRegisterClass *RC = &*I; 2000 2001 // Synthesize answers for getSubClassWithSubReg(). 2002 inferSubClassWithSubReg(RC); 2003 2004 // Synthesize answers for getCommonSubClass(). 2005 inferCommonSubClass(RC); 2006 2007 // Synthesize answers for getMatchingSuperRegClass(). 2008 inferMatchingSuperRegClass(RC); 2009 2010 // New register classes are created while this loop is running, and we need 2011 // to visit all of them. I particular, inferMatchingSuperRegClass needs 2012 // to match old super-register classes with sub-register classes created 2013 // after inferMatchingSuperRegClass was called. At this point, 2014 // inferMatchingSuperRegClass has checked SuperRC = [0..rci] with SubRC = 2015 // [0..FirstNewRC). We need to cover SubRC = [FirstNewRC..rci]. 2016 if (I == FirstNewRC) { 2017 auto NextNewRC = std::prev(RegClasses.end()); 2018 for (auto I2 = RegClasses.begin(), E2 = std::next(FirstNewRC); I2 != E2; 2019 ++I2) 2020 inferMatchingSuperRegClass(&*I2, E2); 2021 FirstNewRC = NextNewRC; 2022 } 2023 } 2024 } 2025 2026 /// getRegisterClassForRegister - Find the register class that contains the 2027 /// specified physical register. If the register is not in a register class, 2028 /// return null. If the register is in multiple classes, and the classes have a 2029 /// superset-subset relationship and the same set of types, return the 2030 /// superclass. Otherwise return null. 2031 const CodeGenRegisterClass* 2032 CodeGenRegBank::getRegClassForRegister(Record *R) { 2033 const CodeGenRegister *Reg = getReg(R); 2034 const CodeGenRegisterClass *FoundRC = nullptr; 2035 for (const auto &RC : getRegClasses()) { 2036 if (!RC.contains(Reg)) 2037 continue; 2038 2039 // If this is the first class that contains the register, 2040 // make a note of it and go on to the next class. 2041 if (!FoundRC) { 2042 FoundRC = &RC; 2043 continue; 2044 } 2045 2046 // If a register's classes have different types, return null. 2047 if (RC.getValueTypes() != FoundRC->getValueTypes()) 2048 return nullptr; 2049 2050 // Check to see if the previously found class that contains 2051 // the register is a subclass of the current class. If so, 2052 // prefer the superclass. 2053 if (RC.hasSubClass(FoundRC)) { 2054 FoundRC = &RC; 2055 continue; 2056 } 2057 2058 // Check to see if the previously found class that contains 2059 // the register is a superclass of the current class. If so, 2060 // prefer the superclass. 2061 if (FoundRC->hasSubClass(&RC)) 2062 continue; 2063 2064 // Multiple classes, and neither is a superclass of the other. 2065 // Return null. 2066 return nullptr; 2067 } 2068 return FoundRC; 2069 } 2070 2071 BitVector CodeGenRegBank::computeCoveredRegisters(ArrayRef<Record*> Regs) { 2072 SetVector<const CodeGenRegister*> Set; 2073 2074 // First add Regs with all sub-registers. 2075 for (unsigned i = 0, e = Regs.size(); i != e; ++i) { 2076 CodeGenRegister *Reg = getReg(Regs[i]); 2077 if (Set.insert(Reg)) 2078 // Reg is new, add all sub-registers. 2079 // The pre-ordering is not important here. 2080 Reg->addSubRegsPreOrder(Set, *this); 2081 } 2082 2083 // Second, find all super-registers that are completely covered by the set. 2084 for (unsigned i = 0; i != Set.size(); ++i) { 2085 const CodeGenRegister::SuperRegList &SR = Set[i]->getSuperRegs(); 2086 for (unsigned j = 0, e = SR.size(); j != e; ++j) { 2087 const CodeGenRegister *Super = SR[j]; 2088 if (!Super->CoveredBySubRegs || Set.count(Super)) 2089 continue; 2090 // This new super-register is covered by its sub-registers. 2091 bool AllSubsInSet = true; 2092 const CodeGenRegister::SubRegMap &SRM = Super->getSubRegs(); 2093 for (CodeGenRegister::SubRegMap::const_iterator I = SRM.begin(), 2094 E = SRM.end(); I != E; ++I) 2095 if (!Set.count(I->second)) { 2096 AllSubsInSet = false; 2097 break; 2098 } 2099 // All sub-registers in Set, add Super as well. 2100 // We will visit Super later to recheck its super-registers. 2101 if (AllSubsInSet) 2102 Set.insert(Super); 2103 } 2104 } 2105 2106 // Convert to BitVector. 2107 BitVector BV(Registers.size() + 1); 2108 for (unsigned i = 0, e = Set.size(); i != e; ++i) 2109 BV.set(Set[i]->EnumValue); 2110 return BV; 2111 } 2112