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"
19 #include "llvm/TableGen/Record.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::Glue: return "MVT::Glue";
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 case MVT::Untyped: return "MVT::Untyped";
94 default: assert(0 && "ILLEGAL VALUE TYPE!"); return "";
98 /// getQualifiedName - Return the name of the specified record, with a
99 /// namespace qualifier if the record contains one.
101 std::string llvm::getQualifiedName(const Record *R) {
102 std::string Namespace;
103 if (R->getValue("Namespace"))
104 Namespace = R->getValueAsString("Namespace");
105 if (Namespace.empty()) return R->getName();
106 return Namespace + "::" + R->getName();
110 /// getTarget - Return the current instance of the Target class.
112 CodeGenTarget::CodeGenTarget(RecordKeeper &records)
113 : Records(records), RegBank(0) {
114 std::vector<Record*> Targets = Records.getAllDerivedDefinitions("Target");
115 if (Targets.size() == 0)
116 throw std::string("ERROR: No 'Target' subclasses defined!");
117 if (Targets.size() != 1)
118 throw std::string("ERROR: Multiple subclasses of Target defined!");
119 TargetRec = Targets[0];
123 const std::string &CodeGenTarget::getName() const {
124 return TargetRec->getName();
127 std::string CodeGenTarget::getInstNamespace() const {
128 for (inst_iterator i = inst_begin(), e = inst_end(); i != e; ++i) {
129 // Make sure not to pick up "TargetOpcode" by accidentally getting
130 // the namespace off the PHI instruction or something.
131 if ((*i)->Namespace != "TargetOpcode")
132 return (*i)->Namespace;
138 Record *CodeGenTarget::getInstructionSet() const {
139 return TargetRec->getValueAsDef("InstructionSet");
143 /// getAsmParser - Return the AssemblyParser definition for this target.
145 Record *CodeGenTarget::getAsmParser() const {
146 std::vector<Record*> LI = TargetRec->getValueAsListOfDefs("AssemblyParsers");
147 if (AsmParserNum >= LI.size())
148 throw "Target does not have an AsmParser #" + utostr(AsmParserNum) + "!";
149 return LI[AsmParserNum];
152 /// getAsmWriter - Return the AssemblyWriter definition for this target.
154 Record *CodeGenTarget::getAsmWriter() const {
155 std::vector<Record*> LI = TargetRec->getValueAsListOfDefs("AssemblyWriters");
156 if (AsmWriterNum >= LI.size())
157 throw "Target does not have an AsmWriter #" + utostr(AsmWriterNum) + "!";
158 return LI[AsmWriterNum];
161 CodeGenRegBank &CodeGenTarget::getRegBank() const {
163 RegBank = new CodeGenRegBank(Records);
167 void CodeGenTarget::ReadRegAltNameIndices() const {
168 RegAltNameIndices = Records.getAllDerivedDefinitions("RegAltNameIndex");
169 std::sort(RegAltNameIndices.begin(), RegAltNameIndices.end(), LessRecord());
172 /// getRegisterByName - If there is a register with the specific AsmName,
174 const CodeGenRegister *CodeGenTarget::getRegisterByName(StringRef Name) const {
175 const std::vector<CodeGenRegister*> &Regs = getRegBank().getRegisters();
176 for (unsigned i = 0, e = Regs.size(); i != e; ++i)
177 if (Regs[i]->TheDef->getValueAsString("AsmName") == Name)
183 std::vector<MVT::SimpleValueType> CodeGenTarget::
184 getRegisterVTs(Record *R) const {
185 const CodeGenRegister *Reg = getRegBank().getReg(R);
186 std::vector<MVT::SimpleValueType> Result;
187 ArrayRef<CodeGenRegisterClass*> RCs = getRegBank().getRegClasses();
188 for (unsigned i = 0, e = RCs.size(); i != e; ++i) {
189 const CodeGenRegisterClass &RC = *RCs[i];
190 if (RC.contains(Reg)) {
191 const std::vector<MVT::SimpleValueType> &InVTs = RC.getValueTypes();
192 Result.insert(Result.end(), InVTs.begin(), InVTs.end());
196 // Remove duplicates.
197 array_pod_sort(Result.begin(), Result.end());
198 Result.erase(std::unique(Result.begin(), Result.end()), Result.end());
203 void CodeGenTarget::ReadLegalValueTypes() const {
204 ArrayRef<CodeGenRegisterClass*> RCs = getRegBank().getRegClasses();
205 for (unsigned i = 0, e = RCs.size(); i != e; ++i)
206 for (unsigned ri = 0, re = RCs[i]->VTs.size(); ri != re; ++ri)
207 LegalValueTypes.push_back(RCs[i]->VTs[ri]);
209 // Remove duplicates.
210 std::sort(LegalValueTypes.begin(), LegalValueTypes.end());
211 LegalValueTypes.erase(std::unique(LegalValueTypes.begin(),
212 LegalValueTypes.end()),
213 LegalValueTypes.end());
217 void CodeGenTarget::ReadInstructions() const {
218 std::vector<Record*> Insts = Records.getAllDerivedDefinitions("Instruction");
219 if (Insts.size() <= 2)
220 throw std::string("No 'Instruction' subclasses defined!");
222 // Parse the instructions defined in the .td file.
223 for (unsigned i = 0, e = Insts.size(); i != e; ++i)
224 Instructions[Insts[i]] = new CodeGenInstruction(Insts[i]);
227 static const CodeGenInstruction *
228 GetInstByName(const char *Name,
229 const DenseMap<const Record*, CodeGenInstruction*> &Insts,
230 RecordKeeper &Records) {
231 const Record *Rec = Records.getDef(Name);
233 DenseMap<const Record*, CodeGenInstruction*>::const_iterator
235 if (Rec == 0 || I == Insts.end())
236 throw std::string("Could not find '") + Name + "' instruction!";
241 /// SortInstByName - Sorting predicate to sort instructions by name.
243 struct SortInstByName {
244 bool operator()(const CodeGenInstruction *Rec1,
245 const CodeGenInstruction *Rec2) const {
246 return Rec1->TheDef->getName() < Rec2->TheDef->getName();
251 /// getInstructionsByEnumValue - Return all of the instructions defined by the
252 /// target, ordered by their enum value.
253 void CodeGenTarget::ComputeInstrsByEnum() const {
254 // The ordering here must match the ordering in TargetOpcodes.h.
255 const char *const FixedInstrs[] = {
273 const DenseMap<const Record*, CodeGenInstruction*> &Insts = getInstructions();
274 for (const char *const *p = FixedInstrs; *p; ++p) {
275 const CodeGenInstruction *Instr = GetInstByName(*p, Insts, Records);
276 assert(Instr && "Missing target independent instruction");
277 assert(Instr->Namespace == "TargetOpcode" && "Bad namespace");
278 InstrsByEnum.push_back(Instr);
280 unsigned EndOfPredefines = InstrsByEnum.size();
282 for (DenseMap<const Record*, CodeGenInstruction*>::const_iterator
283 I = Insts.begin(), E = Insts.end(); I != E; ++I) {
284 const CodeGenInstruction *CGI = I->second;
285 if (CGI->Namespace != "TargetOpcode")
286 InstrsByEnum.push_back(CGI);
289 assert(InstrsByEnum.size() == Insts.size() && "Missing predefined instr");
291 // All of the instructions are now in random order based on the map iteration.
292 // Sort them by name.
293 std::sort(InstrsByEnum.begin()+EndOfPredefines, InstrsByEnum.end(),
298 /// isLittleEndianEncoding - Return whether this target encodes its instruction
299 /// in little-endian format, i.e. bits laid out in the order [0..n]
301 bool CodeGenTarget::isLittleEndianEncoding() const {
302 return getInstructionSet()->getValueAsBit("isLittleEndianEncoding");
305 //===----------------------------------------------------------------------===//
306 // ComplexPattern implementation
308 ComplexPattern::ComplexPattern(Record *R) {
309 Ty = ::getValueType(R->getValueAsDef("Ty"));
310 NumOperands = R->getValueAsInt("NumOperands");
311 SelectFunc = R->getValueAsString("SelectFunc");
312 RootNodes = R->getValueAsListOfDefs("RootNodes");
314 // Parse the properties.
316 std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
317 for (unsigned i = 0, e = PropList.size(); i != e; ++i)
318 if (PropList[i]->getName() == "SDNPHasChain") {
319 Properties |= 1 << SDNPHasChain;
320 } else if (PropList[i]->getName() == "SDNPOptInGlue") {
321 Properties |= 1 << SDNPOptInGlue;
322 } else if (PropList[i]->getName() == "SDNPMayStore") {
323 Properties |= 1 << SDNPMayStore;
324 } else if (PropList[i]->getName() == "SDNPMayLoad") {
325 Properties |= 1 << SDNPMayLoad;
326 } else if (PropList[i]->getName() == "SDNPSideEffect") {
327 Properties |= 1 << SDNPSideEffect;
328 } else if (PropList[i]->getName() == "SDNPMemOperand") {
329 Properties |= 1 << SDNPMemOperand;
330 } else if (PropList[i]->getName() == "SDNPVariadic") {
331 Properties |= 1 << SDNPVariadic;
332 } else if (PropList[i]->getName() == "SDNPWantRoot") {
333 Properties |= 1 << SDNPWantRoot;
334 } else if (PropList[i]->getName() == "SDNPWantParent") {
335 Properties |= 1 << SDNPWantParent;
337 errs() << "Unsupported SD Node property '" << PropList[i]->getName()
338 << "' on ComplexPattern '" << R->getName() << "'!\n";
343 //===----------------------------------------------------------------------===//
344 // CodeGenIntrinsic Implementation
345 //===----------------------------------------------------------------------===//
347 std::vector<CodeGenIntrinsic> llvm::LoadIntrinsics(const RecordKeeper &RC,
349 std::vector<Record*> I = RC.getAllDerivedDefinitions("Intrinsic");
351 std::vector<CodeGenIntrinsic> Result;
353 for (unsigned i = 0, e = I.size(); i != e; ++i) {
354 bool isTarget = I[i]->getValueAsBit("isTarget");
355 if (isTarget == TargetOnly)
356 Result.push_back(CodeGenIntrinsic(I[i]));
361 CodeGenIntrinsic::CodeGenIntrinsic(Record *R) {
363 std::string DefName = R->getName();
364 ModRef = ReadWriteMem;
365 isOverloaded = false;
366 isCommutative = false;
369 if (DefName.size() <= 4 ||
370 std::string(DefName.begin(), DefName.begin() + 4) != "int_")
371 throw "Intrinsic '" + DefName + "' does not start with 'int_'!";
373 EnumName = std::string(DefName.begin()+4, DefName.end());
375 if (R->getValue("GCCBuiltinName")) // Ignore a missing GCCBuiltinName field.
376 GCCBuiltinName = R->getValueAsString("GCCBuiltinName");
378 TargetPrefix = R->getValueAsString("TargetPrefix");
379 Name = R->getValueAsString("LLVMName");
382 // If an explicit name isn't specified, derive one from the DefName.
385 for (unsigned i = 0, e = EnumName.size(); i != e; ++i)
386 Name += (EnumName[i] == '_') ? '.' : EnumName[i];
388 // Verify it starts with "llvm.".
389 if (Name.size() <= 5 ||
390 std::string(Name.begin(), Name.begin() + 5) != "llvm.")
391 throw "Intrinsic '" + DefName + "'s name does not start with 'llvm.'!";
394 // If TargetPrefix is specified, make sure that Name starts with
395 // "llvm.<targetprefix>.".
396 if (!TargetPrefix.empty()) {
397 if (Name.size() < 6+TargetPrefix.size() ||
398 std::string(Name.begin() + 5, Name.begin() + 6 + TargetPrefix.size())
399 != (TargetPrefix + "."))
400 throw "Intrinsic '" + DefName + "' does not start with 'llvm." +
401 TargetPrefix + ".'!";
404 // Parse the list of return types.
405 std::vector<MVT::SimpleValueType> OverloadedVTs;
406 ListInit *TypeList = R->getValueAsListInit("RetTypes");
407 for (unsigned i = 0, e = TypeList->getSize(); i != e; ++i) {
408 Record *TyEl = TypeList->getElementAsRecord(i);
409 assert(TyEl->isSubClassOf("LLVMType") && "Expected a type!");
410 MVT::SimpleValueType VT;
411 if (TyEl->isSubClassOf("LLVMMatchType")) {
412 unsigned MatchTy = TyEl->getValueAsInt("Number");
413 assert(MatchTy < OverloadedVTs.size() &&
414 "Invalid matching number!");
415 VT = OverloadedVTs[MatchTy];
416 // It only makes sense to use the extended and truncated vector element
417 // variants with iAny types; otherwise, if the intrinsic is not
418 // overloaded, all the types can be specified directly.
419 assert(((!TyEl->isSubClassOf("LLVMExtendedElementVectorType") &&
420 !TyEl->isSubClassOf("LLVMTruncatedElementVectorType")) ||
421 VT == MVT::iAny || VT == MVT::vAny) &&
422 "Expected iAny or vAny type");
424 VT = getValueType(TyEl->getValueAsDef("VT"));
426 if (EVT(VT).isOverloaded()) {
427 OverloadedVTs.push_back(VT);
431 // Reject invalid types.
432 if (VT == MVT::isVoid)
433 throw "Intrinsic '" + DefName + " has void in result type list!";
435 IS.RetVTs.push_back(VT);
436 IS.RetTypeDefs.push_back(TyEl);
439 // Parse the list of parameter types.
440 TypeList = R->getValueAsListInit("ParamTypes");
441 for (unsigned i = 0, e = TypeList->getSize(); i != e; ++i) {
442 Record *TyEl = TypeList->getElementAsRecord(i);
443 assert(TyEl->isSubClassOf("LLVMType") && "Expected a type!");
444 MVT::SimpleValueType VT;
445 if (TyEl->isSubClassOf("LLVMMatchType")) {
446 unsigned MatchTy = TyEl->getValueAsInt("Number");
447 assert(MatchTy < OverloadedVTs.size() &&
448 "Invalid matching number!");
449 VT = OverloadedVTs[MatchTy];
450 // It only makes sense to use the extended and truncated vector element
451 // variants with iAny types; otherwise, if the intrinsic is not
452 // overloaded, all the types can be specified directly.
453 assert(((!TyEl->isSubClassOf("LLVMExtendedElementVectorType") &&
454 !TyEl->isSubClassOf("LLVMTruncatedElementVectorType")) ||
455 VT == MVT::iAny || VT == MVT::vAny) &&
456 "Expected iAny or vAny type");
458 VT = getValueType(TyEl->getValueAsDef("VT"));
460 if (EVT(VT).isOverloaded()) {
461 OverloadedVTs.push_back(VT);
465 // Reject invalid types.
466 if (VT == MVT::isVoid && i != e-1 /*void at end means varargs*/)
467 throw "Intrinsic '" + DefName + " has void in result type list!";
469 IS.ParamVTs.push_back(VT);
470 IS.ParamTypeDefs.push_back(TyEl);
473 // Parse the intrinsic properties.
474 ListInit *PropList = R->getValueAsListInit("Properties");
475 for (unsigned i = 0, e = PropList->getSize(); i != e; ++i) {
476 Record *Property = PropList->getElementAsRecord(i);
477 assert(Property->isSubClassOf("IntrinsicProperty") &&
478 "Expected a property!");
480 if (Property->getName() == "IntrNoMem")
482 else if (Property->getName() == "IntrReadArgMem")
484 else if (Property->getName() == "IntrReadMem")
486 else if (Property->getName() == "IntrReadWriteArgMem")
487 ModRef = ReadWriteArgMem;
488 else if (Property->getName() == "Commutative")
489 isCommutative = true;
490 else if (Property->getName() == "Throws")
492 else if (Property->isSubClassOf("NoCapture")) {
493 unsigned ArgNo = Property->getValueAsInt("ArgNo");
494 ArgumentAttributes.push_back(std::make_pair(ArgNo, NoCapture));
496 assert(0 && "Unknown property!");
499 // Sort the argument attributes for later benefit.
500 std::sort(ArgumentAttributes.begin(), ArgumentAttributes.end());