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