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::v8i64: return "MVT::v8i64";
84 case MVT::v2f32: return "MVT::v2f32";
85 case MVT::v4f32: return "MVT::v4f32";
86 case MVT::v8f32: return "MVT::v8f32";
87 case MVT::v2f64: return "MVT::v2f64";
88 case MVT::v4f64: return "MVT::v4f64";
89 case MVT::Metadata: return "MVT::Metadata";
90 case MVT::iPTR: return "MVT::iPTR";
91 case MVT::iPTRAny: return "MVT::iPTRAny";
92 default: assert(0 && "ILLEGAL VALUE TYPE!"); return "";
96 /// getQualifiedName - Return the name of the specified record, with a
97 /// namespace qualifier if the record contains one.
99 std::string llvm::getQualifiedName(const Record *R) {
100 std::string Namespace = R->getValueAsString("Namespace");
101 if (Namespace.empty()) return R->getName();
102 return Namespace + "::" + R->getName();
108 /// getTarget - Return the current instance of the Target class.
110 CodeGenTarget::CodeGenTarget() {
111 std::vector<Record*> Targets = Records.getAllDerivedDefinitions("Target");
112 if (Targets.size() == 0)
113 throw std::string("ERROR: No 'Target' subclasses defined!");
114 if (Targets.size() != 1)
115 throw std::string("ERROR: Multiple subclasses of Target defined!");
116 TargetRec = Targets[0];
120 const std::string &CodeGenTarget::getName() const {
121 return TargetRec->getName();
124 std::string CodeGenTarget::getInstNamespace() const {
125 for (inst_iterator i = inst_begin(), e = inst_end(); i != e; ++i) {
126 // Make sure not to pick up "TargetOpcode" by accidentally getting
127 // the namespace off the PHI instruction or something.
128 if ((*i)->Namespace != "TargetOpcode")
129 return (*i)->Namespace;
135 Record *CodeGenTarget::getInstructionSet() const {
136 return TargetRec->getValueAsDef("InstructionSet");
140 /// getAsmParser - Return the AssemblyParser definition for this target.
142 Record *CodeGenTarget::getAsmParser() const {
143 std::vector<Record*> LI = TargetRec->getValueAsListOfDefs("AssemblyParsers");
144 if (AsmParserNum >= LI.size())
145 throw "Target does not have an AsmParser #" + utostr(AsmParserNum) + "!";
146 return LI[AsmParserNum];
149 /// getAsmWriter - Return the AssemblyWriter definition for this target.
151 Record *CodeGenTarget::getAsmWriter() const {
152 std::vector<Record*> LI = TargetRec->getValueAsListOfDefs("AssemblyWriters");
153 if (AsmWriterNum >= LI.size())
154 throw "Target does not have an AsmWriter #" + utostr(AsmWriterNum) + "!";
155 return LI[AsmWriterNum];
158 void CodeGenTarget::ReadRegisters() const {
159 std::vector<Record*> Regs = Records.getAllDerivedDefinitions("Register");
161 throw std::string("No 'Register' subclasses defined!");
162 std::sort(Regs.begin(), Regs.end(), LessRecord());
164 Registers.reserve(Regs.size());
165 Registers.assign(Regs.begin(), Regs.end());
168 CodeGenRegister::CodeGenRegister(Record *R) : TheDef(R) {
169 DeclaredSpillSize = R->getValueAsInt("SpillSize");
170 DeclaredSpillAlignment = R->getValueAsInt("SpillAlignment");
173 const std::string &CodeGenRegister::getName() const {
174 return TheDef->getName();
177 void CodeGenTarget::ReadSubRegIndices() const {
178 SubRegIndices = Records.getAllDerivedDefinitions("SubRegIndex");
179 std::sort(SubRegIndices.begin(), SubRegIndices.end(), LessRecord());
182 void CodeGenTarget::ReadRegisterClasses() const {
183 std::vector<Record*> RegClasses =
184 Records.getAllDerivedDefinitions("RegisterClass");
185 if (RegClasses.empty())
186 throw std::string("No 'RegisterClass' subclasses defined!");
188 RegisterClasses.reserve(RegClasses.size());
189 RegisterClasses.assign(RegClasses.begin(), RegClasses.end());
192 std::vector<MVT::SimpleValueType> CodeGenTarget::
193 getRegisterVTs(Record *R) const {
194 std::vector<MVT::SimpleValueType> Result;
195 const std::vector<CodeGenRegisterClass> &RCs = getRegisterClasses();
196 for (unsigned i = 0, e = RCs.size(); i != e; ++i) {
197 const CodeGenRegisterClass &RC = RegisterClasses[i];
198 for (unsigned ei = 0, ee = RC.Elements.size(); ei != ee; ++ei) {
199 if (R == RC.Elements[ei]) {
200 const std::vector<MVT::SimpleValueType> &InVTs = RC.getValueTypes();
201 Result.insert(Result.end(), InVTs.begin(), InVTs.end());
206 // Remove duplicates.
207 array_pod_sort(Result.begin(), Result.end());
208 Result.erase(std::unique(Result.begin(), Result.end()), Result.end());
213 CodeGenRegisterClass::CodeGenRegisterClass(Record *R) : TheDef(R) {
214 // Rename anonymous register classes.
215 if (R->getName().size() > 9 && R->getName()[9] == '.') {
216 static unsigned AnonCounter = 0;
217 R->setName("AnonRegClass_"+utostr(AnonCounter++));
220 std::vector<Record*> TypeList = R->getValueAsListOfDefs("RegTypes");
221 for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
222 Record *Type = TypeList[i];
223 if (!Type->isSubClassOf("ValueType"))
224 throw "RegTypes list member '" + Type->getName() +
225 "' does not derive from the ValueType class!";
226 VTs.push_back(getValueType(Type));
228 assert(!VTs.empty() && "RegisterClass must contain at least one ValueType!");
230 std::vector<Record*> RegList = R->getValueAsListOfDefs("MemberList");
231 for (unsigned i = 0, e = RegList.size(); i != e; ++i) {
232 Record *Reg = RegList[i];
233 if (!Reg->isSubClassOf("Register"))
234 throw "Register Class member '" + Reg->getName() +
235 "' does not derive from the Register class!";
236 Elements.push_back(Reg);
239 // SubRegClasses is a list<dag> containing (RC, subregindex, ...) dags.
240 ListInit *SRC = R->getValueAsListInit("SubRegClasses");
241 for (ListInit::const_iterator i = SRC->begin(), e = SRC->end(); i != e; ++i) {
242 DagInit *DAG = dynamic_cast<DagInit*>(*i);
243 if (!DAG) throw "SubRegClasses must contain DAGs";
244 DefInit *DAGOp = dynamic_cast<DefInit*>(DAG->getOperator());
246 if (!DAGOp || !(RCRec = DAGOp->getDef())->isSubClassOf("RegisterClass"))
247 throw "Operator '" + DAG->getOperator()->getAsString() +
248 "' in SubRegClasses is not a RegisterClass";
249 // Iterate over args, all SubRegIndex instances.
250 for (DagInit::const_arg_iterator ai = DAG->arg_begin(), ae = DAG->arg_end();
252 DefInit *Idx = dynamic_cast<DefInit*>(*ai);
254 if (!Idx || !(IdxRec = Idx->getDef())->isSubClassOf("SubRegIndex"))
255 throw "Argument '" + (*ai)->getAsString() +
256 "' in SubRegClasses is not a SubRegIndex";
257 if (!SubRegClasses.insert(std::make_pair(IdxRec, RCRec)).second)
258 throw "SubRegIndex '" + IdxRec->getName() + "' mentioned twice";
262 // Allow targets to override the size in bits of the RegisterClass.
263 unsigned Size = R->getValueAsInt("Size");
265 Namespace = R->getValueAsString("Namespace");
266 SpillSize = Size ? Size : EVT(VTs[0]).getSizeInBits();
267 SpillAlignment = R->getValueAsInt("Alignment");
268 CopyCost = R->getValueAsInt("CopyCost");
269 MethodBodies = R->getValueAsCode("MethodBodies");
270 MethodProtos = R->getValueAsCode("MethodProtos");
273 const std::string &CodeGenRegisterClass::getName() const {
274 return TheDef->getName();
277 void CodeGenTarget::ReadLegalValueTypes() const {
278 const std::vector<CodeGenRegisterClass> &RCs = getRegisterClasses();
279 for (unsigned i = 0, e = RCs.size(); i != e; ++i)
280 for (unsigned ri = 0, re = RCs[i].VTs.size(); ri != re; ++ri)
281 LegalValueTypes.push_back(RCs[i].VTs[ri]);
283 // Remove duplicates.
284 std::sort(LegalValueTypes.begin(), LegalValueTypes.end());
285 LegalValueTypes.erase(std::unique(LegalValueTypes.begin(),
286 LegalValueTypes.end()),
287 LegalValueTypes.end());
291 void CodeGenTarget::ReadInstructions() const {
292 std::vector<Record*> Insts = Records.getAllDerivedDefinitions("Instruction");
293 if (Insts.size() <= 2)
294 throw std::string("No 'Instruction' subclasses defined!");
296 // Parse the instructions defined in the .td file.
297 std::string InstFormatName =
298 getAsmWriter()->getValueAsString("InstFormatName");
300 for (unsigned i = 0, e = Insts.size(); i != e; ++i) {
301 std::string AsmStr = Insts[i]->getValueAsString(InstFormatName);
302 Instructions[Insts[i]] = new CodeGenInstruction(Insts[i], AsmStr);
306 static const CodeGenInstruction *
307 GetInstByName(const char *Name,
308 const DenseMap<const Record*, CodeGenInstruction*> &Insts) {
309 const Record *Rec = Records.getDef(Name);
311 DenseMap<const Record*, CodeGenInstruction*>::const_iterator
313 if (Rec == 0 || I == Insts.end())
314 throw std::string("Could not find '") + Name + "' instruction!";
319 /// SortInstByName - Sorting predicate to sort instructions by name.
321 struct SortInstByName {
322 bool operator()(const CodeGenInstruction *Rec1,
323 const CodeGenInstruction *Rec2) const {
324 return Rec1->TheDef->getName() < Rec2->TheDef->getName();
329 /// getInstructionsByEnumValue - Return all of the instructions defined by the
330 /// target, ordered by their enum value.
331 void CodeGenTarget::ComputeInstrsByEnum() const {
332 // The ordering here must match the ordering in TargetOpcodes.h.
333 const char *const FixedInstrs[] = {
349 const DenseMap<const Record*, CodeGenInstruction*> &Insts = getInstructions();
350 for (const char *const *p = FixedInstrs; *p; ++p) {
351 const CodeGenInstruction *Instr = GetInstByName(*p, Insts);
352 assert(Instr && "Missing target independent instruction");
353 assert(Instr->Namespace == "TargetOpcode" && "Bad namespace");
354 InstrsByEnum.push_back(Instr);
356 unsigned EndOfPredefines = InstrsByEnum.size();
358 for (DenseMap<const Record*, CodeGenInstruction*>::const_iterator
359 I = Insts.begin(), E = Insts.end(); I != E; ++I) {
360 const CodeGenInstruction *CGI = I->second;
361 if (CGI->Namespace != "TargetOpcode")
362 InstrsByEnum.push_back(CGI);
365 assert(InstrsByEnum.size() == Insts.size() && "Missing predefined instr");
367 // All of the instructions are now in random order based on the map iteration.
368 // Sort them by name.
369 std::sort(InstrsByEnum.begin()+EndOfPredefines, InstrsByEnum.end(),
374 /// isLittleEndianEncoding - Return whether this target encodes its instruction
375 /// in little-endian format, i.e. bits laid out in the order [0..n]
377 bool CodeGenTarget::isLittleEndianEncoding() const {
378 return getInstructionSet()->getValueAsBit("isLittleEndianEncoding");
381 //===----------------------------------------------------------------------===//
382 // ComplexPattern implementation
384 ComplexPattern::ComplexPattern(Record *R) {
385 Ty = ::getValueType(R->getValueAsDef("Ty"));
386 NumOperands = R->getValueAsInt("NumOperands");
387 SelectFunc = R->getValueAsString("SelectFunc");
388 RootNodes = R->getValueAsListOfDefs("RootNodes");
390 // Parse the properties.
392 std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
393 for (unsigned i = 0, e = PropList.size(); i != e; ++i)
394 if (PropList[i]->getName() == "SDNPHasChain") {
395 Properties |= 1 << SDNPHasChain;
396 } else if (PropList[i]->getName() == "SDNPOptInFlag") {
397 Properties |= 1 << SDNPOptInFlag;
398 } else if (PropList[i]->getName() == "SDNPMayStore") {
399 Properties |= 1 << SDNPMayStore;
400 } else if (PropList[i]->getName() == "SDNPMayLoad") {
401 Properties |= 1 << SDNPMayLoad;
402 } else if (PropList[i]->getName() == "SDNPSideEffect") {
403 Properties |= 1 << SDNPSideEffect;
404 } else if (PropList[i]->getName() == "SDNPMemOperand") {
405 Properties |= 1 << SDNPMemOperand;
406 } else if (PropList[i]->getName() == "SDNPVariadic") {
407 Properties |= 1 << SDNPVariadic;
409 errs() << "Unsupported SD Node property '" << PropList[i]->getName()
410 << "' on ComplexPattern '" << R->getName() << "'!\n";
415 //===----------------------------------------------------------------------===//
416 // CodeGenIntrinsic Implementation
417 //===----------------------------------------------------------------------===//
419 std::vector<CodeGenIntrinsic> llvm::LoadIntrinsics(const RecordKeeper &RC,
421 std::vector<Record*> I = RC.getAllDerivedDefinitions("Intrinsic");
423 std::vector<CodeGenIntrinsic> Result;
425 for (unsigned i = 0, e = I.size(); i != e; ++i) {
426 bool isTarget = I[i]->getValueAsBit("isTarget");
427 if (isTarget == TargetOnly)
428 Result.push_back(CodeGenIntrinsic(I[i]));
433 CodeGenIntrinsic::CodeGenIntrinsic(Record *R) {
435 std::string DefName = R->getName();
437 isOverloaded = false;
438 isCommutative = false;
440 if (DefName.size() <= 4 ||
441 std::string(DefName.begin(), DefName.begin() + 4) != "int_")
442 throw "Intrinsic '" + DefName + "' does not start with 'int_'!";
444 EnumName = std::string(DefName.begin()+4, DefName.end());
446 if (R->getValue("GCCBuiltinName")) // Ignore a missing GCCBuiltinName field.
447 GCCBuiltinName = R->getValueAsString("GCCBuiltinName");
449 TargetPrefix = R->getValueAsString("TargetPrefix");
450 Name = R->getValueAsString("LLVMName");
453 // If an explicit name isn't specified, derive one from the DefName.
456 for (unsigned i = 0, e = EnumName.size(); i != e; ++i)
457 Name += (EnumName[i] == '_') ? '.' : EnumName[i];
459 // Verify it starts with "llvm.".
460 if (Name.size() <= 5 ||
461 std::string(Name.begin(), Name.begin() + 5) != "llvm.")
462 throw "Intrinsic '" + DefName + "'s name does not start with 'llvm.'!";
465 // If TargetPrefix is specified, make sure that Name starts with
466 // "llvm.<targetprefix>.".
467 if (!TargetPrefix.empty()) {
468 if (Name.size() < 6+TargetPrefix.size() ||
469 std::string(Name.begin() + 5, Name.begin() + 6 + TargetPrefix.size())
470 != (TargetPrefix + "."))
471 throw "Intrinsic '" + DefName + "' does not start with 'llvm." +
472 TargetPrefix + ".'!";
475 // Parse the list of return types.
476 std::vector<MVT::SimpleValueType> OverloadedVTs;
477 ListInit *TypeList = R->getValueAsListInit("RetTypes");
478 for (unsigned i = 0, e = TypeList->getSize(); i != e; ++i) {
479 Record *TyEl = TypeList->getElementAsRecord(i);
480 assert(TyEl->isSubClassOf("LLVMType") && "Expected a type!");
481 MVT::SimpleValueType VT;
482 if (TyEl->isSubClassOf("LLVMMatchType")) {
483 unsigned MatchTy = TyEl->getValueAsInt("Number");
484 assert(MatchTy < OverloadedVTs.size() &&
485 "Invalid matching number!");
486 VT = OverloadedVTs[MatchTy];
487 // It only makes sense to use the extended and truncated vector element
488 // variants with iAny types; otherwise, if the intrinsic is not
489 // overloaded, all the types can be specified directly.
490 assert(((!TyEl->isSubClassOf("LLVMExtendedElementVectorType") &&
491 !TyEl->isSubClassOf("LLVMTruncatedElementVectorType")) ||
492 VT == MVT::iAny || VT == MVT::vAny) &&
493 "Expected iAny or vAny type");
495 VT = getValueType(TyEl->getValueAsDef("VT"));
497 if (EVT(VT).isOverloaded()) {
498 OverloadedVTs.push_back(VT);
502 // Reject invalid types.
503 if (VT == MVT::isVoid)
504 throw "Intrinsic '" + DefName + " has void in result type list!";
506 IS.RetVTs.push_back(VT);
507 IS.RetTypeDefs.push_back(TyEl);
510 // Parse the list of parameter types.
511 TypeList = R->getValueAsListInit("ParamTypes");
512 for (unsigned i = 0, e = TypeList->getSize(); i != e; ++i) {
513 Record *TyEl = TypeList->getElementAsRecord(i);
514 assert(TyEl->isSubClassOf("LLVMType") && "Expected a type!");
515 MVT::SimpleValueType VT;
516 if (TyEl->isSubClassOf("LLVMMatchType")) {
517 unsigned MatchTy = TyEl->getValueAsInt("Number");
518 assert(MatchTy < OverloadedVTs.size() &&
519 "Invalid matching number!");
520 VT = OverloadedVTs[MatchTy];
521 // It only makes sense to use the extended and truncated vector element
522 // variants with iAny types; otherwise, if the intrinsic is not
523 // overloaded, all the types can be specified directly.
524 assert(((!TyEl->isSubClassOf("LLVMExtendedElementVectorType") &&
525 !TyEl->isSubClassOf("LLVMTruncatedElementVectorType")) ||
526 VT == MVT::iAny || VT == MVT::vAny) &&
527 "Expected iAny or vAny type");
529 VT = getValueType(TyEl->getValueAsDef("VT"));
531 if (EVT(VT).isOverloaded()) {
532 OverloadedVTs.push_back(VT);
536 // Reject invalid types.
537 if (VT == MVT::isVoid && i != e-1 /*void at end means varargs*/)
538 throw "Intrinsic '" + DefName + " has void in result type list!";
540 IS.ParamVTs.push_back(VT);
541 IS.ParamTypeDefs.push_back(TyEl);
544 // Parse the intrinsic properties.
545 ListInit *PropList = R->getValueAsListInit("Properties");
546 for (unsigned i = 0, e = PropList->getSize(); i != e; ++i) {
547 Record *Property = PropList->getElementAsRecord(i);
548 assert(Property->isSubClassOf("IntrinsicProperty") &&
549 "Expected a property!");
551 if (Property->getName() == "IntrNoMem")
553 else if (Property->getName() == "IntrReadArgMem")
555 else if (Property->getName() == "IntrReadMem")
557 else if (Property->getName() == "IntrWriteArgMem")
558 ModRef = WriteArgMem;
559 else if (Property->getName() == "IntrWriteMem")
561 else if (Property->getName() == "Commutative")
562 isCommutative = true;
563 else if (Property->isSubClassOf("NoCapture")) {
564 unsigned ArgNo = Property->getValueAsInt("ArgNo");
565 ArgumentAttributes.push_back(std::make_pair(ArgNo, NoCapture));
567 assert(0 && "Unknown property!");