Compute a map from register names to registers, rather than scanning the list of...
[oota-llvm.git] / utils / TableGen / CodeGenTarget.cpp
1 //===- CodeGenTarget.cpp - CodeGen Target Class Wrapper -------------------===//
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 class wraps target description classes used by the various code
11 // generation TableGen backends.  This makes it easier to access the data and
12 // provides a single place that needs to check it for validity.  All of these
13 // classes throw exceptions on error conditions.
14 //
15 //===----------------------------------------------------------------------===//
16
17 #include "CodeGenTarget.h"
18 #include "CodeGenIntrinsics.h"
19 #include "CodeGenSchedule.h"
20 #include "llvm/TableGen/Record.h"
21 #include "llvm/ADT/StringExtras.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/Support/CommandLine.h"
24 #include <algorithm>
25 using namespace llvm;
26
27 static cl::opt<unsigned>
28 AsmParserNum("asmparsernum", cl::init(0),
29              cl::desc("Make -gen-asm-parser emit assembly parser #N"));
30
31 static cl::opt<unsigned>
32 AsmWriterNum("asmwriternum", cl::init(0),
33              cl::desc("Make -gen-asm-writer emit assembly writer #N"));
34
35 /// getValueType - Return the MVT::SimpleValueType that the specified TableGen
36 /// record corresponds to.
37 MVT::SimpleValueType llvm::getValueType(Record *Rec) {
38   return (MVT::SimpleValueType)Rec->getValueAsInt("Value");
39 }
40
41 std::string llvm::getName(MVT::SimpleValueType T) {
42   switch (T) {
43   case MVT::Other:   return "UNKNOWN";
44   case MVT::iPTR:    return "TLI.getPointerTy()";
45   case MVT::iPTRAny: return "TLI.getPointerTy()";
46   default: return getEnumName(T);
47   }
48 }
49
50 std::string llvm::getEnumName(MVT::SimpleValueType T) {
51   switch (T) {
52   case MVT::Other:    return "MVT::Other";
53   case MVT::i1:       return "MVT::i1";
54   case MVT::i8:       return "MVT::i8";
55   case MVT::i16:      return "MVT::i16";
56   case MVT::i32:      return "MVT::i32";
57   case MVT::i64:      return "MVT::i64";
58   case MVT::i128:     return "MVT::i128";
59   case MVT::iAny:     return "MVT::iAny";
60   case MVT::fAny:     return "MVT::fAny";
61   case MVT::vAny:     return "MVT::vAny";
62   case MVT::f16:      return "MVT::f16";
63   case MVT::f32:      return "MVT::f32";
64   case MVT::f64:      return "MVT::f64";
65   case MVT::f80:      return "MVT::f80";
66   case MVT::f128:     return "MVT::f128";
67   case MVT::ppcf128:  return "MVT::ppcf128";
68   case MVT::x86mmx:   return "MVT::x86mmx";
69   case MVT::Glue:     return "MVT::Glue";
70   case MVT::isVoid:   return "MVT::isVoid";
71   case MVT::v2i8:     return "MVT::v2i8";
72   case MVT::v4i8:     return "MVT::v4i8";
73   case MVT::v8i8:     return "MVT::v8i8";
74   case MVT::v16i8:    return "MVT::v16i8";
75   case MVT::v32i8:    return "MVT::v32i8";
76   case MVT::v2i16:    return "MVT::v2i16";
77   case MVT::v4i16:    return "MVT::v4i16";
78   case MVT::v8i16:    return "MVT::v8i16";
79   case MVT::v16i16:   return "MVT::v16i16";
80   case MVT::v2i32:    return "MVT::v2i32";
81   case MVT::v4i32:    return "MVT::v4i32";
82   case MVT::v8i32:    return "MVT::v8i32";
83   case MVT::v1i64:    return "MVT::v1i64";
84   case MVT::v2i64:    return "MVT::v2i64";
85   case MVT::v4i64:    return "MVT::v4i64";
86   case MVT::v8i64:    return "MVT::v8i64";
87   case MVT::v2f16:    return "MVT::v2f16";
88   case MVT::v2f32:    return "MVT::v2f32";
89   case MVT::v4f32:    return "MVT::v4f32";
90   case MVT::v8f32:    return "MVT::v8f32";
91   case MVT::v2f64:    return "MVT::v2f64";
92   case MVT::v4f64:    return "MVT::v4f64";
93   case MVT::Metadata: return "MVT::Metadata";
94   case MVT::iPTR:     return "MVT::iPTR";
95   case MVT::iPTRAny:  return "MVT::iPTRAny";
96   case MVT::Untyped:  return "MVT::Untyped";
97   default: llvm_unreachable("ILLEGAL VALUE TYPE!");
98   }
99 }
100
101 /// getQualifiedName - Return the name of the specified record, with a
102 /// namespace qualifier if the record contains one.
103 ///
104 std::string llvm::getQualifiedName(const Record *R) {
105   std::string Namespace;
106   if (R->getValue("Namespace"))
107      Namespace = R->getValueAsString("Namespace");
108   if (Namespace.empty()) return R->getName();
109   return Namespace + "::" + R->getName();
110 }
111
112
113 /// getTarget - Return the current instance of the Target class.
114 ///
115 CodeGenTarget::CodeGenTarget(RecordKeeper &records)
116   : Records(records), RegBank(0), SchedModels(0) {
117   std::vector<Record*> Targets = Records.getAllDerivedDefinitions("Target");
118   if (Targets.size() == 0)
119     throw std::string("ERROR: No 'Target' subclasses defined!");
120   if (Targets.size() != 1)
121     throw std::string("ERROR: Multiple subclasses of Target defined!");
122   TargetRec = Targets[0];
123 }
124
125 CodeGenTarget::~CodeGenTarget() {
126   delete RegBank;
127   delete SchedModels;
128 }
129
130 const std::string &CodeGenTarget::getName() const {
131   return TargetRec->getName();
132 }
133
134 std::string CodeGenTarget::getInstNamespace() const {
135   for (inst_iterator i = inst_begin(), e = inst_end(); i != e; ++i) {
136     // Make sure not to pick up "TargetOpcode" by accidentally getting
137     // the namespace off the PHI instruction or something.
138     if ((*i)->Namespace != "TargetOpcode")
139       return (*i)->Namespace;
140   }
141
142   return "";
143 }
144
145 Record *CodeGenTarget::getInstructionSet() const {
146   return TargetRec->getValueAsDef("InstructionSet");
147 }
148
149
150 /// getAsmParser - Return the AssemblyParser definition for this target.
151 ///
152 Record *CodeGenTarget::getAsmParser() const {
153   std::vector<Record*> LI = TargetRec->getValueAsListOfDefs("AssemblyParsers");
154   if (AsmParserNum >= LI.size())
155     throw "Target does not have an AsmParser #" + utostr(AsmParserNum) + "!";
156   return LI[AsmParserNum];
157 }
158
159 /// getAsmParserVariant - Return the AssmblyParserVariant definition for
160 /// this target.
161 ///
162 Record *CodeGenTarget::getAsmParserVariant(unsigned i) const {
163   std::vector<Record*> LI =
164     TargetRec->getValueAsListOfDefs("AssemblyParserVariants");
165   if (i >= LI.size())
166     throw "Target does not have an AsmParserVariant #" + utostr(i) + "!";
167   return LI[i];
168 }
169
170 /// getAsmParserVariantCount - Return the AssmblyParserVariant definition
171 /// available for this target.
172 ///
173 unsigned CodeGenTarget::getAsmParserVariantCount() const {
174   std::vector<Record*> LI =
175     TargetRec->getValueAsListOfDefs("AssemblyParserVariants");
176   return LI.size();
177 }
178
179 /// getAsmWriter - Return the AssemblyWriter definition for this target.
180 ///
181 Record *CodeGenTarget::getAsmWriter() const {
182   std::vector<Record*> LI = TargetRec->getValueAsListOfDefs("AssemblyWriters");
183   if (AsmWriterNum >= LI.size())
184     throw "Target does not have an AsmWriter #" + utostr(AsmWriterNum) + "!";
185   return LI[AsmWriterNum];
186 }
187
188 CodeGenRegBank &CodeGenTarget::getRegBank() const {
189   if (!RegBank)
190     RegBank = new CodeGenRegBank(Records);
191   return *RegBank;
192 }
193
194 void CodeGenTarget::ReadRegAltNameIndices() const {
195   RegAltNameIndices = Records.getAllDerivedDefinitions("RegAltNameIndex");
196   std::sort(RegAltNameIndices.begin(), RegAltNameIndices.end(), LessRecord());
197 }
198
199 /// getRegisterByName - If there is a register with the specific AsmName,
200 /// return it.
201 const CodeGenRegister *CodeGenTarget::getRegisterByName(StringRef Name) const {
202   const StringMap<CodeGenRegister*> &Regs = getRegBank().getRegistersByName();
203   StringMap<CodeGenRegister*>::const_iterator I = Regs.find(Name);
204   if (I == Regs.end())
205     return 0;
206   return I->second;
207 }
208
209 std::vector<MVT::SimpleValueType> CodeGenTarget::
210 getRegisterVTs(Record *R) const {
211   const CodeGenRegister *Reg = getRegBank().getReg(R);
212   std::vector<MVT::SimpleValueType> Result;
213   ArrayRef<CodeGenRegisterClass*> RCs = getRegBank().getRegClasses();
214   for (unsigned i = 0, e = RCs.size(); i != e; ++i) {
215     const CodeGenRegisterClass &RC = *RCs[i];
216     if (RC.contains(Reg)) {
217       const std::vector<MVT::SimpleValueType> &InVTs = RC.getValueTypes();
218       Result.insert(Result.end(), InVTs.begin(), InVTs.end());
219     }
220   }
221
222   // Remove duplicates.
223   array_pod_sort(Result.begin(), Result.end());
224   Result.erase(std::unique(Result.begin(), Result.end()), Result.end());
225   return Result;
226 }
227
228
229 void CodeGenTarget::ReadLegalValueTypes() const {
230   ArrayRef<CodeGenRegisterClass*> RCs = getRegBank().getRegClasses();
231   for (unsigned i = 0, e = RCs.size(); i != e; ++i)
232     for (unsigned ri = 0, re = RCs[i]->VTs.size(); ri != re; ++ri)
233       LegalValueTypes.push_back(RCs[i]->VTs[ri]);
234
235   // Remove duplicates.
236   std::sort(LegalValueTypes.begin(), LegalValueTypes.end());
237   LegalValueTypes.erase(std::unique(LegalValueTypes.begin(),
238                                     LegalValueTypes.end()),
239                         LegalValueTypes.end());
240 }
241
242 CodeGenSchedModels &CodeGenTarget::getSchedModels() const {
243   if (!SchedModels)
244     SchedModels = new CodeGenSchedModels(Records, *this);
245   return *SchedModels;
246 }
247
248 void CodeGenTarget::ReadInstructions() const {
249   std::vector<Record*> Insts = Records.getAllDerivedDefinitions("Instruction");
250   if (Insts.size() <= 2)
251     throw std::string("No 'Instruction' subclasses defined!");
252
253   // Parse the instructions defined in the .td file.
254   for (unsigned i = 0, e = Insts.size(); i != e; ++i)
255     Instructions[Insts[i]] = new CodeGenInstruction(Insts[i]);
256 }
257
258 static const CodeGenInstruction *
259 GetInstByName(const char *Name,
260               const DenseMap<const Record*, CodeGenInstruction*> &Insts,
261               RecordKeeper &Records) {
262   const Record *Rec = Records.getDef(Name);
263
264   DenseMap<const Record*, CodeGenInstruction*>::const_iterator
265     I = Insts.find(Rec);
266   if (Rec == 0 || I == Insts.end())
267     throw std::string("Could not find '") + Name + "' instruction!";
268   return I->second;
269 }
270
271 namespace {
272 /// SortInstByName - Sorting predicate to sort instructions by name.
273 ///
274 struct SortInstByName {
275   bool operator()(const CodeGenInstruction *Rec1,
276                   const CodeGenInstruction *Rec2) const {
277     return Rec1->TheDef->getName() < Rec2->TheDef->getName();
278   }
279 };
280 }
281
282 /// getInstructionsByEnumValue - Return all of the instructions defined by the
283 /// target, ordered by their enum value.
284 void CodeGenTarget::ComputeInstrsByEnum() const {
285   // The ordering here must match the ordering in TargetOpcodes.h.
286   const char *const FixedInstrs[] = {
287     "PHI",
288     "INLINEASM",
289     "PROLOG_LABEL",
290     "EH_LABEL",
291     "GC_LABEL",
292     "KILL",
293     "EXTRACT_SUBREG",
294     "INSERT_SUBREG",
295     "IMPLICIT_DEF",
296     "SUBREG_TO_REG",
297     "COPY_TO_REGCLASS",
298     "DBG_VALUE",
299     "REG_SEQUENCE",
300     "COPY",
301     "BUNDLE",
302     "LIFETIME_START",
303     "LIFETIME_END",
304     0
305   };
306   const DenseMap<const Record*, CodeGenInstruction*> &Insts = getInstructions();
307   for (const char *const *p = FixedInstrs; *p; ++p) {
308     const CodeGenInstruction *Instr = GetInstByName(*p, Insts, Records);
309     assert(Instr && "Missing target independent instruction");
310     assert(Instr->Namespace == "TargetOpcode" && "Bad namespace");
311     InstrsByEnum.push_back(Instr);
312   }
313   unsigned EndOfPredefines = InstrsByEnum.size();
314
315   for (DenseMap<const Record*, CodeGenInstruction*>::const_iterator
316        I = Insts.begin(), E = Insts.end(); I != E; ++I) {
317     const CodeGenInstruction *CGI = I->second;
318     if (CGI->Namespace != "TargetOpcode")
319       InstrsByEnum.push_back(CGI);
320   }
321
322   assert(InstrsByEnum.size() == Insts.size() && "Missing predefined instr");
323
324   // All of the instructions are now in random order based on the map iteration.
325   // Sort them by name.
326   std::sort(InstrsByEnum.begin()+EndOfPredefines, InstrsByEnum.end(),
327             SortInstByName());
328 }
329
330
331 /// isLittleEndianEncoding - Return whether this target encodes its instruction
332 /// in little-endian format, i.e. bits laid out in the order [0..n]
333 ///
334 bool CodeGenTarget::isLittleEndianEncoding() const {
335   return getInstructionSet()->getValueAsBit("isLittleEndianEncoding");
336 }
337
338 /// guessInstructionProperties - Return true if it's OK to guess instruction
339 /// properties instead of raising an error.
340 ///
341 /// This is configurable as a temporary migration aid. It will eventually be
342 /// permanently false.
343 bool CodeGenTarget::guessInstructionProperties() const {
344   return getInstructionSet()->getValueAsBit("guessInstructionProperties");
345 }
346
347 //===----------------------------------------------------------------------===//
348 // ComplexPattern implementation
349 //
350 ComplexPattern::ComplexPattern(Record *R) {
351   Ty          = ::getValueType(R->getValueAsDef("Ty"));
352   NumOperands = R->getValueAsInt("NumOperands");
353   SelectFunc  = R->getValueAsString("SelectFunc");
354   RootNodes   = R->getValueAsListOfDefs("RootNodes");
355
356   // Parse the properties.
357   Properties = 0;
358   std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
359   for (unsigned i = 0, e = PropList.size(); i != e; ++i)
360     if (PropList[i]->getName() == "SDNPHasChain") {
361       Properties |= 1 << SDNPHasChain;
362     } else if (PropList[i]->getName() == "SDNPOptInGlue") {
363       Properties |= 1 << SDNPOptInGlue;
364     } else if (PropList[i]->getName() == "SDNPMayStore") {
365       Properties |= 1 << SDNPMayStore;
366     } else if (PropList[i]->getName() == "SDNPMayLoad") {
367       Properties |= 1 << SDNPMayLoad;
368     } else if (PropList[i]->getName() == "SDNPSideEffect") {
369       Properties |= 1 << SDNPSideEffect;
370     } else if (PropList[i]->getName() == "SDNPMemOperand") {
371       Properties |= 1 << SDNPMemOperand;
372     } else if (PropList[i]->getName() == "SDNPVariadic") {
373       Properties |= 1 << SDNPVariadic;
374     } else if (PropList[i]->getName() == "SDNPWantRoot") {
375       Properties |= 1 << SDNPWantRoot;
376     } else if (PropList[i]->getName() == "SDNPWantParent") {
377       Properties |= 1 << SDNPWantParent;
378     } else {
379       errs() << "Unsupported SD Node property '" << PropList[i]->getName()
380              << "' on ComplexPattern '" << R->getName() << "'!\n";
381       exit(1);
382     }
383 }
384
385 //===----------------------------------------------------------------------===//
386 // CodeGenIntrinsic Implementation
387 //===----------------------------------------------------------------------===//
388
389 std::vector<CodeGenIntrinsic> llvm::LoadIntrinsics(const RecordKeeper &RC,
390                                                    bool TargetOnly) {
391   std::vector<Record*> I = RC.getAllDerivedDefinitions("Intrinsic");
392
393   std::vector<CodeGenIntrinsic> Result;
394
395   for (unsigned i = 0, e = I.size(); i != e; ++i) {
396     bool isTarget = I[i]->getValueAsBit("isTarget");
397     if (isTarget == TargetOnly)
398       Result.push_back(CodeGenIntrinsic(I[i]));
399   }
400   return Result;
401 }
402
403 CodeGenIntrinsic::CodeGenIntrinsic(Record *R) {
404   TheDef = R;
405   std::string DefName = R->getName();
406   ModRef = ReadWriteMem;
407   isOverloaded = false;
408   isCommutative = false;
409   canThrow = false;
410   isNoReturn = false;
411
412   if (DefName.size() <= 4 ||
413       std::string(DefName.begin(), DefName.begin() + 4) != "int_")
414     throw "Intrinsic '" + DefName + "' does not start with 'int_'!";
415
416   EnumName = std::string(DefName.begin()+4, DefName.end());
417
418   if (R->getValue("GCCBuiltinName"))  // Ignore a missing GCCBuiltinName field.
419     GCCBuiltinName = R->getValueAsString("GCCBuiltinName");
420
421   TargetPrefix = R->getValueAsString("TargetPrefix");
422   Name = R->getValueAsString("LLVMName");
423
424   if (Name == "") {
425     // If an explicit name isn't specified, derive one from the DefName.
426     Name = "llvm.";
427
428     for (unsigned i = 0, e = EnumName.size(); i != e; ++i)
429       Name += (EnumName[i] == '_') ? '.' : EnumName[i];
430   } else {
431     // Verify it starts with "llvm.".
432     if (Name.size() <= 5 ||
433         std::string(Name.begin(), Name.begin() + 5) != "llvm.")
434       throw "Intrinsic '" + DefName + "'s name does not start with 'llvm.'!";
435   }
436
437   // If TargetPrefix is specified, make sure that Name starts with
438   // "llvm.<targetprefix>.".
439   if (!TargetPrefix.empty()) {
440     if (Name.size() < 6+TargetPrefix.size() ||
441         std::string(Name.begin() + 5, Name.begin() + 6 + TargetPrefix.size())
442         != (TargetPrefix + "."))
443       throw "Intrinsic '" + DefName + "' does not start with 'llvm." +
444         TargetPrefix + ".'!";
445   }
446
447   // Parse the list of return types.
448   std::vector<MVT::SimpleValueType> OverloadedVTs;
449   ListInit *TypeList = R->getValueAsListInit("RetTypes");
450   for (unsigned i = 0, e = TypeList->getSize(); i != e; ++i) {
451     Record *TyEl = TypeList->getElementAsRecord(i);
452     assert(TyEl->isSubClassOf("LLVMType") && "Expected a type!");
453     MVT::SimpleValueType VT;
454     if (TyEl->isSubClassOf("LLVMMatchType")) {
455       unsigned MatchTy = TyEl->getValueAsInt("Number");
456       assert(MatchTy < OverloadedVTs.size() &&
457              "Invalid matching number!");
458       VT = OverloadedVTs[MatchTy];
459       // It only makes sense to use the extended and truncated vector element
460       // variants with iAny types; otherwise, if the intrinsic is not
461       // overloaded, all the types can be specified directly.
462       assert(((!TyEl->isSubClassOf("LLVMExtendedElementVectorType") &&
463                !TyEl->isSubClassOf("LLVMTruncatedElementVectorType")) ||
464               VT == MVT::iAny || VT == MVT::vAny) &&
465              "Expected iAny or vAny type");
466     } else {
467       VT = getValueType(TyEl->getValueAsDef("VT"));
468     }
469     if (EVT(VT).isOverloaded()) {
470       OverloadedVTs.push_back(VT);
471       isOverloaded = true;
472     }
473
474     // Reject invalid types.
475     if (VT == MVT::isVoid)
476       throw "Intrinsic '" + DefName + " has void in result type list!";
477
478     IS.RetVTs.push_back(VT);
479     IS.RetTypeDefs.push_back(TyEl);
480   }
481
482   // Parse the list of parameter types.
483   TypeList = R->getValueAsListInit("ParamTypes");
484   for (unsigned i = 0, e = TypeList->getSize(); i != e; ++i) {
485     Record *TyEl = TypeList->getElementAsRecord(i);
486     assert(TyEl->isSubClassOf("LLVMType") && "Expected a type!");
487     MVT::SimpleValueType VT;
488     if (TyEl->isSubClassOf("LLVMMatchType")) {
489       unsigned MatchTy = TyEl->getValueAsInt("Number");
490       assert(MatchTy < OverloadedVTs.size() &&
491              "Invalid matching number!");
492       VT = OverloadedVTs[MatchTy];
493       // It only makes sense to use the extended and truncated vector element
494       // variants with iAny types; otherwise, if the intrinsic is not
495       // overloaded, all the types can be specified directly.
496       assert(((!TyEl->isSubClassOf("LLVMExtendedElementVectorType") &&
497                !TyEl->isSubClassOf("LLVMTruncatedElementVectorType")) ||
498               VT == MVT::iAny || VT == MVT::vAny) &&
499              "Expected iAny or vAny type");
500     } else
501       VT = getValueType(TyEl->getValueAsDef("VT"));
502
503     if (EVT(VT).isOverloaded()) {
504       OverloadedVTs.push_back(VT);
505       isOverloaded = true;
506     }
507
508     // Reject invalid types.
509     if (VT == MVT::isVoid && i != e-1 /*void at end means varargs*/)
510       throw "Intrinsic '" + DefName + " has void in result type list!";
511
512     IS.ParamVTs.push_back(VT);
513     IS.ParamTypeDefs.push_back(TyEl);
514   }
515
516   // Parse the intrinsic properties.
517   ListInit *PropList = R->getValueAsListInit("Properties");
518   for (unsigned i = 0, e = PropList->getSize(); i != e; ++i) {
519     Record *Property = PropList->getElementAsRecord(i);
520     assert(Property->isSubClassOf("IntrinsicProperty") &&
521            "Expected a property!");
522
523     if (Property->getName() == "IntrNoMem")
524       ModRef = NoMem;
525     else if (Property->getName() == "IntrReadArgMem")
526       ModRef = ReadArgMem;
527     else if (Property->getName() == "IntrReadMem")
528       ModRef = ReadMem;
529     else if (Property->getName() == "IntrReadWriteArgMem")
530       ModRef = ReadWriteArgMem;
531     else if (Property->getName() == "Commutative")
532       isCommutative = true;
533     else if (Property->getName() == "Throws")
534       canThrow = true;
535     else if (Property->getName() == "IntrNoReturn")
536       isNoReturn = true;
537     else if (Property->isSubClassOf("NoCapture")) {
538       unsigned ArgNo = Property->getValueAsInt("ArgNo");
539       ArgumentAttributes.push_back(std::make_pair(ArgNo, NoCapture));
540     } else
541       llvm_unreachable("Unknown property!");
542   }
543
544   // Sort the argument attributes for later benefit.
545   std::sort(ArgumentAttributes.begin(), ArgumentAttributes.end());
546 }