]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/utils/TableGen/CodeGenTarget.cpp
Merge llvm, clang, lld and lldb trunk r300890, and update build glue.
[FreeBSD/FreeBSD.git] / contrib / llvm / utils / TableGen / CodeGenTarget.cpp
1 //===- CodeGenTarget.cpp - CodeGen Target Class Wrapper -------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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 abort on error conditions.
14 //
15 //===----------------------------------------------------------------------===//
16
17 #include "CodeGenTarget.h"
18 #include "CodeGenIntrinsics.h"
19 #include "CodeGenSchedule.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/StringExtras.h"
22 #include "llvm/Support/CommandLine.h"
23 #include "llvm/TableGen/Error.h"
24 #include "llvm/TableGen/Record.h"
25 #include <algorithm>
26 using namespace llvm;
27
28 cl::OptionCategory AsmParserCat("Options for -gen-asm-parser");
29 cl::OptionCategory AsmWriterCat("Options for -gen-asm-writer");
30
31 static cl::opt<unsigned>
32     AsmParserNum("asmparsernum", cl::init(0),
33                  cl::desc("Make -gen-asm-parser emit assembly parser #N"),
34                  cl::cat(AsmParserCat));
35
36 static cl::opt<unsigned>
37     AsmWriterNum("asmwriternum", cl::init(0),
38                  cl::desc("Make -gen-asm-writer emit assembly writer #N"),
39                  cl::cat(AsmWriterCat));
40
41 /// getValueType - Return the MVT::SimpleValueType that the specified TableGen
42 /// record corresponds to.
43 MVT::SimpleValueType llvm::getValueType(Record *Rec) {
44   return (MVT::SimpleValueType)Rec->getValueAsInt("Value");
45 }
46
47 StringRef llvm::getName(MVT::SimpleValueType T) {
48   switch (T) {
49   case MVT::Other:   return "UNKNOWN";
50   case MVT::iPTR:    return "TLI.getPointerTy()";
51   case MVT::iPTRAny: return "TLI.getPointerTy()";
52   default: return getEnumName(T);
53   }
54 }
55
56 StringRef llvm::getEnumName(MVT::SimpleValueType T) {
57   switch (T) {
58   case MVT::Other:    return "MVT::Other";
59   case MVT::i1:       return "MVT::i1";
60   case MVT::i8:       return "MVT::i8";
61   case MVT::i16:      return "MVT::i16";
62   case MVT::i32:      return "MVT::i32";
63   case MVT::i64:      return "MVT::i64";
64   case MVT::i128:     return "MVT::i128";
65   case MVT::Any:      return "MVT::Any";
66   case MVT::iAny:     return "MVT::iAny";
67   case MVT::fAny:     return "MVT::fAny";
68   case MVT::vAny:     return "MVT::vAny";
69   case MVT::f16:      return "MVT::f16";
70   case MVT::f32:      return "MVT::f32";
71   case MVT::f64:      return "MVT::f64";
72   case MVT::f80:      return "MVT::f80";
73   case MVT::f128:     return "MVT::f128";
74   case MVT::ppcf128:  return "MVT::ppcf128";
75   case MVT::x86mmx:   return "MVT::x86mmx";
76   case MVT::Glue:     return "MVT::Glue";
77   case MVT::isVoid:   return "MVT::isVoid";
78   case MVT::v2i1:     return "MVT::v2i1";
79   case MVT::v4i1:     return "MVT::v4i1";
80   case MVT::v8i1:     return "MVT::v8i1";
81   case MVT::v16i1:    return "MVT::v16i1";
82   case MVT::v32i1:    return "MVT::v32i1";
83   case MVT::v64i1:    return "MVT::v64i1";
84   case MVT::v512i1:   return "MVT::v512i1";
85   case MVT::v1024i1:  return "MVT::v1024i1";
86   case MVT::v1i8:     return "MVT::v1i8";
87   case MVT::v2i8:     return "MVT::v2i8";
88   case MVT::v4i8:     return "MVT::v4i8";
89   case MVT::v8i8:     return "MVT::v8i8";
90   case MVT::v16i8:    return "MVT::v16i8";
91   case MVT::v32i8:    return "MVT::v32i8";
92   case MVT::v64i8:    return "MVT::v64i8";
93   case MVT::v128i8:   return "MVT::v128i8";
94   case MVT::v256i8:   return "MVT::v256i8";
95   case MVT::v1i16:    return "MVT::v1i16";
96   case MVT::v2i16:    return "MVT::v2i16";
97   case MVT::v4i16:    return "MVT::v4i16";
98   case MVT::v8i16:    return "MVT::v8i16";
99   case MVT::v16i16:   return "MVT::v16i16";
100   case MVT::v32i16:   return "MVT::v32i16";
101   case MVT::v64i16:   return "MVT::v64i16";
102   case MVT::v128i16:  return "MVT::v128i16";
103   case MVT::v1i32:    return "MVT::v1i32";
104   case MVT::v2i32:    return "MVT::v2i32";
105   case MVT::v4i32:    return "MVT::v4i32";
106   case MVT::v8i32:    return "MVT::v8i32";
107   case MVT::v16i32:   return "MVT::v16i32";
108   case MVT::v32i32:   return "MVT::v32i32";
109   case MVT::v64i32:   return "MVT::v64i32";
110   case MVT::v1i64:    return "MVT::v1i64";
111   case MVT::v2i64:    return "MVT::v2i64";
112   case MVT::v4i64:    return "MVT::v4i64";
113   case MVT::v8i64:    return "MVT::v8i64";
114   case MVT::v16i64:   return "MVT::v16i64";
115   case MVT::v32i64:   return "MVT::v32i64";
116   case MVT::v1i128:   return "MVT::v1i128";
117   case MVT::v2f16:    return "MVT::v2f16";
118   case MVT::v4f16:    return "MVT::v4f16";
119   case MVT::v8f16:    return "MVT::v8f16";
120   case MVT::v1f32:    return "MVT::v1f32";
121   case MVT::v2f32:    return "MVT::v2f32";
122   case MVT::v4f32:    return "MVT::v4f32";
123   case MVT::v8f32:    return "MVT::v8f32";
124   case MVT::v16f32:   return "MVT::v16f32";
125   case MVT::v1f64:    return "MVT::v1f64";
126   case MVT::v2f64:    return "MVT::v2f64";
127   case MVT::v4f64:    return "MVT::v4f64";
128   case MVT::v8f64:    return "MVT::v8f64";
129   case MVT::nxv2i1:   return "MVT::nxv2i1";
130   case MVT::nxv4i1:   return "MVT::nxv4i1";
131   case MVT::nxv8i1:   return "MVT::nxv8i1";
132   case MVT::nxv16i1:  return "MVT::nxv16i1";
133   case MVT::nxv32i1:  return "MVT::nxv32i1";
134   case MVT::nxv1i8:   return "MVT::nxv1i8";
135   case MVT::nxv2i8:   return "MVT::nxv2i8";
136   case MVT::nxv4i8:   return "MVT::nxv4i8";
137   case MVT::nxv8i8:   return "MVT::nxv8i8";
138   case MVT::nxv16i8:  return "MVT::nxv16i8";
139   case MVT::nxv32i8:  return "MVT::nxv32i8";
140   case MVT::nxv1i16:  return "MVT::nxv1i16";
141   case MVT::nxv2i16:  return "MVT::nxv2i16";
142   case MVT::nxv4i16:  return "MVT::nxv4i16";
143   case MVT::nxv8i16:  return "MVT::nxv8i16";
144   case MVT::nxv16i16: return "MVT::nxv16i16";
145   case MVT::nxv32i16: return "MVT::nxv32i16";
146   case MVT::nxv1i32:  return "MVT::nxv1i32";
147   case MVT::nxv2i32:  return "MVT::nxv2i32";
148   case MVT::nxv4i32:  return "MVT::nxv4i32";
149   case MVT::nxv8i32:  return "MVT::nxv8i32";
150   case MVT::nxv16i32: return "MVT::nxv16i32";
151   case MVT::nxv1i64:  return "MVT::nxv1i64";
152   case MVT::nxv2i64:  return "MVT::nxv2i64";
153   case MVT::nxv4i64:  return "MVT::nxv4i64";
154   case MVT::nxv8i64:  return "MVT::nxv8i64";
155   case MVT::nxv16i64: return "MVT::nxv16i64";
156   case MVT::nxv2f16:  return "MVT::nxv2f16";
157   case MVT::nxv4f16:  return "MVT::nxv4f16";
158   case MVT::nxv8f16:  return "MVT::nxv8f16";
159   case MVT::nxv1f32:  return "MVT::nxv1f32";
160   case MVT::nxv2f32:  return "MVT::nxv2f32";
161   case MVT::nxv4f32:  return "MVT::nxv4f32";
162   case MVT::nxv8f32:  return "MVT::nxv8f32";
163   case MVT::nxv16f32: return "MVT::nxv16f32";
164   case MVT::nxv1f64:  return "MVT::nxv1f64";
165   case MVT::nxv2f64:  return "MVT::nxv2f64";
166   case MVT::nxv4f64:  return "MVT::nxv4f64";
167   case MVT::nxv8f64:  return "MVT::nxv8f64";
168   case MVT::token:    return "MVT::token";
169   case MVT::Metadata: return "MVT::Metadata";
170   case MVT::iPTR:     return "MVT::iPTR";
171   case MVT::iPTRAny:  return "MVT::iPTRAny";
172   case MVT::Untyped:  return "MVT::Untyped";
173   default: llvm_unreachable("ILLEGAL VALUE TYPE!");
174   }
175 }
176
177 /// getQualifiedName - Return the name of the specified record, with a
178 /// namespace qualifier if the record contains one.
179 ///
180 std::string llvm::getQualifiedName(const Record *R) {
181   std::string Namespace;
182   if (R->getValue("Namespace"))
183      Namespace = R->getValueAsString("Namespace");
184   if (Namespace.empty()) return R->getName();
185   return Namespace + "::" + R->getName().str();
186 }
187
188
189 /// getTarget - Return the current instance of the Target class.
190 ///
191 CodeGenTarget::CodeGenTarget(RecordKeeper &records)
192   : Records(records) {
193   std::vector<Record*> Targets = Records.getAllDerivedDefinitions("Target");
194   if (Targets.size() == 0)
195     PrintFatalError("ERROR: No 'Target' subclasses defined!");
196   if (Targets.size() != 1)
197     PrintFatalError("ERROR: Multiple subclasses of Target defined!");
198   TargetRec = Targets[0];
199 }
200
201 CodeGenTarget::~CodeGenTarget() {
202 }
203
204 const StringRef CodeGenTarget::getName() const {
205   return TargetRec->getName();
206 }
207
208 std::string CodeGenTarget::getInstNamespace() const {
209   for (const CodeGenInstruction *Inst : getInstructionsByEnumValue()) {
210     // Make sure not to pick up "TargetOpcode" by accidentally getting
211     // the namespace off the PHI instruction or something.
212     if (Inst->Namespace != "TargetOpcode")
213       return Inst->Namespace;
214   }
215
216   return "";
217 }
218
219 Record *CodeGenTarget::getInstructionSet() const {
220   return TargetRec->getValueAsDef("InstructionSet");
221 }
222
223
224 /// getAsmParser - Return the AssemblyParser definition for this target.
225 ///
226 Record *CodeGenTarget::getAsmParser() const {
227   std::vector<Record*> LI = TargetRec->getValueAsListOfDefs("AssemblyParsers");
228   if (AsmParserNum >= LI.size())
229     PrintFatalError("Target does not have an AsmParser #" +
230                     Twine(AsmParserNum) + "!");
231   return LI[AsmParserNum];
232 }
233
234 /// getAsmParserVariant - Return the AssmblyParserVariant definition for
235 /// this target.
236 ///
237 Record *CodeGenTarget::getAsmParserVariant(unsigned i) const {
238   std::vector<Record*> LI =
239     TargetRec->getValueAsListOfDefs("AssemblyParserVariants");
240   if (i >= LI.size())
241     PrintFatalError("Target does not have an AsmParserVariant #" + Twine(i) +
242                     "!");
243   return LI[i];
244 }
245
246 /// getAsmParserVariantCount - Return the AssmblyParserVariant definition
247 /// available for this target.
248 ///
249 unsigned CodeGenTarget::getAsmParserVariantCount() const {
250   std::vector<Record*> LI =
251     TargetRec->getValueAsListOfDefs("AssemblyParserVariants");
252   return LI.size();
253 }
254
255 /// getAsmWriter - Return the AssemblyWriter definition for this target.
256 ///
257 Record *CodeGenTarget::getAsmWriter() const {
258   std::vector<Record*> LI = TargetRec->getValueAsListOfDefs("AssemblyWriters");
259   if (AsmWriterNum >= LI.size())
260     PrintFatalError("Target does not have an AsmWriter #" +
261                     Twine(AsmWriterNum) + "!");
262   return LI[AsmWriterNum];
263 }
264
265 CodeGenRegBank &CodeGenTarget::getRegBank() const {
266   if (!RegBank)
267     RegBank = llvm::make_unique<CodeGenRegBank>(Records);
268   return *RegBank;
269 }
270
271 void CodeGenTarget::ReadRegAltNameIndices() const {
272   RegAltNameIndices = Records.getAllDerivedDefinitions("RegAltNameIndex");
273   std::sort(RegAltNameIndices.begin(), RegAltNameIndices.end(), LessRecord());
274 }
275
276 /// getRegisterByName - If there is a register with the specific AsmName,
277 /// return it.
278 const CodeGenRegister *CodeGenTarget::getRegisterByName(StringRef Name) const {
279   const StringMap<CodeGenRegister*> &Regs = getRegBank().getRegistersByName();
280   StringMap<CodeGenRegister*>::const_iterator I = Regs.find(Name);
281   if (I == Regs.end())
282     return nullptr;
283   return I->second;
284 }
285
286 std::vector<MVT::SimpleValueType> CodeGenTarget::
287 getRegisterVTs(Record *R) const {
288   const CodeGenRegister *Reg = getRegBank().getReg(R);
289   std::vector<MVT::SimpleValueType> Result;
290   for (const auto &RC : getRegBank().getRegClasses()) {
291     if (RC.contains(Reg)) {
292       ArrayRef<MVT::SimpleValueType> InVTs = RC.getValueTypes();
293       Result.insert(Result.end(), InVTs.begin(), InVTs.end());
294     }
295   }
296
297   // Remove duplicates.
298   array_pod_sort(Result.begin(), Result.end());
299   Result.erase(std::unique(Result.begin(), Result.end()), Result.end());
300   return Result;
301 }
302
303
304 void CodeGenTarget::ReadLegalValueTypes() const {
305   for (const auto &RC : getRegBank().getRegClasses())
306     LegalValueTypes.insert(LegalValueTypes.end(), RC.VTs.begin(), RC.VTs.end());
307
308   // Remove duplicates.
309   array_pod_sort(LegalValueTypes.begin(), LegalValueTypes.end());
310   LegalValueTypes.erase(std::unique(LegalValueTypes.begin(),
311                                     LegalValueTypes.end()),
312                         LegalValueTypes.end());
313 }
314
315 CodeGenSchedModels &CodeGenTarget::getSchedModels() const {
316   if (!SchedModels)
317     SchedModels = llvm::make_unique<CodeGenSchedModels>(Records, *this);
318   return *SchedModels;
319 }
320
321 void CodeGenTarget::ReadInstructions() const {
322   std::vector<Record*> Insts = Records.getAllDerivedDefinitions("Instruction");
323   if (Insts.size() <= 2)
324     PrintFatalError("No 'Instruction' subclasses defined!");
325
326   // Parse the instructions defined in the .td file.
327   for (unsigned i = 0, e = Insts.size(); i != e; ++i)
328     Instructions[Insts[i]] = llvm::make_unique<CodeGenInstruction>(Insts[i]);
329 }
330
331 static const CodeGenInstruction *
332 GetInstByName(const char *Name,
333               const DenseMap<const Record*,
334                              std::unique_ptr<CodeGenInstruction>> &Insts,
335               RecordKeeper &Records) {
336   const Record *Rec = Records.getDef(Name);
337
338   const auto I = Insts.find(Rec);
339   if (!Rec || I == Insts.end())
340     PrintFatalError(Twine("Could not find '") + Name + "' instruction!");
341   return I->second.get();
342 }
343
344 /// \brief Return all of the instructions defined by the target, ordered by
345 /// their enum value.
346 void CodeGenTarget::ComputeInstrsByEnum() const {
347   static const char *const FixedInstrs[] = {
348 #define HANDLE_TARGET_OPCODE(OPC) #OPC,
349 #include "llvm/Target/TargetOpcodes.def"
350       nullptr};
351   const auto &Insts = getInstructions();
352   for (const char *const *p = FixedInstrs; *p; ++p) {
353     const CodeGenInstruction *Instr = GetInstByName(*p, Insts, Records);
354     assert(Instr && "Missing target independent instruction");
355     assert(Instr->Namespace == "TargetOpcode" && "Bad namespace");
356     InstrsByEnum.push_back(Instr);
357   }
358   unsigned EndOfPredefines = InstrsByEnum.size();
359
360   for (const auto &I : Insts) {
361     const CodeGenInstruction *CGI = I.second.get();
362     if (CGI->Namespace != "TargetOpcode")
363       InstrsByEnum.push_back(CGI);
364   }
365
366   assert(InstrsByEnum.size() == Insts.size() && "Missing predefined instr");
367
368   // All of the instructions are now in random order based on the map iteration.
369   // Sort them by name.
370   std::sort(InstrsByEnum.begin() + EndOfPredefines, InstrsByEnum.end(),
371             [](const CodeGenInstruction *Rec1, const CodeGenInstruction *Rec2) {
372     return Rec1->TheDef->getName() < Rec2->TheDef->getName();
373   });
374 }
375
376
377 /// isLittleEndianEncoding - Return whether this target encodes its instruction
378 /// in little-endian format, i.e. bits laid out in the order [0..n]
379 ///
380 bool CodeGenTarget::isLittleEndianEncoding() const {
381   return getInstructionSet()->getValueAsBit("isLittleEndianEncoding");
382 }
383
384 /// reverseBitsForLittleEndianEncoding - For little-endian instruction bit
385 /// encodings, reverse the bit order of all instructions.
386 void CodeGenTarget::reverseBitsForLittleEndianEncoding() {
387   if (!isLittleEndianEncoding())
388     return;
389
390   std::vector<Record*> Insts = Records.getAllDerivedDefinitions("Instruction");
391   for (Record *R : Insts) {
392     if (R->getValueAsString("Namespace") == "TargetOpcode" ||
393         R->getValueAsBit("isPseudo"))
394       continue;
395
396     BitsInit *BI = R->getValueAsBitsInit("Inst");
397
398     unsigned numBits = BI->getNumBits();
399
400     SmallVector<Init *, 16> NewBits(numBits);
401
402     for (unsigned bit = 0, end = numBits / 2; bit != end; ++bit) {
403       unsigned bitSwapIdx = numBits - bit - 1;
404       Init *OrigBit = BI->getBit(bit);
405       Init *BitSwap = BI->getBit(bitSwapIdx);
406       NewBits[bit]        = BitSwap;
407       NewBits[bitSwapIdx] = OrigBit;
408     }
409     if (numBits % 2) {
410       unsigned middle = (numBits + 1) / 2;
411       NewBits[middle] = BI->getBit(middle);
412     }
413
414     BitsInit *NewBI = BitsInit::get(NewBits);
415
416     // Update the bits in reversed order so that emitInstrOpBits will get the
417     // correct endianness.
418     R->getValue("Inst")->setValue(NewBI);
419   }
420 }
421
422 /// guessInstructionProperties - Return true if it's OK to guess instruction
423 /// properties instead of raising an error.
424 ///
425 /// This is configurable as a temporary migration aid. It will eventually be
426 /// permanently false.
427 bool CodeGenTarget::guessInstructionProperties() const {
428   return getInstructionSet()->getValueAsBit("guessInstructionProperties");
429 }
430
431 //===----------------------------------------------------------------------===//
432 // ComplexPattern implementation
433 //
434 ComplexPattern::ComplexPattern(Record *R) {
435   Ty          = ::getValueType(R->getValueAsDef("Ty"));
436   NumOperands = R->getValueAsInt("NumOperands");
437   SelectFunc  = R->getValueAsString("SelectFunc");
438   RootNodes   = R->getValueAsListOfDefs("RootNodes");
439
440   // FIXME: This is a hack to statically increase the priority of patterns which
441   // maps a sub-dag to a complex pattern. e.g. favors LEA over ADD. To get best
442   // possible pattern match we'll need to dynamically calculate the complexity
443   // of all patterns a dag can potentially map to.
444   int64_t RawComplexity = R->getValueAsInt("Complexity");
445   if (RawComplexity == -1)
446     Complexity = NumOperands * 3;
447   else
448     Complexity = RawComplexity;
449
450   // Parse the properties.
451   Properties = 0;
452   std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
453   for (unsigned i = 0, e = PropList.size(); i != e; ++i)
454     if (PropList[i]->getName() == "SDNPHasChain") {
455       Properties |= 1 << SDNPHasChain;
456     } else if (PropList[i]->getName() == "SDNPOptInGlue") {
457       Properties |= 1 << SDNPOptInGlue;
458     } else if (PropList[i]->getName() == "SDNPMayStore") {
459       Properties |= 1 << SDNPMayStore;
460     } else if (PropList[i]->getName() == "SDNPMayLoad") {
461       Properties |= 1 << SDNPMayLoad;
462     } else if (PropList[i]->getName() == "SDNPSideEffect") {
463       Properties |= 1 << SDNPSideEffect;
464     } else if (PropList[i]->getName() == "SDNPMemOperand") {
465       Properties |= 1 << SDNPMemOperand;
466     } else if (PropList[i]->getName() == "SDNPVariadic") {
467       Properties |= 1 << SDNPVariadic;
468     } else if (PropList[i]->getName() == "SDNPWantRoot") {
469       Properties |= 1 << SDNPWantRoot;
470     } else if (PropList[i]->getName() == "SDNPWantParent") {
471       Properties |= 1 << SDNPWantParent;
472     } else {
473       PrintFatalError("Unsupported SD Node property '" +
474                       PropList[i]->getName() + "' on ComplexPattern '" +
475                       R->getName() + "'!");
476     }
477 }
478
479 //===----------------------------------------------------------------------===//
480 // CodeGenIntrinsic Implementation
481 //===----------------------------------------------------------------------===//
482
483 CodeGenIntrinsicTable::CodeGenIntrinsicTable(const RecordKeeper &RC,
484                                              bool TargetOnly) {
485   std::vector<Record*> Defs = RC.getAllDerivedDefinitions("Intrinsic");
486
487   Intrinsics.reserve(Defs.size());
488
489   for (unsigned I = 0, e = Defs.size(); I != e; ++I) {
490     bool isTarget = Defs[I]->getValueAsBit("isTarget");
491     if (isTarget == TargetOnly)
492       Intrinsics.push_back(CodeGenIntrinsic(Defs[I]));
493   }
494   std::sort(Intrinsics.begin(), Intrinsics.end(),
495             [](const CodeGenIntrinsic &LHS, const CodeGenIntrinsic &RHS) {
496               return std::tie(LHS.TargetPrefix, LHS.Name) <
497                      std::tie(RHS.TargetPrefix, RHS.Name);
498             });
499   Targets.push_back({"", 0, 0});
500   for (size_t I = 0, E = Intrinsics.size(); I < E; ++I)
501     if (Intrinsics[I].TargetPrefix != Targets.back().Name) {
502       Targets.back().Count = I - Targets.back().Offset;
503       Targets.push_back({Intrinsics[I].TargetPrefix, I, 0});
504     }
505   Targets.back().Count = Intrinsics.size() - Targets.back().Offset;
506 }
507
508 CodeGenIntrinsic::CodeGenIntrinsic(Record *R) {
509   TheDef = R;
510   std::string DefName = R->getName();
511   ModRef = ReadWriteMem;
512   isOverloaded = false;
513   isCommutative = false;
514   canThrow = false;
515   isNoReturn = false;
516   isNoDuplicate = false;
517   isConvergent = false;
518
519   if (DefName.size() <= 4 ||
520       std::string(DefName.begin(), DefName.begin() + 4) != "int_")
521     PrintFatalError("Intrinsic '" + DefName + "' does not start with 'int_'!");
522
523   EnumName = std::string(DefName.begin()+4, DefName.end());
524
525   if (R->getValue("GCCBuiltinName"))  // Ignore a missing GCCBuiltinName field.
526     GCCBuiltinName = R->getValueAsString("GCCBuiltinName");
527   if (R->getValue("MSBuiltinName"))   // Ignore a missing MSBuiltinName field.
528     MSBuiltinName = R->getValueAsString("MSBuiltinName");
529
530   TargetPrefix = R->getValueAsString("TargetPrefix");
531   Name = R->getValueAsString("LLVMName");
532
533   if (Name == "") {
534     // If an explicit name isn't specified, derive one from the DefName.
535     Name = "llvm.";
536
537     for (unsigned i = 0, e = EnumName.size(); i != e; ++i)
538       Name += (EnumName[i] == '_') ? '.' : EnumName[i];
539   } else {
540     // Verify it starts with "llvm.".
541     if (Name.size() <= 5 ||
542         std::string(Name.begin(), Name.begin() + 5) != "llvm.")
543       PrintFatalError("Intrinsic '" + DefName + "'s name does not start with 'llvm.'!");
544   }
545
546   // If TargetPrefix is specified, make sure that Name starts with
547   // "llvm.<targetprefix>.".
548   if (!TargetPrefix.empty()) {
549     if (Name.size() < 6+TargetPrefix.size() ||
550         std::string(Name.begin() + 5, Name.begin() + 6 + TargetPrefix.size())
551         != (TargetPrefix + "."))
552       PrintFatalError("Intrinsic '" + DefName + "' does not start with 'llvm." +
553         TargetPrefix + ".'!");
554   }
555
556   // Parse the list of return types.
557   std::vector<MVT::SimpleValueType> OverloadedVTs;
558   ListInit *TypeList = R->getValueAsListInit("RetTypes");
559   for (unsigned i = 0, e = TypeList->size(); i != e; ++i) {
560     Record *TyEl = TypeList->getElementAsRecord(i);
561     assert(TyEl->isSubClassOf("LLVMType") && "Expected a type!");
562     MVT::SimpleValueType VT;
563     if (TyEl->isSubClassOf("LLVMMatchType")) {
564       unsigned MatchTy = TyEl->getValueAsInt("Number");
565       assert(MatchTy < OverloadedVTs.size() &&
566              "Invalid matching number!");
567       VT = OverloadedVTs[MatchTy];
568       // It only makes sense to use the extended and truncated vector element
569       // variants with iAny types; otherwise, if the intrinsic is not
570       // overloaded, all the types can be specified directly.
571       assert(((!TyEl->isSubClassOf("LLVMExtendedType") &&
572                !TyEl->isSubClassOf("LLVMTruncatedType")) ||
573               VT == MVT::iAny || VT == MVT::vAny) &&
574              "Expected iAny or vAny type");
575     } else {
576       VT = getValueType(TyEl->getValueAsDef("VT"));
577     }
578     if (MVT(VT).isOverloaded()) {
579       OverloadedVTs.push_back(VT);
580       isOverloaded = true;
581     }
582
583     // Reject invalid types.
584     if (VT == MVT::isVoid)
585       PrintFatalError("Intrinsic '" + DefName + " has void in result type list!");
586
587     IS.RetVTs.push_back(VT);
588     IS.RetTypeDefs.push_back(TyEl);
589   }
590
591   // Parse the list of parameter types.
592   TypeList = R->getValueAsListInit("ParamTypes");
593   for (unsigned i = 0, e = TypeList->size(); i != e; ++i) {
594     Record *TyEl = TypeList->getElementAsRecord(i);
595     assert(TyEl->isSubClassOf("LLVMType") && "Expected a type!");
596     MVT::SimpleValueType VT;
597     if (TyEl->isSubClassOf("LLVMMatchType")) {
598       unsigned MatchTy = TyEl->getValueAsInt("Number");
599       assert(MatchTy < OverloadedVTs.size() &&
600              "Invalid matching number!");
601       VT = OverloadedVTs[MatchTy];
602       // It only makes sense to use the extended and truncated vector element
603       // variants with iAny types; otherwise, if the intrinsic is not
604       // overloaded, all the types can be specified directly.
605       assert(((!TyEl->isSubClassOf("LLVMExtendedType") &&
606                !TyEl->isSubClassOf("LLVMTruncatedType") &&
607                !TyEl->isSubClassOf("LLVMVectorSameWidth")) ||
608               VT == MVT::iAny || VT == MVT::vAny) &&
609              "Expected iAny or vAny type");
610     } else
611       VT = getValueType(TyEl->getValueAsDef("VT"));
612
613     if (MVT(VT).isOverloaded()) {
614       OverloadedVTs.push_back(VT);
615       isOverloaded = true;
616     }
617
618     // Reject invalid types.
619     if (VT == MVT::isVoid && i != e-1 /*void at end means varargs*/)
620       PrintFatalError("Intrinsic '" + DefName + " has void in result type list!");
621
622     IS.ParamVTs.push_back(VT);
623     IS.ParamTypeDefs.push_back(TyEl);
624   }
625
626   // Parse the intrinsic properties.
627   ListInit *PropList = R->getValueAsListInit("IntrProperties");
628   for (unsigned i = 0, e = PropList->size(); i != e; ++i) {
629     Record *Property = PropList->getElementAsRecord(i);
630     assert(Property->isSubClassOf("IntrinsicProperty") &&
631            "Expected a property!");
632
633     if (Property->getName() == "IntrNoMem")
634       ModRef = NoMem;
635     else if (Property->getName() == "IntrReadMem")
636       ModRef = ModRefBehavior(ModRef & ~MR_Mod);
637     else if (Property->getName() == "IntrWriteMem")
638       ModRef = ModRefBehavior(ModRef & ~MR_Ref);
639     else if (Property->getName() == "IntrArgMemOnly")
640       ModRef = ModRefBehavior((ModRef & ~MR_Anywhere) | MR_ArgMem);
641     else if (Property->getName() == "IntrInaccessibleMemOnly")
642       ModRef = ModRefBehavior((ModRef & ~MR_Anywhere) | MR_InaccessibleMem);
643     else if (Property->getName() == "IntrInaccessibleMemOrArgMemOnly")
644       ModRef = ModRefBehavior((ModRef & ~MR_Anywhere) | MR_ArgMem |
645                               MR_InaccessibleMem);
646     else if (Property->getName() == "Commutative")
647       isCommutative = true;
648     else if (Property->getName() == "Throws")
649       canThrow = true;
650     else if (Property->getName() == "IntrNoDuplicate")
651       isNoDuplicate = true;
652     else if (Property->getName() == "IntrConvergent")
653       isConvergent = true;
654     else if (Property->getName() == "IntrNoReturn")
655       isNoReturn = true;
656     else if (Property->isSubClassOf("NoCapture")) {
657       unsigned ArgNo = Property->getValueAsInt("ArgNo");
658       ArgumentAttributes.push_back(std::make_pair(ArgNo, NoCapture));
659     } else if (Property->isSubClassOf("Returned")) {
660       unsigned ArgNo = Property->getValueAsInt("ArgNo");
661       ArgumentAttributes.push_back(std::make_pair(ArgNo, Returned));
662     } else if (Property->isSubClassOf("ReadOnly")) {
663       unsigned ArgNo = Property->getValueAsInt("ArgNo");
664       ArgumentAttributes.push_back(std::make_pair(ArgNo, ReadOnly));
665     } else if (Property->isSubClassOf("WriteOnly")) {
666       unsigned ArgNo = Property->getValueAsInt("ArgNo");
667       ArgumentAttributes.push_back(std::make_pair(ArgNo, WriteOnly));
668     } else if (Property->isSubClassOf("ReadNone")) {
669       unsigned ArgNo = Property->getValueAsInt("ArgNo");
670       ArgumentAttributes.push_back(std::make_pair(ArgNo, ReadNone));
671     } else
672       llvm_unreachable("Unknown property!");
673   }
674
675   // Sort the argument attributes for later benefit.
676   std::sort(ArgumentAttributes.begin(), ArgumentAttributes.end());
677 }