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 throw exceptions on error conditions.
15 //===----------------------------------------------------------------------===//
17 #include "CodeGenTarget.h"
18 #include "CodeGenIntrinsics.h"
20 #include "llvm/ADT/StringExtras.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/Support/CommandLine.h"
26 static cl::opt<unsigned>
27 AsmParserNum("asmparsernum", cl::init(0),
28 cl::desc("Make -gen-asm-parser emit assembly parser #N"));
30 static cl::opt<unsigned>
31 AsmWriterNum("asmwriternum", cl::init(0),
32 cl::desc("Make -gen-asm-writer emit assembly writer #N"));
34 /// getValueType - Return the MVT::SimpleValueType that the specified TableGen
35 /// record corresponds to.
36 MVT::SimpleValueType llvm::getValueType(Record *Rec) {
37 return (MVT::SimpleValueType)Rec->getValueAsInt("Value");
40 std::string llvm::getName(MVT::SimpleValueType T) {
42 case MVT::Other: return "UNKNOWN";
43 case MVT::iPTR: return "TLI.getPointerTy()";
44 case MVT::iPTRAny: return "TLI.getPointerTy()";
45 default: return getEnumName(T);
49 std::string llvm::getEnumName(MVT::SimpleValueType T) {
51 case MVT::Other: return "MVT::Other";
52 case MVT::i1: return "MVT::i1";
53 case MVT::i8: return "MVT::i8";
54 case MVT::i16: return "MVT::i16";
55 case MVT::i32: return "MVT::i32";
56 case MVT::i64: return "MVT::i64";
57 case MVT::i128: return "MVT::i128";
58 case MVT::iAny: return "MVT::iAny";
59 case MVT::fAny: return "MVT::fAny";
60 case MVT::vAny: return "MVT::vAny";
61 case MVT::f32: return "MVT::f32";
62 case MVT::f64: return "MVT::f64";
63 case MVT::f80: return "MVT::f80";
64 case MVT::f128: return "MVT::f128";
65 case MVT::ppcf128: return "MVT::ppcf128";
66 case MVT::x86mmx: return "MVT::x86mmx";
67 case MVT::Flag: return "MVT::Flag";
68 case MVT::isVoid: return "MVT::isVoid";
69 case MVT::v2i8: return "MVT::v2i8";
70 case MVT::v4i8: return "MVT::v4i8";
71 case MVT::v8i8: return "MVT::v8i8";
72 case MVT::v16i8: return "MVT::v16i8";
73 case MVT::v32i8: return "MVT::v32i8";
74 case MVT::v2i16: return "MVT::v2i16";
75 case MVT::v4i16: return "MVT::v4i16";
76 case MVT::v8i16: return "MVT::v8i16";
77 case MVT::v16i16: return "MVT::v16i16";
78 case MVT::v2i32: return "MVT::v2i32";
79 case MVT::v4i32: return "MVT::v4i32";
80 case MVT::v8i32: return "MVT::v8i32";
81 case MVT::v1i64: return "MVT::v1i64";
82 case MVT::v2i64: return "MVT::v2i64";
83 case MVT::v4i64: return "MVT::v4i64";
84 case MVT::v8i64: return "MVT::v8i64";
85 case MVT::v2f32: return "MVT::v2f32";
86 case MVT::v4f32: return "MVT::v4f32";
87 case MVT::v8f32: return "MVT::v8f32";
88 case MVT::v2f64: return "MVT::v2f64";
89 case MVT::v4f64: return "MVT::v4f64";
90 case MVT::Metadata: return "MVT::Metadata";
91 case MVT::iPTR: return "MVT::iPTR";
92 case MVT::iPTRAny: return "MVT::iPTRAny";
93 default: assert(0 && "ILLEGAL VALUE TYPE!"); return "";
97 /// getQualifiedName - Return the name of the specified record, with a
98 /// namespace qualifier if the record contains one.
100 std::string llvm::getQualifiedName(const Record *R) {
101 std::string Namespace = R->getValueAsString("Namespace");
102 if (Namespace.empty()) return R->getName();
103 return Namespace + "::" + R->getName();
109 /// getTarget - Return the current instance of the Target class.
111 CodeGenTarget::CodeGenTarget() {
112 std::vector<Record*> Targets = Records.getAllDerivedDefinitions("Target");
113 if (Targets.size() == 0)
114 throw std::string("ERROR: No 'Target' subclasses defined!");
115 if (Targets.size() != 1)
116 throw std::string("ERROR: Multiple subclasses of Target defined!");
117 TargetRec = Targets[0];
121 const std::string &CodeGenTarget::getName() const {
122 return TargetRec->getName();
125 std::string CodeGenTarget::getInstNamespace() const {
126 for (inst_iterator i = inst_begin(), e = inst_end(); i != e; ++i) {
127 // Make sure not to pick up "TargetOpcode" by accidentally getting
128 // the namespace off the PHI instruction or something.
129 if ((*i)->Namespace != "TargetOpcode")
130 return (*i)->Namespace;
136 Record *CodeGenTarget::getInstructionSet() const {
137 return TargetRec->getValueAsDef("InstructionSet");
141 /// getAsmParser - Return the AssemblyParser definition for this target.
143 Record *CodeGenTarget::getAsmParser() const {
144 std::vector<Record*> LI = TargetRec->getValueAsListOfDefs("AssemblyParsers");
145 if (AsmParserNum >= LI.size())
146 throw "Target does not have an AsmParser #" + utostr(AsmParserNum) + "!";
147 return LI[AsmParserNum];
150 /// getAsmWriter - Return the AssemblyWriter definition for this target.
152 Record *CodeGenTarget::getAsmWriter() const {
153 std::vector<Record*> LI = TargetRec->getValueAsListOfDefs("AssemblyWriters");
154 if (AsmWriterNum >= LI.size())
155 throw "Target does not have an AsmWriter #" + utostr(AsmWriterNum) + "!";
156 return LI[AsmWriterNum];
159 void CodeGenTarget::ReadRegisters() const {
160 std::vector<Record*> Regs = Records.getAllDerivedDefinitions("Register");
162 throw std::string("No 'Register' subclasses defined!");
163 std::sort(Regs.begin(), Regs.end(), LessRecord());
165 Registers.reserve(Regs.size());
166 Registers.assign(Regs.begin(), Regs.end());
169 CodeGenRegister::CodeGenRegister(Record *R) : TheDef(R) {
170 DeclaredSpillSize = R->getValueAsInt("SpillSize");
171 DeclaredSpillAlignment = R->getValueAsInt("SpillAlignment");
174 const std::string &CodeGenRegister::getName() const {
175 return TheDef->getName();
178 void CodeGenTarget::ReadSubRegIndices() const {
179 SubRegIndices = Records.getAllDerivedDefinitions("SubRegIndex");
180 std::sort(SubRegIndices.begin(), SubRegIndices.end(), LessRecord());
183 void CodeGenTarget::ReadRegisterClasses() const {
184 std::vector<Record*> RegClasses =
185 Records.getAllDerivedDefinitions("RegisterClass");
186 if (RegClasses.empty())
187 throw std::string("No 'RegisterClass' subclasses defined!");
189 RegisterClasses.reserve(RegClasses.size());
190 RegisterClasses.assign(RegClasses.begin(), RegClasses.end());
193 std::vector<MVT::SimpleValueType> CodeGenTarget::
194 getRegisterVTs(Record *R) const {
195 std::vector<MVT::SimpleValueType> Result;
196 const std::vector<CodeGenRegisterClass> &RCs = getRegisterClasses();
197 for (unsigned i = 0, e = RCs.size(); i != e; ++i) {
198 const CodeGenRegisterClass &RC = RegisterClasses[i];
199 for (unsigned ei = 0, ee = RC.Elements.size(); ei != ee; ++ei) {
200 if (R == RC.Elements[ei]) {
201 const std::vector<MVT::SimpleValueType> &InVTs = RC.getValueTypes();
202 Result.insert(Result.end(), InVTs.begin(), InVTs.end());
207 // Remove duplicates.
208 array_pod_sort(Result.begin(), Result.end());
209 Result.erase(std::unique(Result.begin(), Result.end()), Result.end());
214 CodeGenRegisterClass::CodeGenRegisterClass(Record *R) : TheDef(R) {
215 // Rename anonymous register classes.
216 if (R->getName().size() > 9 && R->getName()[9] == '.') {
217 static unsigned AnonCounter = 0;
218 R->setName("AnonRegClass_"+utostr(AnonCounter++));
221 std::vector<Record*> TypeList = R->getValueAsListOfDefs("RegTypes");
222 for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
223 Record *Type = TypeList[i];
224 if (!Type->isSubClassOf("ValueType"))
225 throw "RegTypes list member '" + Type->getName() +
226 "' does not derive from the ValueType class!";
227 VTs.push_back(getValueType(Type));
229 assert(!VTs.empty() && "RegisterClass must contain at least one ValueType!");
231 std::vector<Record*> RegList = R->getValueAsListOfDefs("MemberList");
232 for (unsigned i = 0, e = RegList.size(); i != e; ++i) {
233 Record *Reg = RegList[i];
234 if (!Reg->isSubClassOf("Register"))
235 throw "Register Class member '" + Reg->getName() +
236 "' does not derive from the Register class!";
237 Elements.push_back(Reg);
240 // SubRegClasses is a list<dag> containing (RC, subregindex, ...) dags.
241 ListInit *SRC = R->getValueAsListInit("SubRegClasses");
242 for (ListInit::const_iterator i = SRC->begin(), e = SRC->end(); i != e; ++i) {
243 DagInit *DAG = dynamic_cast<DagInit*>(*i);
244 if (!DAG) throw "SubRegClasses must contain DAGs";
245 DefInit *DAGOp = dynamic_cast<DefInit*>(DAG->getOperator());
247 if (!DAGOp || !(RCRec = DAGOp->getDef())->isSubClassOf("RegisterClass"))
248 throw "Operator '" + DAG->getOperator()->getAsString() +
249 "' in SubRegClasses is not a RegisterClass";
250 // Iterate over args, all SubRegIndex instances.
251 for (DagInit::const_arg_iterator ai = DAG->arg_begin(), ae = DAG->arg_end();
253 DefInit *Idx = dynamic_cast<DefInit*>(*ai);
255 if (!Idx || !(IdxRec = Idx->getDef())->isSubClassOf("SubRegIndex"))
256 throw "Argument '" + (*ai)->getAsString() +
257 "' in SubRegClasses is not a SubRegIndex";
258 if (!SubRegClasses.insert(std::make_pair(IdxRec, RCRec)).second)
259 throw "SubRegIndex '" + IdxRec->getName() + "' mentioned twice";
263 // Allow targets to override the size in bits of the RegisterClass.
264 unsigned Size = R->getValueAsInt("Size");
266 Namespace = R->getValueAsString("Namespace");
267 SpillSize = Size ? Size : EVT(VTs[0]).getSizeInBits();
268 SpillAlignment = R->getValueAsInt("Alignment");
269 CopyCost = R->getValueAsInt("CopyCost");
270 MethodBodies = R->getValueAsCode("MethodBodies");
271 MethodProtos = R->getValueAsCode("MethodProtos");
274 const std::string &CodeGenRegisterClass::getName() const {
275 return TheDef->getName();
278 void CodeGenTarget::ReadLegalValueTypes() const {
279 const std::vector<CodeGenRegisterClass> &RCs = getRegisterClasses();
280 for (unsigned i = 0, e = RCs.size(); i != e; ++i)
281 for (unsigned ri = 0, re = RCs[i].VTs.size(); ri != re; ++ri)
282 LegalValueTypes.push_back(RCs[i].VTs[ri]);
284 // Remove duplicates.
285 std::sort(LegalValueTypes.begin(), LegalValueTypes.end());
286 LegalValueTypes.erase(std::unique(LegalValueTypes.begin(),
287 LegalValueTypes.end()),
288 LegalValueTypes.end());
292 void CodeGenTarget::ReadInstructions() const {
293 std::vector<Record*> Insts = Records.getAllDerivedDefinitions("Instruction");
294 if (Insts.size() <= 2)
295 throw std::string("No 'Instruction' subclasses defined!");
297 // Parse the instructions defined in the .td file.
298 std::string InstFormatName =
299 getAsmWriter()->getValueAsString("InstFormatName");
301 for (unsigned i = 0, e = Insts.size(); i != e; ++i) {
302 std::string AsmStr = Insts[i]->getValueAsString(InstFormatName);
303 Instructions[Insts[i]] = new CodeGenInstruction(Insts[i], AsmStr);
307 static const CodeGenInstruction *
308 GetInstByName(const char *Name,
309 const DenseMap<const Record*, CodeGenInstruction*> &Insts) {
310 const Record *Rec = Records.getDef(Name);
312 DenseMap<const Record*, CodeGenInstruction*>::const_iterator
314 if (Rec == 0 || I == Insts.end())
315 throw std::string("Could not find '") + Name + "' instruction!";
320 /// SortInstByName - Sorting predicate to sort instructions by name.
322 struct SortInstByName {
323 bool operator()(const CodeGenInstruction *Rec1,
324 const CodeGenInstruction *Rec2) const {
325 return Rec1->TheDef->getName() < Rec2->TheDef->getName();
330 /// getInstructionsByEnumValue - Return all of the instructions defined by the
331 /// target, ordered by their enum value.
332 void CodeGenTarget::ComputeInstrsByEnum() const {
333 // The ordering here must match the ordering in TargetOpcodes.h.
334 const char *const FixedInstrs[] = {
351 const DenseMap<const Record*, CodeGenInstruction*> &Insts = getInstructions();
352 for (const char *const *p = FixedInstrs; *p; ++p) {
353 const CodeGenInstruction *Instr = GetInstByName(*p, Insts);
354 assert(Instr && "Missing target independent instruction");
355 assert(Instr->Namespace == "TargetOpcode" && "Bad namespace");
356 InstrsByEnum.push_back(Instr);
358 unsigned EndOfPredefines = InstrsByEnum.size();
360 for (DenseMap<const Record*, CodeGenInstruction*>::const_iterator
361 I = Insts.begin(), E = Insts.end(); I != E; ++I) {
362 const CodeGenInstruction *CGI = I->second;
363 if (CGI->Namespace != "TargetOpcode")
364 InstrsByEnum.push_back(CGI);
367 assert(InstrsByEnum.size() == Insts.size() && "Missing predefined instr");
369 // All of the instructions are now in random order based on the map iteration.
370 // Sort them by name.
371 std::sort(InstrsByEnum.begin()+EndOfPredefines, InstrsByEnum.end(),
376 /// isLittleEndianEncoding - Return whether this target encodes its instruction
377 /// in little-endian format, i.e. bits laid out in the order [0..n]
379 bool CodeGenTarget::isLittleEndianEncoding() const {
380 return getInstructionSet()->getValueAsBit("isLittleEndianEncoding");
383 //===----------------------------------------------------------------------===//
384 // ComplexPattern implementation
386 ComplexPattern::ComplexPattern(Record *R) {
387 Ty = ::getValueType(R->getValueAsDef("Ty"));
388 NumOperands = R->getValueAsInt("NumOperands");
389 SelectFunc = R->getValueAsString("SelectFunc");
390 RootNodes = R->getValueAsListOfDefs("RootNodes");
392 // Parse the properties.
394 std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
395 for (unsigned i = 0, e = PropList.size(); i != e; ++i)
396 if (PropList[i]->getName() == "SDNPHasChain") {
397 Properties |= 1 << SDNPHasChain;
398 } else if (PropList[i]->getName() == "SDNPOptInFlag") {
399 Properties |= 1 << SDNPOptInFlag;
400 } else if (PropList[i]->getName() == "SDNPMayStore") {
401 Properties |= 1 << SDNPMayStore;
402 } else if (PropList[i]->getName() == "SDNPMayLoad") {
403 Properties |= 1 << SDNPMayLoad;
404 } else if (PropList[i]->getName() == "SDNPSideEffect") {
405 Properties |= 1 << SDNPSideEffect;
406 } else if (PropList[i]->getName() == "SDNPMemOperand") {
407 Properties |= 1 << SDNPMemOperand;
408 } else if (PropList[i]->getName() == "SDNPVariadic") {
409 Properties |= 1 << SDNPVariadic;
410 } else if (PropList[i]->getName() == "SDNPWantRoot") {
411 Properties |= 1 << SDNPWantRoot;
412 } else if (PropList[i]->getName() == "SDNPWantParent") {
413 Properties |= 1 << SDNPWantParent;
415 errs() << "Unsupported SD Node property '" << PropList[i]->getName()
416 << "' on ComplexPattern '" << R->getName() << "'!\n";
421 //===----------------------------------------------------------------------===//
422 // CodeGenIntrinsic Implementation
423 //===----------------------------------------------------------------------===//
425 std::vector<CodeGenIntrinsic> llvm::LoadIntrinsics(const RecordKeeper &RC,
427 std::vector<Record*> I = RC.getAllDerivedDefinitions("Intrinsic");
429 std::vector<CodeGenIntrinsic> Result;
431 for (unsigned i = 0, e = I.size(); i != e; ++i) {
432 bool isTarget = I[i]->getValueAsBit("isTarget");
433 if (isTarget == TargetOnly)
434 Result.push_back(CodeGenIntrinsic(I[i]));
439 CodeGenIntrinsic::CodeGenIntrinsic(Record *R) {
441 std::string DefName = R->getName();
442 ModRef = ReadWriteMem;
443 isOverloaded = false;
444 isCommutative = false;
446 if (DefName.size() <= 4 ||
447 std::string(DefName.begin(), DefName.begin() + 4) != "int_")
448 throw "Intrinsic '" + DefName + "' does not start with 'int_'!";
450 EnumName = std::string(DefName.begin()+4, DefName.end());
452 if (R->getValue("GCCBuiltinName")) // Ignore a missing GCCBuiltinName field.
453 GCCBuiltinName = R->getValueAsString("GCCBuiltinName");
455 TargetPrefix = R->getValueAsString("TargetPrefix");
456 Name = R->getValueAsString("LLVMName");
459 // If an explicit name isn't specified, derive one from the DefName.
462 for (unsigned i = 0, e = EnumName.size(); i != e; ++i)
463 Name += (EnumName[i] == '_') ? '.' : EnumName[i];
465 // Verify it starts with "llvm.".
466 if (Name.size() <= 5 ||
467 std::string(Name.begin(), Name.begin() + 5) != "llvm.")
468 throw "Intrinsic '" + DefName + "'s name does not start with 'llvm.'!";
471 // If TargetPrefix is specified, make sure that Name starts with
472 // "llvm.<targetprefix>.".
473 if (!TargetPrefix.empty()) {
474 if (Name.size() < 6+TargetPrefix.size() ||
475 std::string(Name.begin() + 5, Name.begin() + 6 + TargetPrefix.size())
476 != (TargetPrefix + "."))
477 throw "Intrinsic '" + DefName + "' does not start with 'llvm." +
478 TargetPrefix + ".'!";
481 // Parse the list of return types.
482 std::vector<MVT::SimpleValueType> OverloadedVTs;
483 ListInit *TypeList = R->getValueAsListInit("RetTypes");
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");
501 VT = getValueType(TyEl->getValueAsDef("VT"));
503 if (EVT(VT).isOverloaded()) {
504 OverloadedVTs.push_back(VT);
508 // Reject invalid types.
509 if (VT == MVT::isVoid)
510 throw "Intrinsic '" + DefName + " has void in result type list!";
512 IS.RetVTs.push_back(VT);
513 IS.RetTypeDefs.push_back(TyEl);
516 // Parse the list of parameter types.
517 TypeList = R->getValueAsListInit("ParamTypes");
518 for (unsigned i = 0, e = TypeList->getSize(); i != e; ++i) {
519 Record *TyEl = TypeList->getElementAsRecord(i);
520 assert(TyEl->isSubClassOf("LLVMType") && "Expected a type!");
521 MVT::SimpleValueType VT;
522 if (TyEl->isSubClassOf("LLVMMatchType")) {
523 unsigned MatchTy = TyEl->getValueAsInt("Number");
524 assert(MatchTy < OverloadedVTs.size() &&
525 "Invalid matching number!");
526 VT = OverloadedVTs[MatchTy];
527 // It only makes sense to use the extended and truncated vector element
528 // variants with iAny types; otherwise, if the intrinsic is not
529 // overloaded, all the types can be specified directly.
530 assert(((!TyEl->isSubClassOf("LLVMExtendedElementVectorType") &&
531 !TyEl->isSubClassOf("LLVMTruncatedElementVectorType")) ||
532 VT == MVT::iAny || VT == MVT::vAny) &&
533 "Expected iAny or vAny type");
535 VT = getValueType(TyEl->getValueAsDef("VT"));
537 if (EVT(VT).isOverloaded()) {
538 OverloadedVTs.push_back(VT);
542 // Reject invalid types.
543 if (VT == MVT::isVoid && i != e-1 /*void at end means varargs*/)
544 throw "Intrinsic '" + DefName + " has void in result type list!";
546 IS.ParamVTs.push_back(VT);
547 IS.ParamTypeDefs.push_back(TyEl);
550 // Parse the intrinsic properties.
551 ListInit *PropList = R->getValueAsListInit("Properties");
552 for (unsigned i = 0, e = PropList->getSize(); i != e; ++i) {
553 Record *Property = PropList->getElementAsRecord(i);
554 assert(Property->isSubClassOf("IntrinsicProperty") &&
555 "Expected a property!");
557 if (Property->getName() == "IntrNoMem")
559 else if (Property->getName() == "IntrReadArgMem")
561 else if (Property->getName() == "IntrReadMem")
563 else if (Property->getName() == "IntrReadWriteArgMem")
564 ModRef = ReadWriteArgMem;
565 else if (Property->getName() == "Commutative")
566 isCommutative = true;
567 else if (Property->isSubClassOf("NoCapture")) {
568 unsigned ArgNo = Property->getValueAsInt("ArgNo");
569 ArgumentAttributes.push_back(std::make_pair(ArgNo, NoCapture));
571 assert(0 && "Unknown property!");