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 "CodeGenInstruction.h"
18 #include "CodeGenIntrinsics.h"
19 #include "CodeGenSchedule.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/Support/CommandLine.h"
22 #include "llvm/TableGen/Error.h"
23 #include "llvm/TableGen/Record.h"
24 #include <algorithm>
25 using namespace llvm;
26 
27 cl::OptionCategory AsmParserCat("Options for -gen-asm-parser");
28 cl::OptionCategory AsmWriterCat("Options for -gen-asm-writer");
29 
30 static cl::opt<unsigned>
31     AsmParserNum("asmparsernum", cl::init(0),
32                  cl::desc("Make -gen-asm-parser emit assembly parser #N"),
33                  cl::cat(AsmParserCat));
34 
35 static cl::opt<unsigned>
36     AsmWriterNum("asmwriternum", cl::init(0),
37                  cl::desc("Make -gen-asm-writer emit assembly writer #N"),
38                  cl::cat(AsmWriterCat));
39 
40 /// getValueType - Return the MVT::SimpleValueType that the specified TableGen
41 /// record corresponds to.
42 MVT::SimpleValueType llvm::getValueType(Record *Rec) {
43   return (MVT::SimpleValueType)Rec->getValueAsInt("Value");
44 }
45 
46 StringRef llvm::getName(MVT::SimpleValueType T) {
47   switch (T) {
48   case MVT::Other:   return "UNKNOWN";
49   case MVT::iPTR:    return "TLI.getPointerTy()";
50   case MVT::iPTRAny: return "TLI.getPointerTy()";
51   default: return getEnumName(T);
52   }
53 }
54 
55 StringRef llvm::getEnumName(MVT::SimpleValueType T) {
56   // clang-format off
57   switch (T) {
58   case MVT::Other:    return "MVT::Other";
59   case MVT::i1:       return "MVT::i1";
60   case MVT::i2:       return "MVT::i2";
61   case MVT::i4:       return "MVT::i4";
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::bf16:     return "MVT::bf16";
73   case MVT::f32:      return "MVT::f32";
74   case MVT::f64:      return "MVT::f64";
75   case MVT::f80:      return "MVT::f80";
76   case MVT::f128:     return "MVT::f128";
77   case MVT::ppcf128:  return "MVT::ppcf128";
78   case MVT::x86mmx:   return "MVT::x86mmx";
79   case MVT::x86amx:   return "MVT::x86amx";
80   case MVT::i64x8:    return "MVT::i64x8";
81   case MVT::Glue:     return "MVT::Glue";
82   case MVT::isVoid:   return "MVT::isVoid";
83   case MVT::v1i1:     return "MVT::v1i1";
84   case MVT::v2i1:     return "MVT::v2i1";
85   case MVT::v4i1:     return "MVT::v4i1";
86   case MVT::v8i1:     return "MVT::v8i1";
87   case MVT::v16i1:    return "MVT::v16i1";
88   case MVT::v32i1:    return "MVT::v32i1";
89   case MVT::v64i1:    return "MVT::v64i1";
90   case MVT::v128i1:   return "MVT::v128i1";
91   case MVT::v256i1:   return "MVT::v256i1";
92   case MVT::v512i1:   return "MVT::v512i1";
93   case MVT::v1024i1:  return "MVT::v1024i1";
94   case MVT::v128i2:   return "MVT::v128i2";
95   case MVT::v64i4:    return "MVT::v64i4";
96   case MVT::v1i8:     return "MVT::v1i8";
97   case MVT::v2i8:     return "MVT::v2i8";
98   case MVT::v4i8:     return "MVT::v4i8";
99   case MVT::v8i8:     return "MVT::v8i8";
100   case MVT::v16i8:    return "MVT::v16i8";
101   case MVT::v32i8:    return "MVT::v32i8";
102   case MVT::v64i8:    return "MVT::v64i8";
103   case MVT::v128i8:   return "MVT::v128i8";
104   case MVT::v256i8:   return "MVT::v256i8";
105   case MVT::v512i8:   return "MVT::v512i8";
106   case MVT::v1024i8:  return "MVT::v1024i8";
107   case MVT::v1i16:    return "MVT::v1i16";
108   case MVT::v2i16:    return "MVT::v2i16";
109   case MVT::v3i16:    return "MVT::v3i16";
110   case MVT::v4i16:    return "MVT::v4i16";
111   case MVT::v8i16:    return "MVT::v8i16";
112   case MVT::v16i16:   return "MVT::v16i16";
113   case MVT::v32i16:   return "MVT::v32i16";
114   case MVT::v64i16:   return "MVT::v64i16";
115   case MVT::v128i16:  return "MVT::v128i16";
116   case MVT::v256i16:  return "MVT::v256i16";
117   case MVT::v512i16:  return "MVT::v512i16";
118   case MVT::v1i32:    return "MVT::v1i32";
119   case MVT::v2i32:    return "MVT::v2i32";
120   case MVT::v3i32:    return "MVT::v3i32";
121   case MVT::v4i32:    return "MVT::v4i32";
122   case MVT::v5i32:    return "MVT::v5i32";
123   case MVT::v6i32:    return "MVT::v6i32";
124   case MVT::v7i32:    return "MVT::v7i32";
125   case MVT::v8i32:    return "MVT::v8i32";
126   case MVT::v16i32:   return "MVT::v16i32";
127   case MVT::v32i32:   return "MVT::v32i32";
128   case MVT::v64i32:   return "MVT::v64i32";
129   case MVT::v128i32:  return "MVT::v128i32";
130   case MVT::v256i32:  return "MVT::v256i32";
131   case MVT::v512i32:  return "MVT::v512i32";
132   case MVT::v1024i32: return "MVT::v1024i32";
133   case MVT::v2048i32: return "MVT::v2048i32";
134   case MVT::v1i64:    return "MVT::v1i64";
135   case MVT::v2i64:    return "MVT::v2i64";
136   case MVT::v3i64:    return "MVT::v3i64";
137   case MVT::v4i64:    return "MVT::v4i64";
138   case MVT::v8i64:    return "MVT::v8i64";
139   case MVT::v16i64:   return "MVT::v16i64";
140   case MVT::v32i64:   return "MVT::v32i64";
141   case MVT::v64i64:   return "MVT::v64i64";
142   case MVT::v128i64:  return "MVT::v128i64";
143   case MVT::v256i64:  return "MVT::v256i64";
144   case MVT::v1i128:   return "MVT::v1i128";
145   case MVT::v1f16:    return "MVT::v1f16";
146   case MVT::v2f16:    return "MVT::v2f16";
147   case MVT::v3f16:    return "MVT::v3f16";
148   case MVT::v4f16:    return "MVT::v4f16";
149   case MVT::v8f16:    return "MVT::v8f16";
150   case MVT::v16f16:   return "MVT::v16f16";
151   case MVT::v32f16:   return "MVT::v32f16";
152   case MVT::v64f16:   return "MVT::v64f16";
153   case MVT::v128f16:  return "MVT::v128f16";
154   case MVT::v256f16:  return "MVT::v256f16";
155   case MVT::v512f16:  return "MVT::v512f16";
156   case MVT::v2bf16:   return "MVT::v2bf16";
157   case MVT::v3bf16:   return "MVT::v3bf16";
158   case MVT::v4bf16:   return "MVT::v4bf16";
159   case MVT::v8bf16:   return "MVT::v8bf16";
160   case MVT::v16bf16:  return "MVT::v16bf16";
161   case MVT::v32bf16:  return "MVT::v32bf16";
162   case MVT::v64bf16:  return "MVT::v64bf16";
163   case MVT::v128bf16: return "MVT::v128bf16";
164   case MVT::v1f32:    return "MVT::v1f32";
165   case MVT::v2f32:    return "MVT::v2f32";
166   case MVT::v3f32:    return "MVT::v3f32";
167   case MVT::v4f32:    return "MVT::v4f32";
168   case MVT::v5f32:    return "MVT::v5f32";
169   case MVT::v6f32:    return "MVT::v6f32";
170   case MVT::v7f32:    return "MVT::v7f32";
171   case MVT::v8f32:    return "MVT::v8f32";
172   case MVT::v16f32:   return "MVT::v16f32";
173   case MVT::v32f32:   return "MVT::v32f32";
174   case MVT::v64f32:   return "MVT::v64f32";
175   case MVT::v128f32:  return "MVT::v128f32";
176   case MVT::v256f32:  return "MVT::v256f32";
177   case MVT::v512f32:  return "MVT::v512f32";
178   case MVT::v1024f32: return "MVT::v1024f32";
179   case MVT::v2048f32: return "MVT::v2048f32";
180   case MVT::v1f64:    return "MVT::v1f64";
181   case MVT::v2f64:    return "MVT::v2f64";
182   case MVT::v3f64:    return "MVT::v3f64";
183   case MVT::v4f64:    return "MVT::v4f64";
184   case MVT::v8f64:    return "MVT::v8f64";
185   case MVT::v16f64:   return "MVT::v16f64";
186   case MVT::v32f64:   return "MVT::v32f64";
187   case MVT::v64f64:   return "MVT::v64f64";
188   case MVT::v128f64:  return "MVT::v128f64";
189   case MVT::v256f64:  return "MVT::v256f64";
190   case MVT::nxv1i1:   return "MVT::nxv1i1";
191   case MVT::nxv2i1:   return "MVT::nxv2i1";
192   case MVT::nxv4i1:   return "MVT::nxv4i1";
193   case MVT::nxv8i1:   return "MVT::nxv8i1";
194   case MVT::nxv16i1:  return "MVT::nxv16i1";
195   case MVT::nxv32i1:  return "MVT::nxv32i1";
196   case MVT::nxv64i1:  return "MVT::nxv64i1";
197   case MVT::nxv1i8:   return "MVT::nxv1i8";
198   case MVT::nxv2i8:   return "MVT::nxv2i8";
199   case MVT::nxv4i8:   return "MVT::nxv4i8";
200   case MVT::nxv8i8:   return "MVT::nxv8i8";
201   case MVT::nxv16i8:  return "MVT::nxv16i8";
202   case MVT::nxv32i8:  return "MVT::nxv32i8";
203   case MVT::nxv64i8:  return "MVT::nxv64i8";
204   case MVT::nxv1i16:  return "MVT::nxv1i16";
205   case MVT::nxv2i16:  return "MVT::nxv2i16";
206   case MVT::nxv4i16:  return "MVT::nxv4i16";
207   case MVT::nxv8i16:  return "MVT::nxv8i16";
208   case MVT::nxv16i16: return "MVT::nxv16i16";
209   case MVT::nxv32i16: return "MVT::nxv32i16";
210   case MVT::nxv1i32:  return "MVT::nxv1i32";
211   case MVT::nxv2i32:  return "MVT::nxv2i32";
212   case MVT::nxv4i32:  return "MVT::nxv4i32";
213   case MVT::nxv8i32:  return "MVT::nxv8i32";
214   case MVT::nxv16i32: return "MVT::nxv16i32";
215   case MVT::nxv32i32: return "MVT::nxv32i32";
216   case MVT::nxv1i64:  return "MVT::nxv1i64";
217   case MVT::nxv2i64:  return "MVT::nxv2i64";
218   case MVT::nxv4i64:  return "MVT::nxv4i64";
219   case MVT::nxv8i64:  return "MVT::nxv8i64";
220   case MVT::nxv16i64: return "MVT::nxv16i64";
221   case MVT::nxv32i64: return "MVT::nxv32i64";
222   case MVT::nxv1f16:  return "MVT::nxv1f16";
223   case MVT::nxv2f16:  return "MVT::nxv2f16";
224   case MVT::nxv4f16:  return "MVT::nxv4f16";
225   case MVT::nxv8f16:  return "MVT::nxv8f16";
226   case MVT::nxv16f16: return "MVT::nxv16f16";
227   case MVT::nxv32f16: return "MVT::nxv32f16";
228   case MVT::nxv1bf16:  return "MVT::nxv1bf16";
229   case MVT::nxv2bf16:  return "MVT::nxv2bf16";
230   case MVT::nxv4bf16:  return "MVT::nxv4bf16";
231   case MVT::nxv8bf16:  return "MVT::nxv8bf16";
232   case MVT::nxv1f32:   return "MVT::nxv1f32";
233   case MVT::nxv2f32:   return "MVT::nxv2f32";
234   case MVT::nxv4f32:   return "MVT::nxv4f32";
235   case MVT::nxv8f32:   return "MVT::nxv8f32";
236   case MVT::nxv16f32:  return "MVT::nxv16f32";
237   case MVT::nxv1f64:   return "MVT::nxv1f64";
238   case MVT::nxv2f64:   return "MVT::nxv2f64";
239   case MVT::nxv4f64:   return "MVT::nxv4f64";
240   case MVT::nxv8f64:   return "MVT::nxv8f64";
241   case MVT::token:     return "MVT::token";
242   case MVT::Metadata:  return "MVT::Metadata";
243   case MVT::iPTR:      return "MVT::iPTR";
244   case MVT::iPTRAny:   return "MVT::iPTRAny";
245   case MVT::Untyped:   return "MVT::Untyped";
246   case MVT::funcref:   return "MVT::funcref";
247   case MVT::externref: return "MVT::externref";
248   default: llvm_unreachable("ILLEGAL VALUE TYPE!");
249   }
250   // clang-format on
251 }
252 
253 /// getQualifiedName - Return the name of the specified record, with a
254 /// namespace qualifier if the record contains one.
255 ///
256 std::string llvm::getQualifiedName(const Record *R) {
257   std::string Namespace;
258   if (R->getValue("Namespace"))
259     Namespace = std::string(R->getValueAsString("Namespace"));
260   if (Namespace.empty())
261     return std::string(R->getName());
262   return Namespace + "::" + R->getName().str();
263 }
264 
265 
266 /// getTarget - Return the current instance of the Target class.
267 ///
268 CodeGenTarget::CodeGenTarget(RecordKeeper &records)
269   : Records(records), CGH(records) {
270   std::vector<Record*> Targets = Records.getAllDerivedDefinitions("Target");
271   if (Targets.size() == 0)
272     PrintFatalError("No 'Target' subclasses defined!");
273   if (Targets.size() != 1)
274     PrintFatalError("Multiple subclasses of Target defined!");
275   TargetRec = Targets[0];
276 }
277 
278 CodeGenTarget::~CodeGenTarget() {
279 }
280 
281 StringRef CodeGenTarget::getName() const { return TargetRec->getName(); }
282 
283 /// getInstNamespace - Find and return the target machine's instruction
284 /// namespace. The namespace is cached because it is requested multiple times.
285 StringRef CodeGenTarget::getInstNamespace() const {
286   if (InstNamespace.empty()) {
287     for (const CodeGenInstruction *Inst : getInstructionsByEnumValue()) {
288       // We are not interested in the "TargetOpcode" namespace.
289       if (Inst->Namespace != "TargetOpcode") {
290         InstNamespace = Inst->Namespace;
291         break;
292       }
293     }
294   }
295 
296   return InstNamespace;
297 }
298 
299 StringRef CodeGenTarget::getRegNamespace() const {
300   auto &RegClasses = RegBank->getRegClasses();
301   return RegClasses.size() > 0 ? RegClasses.front().Namespace : "";
302 }
303 
304 Record *CodeGenTarget::getInstructionSet() const {
305   return TargetRec->getValueAsDef("InstructionSet");
306 }
307 
308 bool CodeGenTarget::getAllowRegisterRenaming() const {
309   return TargetRec->getValueAsInt("AllowRegisterRenaming");
310 }
311 
312 /// getAsmParser - Return the AssemblyParser definition for this target.
313 ///
314 Record *CodeGenTarget::getAsmParser() const {
315   std::vector<Record*> LI = TargetRec->getValueAsListOfDefs("AssemblyParsers");
316   if (AsmParserNum >= LI.size())
317     PrintFatalError("Target does not have an AsmParser #" +
318                     Twine(AsmParserNum) + "!");
319   return LI[AsmParserNum];
320 }
321 
322 /// getAsmParserVariant - Return the AssemblyParserVariant definition for
323 /// this target.
324 ///
325 Record *CodeGenTarget::getAsmParserVariant(unsigned i) const {
326   std::vector<Record*> LI =
327     TargetRec->getValueAsListOfDefs("AssemblyParserVariants");
328   if (i >= LI.size())
329     PrintFatalError("Target does not have an AsmParserVariant #" + Twine(i) +
330                     "!");
331   return LI[i];
332 }
333 
334 /// getAsmParserVariantCount - Return the AssemblyParserVariant definition
335 /// available for this target.
336 ///
337 unsigned CodeGenTarget::getAsmParserVariantCount() const {
338   std::vector<Record*> LI =
339     TargetRec->getValueAsListOfDefs("AssemblyParserVariants");
340   return LI.size();
341 }
342 
343 /// getAsmWriter - Return the AssemblyWriter definition for this target.
344 ///
345 Record *CodeGenTarget::getAsmWriter() const {
346   std::vector<Record*> LI = TargetRec->getValueAsListOfDefs("AssemblyWriters");
347   if (AsmWriterNum >= LI.size())
348     PrintFatalError("Target does not have an AsmWriter #" +
349                     Twine(AsmWriterNum) + "!");
350   return LI[AsmWriterNum];
351 }
352 
353 CodeGenRegBank &CodeGenTarget::getRegBank() const {
354   if (!RegBank)
355     RegBank = std::make_unique<CodeGenRegBank>(Records, getHwModes());
356   return *RegBank;
357 }
358 
359 Optional<CodeGenRegisterClass *>
360 CodeGenTarget::getSuperRegForSubReg(const ValueTypeByHwMode &ValueTy,
361                                     CodeGenRegBank &RegBank,
362                                     const CodeGenSubRegIndex *SubIdx,
363                                     bool MustBeAllocatable) const {
364   std::vector<CodeGenRegisterClass *> Candidates;
365   auto &RegClasses = RegBank.getRegClasses();
366 
367   // Try to find a register class which supports ValueTy, and also contains
368   // SubIdx.
369   for (CodeGenRegisterClass &RC : RegClasses) {
370     // Is there a subclass of this class which contains this subregister index?
371     CodeGenRegisterClass *SubClassWithSubReg = RC.getSubClassWithSubReg(SubIdx);
372     if (!SubClassWithSubReg)
373       continue;
374 
375     // We have a class. Check if it supports this value type.
376     if (!llvm::is_contained(SubClassWithSubReg->VTs, ValueTy))
377       continue;
378 
379     // If necessary, check that it is allocatable.
380     if (MustBeAllocatable && !SubClassWithSubReg->Allocatable)
381       continue;
382 
383     // We have a register class which supports both the value type and
384     // subregister index. Remember it.
385     Candidates.push_back(SubClassWithSubReg);
386   }
387 
388   // If we didn't find anything, we're done.
389   if (Candidates.empty())
390     return None;
391 
392   // Find and return the largest of our candidate classes.
393   llvm::stable_sort(Candidates, [&](const CodeGenRegisterClass *A,
394                                     const CodeGenRegisterClass *B) {
395     if (A->getMembers().size() > B->getMembers().size())
396       return true;
397 
398     if (A->getMembers().size() < B->getMembers().size())
399       return false;
400 
401     // Order by name as a tie-breaker.
402     return StringRef(A->getName()) < B->getName();
403   });
404 
405   return Candidates[0];
406 }
407 
408 void CodeGenTarget::ReadRegAltNameIndices() const {
409   RegAltNameIndices = Records.getAllDerivedDefinitions("RegAltNameIndex");
410   llvm::sort(RegAltNameIndices, LessRecord());
411 }
412 
413 /// getRegisterByName - If there is a register with the specific AsmName,
414 /// return it.
415 const CodeGenRegister *CodeGenTarget::getRegisterByName(StringRef Name) const {
416   return getRegBank().getRegistersByName().lookup(Name);
417 }
418 
419 std::vector<ValueTypeByHwMode> CodeGenTarget::getRegisterVTs(Record *R)
420       const {
421   const CodeGenRegister *Reg = getRegBank().getReg(R);
422   std::vector<ValueTypeByHwMode> Result;
423   for (const auto &RC : getRegBank().getRegClasses()) {
424     if (RC.contains(Reg)) {
425       ArrayRef<ValueTypeByHwMode> InVTs = RC.getValueTypes();
426       llvm::append_range(Result, InVTs);
427     }
428   }
429 
430   // Remove duplicates.
431   llvm::sort(Result);
432   Result.erase(std::unique(Result.begin(), Result.end()), Result.end());
433   return Result;
434 }
435 
436 
437 void CodeGenTarget::ReadLegalValueTypes() const {
438   for (const auto &RC : getRegBank().getRegClasses())
439     llvm::append_range(LegalValueTypes, RC.VTs);
440 
441   // Remove duplicates.
442   llvm::sort(LegalValueTypes);
443   LegalValueTypes.erase(std::unique(LegalValueTypes.begin(),
444                                     LegalValueTypes.end()),
445                         LegalValueTypes.end());
446 }
447 
448 CodeGenSchedModels &CodeGenTarget::getSchedModels() const {
449   if (!SchedModels)
450     SchedModels = std::make_unique<CodeGenSchedModels>(Records, *this);
451   return *SchedModels;
452 }
453 
454 void CodeGenTarget::ReadInstructions() const {
455   std::vector<Record*> Insts = Records.getAllDerivedDefinitions("Instruction");
456   if (Insts.size() <= 2)
457     PrintFatalError("No 'Instruction' subclasses defined!");
458 
459   // Parse the instructions defined in the .td file.
460   for (unsigned i = 0, e = Insts.size(); i != e; ++i)
461     Instructions[Insts[i]] = std::make_unique<CodeGenInstruction>(Insts[i]);
462 }
463 
464 static const CodeGenInstruction *
465 GetInstByName(const char *Name,
466               const DenseMap<const Record*,
467                              std::unique_ptr<CodeGenInstruction>> &Insts,
468               RecordKeeper &Records) {
469   const Record *Rec = Records.getDef(Name);
470 
471   const auto I = Insts.find(Rec);
472   if (!Rec || I == Insts.end())
473     PrintFatalError(Twine("Could not find '") + Name + "' instruction!");
474   return I->second.get();
475 }
476 
477 static const char *const FixedInstrs[] = {
478 #define HANDLE_TARGET_OPCODE(OPC) #OPC,
479 #include "llvm/Support/TargetOpcodes.def"
480     nullptr};
481 
482 unsigned CodeGenTarget::getNumFixedInstructions() {
483   return array_lengthof(FixedInstrs) - 1;
484 }
485 
486 /// Return all of the instructions defined by the target, ordered by
487 /// their enum value.
488 void CodeGenTarget::ComputeInstrsByEnum() const {
489   const auto &Insts = getInstructions();
490   for (const char *const *p = FixedInstrs; *p; ++p) {
491     const CodeGenInstruction *Instr = GetInstByName(*p, Insts, Records);
492     assert(Instr && "Missing target independent instruction");
493     assert(Instr->Namespace == "TargetOpcode" && "Bad namespace");
494     InstrsByEnum.push_back(Instr);
495   }
496   unsigned EndOfPredefines = InstrsByEnum.size();
497   assert(EndOfPredefines == getNumFixedInstructions() &&
498          "Missing generic opcode");
499 
500   for (const auto &I : Insts) {
501     const CodeGenInstruction *CGI = I.second.get();
502     if (CGI->Namespace != "TargetOpcode") {
503       InstrsByEnum.push_back(CGI);
504       if (CGI->TheDef->getValueAsBit("isPseudo"))
505         ++NumPseudoInstructions;
506     }
507   }
508 
509   assert(InstrsByEnum.size() == Insts.size() && "Missing predefined instr");
510 
511   // All of the instructions are now in random order based on the map iteration.
512   llvm::sort(
513       InstrsByEnum.begin() + EndOfPredefines, InstrsByEnum.end(),
514       [](const CodeGenInstruction *Rec1, const CodeGenInstruction *Rec2) {
515         const auto &D1 = *Rec1->TheDef;
516         const auto &D2 = *Rec2->TheDef;
517         return std::make_tuple(!D1.getValueAsBit("isPseudo"), D1.getName()) <
518                std::make_tuple(!D2.getValueAsBit("isPseudo"), D2.getName());
519       });
520 }
521 
522 
523 /// isLittleEndianEncoding - Return whether this target encodes its instruction
524 /// in little-endian format, i.e. bits laid out in the order [0..n]
525 ///
526 bool CodeGenTarget::isLittleEndianEncoding() const {
527   return getInstructionSet()->getValueAsBit("isLittleEndianEncoding");
528 }
529 
530 /// reverseBitsForLittleEndianEncoding - For little-endian instruction bit
531 /// encodings, reverse the bit order of all instructions.
532 void CodeGenTarget::reverseBitsForLittleEndianEncoding() {
533   if (!isLittleEndianEncoding())
534     return;
535 
536   std::vector<Record *> Insts =
537       Records.getAllDerivedDefinitions("InstructionEncoding");
538   for (Record *R : Insts) {
539     if (R->getValueAsString("Namespace") == "TargetOpcode" ||
540         R->getValueAsBit("isPseudo"))
541       continue;
542 
543     BitsInit *BI = R->getValueAsBitsInit("Inst");
544 
545     unsigned numBits = BI->getNumBits();
546 
547     SmallVector<Init *, 16> NewBits(numBits);
548 
549     for (unsigned bit = 0, end = numBits / 2; bit != end; ++bit) {
550       unsigned bitSwapIdx = numBits - bit - 1;
551       Init *OrigBit = BI->getBit(bit);
552       Init *BitSwap = BI->getBit(bitSwapIdx);
553       NewBits[bit]        = BitSwap;
554       NewBits[bitSwapIdx] = OrigBit;
555     }
556     if (numBits % 2) {
557       unsigned middle = (numBits + 1) / 2;
558       NewBits[middle] = BI->getBit(middle);
559     }
560 
561     BitsInit *NewBI = BitsInit::get(Records, NewBits);
562 
563     // Update the bits in reversed order so that emitInstrOpBits will get the
564     // correct endianness.
565     R->getValue("Inst")->setValue(NewBI);
566   }
567 }
568 
569 /// guessInstructionProperties - Return true if it's OK to guess instruction
570 /// properties instead of raising an error.
571 ///
572 /// This is configurable as a temporary migration aid. It will eventually be
573 /// permanently false.
574 bool CodeGenTarget::guessInstructionProperties() const {
575   return getInstructionSet()->getValueAsBit("guessInstructionProperties");
576 }
577 
578 //===----------------------------------------------------------------------===//
579 // ComplexPattern implementation
580 //
581 ComplexPattern::ComplexPattern(Record *R) {
582   Ty          = R->getValueAsDef("Ty");
583   NumOperands = R->getValueAsInt("NumOperands");
584   SelectFunc = std::string(R->getValueAsString("SelectFunc"));
585   RootNodes   = R->getValueAsListOfDefs("RootNodes");
586 
587   // FIXME: This is a hack to statically increase the priority of patterns which
588   // maps a sub-dag to a complex pattern. e.g. favors LEA over ADD. To get best
589   // possible pattern match we'll need to dynamically calculate the complexity
590   // of all patterns a dag can potentially map to.
591   int64_t RawComplexity = R->getValueAsInt("Complexity");
592   if (RawComplexity == -1)
593     Complexity = NumOperands * 3;
594   else
595     Complexity = RawComplexity;
596 
597   // FIXME: Why is this different from parseSDPatternOperatorProperties?
598   // Parse the properties.
599   Properties = 0;
600   std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
601   for (unsigned i = 0, e = PropList.size(); i != e; ++i)
602     if (PropList[i]->getName() == "SDNPHasChain") {
603       Properties |= 1 << SDNPHasChain;
604     } else if (PropList[i]->getName() == "SDNPOptInGlue") {
605       Properties |= 1 << SDNPOptInGlue;
606     } else if (PropList[i]->getName() == "SDNPMayStore") {
607       Properties |= 1 << SDNPMayStore;
608     } else if (PropList[i]->getName() == "SDNPMayLoad") {
609       Properties |= 1 << SDNPMayLoad;
610     } else if (PropList[i]->getName() == "SDNPSideEffect") {
611       Properties |= 1 << SDNPSideEffect;
612     } else if (PropList[i]->getName() == "SDNPMemOperand") {
613       Properties |= 1 << SDNPMemOperand;
614     } else if (PropList[i]->getName() == "SDNPVariadic") {
615       Properties |= 1 << SDNPVariadic;
616     } else if (PropList[i]->getName() == "SDNPWantRoot") {
617       Properties |= 1 << SDNPWantRoot;
618     } else if (PropList[i]->getName() == "SDNPWantParent") {
619       Properties |= 1 << SDNPWantParent;
620     } else {
621       PrintFatalError(R->getLoc(), "Unsupported SD Node property '" +
622                                        PropList[i]->getName() +
623                                        "' on ComplexPattern '" + R->getName() +
624                                        "'!");
625     }
626 }
627 
628 //===----------------------------------------------------------------------===//
629 // CodeGenIntrinsic Implementation
630 //===----------------------------------------------------------------------===//
631 
632 CodeGenIntrinsicTable::CodeGenIntrinsicTable(const RecordKeeper &RC) {
633   std::vector<Record *> IntrProperties =
634       RC.getAllDerivedDefinitions("IntrinsicProperty");
635 
636   std::vector<Record *> DefaultProperties;
637   for (Record *Rec : IntrProperties)
638     if (Rec->getValueAsBit("IsDefault"))
639       DefaultProperties.push_back(Rec);
640 
641   std::vector<Record *> Defs = RC.getAllDerivedDefinitions("Intrinsic");
642   Intrinsics.reserve(Defs.size());
643 
644   for (unsigned I = 0, e = Defs.size(); I != e; ++I)
645     Intrinsics.push_back(CodeGenIntrinsic(Defs[I], DefaultProperties));
646 
647   llvm::sort(Intrinsics,
648              [](const CodeGenIntrinsic &LHS, const CodeGenIntrinsic &RHS) {
649                return std::tie(LHS.TargetPrefix, LHS.Name) <
650                       std::tie(RHS.TargetPrefix, RHS.Name);
651              });
652   Targets.push_back({"", 0, 0});
653   for (size_t I = 0, E = Intrinsics.size(); I < E; ++I)
654     if (Intrinsics[I].TargetPrefix != Targets.back().Name) {
655       Targets.back().Count = I - Targets.back().Offset;
656       Targets.push_back({Intrinsics[I].TargetPrefix, I, 0});
657     }
658   Targets.back().Count = Intrinsics.size() - Targets.back().Offset;
659 }
660 
661 CodeGenIntrinsic::CodeGenIntrinsic(Record *R,
662                                    std::vector<Record *> DefaultProperties) {
663   TheDef = R;
664   std::string DefName = std::string(R->getName());
665   ArrayRef<SMLoc> DefLoc = R->getLoc();
666   ModRef = ReadWriteMem;
667   Properties = 0;
668   isOverloaded = false;
669   isCommutative = false;
670   canThrow = false;
671   isNoReturn = false;
672   isNoCallback = false;
673   isNoSync = false;
674   isNoFree = false;
675   isWillReturn = false;
676   isCold = false;
677   isNoDuplicate = false;
678   isNoMerge = false;
679   isConvergent = false;
680   isSpeculatable = false;
681   hasSideEffects = false;
682 
683   if (DefName.size() <= 4 || DefName.substr(0, 4) != "int_")
684     PrintFatalError(DefLoc,
685                     "Intrinsic '" + DefName + "' does not start with 'int_'!");
686 
687   EnumName = DefName.substr(4);
688 
689   if (R->getValue("GCCBuiltinName"))  // Ignore a missing GCCBuiltinName field.
690     GCCBuiltinName = std::string(R->getValueAsString("GCCBuiltinName"));
691   if (R->getValue("MSBuiltinName"))   // Ignore a missing MSBuiltinName field.
692     MSBuiltinName = std::string(R->getValueAsString("MSBuiltinName"));
693 
694   TargetPrefix = std::string(R->getValueAsString("TargetPrefix"));
695   Name = std::string(R->getValueAsString("LLVMName"));
696 
697   if (Name == "") {
698     // If an explicit name isn't specified, derive one from the DefName.
699     Name = "llvm.";
700 
701     for (unsigned i = 0, e = EnumName.size(); i != e; ++i)
702       Name += (EnumName[i] == '_') ? '.' : EnumName[i];
703   } else {
704     // Verify it starts with "llvm.".
705     if (Name.size() <= 5 || Name.substr(0, 5) != "llvm.")
706       PrintFatalError(DefLoc, "Intrinsic '" + DefName +
707                                   "'s name does not start with 'llvm.'!");
708   }
709 
710   // If TargetPrefix is specified, make sure that Name starts with
711   // "llvm.<targetprefix>.".
712   if (!TargetPrefix.empty()) {
713     if (Name.size() < 6+TargetPrefix.size() ||
714         Name.substr(5, 1 + TargetPrefix.size()) != (TargetPrefix + "."))
715       PrintFatalError(DefLoc, "Intrinsic '" + DefName +
716                                   "' does not start with 'llvm." +
717                                   TargetPrefix + ".'!");
718   }
719 
720   ListInit *RetTypes = R->getValueAsListInit("RetTypes");
721   ListInit *ParamTypes = R->getValueAsListInit("ParamTypes");
722 
723   // First collate a list of overloaded types.
724   std::vector<MVT::SimpleValueType> OverloadedVTs;
725   for (ListInit *TypeList : {RetTypes, ParamTypes}) {
726     for (unsigned i = 0, e = TypeList->size(); i != e; ++i) {
727       Record *TyEl = TypeList->getElementAsRecord(i);
728       assert(TyEl->isSubClassOf("LLVMType") && "Expected a type!");
729 
730       if (TyEl->isSubClassOf("LLVMMatchType"))
731         continue;
732 
733       MVT::SimpleValueType VT = getValueType(TyEl->getValueAsDef("VT"));
734       if (MVT(VT).isOverloaded()) {
735         OverloadedVTs.push_back(VT);
736         isOverloaded = true;
737       }
738     }
739   }
740 
741   // Parse the list of return types.
742   ListInit *TypeList = RetTypes;
743   for (unsigned i = 0, e = TypeList->size(); i != e; ++i) {
744     Record *TyEl = TypeList->getElementAsRecord(i);
745     assert(TyEl->isSubClassOf("LLVMType") && "Expected a type!");
746     MVT::SimpleValueType VT;
747     if (TyEl->isSubClassOf("LLVMMatchType")) {
748       unsigned MatchTy = TyEl->getValueAsInt("Number");
749       assert(MatchTy < OverloadedVTs.size() &&
750              "Invalid matching number!");
751       VT = OverloadedVTs[MatchTy];
752       // It only makes sense to use the extended and truncated vector element
753       // variants with iAny types; otherwise, if the intrinsic is not
754       // overloaded, all the types can be specified directly.
755       assert(((!TyEl->isSubClassOf("LLVMExtendedType") &&
756                !TyEl->isSubClassOf("LLVMTruncatedType")) ||
757               VT == MVT::iAny || VT == MVT::vAny) &&
758              "Expected iAny or vAny type");
759     } else {
760       VT = getValueType(TyEl->getValueAsDef("VT"));
761     }
762 
763     // Reject invalid types.
764     if (VT == MVT::isVoid)
765       PrintFatalError(DefLoc, "Intrinsic '" + DefName +
766                                   " has void in result type list!");
767 
768     IS.RetVTs.push_back(VT);
769     IS.RetTypeDefs.push_back(TyEl);
770   }
771 
772   // Parse the list of parameter types.
773   TypeList = ParamTypes;
774   for (unsigned i = 0, e = TypeList->size(); i != e; ++i) {
775     Record *TyEl = TypeList->getElementAsRecord(i);
776     assert(TyEl->isSubClassOf("LLVMType") && "Expected a type!");
777     MVT::SimpleValueType VT;
778     if (TyEl->isSubClassOf("LLVMMatchType")) {
779       unsigned MatchTy = TyEl->getValueAsInt("Number");
780       if (MatchTy >= OverloadedVTs.size()) {
781         PrintError(R->getLoc(),
782                    "Parameter #" + Twine(i) + " has out of bounds matching "
783                    "number " + Twine(MatchTy));
784         PrintFatalError(DefLoc,
785                         Twine("ParamTypes is ") + TypeList->getAsString());
786       }
787       VT = OverloadedVTs[MatchTy];
788       // It only makes sense to use the extended and truncated vector element
789       // variants with iAny types; otherwise, if the intrinsic is not
790       // overloaded, all the types can be specified directly.
791       assert(((!TyEl->isSubClassOf("LLVMExtendedType") &&
792                !TyEl->isSubClassOf("LLVMTruncatedType")) ||
793               VT == MVT::iAny || VT == MVT::vAny) &&
794              "Expected iAny or vAny type");
795     } else
796       VT = getValueType(TyEl->getValueAsDef("VT"));
797 
798     // Reject invalid types.
799     if (VT == MVT::isVoid && i != e-1 /*void at end means varargs*/)
800       PrintFatalError(DefLoc, "Intrinsic '" + DefName +
801                                   " has void in result type list!");
802 
803     IS.ParamVTs.push_back(VT);
804     IS.ParamTypeDefs.push_back(TyEl);
805   }
806 
807   // Parse the intrinsic properties.
808   ListInit *PropList = R->getValueAsListInit("IntrProperties");
809   for (unsigned i = 0, e = PropList->size(); i != e; ++i) {
810     Record *Property = PropList->getElementAsRecord(i);
811     assert(Property->isSubClassOf("IntrinsicProperty") &&
812            "Expected a property!");
813 
814     setProperty(Property);
815   }
816 
817   // Set default properties to true.
818   setDefaultProperties(R, DefaultProperties);
819 
820   // Also record the SDPatternOperator Properties.
821   Properties = parseSDPatternOperatorProperties(R);
822 
823   // Sort the argument attributes for later benefit.
824   llvm::sort(ArgumentAttributes);
825 }
826 
827 void CodeGenIntrinsic::setDefaultProperties(
828     Record *R, std::vector<Record *> DefaultProperties) {
829   // opt-out of using default attributes.
830   if (R->getValueAsBit("DisableDefaultAttributes"))
831     return;
832 
833   for (Record *Rec : DefaultProperties)
834     setProperty(Rec);
835 }
836 
837 void CodeGenIntrinsic::setProperty(Record *R) {
838   if (R->getName() == "IntrNoMem")
839     ModRef = NoMem;
840   else if (R->getName() == "IntrReadMem") {
841     if (!(ModRef & MR_Ref))
842       PrintFatalError(TheDef->getLoc(),
843                       Twine("IntrReadMem cannot be used after IntrNoMem or "
844                             "IntrWriteMem. Default is ReadWrite"));
845     ModRef = ModRefBehavior(ModRef & ~MR_Mod);
846   } else if (R->getName() == "IntrWriteMem") {
847     if (!(ModRef & MR_Mod))
848       PrintFatalError(TheDef->getLoc(),
849                       Twine("IntrWriteMem cannot be used after IntrNoMem or "
850                             "IntrReadMem. Default is ReadWrite"));
851     ModRef = ModRefBehavior(ModRef & ~MR_Ref);
852   } else if (R->getName() == "IntrArgMemOnly")
853     ModRef = ModRefBehavior((ModRef & ~MR_Anywhere) | MR_ArgMem);
854   else if (R->getName() == "IntrInaccessibleMemOnly")
855     ModRef = ModRefBehavior((ModRef & ~MR_Anywhere) | MR_InaccessibleMem);
856   else if (R->getName() == "IntrInaccessibleMemOrArgMemOnly")
857     ModRef = ModRefBehavior((ModRef & ~MR_Anywhere) | MR_ArgMem |
858                             MR_InaccessibleMem);
859   else if (R->getName() == "Commutative")
860     isCommutative = true;
861   else if (R->getName() == "Throws")
862     canThrow = true;
863   else if (R->getName() == "IntrNoDuplicate")
864     isNoDuplicate = true;
865   else if (R->getName() == "IntrNoMerge")
866     isNoMerge = true;
867   else if (R->getName() == "IntrConvergent")
868     isConvergent = true;
869   else if (R->getName() == "IntrNoReturn")
870     isNoReturn = true;
871   else if (R->getName() == "IntrNoCallback")
872     isNoCallback = true;
873   else if (R->getName() == "IntrNoSync")
874     isNoSync = true;
875   else if (R->getName() == "IntrNoFree")
876     isNoFree = true;
877   else if (R->getName() == "IntrWillReturn")
878     isWillReturn = !isNoReturn;
879   else if (R->getName() == "IntrCold")
880     isCold = true;
881   else if (R->getName() == "IntrSpeculatable")
882     isSpeculatable = true;
883   else if (R->getName() == "IntrHasSideEffects")
884     hasSideEffects = true;
885   else if (R->isSubClassOf("NoCapture")) {
886     unsigned ArgNo = R->getValueAsInt("ArgNo");
887     ArgumentAttributes.emplace_back(ArgNo, NoCapture, 0);
888   } else if (R->isSubClassOf("NoAlias")) {
889     unsigned ArgNo = R->getValueAsInt("ArgNo");
890     ArgumentAttributes.emplace_back(ArgNo, NoAlias, 0);
891   } else if (R->isSubClassOf("NoUndef")) {
892     unsigned ArgNo = R->getValueAsInt("ArgNo");
893     ArgumentAttributes.emplace_back(ArgNo, NoUndef, 0);
894   } else if (R->isSubClassOf("Returned")) {
895     unsigned ArgNo = R->getValueAsInt("ArgNo");
896     ArgumentAttributes.emplace_back(ArgNo, Returned, 0);
897   } else if (R->isSubClassOf("ReadOnly")) {
898     unsigned ArgNo = R->getValueAsInt("ArgNo");
899     ArgumentAttributes.emplace_back(ArgNo, ReadOnly, 0);
900   } else if (R->isSubClassOf("WriteOnly")) {
901     unsigned ArgNo = R->getValueAsInt("ArgNo");
902     ArgumentAttributes.emplace_back(ArgNo, WriteOnly, 0);
903   } else if (R->isSubClassOf("ReadNone")) {
904     unsigned ArgNo = R->getValueAsInt("ArgNo");
905     ArgumentAttributes.emplace_back(ArgNo, ReadNone, 0);
906   } else if (R->isSubClassOf("ImmArg")) {
907     unsigned ArgNo = R->getValueAsInt("ArgNo");
908     ArgumentAttributes.emplace_back(ArgNo, ImmArg, 0);
909   } else if (R->isSubClassOf("Align")) {
910     unsigned ArgNo = R->getValueAsInt("ArgNo");
911     uint64_t Align = R->getValueAsInt("Align");
912     ArgumentAttributes.emplace_back(ArgNo, Alignment, Align);
913   } else
914     llvm_unreachable("Unknown property!");
915 }
916 
917 bool CodeGenIntrinsic::isParamAPointer(unsigned ParamIdx) const {
918   if (ParamIdx >= IS.ParamVTs.size())
919     return false;
920   MVT ParamType = MVT(IS.ParamVTs[ParamIdx]);
921   return ParamType == MVT::iPTR || ParamType == MVT::iPTRAny;
922 }
923 
924 bool CodeGenIntrinsic::isParamImmArg(unsigned ParamIdx) const {
925   // Convert argument index to attribute index starting from `FirstArgIndex`.
926   ArgAttribute Val{ParamIdx + 1, ImmArg, 0};
927   return std::binary_search(ArgumentAttributes.begin(),
928                             ArgumentAttributes.end(), Val);
929 }
930