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