1 //===- CodeGenTarget.cpp - CodeGen Target Class Wrapper -------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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 abort on error conditions.
15 //===----------------------------------------------------------------------===//
17 #include "CodeGenTarget.h"
18 #include "CodeGenIntrinsics.h"
19 #include "CodeGenSchedule.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/StringExtras.h"
22 #include "llvm/Support/CommandLine.h"
23 #include "llvm/TableGen/Error.h"
24 #include "llvm/TableGen/Record.h"
28 static cl::opt<unsigned>
29 AsmParserNum("asmparsernum", cl::init(0),
30 cl::desc("Make -gen-asm-parser emit assembly parser #N"));
32 static cl::opt<unsigned>
33 AsmWriterNum("asmwriternum", cl::init(0),
34 cl::desc("Make -gen-asm-writer emit assembly writer #N"));
36 /// getValueType - Return the MVT::SimpleValueType that the specified TableGen
37 /// record corresponds to.
38 MVT::SimpleValueType llvm::getValueType(Record *Rec) {
39 return (MVT::SimpleValueType)Rec->getValueAsInt("Value");
42 std::string llvm::getName(MVT::SimpleValueType T) {
44 case MVT::Other: return "UNKNOWN";
45 case MVT::iPTR: return "TLI.getPointerTy()";
46 case MVT::iPTRAny: return "TLI.getPointerTy()";
47 default: return getEnumName(T);
51 std::string llvm::getEnumName(MVT::SimpleValueType T) {
53 case MVT::Other: return "MVT::Other";
54 case MVT::i1: return "MVT::i1";
55 case MVT::i8: return "MVT::i8";
56 case MVT::i16: return "MVT::i16";
57 case MVT::i32: return "MVT::i32";
58 case MVT::i64: return "MVT::i64";
59 case MVT::i128: return "MVT::i128";
60 case MVT::iAny: return "MVT::iAny";
61 case MVT::fAny: return "MVT::fAny";
62 case MVT::vAny: return "MVT::vAny";
63 case MVT::f16: return "MVT::f16";
64 case MVT::f32: return "MVT::f32";
65 case MVT::f64: return "MVT::f64";
66 case MVT::f80: return "MVT::f80";
67 case MVT::f128: return "MVT::f128";
68 case MVT::ppcf128: return "MVT::ppcf128";
69 case MVT::x86mmx: return "MVT::x86mmx";
70 case MVT::Glue: return "MVT::Glue";
71 case MVT::isVoid: return "MVT::isVoid";
72 case MVT::v2i1: return "MVT::v2i1";
73 case MVT::v4i1: return "MVT::v4i1";
74 case MVT::v8i1: return "MVT::v8i1";
75 case MVT::v16i1: return "MVT::v16i1";
76 case MVT::v32i1: return "MVT::v32i1";
77 case MVT::v64i1: return "MVT::v64i1";
78 case MVT::v2i8: return "MVT::v2i8";
79 case MVT::v4i8: return "MVT::v4i8";
80 case MVT::v8i8: return "MVT::v8i8";
81 case MVT::v16i8: return "MVT::v16i8";
82 case MVT::v32i8: return "MVT::v32i8";
83 case MVT::v64i8: return "MVT::v64i8";
84 case MVT::v1i16: return "MVT::v1i16";
85 case MVT::v2i16: return "MVT::v2i16";
86 case MVT::v4i16: return "MVT::v4i16";
87 case MVT::v8i16: return "MVT::v8i16";
88 case MVT::v16i16: return "MVT::v16i16";
89 case MVT::v32i16: return "MVT::v32i16";
90 case MVT::v1i32: return "MVT::v1i32";
91 case MVT::v2i32: return "MVT::v2i32";
92 case MVT::v4i32: return "MVT::v4i32";
93 case MVT::v8i32: return "MVT::v8i32";
94 case MVT::v16i32: return "MVT::v16i32";
95 case MVT::v1i64: return "MVT::v1i64";
96 case MVT::v2i64: return "MVT::v2i64";
97 case MVT::v4i64: return "MVT::v4i64";
98 case MVT::v8i64: return "MVT::v8i64";
99 case MVT::v16i64: return "MVT::v16i64";
100 case MVT::v2f16: return "MVT::v2f16";
101 case MVT::v2f32: return "MVT::v2f32";
102 case MVT::v4f32: return "MVT::v4f32";
103 case MVT::v8f32: return "MVT::v8f32";
104 case MVT::v16f32: return "MVT::v16f32";
105 case MVT::v2f64: return "MVT::v2f64";
106 case MVT::v4f64: return "MVT::v4f64";
107 case MVT::v8f64: return "MVT::v8f64";
108 case MVT::Metadata: return "MVT::Metadata";
109 case MVT::iPTR: return "MVT::iPTR";
110 case MVT::iPTRAny: return "MVT::iPTRAny";
111 case MVT::Untyped: return "MVT::Untyped";
112 default: llvm_unreachable("ILLEGAL VALUE TYPE!");
116 /// getQualifiedName - Return the name of the specified record, with a
117 /// namespace qualifier if the record contains one.
119 std::string llvm::getQualifiedName(const Record *R) {
120 std::string Namespace;
121 if (R->getValue("Namespace"))
122 Namespace = R->getValueAsString("Namespace");
123 if (Namespace.empty()) return R->getName();
124 return Namespace + "::" + R->getName();
128 /// getTarget - Return the current instance of the Target class.
130 CodeGenTarget::CodeGenTarget(RecordKeeper &records)
131 : Records(records), RegBank(0), SchedModels(0) {
132 std::vector<Record*> Targets = Records.getAllDerivedDefinitions("Target");
133 if (Targets.size() == 0)
134 PrintFatalError("ERROR: No 'Target' subclasses defined!");
135 if (Targets.size() != 1)
136 PrintFatalError("ERROR: Multiple subclasses of Target defined!");
137 TargetRec = Targets[0];
140 CodeGenTarget::~CodeGenTarget() {
145 const std::string &CodeGenTarget::getName() const {
146 return TargetRec->getName();
149 std::string CodeGenTarget::getInstNamespace() const {
150 for (inst_iterator i = inst_begin(), e = inst_end(); i != e; ++i) {
151 // Make sure not to pick up "TargetOpcode" by accidentally getting
152 // the namespace off the PHI instruction or something.
153 if ((*i)->Namespace != "TargetOpcode")
154 return (*i)->Namespace;
160 Record *CodeGenTarget::getInstructionSet() const {
161 return TargetRec->getValueAsDef("InstructionSet");
165 /// getAsmParser - Return the AssemblyParser definition for this target.
167 Record *CodeGenTarget::getAsmParser() const {
168 std::vector<Record*> LI = TargetRec->getValueAsListOfDefs("AssemblyParsers");
169 if (AsmParserNum >= LI.size())
170 PrintFatalError("Target does not have an AsmParser #" + utostr(AsmParserNum) + "!");
171 return LI[AsmParserNum];
174 /// getAsmParserVariant - Return the AssmblyParserVariant definition for
177 Record *CodeGenTarget::getAsmParserVariant(unsigned i) const {
178 std::vector<Record*> LI =
179 TargetRec->getValueAsListOfDefs("AssemblyParserVariants");
181 PrintFatalError("Target does not have an AsmParserVariant #" + utostr(i) + "!");
185 /// getAsmParserVariantCount - Return the AssmblyParserVariant definition
186 /// available for this target.
188 unsigned CodeGenTarget::getAsmParserVariantCount() const {
189 std::vector<Record*> LI =
190 TargetRec->getValueAsListOfDefs("AssemblyParserVariants");
194 /// getAsmWriter - Return the AssemblyWriter definition for this target.
196 Record *CodeGenTarget::getAsmWriter() const {
197 std::vector<Record*> LI = TargetRec->getValueAsListOfDefs("AssemblyWriters");
198 if (AsmWriterNum >= LI.size())
199 PrintFatalError("Target does not have an AsmWriter #" + utostr(AsmWriterNum) + "!");
200 return LI[AsmWriterNum];
203 CodeGenRegBank &CodeGenTarget::getRegBank() const {
205 RegBank = new CodeGenRegBank(Records);
209 void CodeGenTarget::ReadRegAltNameIndices() const {
210 RegAltNameIndices = Records.getAllDerivedDefinitions("RegAltNameIndex");
211 std::sort(RegAltNameIndices.begin(), RegAltNameIndices.end(), LessRecord());
214 /// getRegisterByName - If there is a register with the specific AsmName,
216 const CodeGenRegister *CodeGenTarget::getRegisterByName(StringRef Name) const {
217 const StringMap<CodeGenRegister*> &Regs = getRegBank().getRegistersByName();
218 StringMap<CodeGenRegister*>::const_iterator I = Regs.find(Name);
224 std::vector<MVT::SimpleValueType> CodeGenTarget::
225 getRegisterVTs(Record *R) const {
226 const CodeGenRegister *Reg = getRegBank().getReg(R);
227 std::vector<MVT::SimpleValueType> Result;
228 ArrayRef<CodeGenRegisterClass*> RCs = getRegBank().getRegClasses();
229 for (unsigned i = 0, e = RCs.size(); i != e; ++i) {
230 const CodeGenRegisterClass &RC = *RCs[i];
231 if (RC.contains(Reg)) {
232 ArrayRef<MVT::SimpleValueType> InVTs = RC.getValueTypes();
233 Result.insert(Result.end(), InVTs.begin(), InVTs.end());
237 // Remove duplicates.
238 array_pod_sort(Result.begin(), Result.end());
239 Result.erase(std::unique(Result.begin(), Result.end()), Result.end());
244 void CodeGenTarget::ReadLegalValueTypes() const {
245 ArrayRef<CodeGenRegisterClass*> RCs = getRegBank().getRegClasses();
246 for (unsigned i = 0, e = RCs.size(); i != e; ++i)
247 for (unsigned ri = 0, re = RCs[i]->VTs.size(); ri != re; ++ri)
248 LegalValueTypes.push_back(RCs[i]->VTs[ri]);
250 // Remove duplicates.
251 std::sort(LegalValueTypes.begin(), LegalValueTypes.end());
252 LegalValueTypes.erase(std::unique(LegalValueTypes.begin(),
253 LegalValueTypes.end()),
254 LegalValueTypes.end());
257 CodeGenSchedModels &CodeGenTarget::getSchedModels() const {
259 SchedModels = new CodeGenSchedModels(Records, *this);
263 void CodeGenTarget::ReadInstructions() const {
264 std::vector<Record*> Insts = Records.getAllDerivedDefinitions("Instruction");
265 if (Insts.size() <= 2)
266 PrintFatalError("No 'Instruction' subclasses defined!");
268 // Parse the instructions defined in the .td file.
269 for (unsigned i = 0, e = Insts.size(); i != e; ++i)
270 Instructions[Insts[i]] = new CodeGenInstruction(Insts[i]);
273 static const CodeGenInstruction *
274 GetInstByName(const char *Name,
275 const DenseMap<const Record*, CodeGenInstruction*> &Insts,
276 RecordKeeper &Records) {
277 const Record *Rec = Records.getDef(Name);
279 DenseMap<const Record*, CodeGenInstruction*>::const_iterator
281 if (Rec == 0 || I == Insts.end())
282 PrintFatalError(std::string("Could not find '") + Name + "' instruction!");
287 /// SortInstByName - Sorting predicate to sort instructions by name.
289 struct SortInstByName {
290 bool operator()(const CodeGenInstruction *Rec1,
291 const CodeGenInstruction *Rec2) const {
292 return Rec1->TheDef->getName() < Rec2->TheDef->getName();
297 /// getInstructionsByEnumValue - Return all of the instructions defined by the
298 /// target, ordered by their enum value.
299 void CodeGenTarget::ComputeInstrsByEnum() const {
300 // The ordering here must match the ordering in TargetOpcodes.h.
301 const char *const FixedInstrs[] = {
321 const DenseMap<const Record*, CodeGenInstruction*> &Insts = getInstructions();
322 for (const char *const *p = FixedInstrs; *p; ++p) {
323 const CodeGenInstruction *Instr = GetInstByName(*p, Insts, Records);
324 assert(Instr && "Missing target independent instruction");
325 assert(Instr->Namespace == "TargetOpcode" && "Bad namespace");
326 InstrsByEnum.push_back(Instr);
328 unsigned EndOfPredefines = InstrsByEnum.size();
330 for (DenseMap<const Record*, CodeGenInstruction*>::const_iterator
331 I = Insts.begin(), E = Insts.end(); I != E; ++I) {
332 const CodeGenInstruction *CGI = I->second;
333 if (CGI->Namespace != "TargetOpcode")
334 InstrsByEnum.push_back(CGI);
337 assert(InstrsByEnum.size() == Insts.size() && "Missing predefined instr");
339 // All of the instructions are now in random order based on the map iteration.
340 // Sort them by name.
341 std::sort(InstrsByEnum.begin()+EndOfPredefines, InstrsByEnum.end(),
346 /// isLittleEndianEncoding - Return whether this target encodes its instruction
347 /// in little-endian format, i.e. bits laid out in the order [0..n]
349 bool CodeGenTarget::isLittleEndianEncoding() const {
350 return getInstructionSet()->getValueAsBit("isLittleEndianEncoding");
353 /// guessInstructionProperties - Return true if it's OK to guess instruction
354 /// properties instead of raising an error.
356 /// This is configurable as a temporary migration aid. It will eventually be
357 /// permanently false.
358 bool CodeGenTarget::guessInstructionProperties() const {
359 return getInstructionSet()->getValueAsBit("guessInstructionProperties");
362 //===----------------------------------------------------------------------===//
363 // ComplexPattern implementation
365 ComplexPattern::ComplexPattern(Record *R) {
366 Ty = ::getValueType(R->getValueAsDef("Ty"));
367 NumOperands = R->getValueAsInt("NumOperands");
368 SelectFunc = R->getValueAsString("SelectFunc");
369 RootNodes = R->getValueAsListOfDefs("RootNodes");
371 // Parse the properties.
373 std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
374 for (unsigned i = 0, e = PropList.size(); i != e; ++i)
375 if (PropList[i]->getName() == "SDNPHasChain") {
376 Properties |= 1 << SDNPHasChain;
377 } else if (PropList[i]->getName() == "SDNPOptInGlue") {
378 Properties |= 1 << SDNPOptInGlue;
379 } else if (PropList[i]->getName() == "SDNPMayStore") {
380 Properties |= 1 << SDNPMayStore;
381 } else if (PropList[i]->getName() == "SDNPMayLoad") {
382 Properties |= 1 << SDNPMayLoad;
383 } else if (PropList[i]->getName() == "SDNPSideEffect") {
384 Properties |= 1 << SDNPSideEffect;
385 } else if (PropList[i]->getName() == "SDNPMemOperand") {
386 Properties |= 1 << SDNPMemOperand;
387 } else if (PropList[i]->getName() == "SDNPVariadic") {
388 Properties |= 1 << SDNPVariadic;
389 } else if (PropList[i]->getName() == "SDNPWantRoot") {
390 Properties |= 1 << SDNPWantRoot;
391 } else if (PropList[i]->getName() == "SDNPWantParent") {
392 Properties |= 1 << SDNPWantParent;
394 errs() << "Unsupported SD Node property '" << PropList[i]->getName()
395 << "' on ComplexPattern '" << R->getName() << "'!\n";
400 //===----------------------------------------------------------------------===//
401 // CodeGenIntrinsic Implementation
402 //===----------------------------------------------------------------------===//
404 std::vector<CodeGenIntrinsic> llvm::LoadIntrinsics(const RecordKeeper &RC,
406 std::vector<Record*> I = RC.getAllDerivedDefinitions("Intrinsic");
408 std::vector<CodeGenIntrinsic> Result;
410 for (unsigned i = 0, e = I.size(); i != e; ++i) {
411 bool isTarget = I[i]->getValueAsBit("isTarget");
412 if (isTarget == TargetOnly)
413 Result.push_back(CodeGenIntrinsic(I[i]));
418 CodeGenIntrinsic::CodeGenIntrinsic(Record *R) {
420 std::string DefName = R->getName();
421 ModRef = ReadWriteMem;
422 isOverloaded = false;
423 isCommutative = false;
427 if (DefName.size() <= 4 ||
428 std::string(DefName.begin(), DefName.begin() + 4) != "int_")
429 PrintFatalError("Intrinsic '" + DefName + "' does not start with 'int_'!");
431 EnumName = std::string(DefName.begin()+4, DefName.end());
433 if (R->getValue("GCCBuiltinName")) // Ignore a missing GCCBuiltinName field.
434 GCCBuiltinName = R->getValueAsString("GCCBuiltinName");
436 TargetPrefix = R->getValueAsString("TargetPrefix");
437 Name = R->getValueAsString("LLVMName");
440 // If an explicit name isn't specified, derive one from the DefName.
443 for (unsigned i = 0, e = EnumName.size(); i != e; ++i)
444 Name += (EnumName[i] == '_') ? '.' : EnumName[i];
446 // Verify it starts with "llvm.".
447 if (Name.size() <= 5 ||
448 std::string(Name.begin(), Name.begin() + 5) != "llvm.")
449 PrintFatalError("Intrinsic '" + DefName + "'s name does not start with 'llvm.'!");
452 // If TargetPrefix is specified, make sure that Name starts with
453 // "llvm.<targetprefix>.".
454 if (!TargetPrefix.empty()) {
455 if (Name.size() < 6+TargetPrefix.size() ||
456 std::string(Name.begin() + 5, Name.begin() + 6 + TargetPrefix.size())
457 != (TargetPrefix + "."))
458 PrintFatalError("Intrinsic '" + DefName + "' does not start with 'llvm." +
459 TargetPrefix + ".'!");
462 // Parse the list of return types.
463 std::vector<MVT::SimpleValueType> OverloadedVTs;
464 ListInit *TypeList = R->getValueAsListInit("RetTypes");
465 for (unsigned i = 0, e = TypeList->getSize(); i != e; ++i) {
466 Record *TyEl = TypeList->getElementAsRecord(i);
467 assert(TyEl->isSubClassOf("LLVMType") && "Expected a type!");
468 MVT::SimpleValueType VT;
469 if (TyEl->isSubClassOf("LLVMMatchType")) {
470 unsigned MatchTy = TyEl->getValueAsInt("Number");
471 assert(MatchTy < OverloadedVTs.size() &&
472 "Invalid matching number!");
473 VT = OverloadedVTs[MatchTy];
474 // It only makes sense to use the extended and truncated vector element
475 // variants with iAny types; otherwise, if the intrinsic is not
476 // overloaded, all the types can be specified directly.
477 assert(((!TyEl->isSubClassOf("LLVMExtendedElementVectorType") &&
478 !TyEl->isSubClassOf("LLVMTruncatedElementVectorType")) ||
479 VT == MVT::iAny || VT == MVT::vAny) &&
480 "Expected iAny or vAny type");
482 VT = getValueType(TyEl->getValueAsDef("VT"));
484 if (EVT(VT).isOverloaded()) {
485 OverloadedVTs.push_back(VT);
489 // Reject invalid types.
490 if (VT == MVT::isVoid)
491 PrintFatalError("Intrinsic '" + DefName + " has void in result type list!");
493 IS.RetVTs.push_back(VT);
494 IS.RetTypeDefs.push_back(TyEl);
497 // Parse the list of parameter types.
498 TypeList = R->getValueAsListInit("ParamTypes");
499 for (unsigned i = 0, e = TypeList->getSize(); i != e; ++i) {
500 Record *TyEl = TypeList->getElementAsRecord(i);
501 assert(TyEl->isSubClassOf("LLVMType") && "Expected a type!");
502 MVT::SimpleValueType VT;
503 if (TyEl->isSubClassOf("LLVMMatchType")) {
504 unsigned MatchTy = TyEl->getValueAsInt("Number");
505 assert(MatchTy < OverloadedVTs.size() &&
506 "Invalid matching number!");
507 VT = OverloadedVTs[MatchTy];
508 // It only makes sense to use the extended and truncated vector element
509 // variants with iAny types; otherwise, if the intrinsic is not
510 // overloaded, all the types can be specified directly.
511 assert(((!TyEl->isSubClassOf("LLVMExtendedElementVectorType") &&
512 !TyEl->isSubClassOf("LLVMTruncatedElementVectorType")) ||
513 VT == MVT::iAny || VT == MVT::vAny) &&
514 "Expected iAny or vAny type");
516 VT = getValueType(TyEl->getValueAsDef("VT"));
518 if (EVT(VT).isOverloaded()) {
519 OverloadedVTs.push_back(VT);
523 // Reject invalid types.
524 if (VT == MVT::isVoid && i != e-1 /*void at end means varargs*/)
525 PrintFatalError("Intrinsic '" + DefName + " has void in result type list!");
527 IS.ParamVTs.push_back(VT);
528 IS.ParamTypeDefs.push_back(TyEl);
531 // Parse the intrinsic properties.
532 ListInit *PropList = R->getValueAsListInit("Properties");
533 for (unsigned i = 0, e = PropList->getSize(); i != e; ++i) {
534 Record *Property = PropList->getElementAsRecord(i);
535 assert(Property->isSubClassOf("IntrinsicProperty") &&
536 "Expected a property!");
538 if (Property->getName() == "IntrNoMem")
540 else if (Property->getName() == "IntrReadArgMem")
542 else if (Property->getName() == "IntrReadMem")
544 else if (Property->getName() == "IntrReadWriteArgMem")
545 ModRef = ReadWriteArgMem;
546 else if (Property->getName() == "Commutative")
547 isCommutative = true;
548 else if (Property->getName() == "Throws")
550 else if (Property->getName() == "IntrNoReturn")
552 else if (Property->isSubClassOf("NoCapture")) {
553 unsigned ArgNo = Property->getValueAsInt("ArgNo");
554 ArgumentAttributes.push_back(std::make_pair(ArgNo, NoCapture));
555 } else if (Property->isSubClassOf("ReadOnly")) {
556 unsigned ArgNo = Property->getValueAsInt("ArgNo");
557 ArgumentAttributes.push_back(std::make_pair(ArgNo, ReadOnly));
558 } else if (Property->isSubClassOf("ReadNone")) {
559 unsigned ArgNo = Property->getValueAsInt("ArgNo");
560 ArgumentAttributes.push_back(std::make_pair(ArgNo, ReadNone));
562 llvm_unreachable("Unknown property!");
565 // Sort the argument attributes for later benefit.
566 std::sort(ArgumentAttributes.begin(), ArgumentAttributes.end());