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::Flag: return "MVT::Flag";
67 case MVT::isVoid:return "MVT::isVoid";
68 case MVT::v2i8: return "MVT::v2i8";
69 case MVT::v4i8: return "MVT::v4i8";
70 case MVT::v8i8: return "MVT::v8i8";
71 case MVT::v16i8: return "MVT::v16i8";
72 case MVT::v32i8: return "MVT::v32i8";
73 case MVT::v2i16: return "MVT::v2i16";
74 case MVT::v4i16: return "MVT::v4i16";
75 case MVT::v8i16: return "MVT::v8i16";
76 case MVT::v16i16: return "MVT::v16i16";
77 case MVT::v2i32: return "MVT::v2i32";
78 case MVT::v4i32: return "MVT::v4i32";
79 case MVT::v8i32: return "MVT::v8i32";
80 case MVT::v1i64: return "MVT::v1i64";
81 case MVT::v2i64: return "MVT::v2i64";
82 case MVT::v4i64: return "MVT::v4i64";
83 case MVT::v2f32: return "MVT::v2f32";
84 case MVT::v4f32: return "MVT::v4f32";
85 case MVT::v8f32: return "MVT::v8f32";
86 case MVT::v2f64: return "MVT::v2f64";
87 case MVT::v4f64: return "MVT::v4f64";
88 case MVT::Metadata: return "MVT::Metadata";
89 case MVT::iPTR: return "MVT::iPTR";
90 case MVT::iPTRAny: return "MVT::iPTRAny";
91 default: assert(0 && "ILLEGAL VALUE TYPE!"); return "";
95 /// getQualifiedName - Return the name of the specified record, with a
96 /// namespace qualifier if the record contains one.
98 std::string llvm::getQualifiedName(const Record *R) {
99 std::string Namespace = R->getValueAsString("Namespace");
100 if (Namespace.empty()) return R->getName();
101 return Namespace + "::" + R->getName();
107 /// getTarget - Return the current instance of the Target class.
109 CodeGenTarget::CodeGenTarget() {
110 std::vector<Record*> Targets = Records.getAllDerivedDefinitions("Target");
111 if (Targets.size() == 0)
112 throw std::string("ERROR: No 'Target' subclasses defined!");
113 if (Targets.size() != 1)
114 throw std::string("ERROR: Multiple subclasses of Target defined!");
115 TargetRec = Targets[0];
119 const std::string &CodeGenTarget::getName() const {
120 return TargetRec->getName();
123 std::string CodeGenTarget::getInstNamespace() const {
124 for (inst_iterator i = inst_begin(), e = inst_end(); i != e; ++i) {
125 // Make sure not to pick up "TargetOpcode" by accidentally getting
126 // the namespace off the PHI instruction or something.
127 if ((*i)->Namespace != "TargetOpcode")
128 return (*i)->Namespace;
134 Record *CodeGenTarget::getInstructionSet() const {
135 return TargetRec->getValueAsDef("InstructionSet");
139 /// getAsmParser - Return the AssemblyParser definition for this target.
141 Record *CodeGenTarget::getAsmParser() const {
142 std::vector<Record*> LI = TargetRec->getValueAsListOfDefs("AssemblyParsers");
143 if (AsmParserNum >= LI.size())
144 throw "Target does not have an AsmParser #" + utostr(AsmParserNum) + "!";
145 return LI[AsmParserNum];
148 /// getAsmWriter - Return the AssemblyWriter definition for this target.
150 Record *CodeGenTarget::getAsmWriter() const {
151 std::vector<Record*> LI = TargetRec->getValueAsListOfDefs("AssemblyWriters");
152 if (AsmWriterNum >= LI.size())
153 throw "Target does not have an AsmWriter #" + utostr(AsmWriterNum) + "!";
154 return LI[AsmWriterNum];
157 void CodeGenTarget::ReadRegisters() const {
158 std::vector<Record*> Regs = Records.getAllDerivedDefinitions("Register");
160 throw std::string("No 'Register' subclasses defined!");
162 Registers.reserve(Regs.size());
163 Registers.assign(Regs.begin(), Regs.end());
166 CodeGenRegister::CodeGenRegister(Record *R) : TheDef(R) {
167 DeclaredSpillSize = R->getValueAsInt("SpillSize");
168 DeclaredSpillAlignment = R->getValueAsInt("SpillAlignment");
171 const std::string &CodeGenRegister::getName() const {
172 return TheDef->getName();
175 void CodeGenTarget::ReadRegisterClasses() const {
176 std::vector<Record*> RegClasses =
177 Records.getAllDerivedDefinitions("RegisterClass");
178 if (RegClasses.empty())
179 throw std::string("No 'RegisterClass' subclasses defined!");
181 RegisterClasses.reserve(RegClasses.size());
182 RegisterClasses.assign(RegClasses.begin(), RegClasses.end());
185 std::vector<MVT::SimpleValueType> CodeGenTarget::
186 getRegisterVTs(Record *R) const {
187 std::vector<MVT::SimpleValueType> Result;
188 const std::vector<CodeGenRegisterClass> &RCs = getRegisterClasses();
189 for (unsigned i = 0, e = RCs.size(); i != e; ++i) {
190 const CodeGenRegisterClass &RC = RegisterClasses[i];
191 for (unsigned ei = 0, ee = RC.Elements.size(); ei != ee; ++ei) {
192 if (R == RC.Elements[ei]) {
193 const std::vector<MVT::SimpleValueType> &InVTs = RC.getValueTypes();
194 Result.insert(Result.end(), InVTs.begin(), InVTs.end());
199 // Remove duplicates.
200 array_pod_sort(Result.begin(), Result.end());
201 Result.erase(std::unique(Result.begin(), Result.end()), Result.end());
206 CodeGenRegisterClass::CodeGenRegisterClass(Record *R) : TheDef(R) {
207 // Rename anonymous register classes.
208 if (R->getName().size() > 9 && R->getName()[9] == '.') {
209 static unsigned AnonCounter = 0;
210 R->setName("AnonRegClass_"+utostr(AnonCounter++));
213 std::vector<Record*> TypeList = R->getValueAsListOfDefs("RegTypes");
214 for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
215 Record *Type = TypeList[i];
216 if (!Type->isSubClassOf("ValueType"))
217 throw "RegTypes list member '" + Type->getName() +
218 "' does not derive from the ValueType class!";
219 VTs.push_back(getValueType(Type));
221 assert(!VTs.empty() && "RegisterClass must contain at least one ValueType!");
223 std::vector<Record*> RegList = R->getValueAsListOfDefs("MemberList");
224 for (unsigned i = 0, e = RegList.size(); i != e; ++i) {
225 Record *Reg = RegList[i];
226 if (!Reg->isSubClassOf("Register"))
227 throw "Register Class member '" + Reg->getName() +
228 "' does not derive from the Register class!";
229 Elements.push_back(Reg);
232 std::vector<Record*> SubRegClassList =
233 R->getValueAsListOfDefs("SubRegClassList");
234 for (unsigned i = 0, e = SubRegClassList.size(); i != e; ++i) {
235 Record *SubRegClass = SubRegClassList[i];
236 if (!SubRegClass->isSubClassOf("RegisterClass"))
237 throw "Register Class member '" + SubRegClass->getName() +
238 "' does not derive from the RegisterClass class!";
239 SubRegClasses.push_back(SubRegClass);
242 // Allow targets to override the size in bits of the RegisterClass.
243 unsigned Size = R->getValueAsInt("Size");
245 Namespace = R->getValueAsString("Namespace");
246 SpillSize = Size ? Size : EVT(VTs[0]).getSizeInBits();
247 SpillAlignment = R->getValueAsInt("Alignment");
248 CopyCost = R->getValueAsInt("CopyCost");
249 MethodBodies = R->getValueAsCode("MethodBodies");
250 MethodProtos = R->getValueAsCode("MethodProtos");
253 const std::string &CodeGenRegisterClass::getName() const {
254 return TheDef->getName();
257 void CodeGenTarget::ReadLegalValueTypes() const {
258 const std::vector<CodeGenRegisterClass> &RCs = getRegisterClasses();
259 for (unsigned i = 0, e = RCs.size(); i != e; ++i)
260 for (unsigned ri = 0, re = RCs[i].VTs.size(); ri != re; ++ri)
261 LegalValueTypes.push_back(RCs[i].VTs[ri]);
263 // Remove duplicates.
264 std::sort(LegalValueTypes.begin(), LegalValueTypes.end());
265 LegalValueTypes.erase(std::unique(LegalValueTypes.begin(),
266 LegalValueTypes.end()),
267 LegalValueTypes.end());
271 void CodeGenTarget::ReadInstructions() const {
272 std::vector<Record*> Insts = Records.getAllDerivedDefinitions("Instruction");
273 if (Insts.size() <= 2)
274 throw std::string("No 'Instruction' subclasses defined!");
276 // Parse the instructions defined in the .td file.
277 std::string InstFormatName =
278 getAsmWriter()->getValueAsString("InstFormatName");
280 for (unsigned i = 0, e = Insts.size(); i != e; ++i) {
281 std::string AsmStr = Insts[i]->getValueAsString(InstFormatName);
282 Instructions[Insts[i]] = new CodeGenInstruction(Insts[i], AsmStr);
286 static const CodeGenInstruction *
287 GetInstByName(const char *Name,
288 const DenseMap<const Record*, CodeGenInstruction*> &Insts) {
289 const Record *Rec = Records.getDef(Name);
291 DenseMap<const Record*, CodeGenInstruction*>::const_iterator
293 if (Rec == 0 || I == Insts.end())
294 throw std::string("Could not find '") + Name + "' instruction!";
299 /// SortInstByName - Sorting predicate to sort instructions by name.
301 struct SortInstByName {
302 bool operator()(const CodeGenInstruction *Rec1,
303 const CodeGenInstruction *Rec2) const {
304 return Rec1->TheDef->getName() < Rec2->TheDef->getName();
309 /// getInstructionsByEnumValue - Return all of the instructions defined by the
310 /// target, ordered by their enum value.
311 void CodeGenTarget::ComputeInstrsByEnum() const {
312 const DenseMap<const Record*, CodeGenInstruction*> &Insts = getInstructions();
313 const CodeGenInstruction *PHI = GetInstByName("PHI", Insts);
314 const CodeGenInstruction *INLINEASM = GetInstByName("INLINEASM", Insts);
315 const CodeGenInstruction *DBG_LABEL = GetInstByName("DBG_LABEL", Insts);
316 const CodeGenInstruction *EH_LABEL = GetInstByName("EH_LABEL", Insts);
317 const CodeGenInstruction *GC_LABEL = GetInstByName("GC_LABEL", Insts);
318 const CodeGenInstruction *KILL = GetInstByName("KILL", Insts);
319 const CodeGenInstruction *EXTRACT_SUBREG =
320 GetInstByName("EXTRACT_SUBREG", Insts);
321 const CodeGenInstruction *INSERT_SUBREG =
322 GetInstByName("INSERT_SUBREG", Insts);
323 const CodeGenInstruction *IMPLICIT_DEF = GetInstByName("IMPLICIT_DEF", Insts);
324 const CodeGenInstruction *SUBREG_TO_REG =
325 GetInstByName("SUBREG_TO_REG", Insts);
326 const CodeGenInstruction *COPY_TO_REGCLASS =
327 GetInstByName("COPY_TO_REGCLASS", Insts);
328 const CodeGenInstruction *DBG_VALUE = GetInstByName("DBG_VALUE", Insts);
330 // Print out the rest of the instructions now.
331 InstrsByEnum.push_back(PHI);
332 InstrsByEnum.push_back(INLINEASM);
333 InstrsByEnum.push_back(DBG_LABEL);
334 InstrsByEnum.push_back(EH_LABEL);
335 InstrsByEnum.push_back(GC_LABEL);
336 InstrsByEnum.push_back(KILL);
337 InstrsByEnum.push_back(EXTRACT_SUBREG);
338 InstrsByEnum.push_back(INSERT_SUBREG);
339 InstrsByEnum.push_back(IMPLICIT_DEF);
340 InstrsByEnum.push_back(SUBREG_TO_REG);
341 InstrsByEnum.push_back(COPY_TO_REGCLASS);
342 InstrsByEnum.push_back(DBG_VALUE);
344 unsigned EndOfPredefines = InstrsByEnum.size();
346 for (DenseMap<const Record*, CodeGenInstruction*>::const_iterator
347 I = Insts.begin(), E = Insts.end(); I != E; ++I) {
348 const CodeGenInstruction *CGI = I->second;
355 CGI != EXTRACT_SUBREG &&
356 CGI != INSERT_SUBREG &&
357 CGI != IMPLICIT_DEF &&
358 CGI != SUBREG_TO_REG &&
359 CGI != COPY_TO_REGCLASS &&
361 InstrsByEnum.push_back(CGI);
364 // All of the instructions are now in random order based on the map iteration.
365 // Sort them by name.
366 std::sort(InstrsByEnum.begin()+EndOfPredefines, InstrsByEnum.end(),
371 /// isLittleEndianEncoding - Return whether this target encodes its instruction
372 /// in little-endian format, i.e. bits laid out in the order [0..n]
374 bool CodeGenTarget::isLittleEndianEncoding() const {
375 return getInstructionSet()->getValueAsBit("isLittleEndianEncoding");
378 //===----------------------------------------------------------------------===//
379 // ComplexPattern implementation
381 ComplexPattern::ComplexPattern(Record *R) {
382 Ty = ::getValueType(R->getValueAsDef("Ty"));
383 NumOperands = R->getValueAsInt("NumOperands");
384 SelectFunc = R->getValueAsString("SelectFunc");
385 RootNodes = R->getValueAsListOfDefs("RootNodes");
387 // Parse the properties.
389 std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
390 for (unsigned i = 0, e = PropList.size(); i != e; ++i)
391 if (PropList[i]->getName() == "SDNPHasChain") {
392 Properties |= 1 << SDNPHasChain;
393 } else if (PropList[i]->getName() == "SDNPOptInFlag") {
394 Properties |= 1 << SDNPOptInFlag;
395 } else if (PropList[i]->getName() == "SDNPMayStore") {
396 Properties |= 1 << SDNPMayStore;
397 } else if (PropList[i]->getName() == "SDNPMayLoad") {
398 Properties |= 1 << SDNPMayLoad;
399 } else if (PropList[i]->getName() == "SDNPSideEffect") {
400 Properties |= 1 << SDNPSideEffect;
401 } else if (PropList[i]->getName() == "SDNPMemOperand") {
402 Properties |= 1 << SDNPMemOperand;
403 } else if (PropList[i]->getName() == "SDNPVariadic") {
404 Properties |= 1 << SDNPVariadic;
406 errs() << "Unsupported SD Node property '" << PropList[i]->getName()
407 << "' on ComplexPattern '" << R->getName() << "'!\n";
412 //===----------------------------------------------------------------------===//
413 // CodeGenIntrinsic Implementation
414 //===----------------------------------------------------------------------===//
416 std::vector<CodeGenIntrinsic> llvm::LoadIntrinsics(const RecordKeeper &RC,
418 std::vector<Record*> I = RC.getAllDerivedDefinitions("Intrinsic");
420 std::vector<CodeGenIntrinsic> Result;
422 for (unsigned i = 0, e = I.size(); i != e; ++i) {
423 bool isTarget = I[i]->getValueAsBit("isTarget");
424 if (isTarget == TargetOnly)
425 Result.push_back(CodeGenIntrinsic(I[i]));
430 CodeGenIntrinsic::CodeGenIntrinsic(Record *R) {
432 std::string DefName = R->getName();
434 isOverloaded = false;
435 isCommutative = false;
437 if (DefName.size() <= 4 ||
438 std::string(DefName.begin(), DefName.begin() + 4) != "int_")
439 throw "Intrinsic '" + DefName + "' does not start with 'int_'!";
441 EnumName = std::string(DefName.begin()+4, DefName.end());
443 if (R->getValue("GCCBuiltinName")) // Ignore a missing GCCBuiltinName field.
444 GCCBuiltinName = R->getValueAsString("GCCBuiltinName");
446 TargetPrefix = R->getValueAsString("TargetPrefix");
447 Name = R->getValueAsString("LLVMName");
450 // If an explicit name isn't specified, derive one from the DefName.
453 for (unsigned i = 0, e = EnumName.size(); i != e; ++i)
454 Name += (EnumName[i] == '_') ? '.' : EnumName[i];
456 // Verify it starts with "llvm.".
457 if (Name.size() <= 5 ||
458 std::string(Name.begin(), Name.begin() + 5) != "llvm.")
459 throw "Intrinsic '" + DefName + "'s name does not start with 'llvm.'!";
462 // If TargetPrefix is specified, make sure that Name starts with
463 // "llvm.<targetprefix>.".
464 if (!TargetPrefix.empty()) {
465 if (Name.size() < 6+TargetPrefix.size() ||
466 std::string(Name.begin() + 5, Name.begin() + 6 + TargetPrefix.size())
467 != (TargetPrefix + "."))
468 throw "Intrinsic '" + DefName + "' does not start with 'llvm." +
469 TargetPrefix + ".'!";
472 // Parse the list of return types.
473 std::vector<MVT::SimpleValueType> OverloadedVTs;
474 ListInit *TypeList = R->getValueAsListInit("RetTypes");
475 for (unsigned i = 0, e = TypeList->getSize(); i != e; ++i) {
476 Record *TyEl = TypeList->getElementAsRecord(i);
477 assert(TyEl->isSubClassOf("LLVMType") && "Expected a type!");
478 MVT::SimpleValueType VT;
479 if (TyEl->isSubClassOf("LLVMMatchType")) {
480 unsigned MatchTy = TyEl->getValueAsInt("Number");
481 assert(MatchTy < OverloadedVTs.size() &&
482 "Invalid matching number!");
483 VT = OverloadedVTs[MatchTy];
484 // It only makes sense to use the extended and truncated vector element
485 // variants with iAny types; otherwise, if the intrinsic is not
486 // overloaded, all the types can be specified directly.
487 assert(((!TyEl->isSubClassOf("LLVMExtendedElementVectorType") &&
488 !TyEl->isSubClassOf("LLVMTruncatedElementVectorType")) ||
489 VT == MVT::iAny || VT == MVT::vAny) &&
490 "Expected iAny or vAny type");
492 VT = getValueType(TyEl->getValueAsDef("VT"));
494 if (EVT(VT).isOverloaded()) {
495 OverloadedVTs.push_back(VT);
499 // Reject invalid types.
500 if (VT == MVT::isVoid)
501 throw "Intrinsic '" + DefName + " has void in result type list!";
503 IS.RetVTs.push_back(VT);
504 IS.RetTypeDefs.push_back(TyEl);
507 // Parse the list of parameter types.
508 TypeList = R->getValueAsListInit("ParamTypes");
509 for (unsigned i = 0, e = TypeList->getSize(); i != e; ++i) {
510 Record *TyEl = TypeList->getElementAsRecord(i);
511 assert(TyEl->isSubClassOf("LLVMType") && "Expected a type!");
512 MVT::SimpleValueType VT;
513 if (TyEl->isSubClassOf("LLVMMatchType")) {
514 unsigned MatchTy = TyEl->getValueAsInt("Number");
515 assert(MatchTy < OverloadedVTs.size() &&
516 "Invalid matching number!");
517 VT = OverloadedVTs[MatchTy];
518 // It only makes sense to use the extended and truncated vector element
519 // variants with iAny types; otherwise, if the intrinsic is not
520 // overloaded, all the types can be specified directly.
521 assert(((!TyEl->isSubClassOf("LLVMExtendedElementVectorType") &&
522 !TyEl->isSubClassOf("LLVMTruncatedElementVectorType")) ||
523 VT == MVT::iAny || VT == MVT::vAny) &&
524 "Expected iAny or vAny type");
526 VT = getValueType(TyEl->getValueAsDef("VT"));
528 if (EVT(VT).isOverloaded()) {
529 OverloadedVTs.push_back(VT);
533 // Reject invalid types.
534 if (VT == MVT::isVoid && i != e-1 /*void at end means varargs*/)
535 throw "Intrinsic '" + DefName + " has void in result type list!";
537 IS.ParamVTs.push_back(VT);
538 IS.ParamTypeDefs.push_back(TyEl);
541 // Parse the intrinsic properties.
542 ListInit *PropList = R->getValueAsListInit("Properties");
543 for (unsigned i = 0, e = PropList->getSize(); i != e; ++i) {
544 Record *Property = PropList->getElementAsRecord(i);
545 assert(Property->isSubClassOf("IntrinsicProperty") &&
546 "Expected a property!");
548 if (Property->getName() == "IntrNoMem")
550 else if (Property->getName() == "IntrReadArgMem")
552 else if (Property->getName() == "IntrReadMem")
554 else if (Property->getName() == "IntrWriteArgMem")
555 ModRef = WriteArgMem;
556 else if (Property->getName() == "IntrWriteMem")
558 else if (Property->getName() == "Commutative")
559 isCommutative = true;
560 else if (Property->isSubClassOf("NoCapture")) {
561 unsigned ArgNo = Property->getValueAsInt("ArgNo");
562 ArgumentAttributes.push_back(std::make_pair(ArgNo, NoCapture));
564 assert(0 && "Unknown property!");