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