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