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