Remove MethodProtos/MethodBodies and allocation_order_begin/end.
[oota-llvm.git] / utils / TableGen / CodeGenRegisters.cpp
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/SmallVector.h"
18 #include "llvm/ADT/StringExtras.h"
19
20 using namespace llvm;
21
22 //===----------------------------------------------------------------------===//
23 //                              CodeGenRegister
24 //===----------------------------------------------------------------------===//
25
26 CodeGenRegister::CodeGenRegister(Record *R, unsigned Enum)
27   : TheDef(R),
28     EnumValue(Enum),
29     CostPerUse(R->getValueAsInt("CostPerUse")),
30     SubRegsComplete(false)
31 {}
32
33 const std::string &CodeGenRegister::getName() const {
34   return TheDef->getName();
35 }
36
37 namespace {
38   struct Orphan {
39     CodeGenRegister *SubReg;
40     Record *First, *Second;
41     Orphan(CodeGenRegister *r, Record *a, Record *b)
42       : SubReg(r), First(a), Second(b) {}
43   };
44 }
45
46 const CodeGenRegister::SubRegMap &
47 CodeGenRegister::getSubRegs(CodeGenRegBank &RegBank) {
48   // Only compute this map once.
49   if (SubRegsComplete)
50     return SubRegs;
51   SubRegsComplete = true;
52
53   std::vector<Record*> SubList = TheDef->getValueAsListOfDefs("SubRegs");
54   std::vector<Record*> Indices = TheDef->getValueAsListOfDefs("SubRegIndices");
55   if (SubList.size() != Indices.size())
56     throw TGError(TheDef->getLoc(), "Register " + getName() +
57                   " SubRegIndices doesn't match SubRegs");
58
59   // First insert the direct subregs and make sure they are fully indexed.
60   for (unsigned i = 0, e = SubList.size(); i != e; ++i) {
61     CodeGenRegister *SR = RegBank.getReg(SubList[i]);
62     if (!SubRegs.insert(std::make_pair(Indices[i], SR)).second)
63       throw TGError(TheDef->getLoc(), "SubRegIndex " + Indices[i]->getName() +
64                     " appears twice in Register " + getName());
65   }
66
67   // Keep track of inherited subregs and how they can be reached.
68   SmallVector<Orphan, 8> Orphans;
69
70   // Clone inherited subregs and place duplicate entries on Orphans.
71   // Here the order is important - earlier subregs take precedence.
72   for (unsigned i = 0, e = SubList.size(); i != e; ++i) {
73     CodeGenRegister *SR = RegBank.getReg(SubList[i]);
74     const SubRegMap &Map = SR->getSubRegs(RegBank);
75
76     // Add this as a super-register of SR now all sub-registers are in the list.
77     // This creates a topological ordering, the exact order depends on the
78     // order getSubRegs is called on all registers.
79     SR->SuperRegs.push_back(this);
80
81     for (SubRegMap::const_iterator SI = Map.begin(), SE = Map.end(); SI != SE;
82          ++SI) {
83       if (!SubRegs.insert(*SI).second)
84         Orphans.push_back(Orphan(SI->second, Indices[i], SI->first));
85
86       // Noop sub-register indexes are possible, so avoid duplicates.
87       if (SI->second != SR)
88         SI->second->SuperRegs.push_back(this);
89     }
90   }
91
92   // Process the composites.
93   ListInit *Comps = TheDef->getValueAsListInit("CompositeIndices");
94   for (unsigned i = 0, e = Comps->size(); i != e; ++i) {
95     DagInit *Pat = dynamic_cast<DagInit*>(Comps->getElement(i));
96     if (!Pat)
97       throw TGError(TheDef->getLoc(), "Invalid dag '" +
98                     Comps->getElement(i)->getAsString() +
99                     "' in CompositeIndices");
100     DefInit *BaseIdxInit = dynamic_cast<DefInit*>(Pat->getOperator());
101     if (!BaseIdxInit || !BaseIdxInit->getDef()->isSubClassOf("SubRegIndex"))
102       throw TGError(TheDef->getLoc(), "Invalid SubClassIndex in " +
103                     Pat->getAsString());
104
105     // Resolve list of subreg indices into R2.
106     CodeGenRegister *R2 = this;
107     for (DagInit::const_arg_iterator di = Pat->arg_begin(),
108          de = Pat->arg_end(); di != de; ++di) {
109       DefInit *IdxInit = dynamic_cast<DefInit*>(*di);
110       if (!IdxInit || !IdxInit->getDef()->isSubClassOf("SubRegIndex"))
111         throw TGError(TheDef->getLoc(), "Invalid SubClassIndex in " +
112                       Pat->getAsString());
113       const SubRegMap &R2Subs = R2->getSubRegs(RegBank);
114       SubRegMap::const_iterator ni = R2Subs.find(IdxInit->getDef());
115       if (ni == R2Subs.end())
116         throw TGError(TheDef->getLoc(), "Composite " + Pat->getAsString() +
117                       " refers to bad index in " + R2->getName());
118       R2 = ni->second;
119     }
120
121     // Insert composite index. Allow overriding inherited indices etc.
122     SubRegs[BaseIdxInit->getDef()] = R2;
123
124     // R2 is no longer an orphan.
125     for (unsigned j = 0, je = Orphans.size(); j != je; ++j)
126       if (Orphans[j].SubReg == R2)
127           Orphans[j].SubReg = 0;
128   }
129
130   // Now Orphans contains the inherited subregisters without a direct index.
131   // Create inferred indexes for all missing entries.
132   for (unsigned i = 0, e = Orphans.size(); i != e; ++i) {
133     Orphan &O = Orphans[i];
134     if (!O.SubReg)
135       continue;
136     SubRegs[RegBank.getCompositeSubRegIndex(O.First, O.Second, true)] =
137       O.SubReg;
138   }
139   return SubRegs;
140 }
141
142 void
143 CodeGenRegister::addSubRegsPreOrder(SetVector<CodeGenRegister*> &OSet) const {
144   assert(SubRegsComplete && "Must precompute sub-registers");
145   std::vector<Record*> Indices = TheDef->getValueAsListOfDefs("SubRegIndices");
146   for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
147     CodeGenRegister *SR = SubRegs.find(Indices[i])->second;
148     if (OSet.insert(SR))
149       SR->addSubRegsPreOrder(OSet);
150   }
151 }
152
153 //===----------------------------------------------------------------------===//
154 //                            CodeGenRegisterClass
155 //===----------------------------------------------------------------------===//
156
157 CodeGenRegisterClass::CodeGenRegisterClass(CodeGenRegBank &RegBank, Record *R)
158   : TheDef(R) {
159   // Rename anonymous register classes.
160   if (R->getName().size() > 9 && R->getName()[9] == '.') {
161     static unsigned AnonCounter = 0;
162     R->setName("AnonRegClass_"+utostr(AnonCounter++));
163   }
164
165   std::vector<Record*> TypeList = R->getValueAsListOfDefs("RegTypes");
166   for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
167     Record *Type = TypeList[i];
168     if (!Type->isSubClassOf("ValueType"))
169       throw "RegTypes list member '" + Type->getName() +
170         "' does not derive from the ValueType class!";
171     VTs.push_back(getValueType(Type));
172   }
173   assert(!VTs.empty() && "RegisterClass must contain at least one ValueType!");
174
175   // Default allocation order always contains all registers.
176   Elements = RegBank.getSets().expand(R);
177   for (unsigned i = 0, e = Elements->size(); i != e; ++i)
178     Members.insert(RegBank.getReg((*Elements)[i]));
179
180   // Alternative allocation orders may be subsets.
181   ListInit *Alts = R->getValueAsListInit("AltOrders");
182   AltOrders.resize(Alts->size());
183   SetTheory::RecSet Order;
184   for (unsigned i = 0, e = Alts->size(); i != e; ++i) {
185     RegBank.getSets().evaluate(Alts->getElement(i), Order);
186     AltOrders[i].append(Order.begin(), Order.end());
187     // Verify that all altorder members are regclass members.
188     while (!Order.empty()) {
189       CodeGenRegister *Reg = RegBank.getReg(Order.back());
190       Order.pop_back();
191       if (!contains(Reg))
192         throw TGError(R->getLoc(), " AltOrder register " + Reg->getName() +
193                       " is not a class member");
194     }
195   }
196
197   // SubRegClasses is a list<dag> containing (RC, subregindex, ...) dags.
198   ListInit *SRC = R->getValueAsListInit("SubRegClasses");
199   for (ListInit::const_iterator i = SRC->begin(), e = SRC->end(); i != e; ++i) {
200     DagInit *DAG = dynamic_cast<DagInit*>(*i);
201     if (!DAG) throw "SubRegClasses must contain DAGs";
202     DefInit *DAGOp = dynamic_cast<DefInit*>(DAG->getOperator());
203     Record *RCRec;
204     if (!DAGOp || !(RCRec = DAGOp->getDef())->isSubClassOf("RegisterClass"))
205       throw "Operator '" + DAG->getOperator()->getAsString() +
206         "' in SubRegClasses is not a RegisterClass";
207     // Iterate over args, all SubRegIndex instances.
208     for (DagInit::const_arg_iterator ai = DAG->arg_begin(), ae = DAG->arg_end();
209          ai != ae; ++ai) {
210       DefInit *Idx = dynamic_cast<DefInit*>(*ai);
211       Record *IdxRec;
212       if (!Idx || !(IdxRec = Idx->getDef())->isSubClassOf("SubRegIndex"))
213         throw "Argument '" + (*ai)->getAsString() +
214           "' in SubRegClasses is not a SubRegIndex";
215       if (!SubRegClasses.insert(std::make_pair(IdxRec, RCRec)).second)
216         throw "SubRegIndex '" + IdxRec->getName() + "' mentioned twice";
217     }
218   }
219
220   // Allow targets to override the size in bits of the RegisterClass.
221   unsigned Size = R->getValueAsInt("Size");
222
223   Namespace = R->getValueAsString("Namespace");
224   SpillSize = Size ? Size : EVT(VTs[0]).getSizeInBits();
225   SpillAlignment = R->getValueAsInt("Alignment");
226   CopyCost = R->getValueAsInt("CopyCost");
227   Allocatable = R->getValueAsBit("isAllocatable");
228   AltOrderSelect = R->getValueAsCode("AltOrderSelect");
229 }
230
231 bool CodeGenRegisterClass::contains(const CodeGenRegister *Reg) const {
232   return Members.count(Reg);
233 }
234
235 // Returns true if RC is a strict subclass.
236 // RC is a sub-class of this class if it is a valid replacement for any
237 // instruction operand where a register of this classis required. It must
238 // satisfy these conditions:
239 //
240 // 1. All RC registers are also in this.
241 // 2. The RC spill size must not be smaller than our spill size.
242 // 3. RC spill alignment must be compatible with ours.
243 //
244 bool CodeGenRegisterClass::hasSubClass(const CodeGenRegisterClass *RC) const {
245   return SpillAlignment && RC->SpillAlignment % SpillAlignment == 0 &&
246     SpillSize <= RC->SpillSize &&
247     std::includes(Members.begin(), Members.end(),
248                   RC->Members.begin(), RC->Members.end());
249 }
250
251 const std::string &CodeGenRegisterClass::getName() const {
252   return TheDef->getName();
253 }
254
255 //===----------------------------------------------------------------------===//
256 //                               CodeGenRegBank
257 //===----------------------------------------------------------------------===//
258
259 CodeGenRegBank::CodeGenRegBank(RecordKeeper &Records) : Records(Records) {
260   // Configure register Sets to understand register classes.
261   Sets.addFieldExpander("RegisterClass", "MemberList");
262
263   // Read in the user-defined (named) sub-register indices.
264   // More indices will be synthesized later.
265   SubRegIndices = Records.getAllDerivedDefinitions("SubRegIndex");
266   std::sort(SubRegIndices.begin(), SubRegIndices.end(), LessRecord());
267   NumNamedIndices = SubRegIndices.size();
268
269   // Read in the register definitions.
270   std::vector<Record*> Regs = Records.getAllDerivedDefinitions("Register");
271   std::sort(Regs.begin(), Regs.end(), LessRecord());
272   Registers.reserve(Regs.size());
273   // Assign the enumeration values.
274   for (unsigned i = 0, e = Regs.size(); i != e; ++i)
275     Registers.push_back(CodeGenRegister(Regs[i], i + 1));
276
277   // Read in register class definitions.
278   std::vector<Record*> RCs = Records.getAllDerivedDefinitions("RegisterClass");
279   if (RCs.empty())
280     throw std::string("No 'RegisterClass' subclasses defined!");
281
282   RegClasses.reserve(RCs.size());
283   for (unsigned i = 0, e = RCs.size(); i != e; ++i)
284     RegClasses.push_back(CodeGenRegisterClass(*this, RCs[i]));
285 }
286
287 CodeGenRegister *CodeGenRegBank::getReg(Record *Def) {
288   if (Def2Reg.empty())
289     for (unsigned i = 0, e = Registers.size(); i != e; ++i)
290       Def2Reg[Registers[i].TheDef] = &Registers[i];
291
292   if (CodeGenRegister *Reg = Def2Reg[Def])
293     return Reg;
294
295   throw TGError(Def->getLoc(), "Not a known Register!");
296 }
297
298 CodeGenRegisterClass *CodeGenRegBank::getRegClass(Record *Def) {
299   if (Def2RC.empty())
300     for (unsigned i = 0, e = RegClasses.size(); i != e; ++i)
301       Def2RC[RegClasses[i].TheDef] = &RegClasses[i];
302
303   if (CodeGenRegisterClass *RC = Def2RC[Def])
304     return RC;
305
306   throw TGError(Def->getLoc(), "Not a known RegisterClass!");
307 }
308
309 Record *CodeGenRegBank::getCompositeSubRegIndex(Record *A, Record *B,
310                                                 bool create) {
311   // Look for an existing entry.
312   Record *&Comp = Composite[std::make_pair(A, B)];
313   if (Comp || !create)
314     return Comp;
315
316   // None exists, synthesize one.
317   std::string Name = A->getName() + "_then_" + B->getName();
318   Comp = new Record(Name, SMLoc(), Records);
319   Records.addDef(Comp);
320   SubRegIndices.push_back(Comp);
321   return Comp;
322 }
323
324 unsigned CodeGenRegBank::getSubRegIndexNo(Record *idx) {
325   std::vector<Record*>::const_iterator i =
326     std::find(SubRegIndices.begin(), SubRegIndices.end(), idx);
327   assert(i != SubRegIndices.end() && "Not a SubRegIndex");
328   return (i - SubRegIndices.begin()) + 1;
329 }
330
331 void CodeGenRegBank::computeComposites() {
332   // Precompute all sub-register maps. This will create Composite entries for
333   // all inferred sub-register indices.
334   for (unsigned i = 0, e = Registers.size(); i != e; ++i)
335     Registers[i].getSubRegs(*this);
336
337   for (unsigned i = 0, e = Registers.size(); i != e; ++i) {
338     CodeGenRegister *Reg1 = &Registers[i];
339     const CodeGenRegister::SubRegMap &SRM1 = Reg1->getSubRegs();
340     for (CodeGenRegister::SubRegMap::const_iterator i1 = SRM1.begin(),
341          e1 = SRM1.end(); i1 != e1; ++i1) {
342       Record *Idx1 = i1->first;
343       CodeGenRegister *Reg2 = i1->second;
344       // Ignore identity compositions.
345       if (Reg1 == Reg2)
346         continue;
347       const CodeGenRegister::SubRegMap &SRM2 = Reg2->getSubRegs();
348       // Try composing Idx1 with another SubRegIndex.
349       for (CodeGenRegister::SubRegMap::const_iterator i2 = SRM2.begin(),
350            e2 = SRM2.end(); i2 != e2; ++i2) {
351         std::pair<Record*, Record*> IdxPair(Idx1, i2->first);
352         CodeGenRegister *Reg3 = i2->second;
353         // Ignore identity compositions.
354         if (Reg2 == Reg3)
355           continue;
356         // OK Reg1:IdxPair == Reg3. Find the index with Reg:Idx == Reg3.
357         for (CodeGenRegister::SubRegMap::const_iterator i1d = SRM1.begin(),
358              e1d = SRM1.end(); i1d != e1d; ++i1d) {
359           if (i1d->second == Reg3) {
360             std::pair<CompositeMap::iterator, bool> Ins =
361               Composite.insert(std::make_pair(IdxPair, i1d->first));
362             // Conflicting composition? Emit a warning but allow it.
363             if (!Ins.second && Ins.first->second != i1d->first) {
364               errs() << "Warning: SubRegIndex " << getQualifiedName(Idx1)
365                      << " and " << getQualifiedName(IdxPair.second)
366                      << " compose ambiguously as "
367                      << getQualifiedName(Ins.first->second) << " or "
368                      << getQualifiedName(i1d->first) << "\n";
369             }
370           }
371         }
372       }
373     }
374   }
375
376   // We don't care about the difference between (Idx1, Idx2) -> Idx2 and invalid
377   // compositions, so remove any mappings of that form.
378   for (CompositeMap::iterator i = Composite.begin(), e = Composite.end();
379        i != e;) {
380     CompositeMap::iterator j = i;
381     ++i;
382     if (j->first.second == j->second)
383       Composite.erase(j);
384   }
385 }
386
387 // Compute sets of overlapping registers.
388 //
389 // The standard set is all super-registers and all sub-registers, but the
390 // target description can add arbitrary overlapping registers via the 'Aliases'
391 // field. This complicates things, but we can compute overlapping sets using
392 // the following rules:
393 //
394 // 1. The relation overlap(A, B) is reflexive and symmetric but not transitive.
395 //
396 // 2. overlap(A, B) implies overlap(A, S) for all S in supers(B).
397 //
398 // Alternatively:
399 //
400 //    overlap(A, B) iff there exists:
401 //    A' in { A, subregs(A) } and B' in { B, subregs(B) } such that:
402 //    A' = B' or A' in aliases(B') or B' in aliases(A').
403 //
404 // Here subregs(A) is the full flattened sub-register set returned by
405 // A.getSubRegs() while aliases(A) is simply the special 'Aliases' field in the
406 // description of register A.
407 //
408 // This also implies that registers with a common sub-register are considered
409 // overlapping. This can happen when forming register pairs:
410 //
411 //    P0 = (R0, R1)
412 //    P1 = (R1, R2)
413 //    P2 = (R2, R3)
414 //
415 // In this case, we will infer an overlap between P0 and P1 because of the
416 // shared sub-register R1. There is no overlap between P0 and P2.
417 //
418 void CodeGenRegBank::
419 computeOverlaps(std::map<const CodeGenRegister*, CodeGenRegister::Set> &Map) {
420   assert(Map.empty());
421
422   // Collect overlaps that don't follow from rule 2.
423   for (unsigned i = 0, e = Registers.size(); i != e; ++i) {
424     CodeGenRegister *Reg = &Registers[i];
425     CodeGenRegister::Set &Overlaps = Map[Reg];
426
427     // Reg overlaps itself.
428     Overlaps.insert(Reg);
429
430     // All super-registers overlap.
431     const CodeGenRegister::SuperRegList &Supers = Reg->getSuperRegs();
432     Overlaps.insert(Supers.begin(), Supers.end());
433
434     // Form symmetrical relations from the special Aliases[] lists.
435     std::vector<Record*> RegList = Reg->TheDef->getValueAsListOfDefs("Aliases");
436     for (unsigned i2 = 0, e2 = RegList.size(); i2 != e2; ++i2) {
437       CodeGenRegister *Reg2 = getReg(RegList[i2]);
438       CodeGenRegister::Set &Overlaps2 = Map[Reg2];
439       const CodeGenRegister::SuperRegList &Supers2 = Reg2->getSuperRegs();
440       // Reg overlaps Reg2 which implies it overlaps supers(Reg2).
441       Overlaps.insert(Reg2);
442       Overlaps.insert(Supers2.begin(), Supers2.end());
443       Overlaps2.insert(Reg);
444       Overlaps2.insert(Supers.begin(), Supers.end());
445     }
446   }
447
448   // Apply rule 2. and inherit all sub-register overlaps.
449   for (unsigned i = 0, e = Registers.size(); i != e; ++i) {
450     CodeGenRegister *Reg = &Registers[i];
451     CodeGenRegister::Set &Overlaps = Map[Reg];
452     const CodeGenRegister::SubRegMap &SRM = Reg->getSubRegs();
453     for (CodeGenRegister::SubRegMap::const_iterator i2 = SRM.begin(),
454          e2 = SRM.end(); i2 != e2; ++i2) {
455       CodeGenRegister::Set &Overlaps2 = Map[i2->second];
456       Overlaps.insert(Overlaps2.begin(), Overlaps2.end());
457     }
458   }
459 }
460
461 void CodeGenRegBank::computeDerivedInfo() {
462   computeComposites();
463 }
464
465 /// getRegisterClassForRegister - Find the register class that contains the
466 /// specified physical register.  If the register is not in a register class,
467 /// return null. If the register is in multiple classes, and the classes have a
468 /// superset-subset relationship and the same set of types, return the
469 /// superclass.  Otherwise return null.
470 const CodeGenRegisterClass*
471 CodeGenRegBank::getRegClassForRegister(Record *R) {
472   const CodeGenRegister *Reg = getReg(R);
473   const std::vector<CodeGenRegisterClass> &RCs = getRegClasses();
474   const CodeGenRegisterClass *FoundRC = 0;
475   for (unsigned i = 0, e = RCs.size(); i != e; ++i) {
476     const CodeGenRegisterClass &RC = RCs[i];
477     if (!RC.contains(Reg))
478       continue;
479
480     // If this is the first class that contains the register,
481     // make a note of it and go on to the next class.
482     if (!FoundRC) {
483       FoundRC = &RC;
484       continue;
485     }
486
487     // If a register's classes have different types, return null.
488     if (RC.getValueTypes() != FoundRC->getValueTypes())
489       return 0;
490
491     // Check to see if the previously found class that contains
492     // the register is a subclass of the current class. If so,
493     // prefer the superclass.
494     if (RC.hasSubClass(FoundRC)) {
495       FoundRC = &RC;
496       continue;
497     }
498
499     // Check to see if the previously found class that contains
500     // the register is a superclass of the current class. If so,
501     // prefer the superclass.
502     if (FoundRC->hasSubClass(&RC))
503       continue;
504
505     // Multiple classes, and neither is a superclass of the other.
506     // Return null.
507     return 0;
508   }
509   return FoundRC;
510 }