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