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