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/Support/CommandLine.h"
25 static cl::opt<unsigned>
26 AsmParserNum("asmparsernum", cl::init(0),
27 cl::desc("Make -gen-asm-parser emit assembly parser #N"));
29 static cl::opt<unsigned>
30 AsmWriterNum("asmwriternum", cl::init(0),
31 cl::desc("Make -gen-asm-writer emit assembly writer #N"));
33 /// getValueType - Return the MVT::SimpleValueType that the specified TableGen
34 /// record corresponds to.
35 MVT::SimpleValueType llvm::getValueType(Record *Rec) {
36 return (MVT::SimpleValueType)Rec->getValueAsInt("Value");
39 std::string llvm::getName(MVT::SimpleValueType T) {
41 case MVT::Other: return "UNKNOWN";
42 case MVT::iPTR: return "TLI.getPointerTy()";
43 case MVT::iPTRAny: return "TLI.getPointerTy()";
44 default: return getEnumName(T);
48 std::string llvm::getEnumName(MVT::SimpleValueType T) {
50 case MVT::Other: return "MVT::Other";
51 case MVT::i1: return "MVT::i1";
52 case MVT::i8: return "MVT::i8";
53 case MVT::i16: return "MVT::i16";
54 case MVT::i32: return "MVT::i32";
55 case MVT::i64: return "MVT::i64";
56 case MVT::i128: return "MVT::i128";
57 case MVT::iAny: return "MVT::iAny";
58 case MVT::fAny: return "MVT::fAny";
59 case MVT::vAny: return "MVT::vAny";
60 case MVT::f32: return "MVT::f32";
61 case MVT::f64: return "MVT::f64";
62 case MVT::f80: return "MVT::f80";
63 case MVT::f128: return "MVT::f128";
64 case MVT::ppcf128: return "MVT::ppcf128";
65 case MVT::Flag: return "MVT::Flag";
66 case MVT::isVoid:return "MVT::isVoid";
67 case MVT::v2i8: return "MVT::v2i8";
68 case MVT::v4i8: return "MVT::v4i8";
69 case MVT::v8i8: return "MVT::v8i8";
70 case MVT::v16i8: return "MVT::v16i8";
71 case MVT::v32i8: return "MVT::v32i8";
72 case MVT::v2i16: return "MVT::v2i16";
73 case MVT::v4i16: return "MVT::v4i16";
74 case MVT::v8i16: return "MVT::v8i16";
75 case MVT::v16i16: return "MVT::v16i16";
76 case MVT::v2i32: return "MVT::v2i32";
77 case MVT::v4i32: return "MVT::v4i32";
78 case MVT::v8i32: return "MVT::v8i32";
79 case MVT::v1i64: return "MVT::v1i64";
80 case MVT::v2i64: return "MVT::v2i64";
81 case MVT::v4i64: return "MVT::v4i64";
82 case MVT::v2f32: return "MVT::v2f32";
83 case MVT::v4f32: return "MVT::v4f32";
84 case MVT::v8f32: return "MVT::v8f32";
85 case MVT::v2f64: return "MVT::v2f64";
86 case MVT::v4f64: return "MVT::v4f64";
87 case MVT::Metadata: return "MVT::Metadata";
88 case MVT::iPTR: return "MVT::iPTR";
89 case MVT::iPTRAny: return "MVT::iPTRAny";
90 default: assert(0 && "ILLEGAL VALUE TYPE!"); return "";
94 /// getQualifiedName - Return the name of the specified record, with a
95 /// namespace qualifier if the record contains one.
97 std::string llvm::getQualifiedName(const Record *R) {
98 std::string Namespace = R->getValueAsString("Namespace");
99 if (Namespace.empty()) return R->getName();
100 return Namespace + "::" + R->getName();
106 /// getTarget - Return the current instance of the Target class.
108 CodeGenTarget::CodeGenTarget() {
109 std::vector<Record*> Targets = Records.getAllDerivedDefinitions("Target");
110 if (Targets.size() == 0)
111 throw std::string("ERROR: No 'Target' subclasses defined!");
112 if (Targets.size() != 1)
113 throw std::string("ERROR: Multiple subclasses of Target defined!");
114 TargetRec = Targets[0];
118 const std::string &CodeGenTarget::getName() const {
119 return TargetRec->getName();
122 std::string CodeGenTarget::getInstNamespace() const {
123 for (inst_iterator i = inst_begin(), e = inst_end(); i != e; ++i) {
124 // Make sure not to pick up "TargetOpcode" by accidentally getting
125 // the namespace off the PHI instruction or something.
126 if ((*i)->Namespace != "TargetOpcode")
127 return (*i)->Namespace;
133 Record *CodeGenTarget::getInstructionSet() const {
134 return TargetRec->getValueAsDef("InstructionSet");
138 /// getAsmParser - Return the AssemblyParser definition for this target.
140 Record *CodeGenTarget::getAsmParser() const {
141 std::vector<Record*> LI = TargetRec->getValueAsListOfDefs("AssemblyParsers");
142 if (AsmParserNum >= LI.size())
143 throw "Target does not have an AsmParser #" + utostr(AsmParserNum) + "!";
144 return LI[AsmParserNum];
147 /// getAsmWriter - Return the AssemblyWriter definition for this target.
149 Record *CodeGenTarget::getAsmWriter() const {
150 std::vector<Record*> LI = TargetRec->getValueAsListOfDefs("AssemblyWriters");
151 if (AsmWriterNum >= LI.size())
152 throw "Target does not have an AsmWriter #" + utostr(AsmWriterNum) + "!";
153 return LI[AsmWriterNum];
156 void CodeGenTarget::ReadRegisters() const {
157 std::vector<Record*> Regs = Records.getAllDerivedDefinitions("Register");
159 throw std::string("No 'Register' subclasses defined!");
161 Registers.reserve(Regs.size());
162 Registers.assign(Regs.begin(), Regs.end());
165 CodeGenRegister::CodeGenRegister(Record *R) : TheDef(R) {
166 DeclaredSpillSize = R->getValueAsInt("SpillSize");
167 DeclaredSpillAlignment = R->getValueAsInt("SpillAlignment");
170 const std::string &CodeGenRegister::getName() const {
171 return TheDef->getName();
174 void CodeGenTarget::ReadRegisterClasses() const {
175 std::vector<Record*> RegClasses =
176 Records.getAllDerivedDefinitions("RegisterClass");
177 if (RegClasses.empty())
178 throw std::string("No 'RegisterClass' subclasses defined!");
180 RegisterClasses.reserve(RegClasses.size());
181 RegisterClasses.assign(RegClasses.begin(), RegClasses.end());
184 std::vector<MVT::SimpleValueType> CodeGenTarget::
185 getRegisterVTs(Record *R) const {
186 std::vector<MVT::SimpleValueType> Result;
187 const std::vector<CodeGenRegisterClass> &RCs = getRegisterClasses();
188 for (unsigned i = 0, e = RCs.size(); i != e; ++i) {
189 const CodeGenRegisterClass &RC = RegisterClasses[i];
190 for (unsigned ei = 0, ee = RC.Elements.size(); ei != ee; ++ei) {
191 if (R == RC.Elements[ei]) {
192 const std::vector<MVT::SimpleValueType> &InVTs = RC.getValueTypes();
193 Result.insert(Result.end(), InVTs.begin(), InVTs.end());
201 CodeGenRegisterClass::CodeGenRegisterClass(Record *R) : TheDef(R) {
202 // Rename anonymous register classes.
203 if (R->getName().size() > 9 && R->getName()[9] == '.') {
204 static unsigned AnonCounter = 0;
205 R->setName("AnonRegClass_"+utostr(AnonCounter++));
208 std::vector<Record*> TypeList = R->getValueAsListOfDefs("RegTypes");
209 for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
210 Record *Type = TypeList[i];
211 if (!Type->isSubClassOf("ValueType"))
212 throw "RegTypes list member '" + Type->getName() +
213 "' does not derive from the ValueType class!";
214 VTs.push_back(getValueType(Type));
216 assert(!VTs.empty() && "RegisterClass must contain at least one ValueType!");
218 std::vector<Record*> RegList = R->getValueAsListOfDefs("MemberList");
219 for (unsigned i = 0, e = RegList.size(); i != e; ++i) {
220 Record *Reg = RegList[i];
221 if (!Reg->isSubClassOf("Register"))
222 throw "Register Class member '" + Reg->getName() +
223 "' does not derive from the Register class!";
224 Elements.push_back(Reg);
227 std::vector<Record*> SubRegClassList =
228 R->getValueAsListOfDefs("SubRegClassList");
229 for (unsigned i = 0, e = SubRegClassList.size(); i != e; ++i) {
230 Record *SubRegClass = SubRegClassList[i];
231 if (!SubRegClass->isSubClassOf("RegisterClass"))
232 throw "Register Class member '" + SubRegClass->getName() +
233 "' does not derive from the RegisterClass class!";
234 SubRegClasses.push_back(SubRegClass);
237 // Allow targets to override the size in bits of the RegisterClass.
238 unsigned Size = R->getValueAsInt("Size");
240 Namespace = R->getValueAsString("Namespace");
241 SpillSize = Size ? Size : EVT(VTs[0]).getSizeInBits();
242 SpillAlignment = R->getValueAsInt("Alignment");
243 CopyCost = R->getValueAsInt("CopyCost");
244 MethodBodies = R->getValueAsCode("MethodBodies");
245 MethodProtos = R->getValueAsCode("MethodProtos");
248 const std::string &CodeGenRegisterClass::getName() const {
249 return TheDef->getName();
252 void CodeGenTarget::ReadLegalValueTypes() const {
253 const std::vector<CodeGenRegisterClass> &RCs = getRegisterClasses();
254 for (unsigned i = 0, e = RCs.size(); i != e; ++i)
255 for (unsigned ri = 0, re = RCs[i].VTs.size(); ri != re; ++ri)
256 LegalValueTypes.push_back(RCs[i].VTs[ri]);
258 // Remove duplicates.
259 std::sort(LegalValueTypes.begin(), LegalValueTypes.end());
260 LegalValueTypes.erase(std::unique(LegalValueTypes.begin(),
261 LegalValueTypes.end()),
262 LegalValueTypes.end());
266 void CodeGenTarget::ReadInstructions() const {
267 std::vector<Record*> Insts = Records.getAllDerivedDefinitions("Instruction");
268 if (Insts.size() <= 2)
269 throw std::string("No 'Instruction' subclasses defined!");
271 // Parse the instructions defined in the .td file.
272 std::string InstFormatName =
273 getAsmWriter()->getValueAsString("InstFormatName");
275 for (unsigned i = 0, e = Insts.size(); i != e; ++i) {
276 std::string AsmStr = Insts[i]->getValueAsString(InstFormatName);
277 Instructions[Insts[i]] = new CodeGenInstruction(Insts[i], AsmStr);
281 static const CodeGenInstruction *
282 GetInstByName(const char *Name,
283 const DenseMap<const Record*, CodeGenInstruction*> &Insts) {
284 const Record *Rec = Records.getDef(Name);
286 DenseMap<const Record*, CodeGenInstruction*>::const_iterator
288 if (Rec == 0 || I == Insts.end())
289 throw std::string("Could not find '") + Name + "' instruction!";
294 /// SortInstByName - Sorting predicate to sort instructions by name.
296 struct SortInstByName {
297 bool operator()(const CodeGenInstruction *Rec1,
298 const CodeGenInstruction *Rec2) const {
299 return Rec1->TheDef->getName() < Rec2->TheDef->getName();
304 /// getInstructionsByEnumValue - Return all of the instructions defined by the
305 /// target, ordered by their enum value.
306 void CodeGenTarget::ComputeInstrsByEnum() const {
307 const DenseMap<const Record*, CodeGenInstruction*> &Insts = getInstructions();
308 const CodeGenInstruction *PHI = GetInstByName("PHI", Insts);
309 const CodeGenInstruction *INLINEASM = GetInstByName("INLINEASM", Insts);
310 const CodeGenInstruction *DBG_LABEL = GetInstByName("DBG_LABEL", Insts);
311 const CodeGenInstruction *EH_LABEL = GetInstByName("EH_LABEL", Insts);
312 const CodeGenInstruction *GC_LABEL = GetInstByName("GC_LABEL", Insts);
313 const CodeGenInstruction *KILL = GetInstByName("KILL", Insts);
314 const CodeGenInstruction *EXTRACT_SUBREG =
315 GetInstByName("EXTRACT_SUBREG", Insts);
316 const CodeGenInstruction *INSERT_SUBREG =
317 GetInstByName("INSERT_SUBREG", Insts);
318 const CodeGenInstruction *IMPLICIT_DEF = GetInstByName("IMPLICIT_DEF", Insts);
319 const CodeGenInstruction *SUBREG_TO_REG =
320 GetInstByName("SUBREG_TO_REG", Insts);
321 const CodeGenInstruction *COPY_TO_REGCLASS =
322 GetInstByName("COPY_TO_REGCLASS", Insts);
323 const CodeGenInstruction *DBG_VALUE = GetInstByName("DBG_VALUE", Insts);
325 // Print out the rest of the instructions now.
326 InstrsByEnum.push_back(PHI);
327 InstrsByEnum.push_back(INLINEASM);
328 InstrsByEnum.push_back(DBG_LABEL);
329 InstrsByEnum.push_back(EH_LABEL);
330 InstrsByEnum.push_back(GC_LABEL);
331 InstrsByEnum.push_back(KILL);
332 InstrsByEnum.push_back(EXTRACT_SUBREG);
333 InstrsByEnum.push_back(INSERT_SUBREG);
334 InstrsByEnum.push_back(IMPLICIT_DEF);
335 InstrsByEnum.push_back(SUBREG_TO_REG);
336 InstrsByEnum.push_back(COPY_TO_REGCLASS);
337 InstrsByEnum.push_back(DBG_VALUE);
339 unsigned EndOfPredefines = InstrsByEnum.size();
341 for (DenseMap<const Record*, CodeGenInstruction*>::const_iterator
342 I = Insts.begin(), E = Insts.end(); I != E; ++I) {
343 const CodeGenInstruction *CGI = I->second;
350 CGI != EXTRACT_SUBREG &&
351 CGI != INSERT_SUBREG &&
352 CGI != IMPLICIT_DEF &&
353 CGI != SUBREG_TO_REG &&
354 CGI != COPY_TO_REGCLASS &&
356 InstrsByEnum.push_back(CGI);
359 // All of the instructions are now in random order based on the map iteration.
360 // Sort them by name.
361 std::sort(InstrsByEnum.begin()+EndOfPredefines, InstrsByEnum.end(),
366 /// isLittleEndianEncoding - Return whether this target encodes its instruction
367 /// in little-endian format, i.e. bits laid out in the order [0..n]
369 bool CodeGenTarget::isLittleEndianEncoding() const {
370 return getInstructionSet()->getValueAsBit("isLittleEndianEncoding");
373 //===----------------------------------------------------------------------===//
374 // ComplexPattern implementation
376 ComplexPattern::ComplexPattern(Record *R) {
377 Ty = ::getValueType(R->getValueAsDef("Ty"));
378 NumOperands = R->getValueAsInt("NumOperands");
379 SelectFunc = R->getValueAsString("SelectFunc");
380 RootNodes = R->getValueAsListOfDefs("RootNodes");
382 // Parse the properties.
384 std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
385 for (unsigned i = 0, e = PropList.size(); i != e; ++i)
386 if (PropList[i]->getName() == "SDNPHasChain") {
387 Properties |= 1 << SDNPHasChain;
388 } else if (PropList[i]->getName() == "SDNPOptInFlag") {
389 Properties |= 1 << SDNPOptInFlag;
390 } else if (PropList[i]->getName() == "SDNPMayStore") {
391 Properties |= 1 << SDNPMayStore;
392 } else if (PropList[i]->getName() == "SDNPMayLoad") {
393 Properties |= 1 << SDNPMayLoad;
394 } else if (PropList[i]->getName() == "SDNPSideEffect") {
395 Properties |= 1 << SDNPSideEffect;
396 } else if (PropList[i]->getName() == "SDNPMemOperand") {
397 Properties |= 1 << SDNPMemOperand;
399 errs() << "Unsupported SD Node property '" << PropList[i]->getName()
400 << "' on ComplexPattern '" << R->getName() << "'!\n";
405 //===----------------------------------------------------------------------===//
406 // CodeGenIntrinsic Implementation
407 //===----------------------------------------------------------------------===//
409 std::vector<CodeGenIntrinsic> llvm::LoadIntrinsics(const RecordKeeper &RC,
411 std::vector<Record*> I = RC.getAllDerivedDefinitions("Intrinsic");
413 std::vector<CodeGenIntrinsic> Result;
415 for (unsigned i = 0, e = I.size(); i != e; ++i) {
416 bool isTarget = I[i]->getValueAsBit("isTarget");
417 if (isTarget == TargetOnly)
418 Result.push_back(CodeGenIntrinsic(I[i]));
423 CodeGenIntrinsic::CodeGenIntrinsic(Record *R) {
425 std::string DefName = R->getName();
427 isOverloaded = false;
428 isCommutative = false;
430 if (DefName.size() <= 4 ||
431 std::string(DefName.begin(), DefName.begin() + 4) != "int_")
432 throw "Intrinsic '" + DefName + "' does not start with 'int_'!";
434 EnumName = std::string(DefName.begin()+4, DefName.end());
436 if (R->getValue("GCCBuiltinName")) // Ignore a missing GCCBuiltinName field.
437 GCCBuiltinName = R->getValueAsString("GCCBuiltinName");
439 TargetPrefix = R->getValueAsString("TargetPrefix");
440 Name = R->getValueAsString("LLVMName");
443 // If an explicit name isn't specified, derive one from the DefName.
446 for (unsigned i = 0, e = EnumName.size(); i != e; ++i)
447 Name += (EnumName[i] == '_') ? '.' : EnumName[i];
449 // Verify it starts with "llvm.".
450 if (Name.size() <= 5 ||
451 std::string(Name.begin(), Name.begin() + 5) != "llvm.")
452 throw "Intrinsic '" + DefName + "'s name does not start with 'llvm.'!";
455 // If TargetPrefix is specified, make sure that Name starts with
456 // "llvm.<targetprefix>.".
457 if (!TargetPrefix.empty()) {
458 if (Name.size() < 6+TargetPrefix.size() ||
459 std::string(Name.begin() + 5, Name.begin() + 6 + TargetPrefix.size())
460 != (TargetPrefix + "."))
461 throw "Intrinsic '" + DefName + "' does not start with 'llvm." +
462 TargetPrefix + ".'!";
465 // Parse the list of return types.
466 std::vector<MVT::SimpleValueType> OverloadedVTs;
467 ListInit *TypeList = R->getValueAsListInit("RetTypes");
468 for (unsigned i = 0, e = TypeList->getSize(); i != e; ++i) {
469 Record *TyEl = TypeList->getElementAsRecord(i);
470 assert(TyEl->isSubClassOf("LLVMType") && "Expected a type!");
471 MVT::SimpleValueType VT;
472 if (TyEl->isSubClassOf("LLVMMatchType")) {
473 unsigned MatchTy = TyEl->getValueAsInt("Number");
474 assert(MatchTy < OverloadedVTs.size() &&
475 "Invalid matching number!");
476 VT = OverloadedVTs[MatchTy];
477 // It only makes sense to use the extended and truncated vector element
478 // variants with iAny types; otherwise, if the intrinsic is not
479 // overloaded, all the types can be specified directly.
480 assert(((!TyEl->isSubClassOf("LLVMExtendedElementVectorType") &&
481 !TyEl->isSubClassOf("LLVMTruncatedElementVectorType")) ||
482 VT == MVT::iAny || VT == MVT::vAny) &&
483 "Expected iAny or vAny type");
485 VT = getValueType(TyEl->getValueAsDef("VT"));
487 if (EVT(VT).isOverloaded()) {
488 OverloadedVTs.push_back(VT);
489 isOverloaded |= true;
491 IS.RetVTs.push_back(VT);
492 IS.RetTypeDefs.push_back(TyEl);
495 if (IS.RetVTs.size() == 0)
496 throw "Intrinsic '"+DefName+"' needs at least a type for the ret value!";
498 // Parse the list of parameter types.
499 TypeList = R->getValueAsListInit("ParamTypes");
500 for (unsigned i = 0, e = TypeList->getSize(); i != e; ++i) {
501 Record *TyEl = TypeList->getElementAsRecord(i);
502 assert(TyEl->isSubClassOf("LLVMType") && "Expected a type!");
503 MVT::SimpleValueType VT;
504 if (TyEl->isSubClassOf("LLVMMatchType")) {
505 unsigned MatchTy = TyEl->getValueAsInt("Number");
506 assert(MatchTy < OverloadedVTs.size() &&
507 "Invalid matching number!");
508 VT = OverloadedVTs[MatchTy];
509 // It only makes sense to use the extended and truncated vector element
510 // variants with iAny types; otherwise, if the intrinsic is not
511 // overloaded, all the types can be specified directly.
512 assert(((!TyEl->isSubClassOf("LLVMExtendedElementVectorType") &&
513 !TyEl->isSubClassOf("LLVMTruncatedElementVectorType")) ||
514 VT == MVT::iAny || VT == MVT::vAny) &&
515 "Expected iAny or vAny type");
517 VT = getValueType(TyEl->getValueAsDef("VT"));
518 if (EVT(VT).isOverloaded()) {
519 OverloadedVTs.push_back(VT);
520 isOverloaded |= true;
522 IS.ParamVTs.push_back(VT);
523 IS.ParamTypeDefs.push_back(TyEl);
526 // Parse the intrinsic properties.
527 ListInit *PropList = R->getValueAsListInit("Properties");
528 for (unsigned i = 0, e = PropList->getSize(); i != e; ++i) {
529 Record *Property = PropList->getElementAsRecord(i);
530 assert(Property->isSubClassOf("IntrinsicProperty") &&
531 "Expected a property!");
533 if (Property->getName() == "IntrNoMem")
535 else if (Property->getName() == "IntrReadArgMem")
537 else if (Property->getName() == "IntrReadMem")
539 else if (Property->getName() == "IntrWriteArgMem")
540 ModRef = WriteArgMem;
541 else if (Property->getName() == "IntrWriteMem")
543 else if (Property->getName() == "Commutative")
544 isCommutative = true;
545 else if (Property->isSubClassOf("NoCapture")) {
546 unsigned ArgNo = Property->getValueAsInt("ArgNo");
547 ArgumentAttributes.push_back(std::make_pair(ArgNo, NoCapture));
549 assert(0 && "Unknown property!");