1 //===- AsmMatcherEmitter.cpp - Generate an assembly matcher ---------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This tablegen backend emits a target specifier matcher for converting parsed 11 // assembly operands in the MCInst structures. It also emits a matcher for 12 // custom operand parsing. 13 // 14 // Converting assembly operands into MCInst structures 15 // --------------------------------------------------- 16 // 17 // The input to the target specific matcher is a list of literal tokens and 18 // operands. The target specific parser should generally eliminate any syntax 19 // which is not relevant for matching; for example, comma tokens should have 20 // already been consumed and eliminated by the parser. Most instructions will 21 // end up with a single literal token (the instruction name) and some number of 22 // operands. 23 // 24 // Some example inputs, for X86: 25 // 'addl' (immediate ...) (register ...) 26 // 'add' (immediate ...) (memory ...) 27 // 'call' '*' %epc 28 // 29 // The assembly matcher is responsible for converting this input into a precise 30 // machine instruction (i.e., an instruction with a well defined encoding). This 31 // mapping has several properties which complicate matching: 32 // 33 // - It may be ambiguous; many architectures can legally encode particular 34 // variants of an instruction in different ways (for example, using a smaller 35 // encoding for small immediates). Such ambiguities should never be 36 // arbitrarily resolved by the assembler, the assembler is always responsible 37 // for choosing the "best" available instruction. 38 // 39 // - It may depend on the subtarget or the assembler context. Instructions 40 // which are invalid for the current mode, but otherwise unambiguous (e.g., 41 // an SSE instruction in a file being assembled for i486) should be accepted 42 // and rejected by the assembler front end. However, if the proper encoding 43 // for an instruction is dependent on the assembler context then the matcher 44 // is responsible for selecting the correct machine instruction for the 45 // current mode. 46 // 47 // The core matching algorithm attempts to exploit the regularity in most 48 // instruction sets to quickly determine the set of possibly matching 49 // instructions, and the simplify the generated code. Additionally, this helps 50 // to ensure that the ambiguities are intentionally resolved by the user. 51 // 52 // The matching is divided into two distinct phases: 53 // 54 // 1. Classification: Each operand is mapped to the unique set which (a) 55 // contains it, and (b) is the largest such subset for which a single 56 // instruction could match all members. 57 // 58 // For register classes, we can generate these subgroups automatically. For 59 // arbitrary operands, we expect the user to define the classes and their 60 // relations to one another (for example, 8-bit signed immediates as a 61 // subset of 32-bit immediates). 62 // 63 // By partitioning the operands in this way, we guarantee that for any 64 // tuple of classes, any single instruction must match either all or none 65 // of the sets of operands which could classify to that tuple. 66 // 67 // In addition, the subset relation amongst classes induces a partial order 68 // on such tuples, which we use to resolve ambiguities. 69 // 70 // 2. The input can now be treated as a tuple of classes (static tokens are 71 // simple singleton sets). Each such tuple should generally map to a single 72 // instruction (we currently ignore cases where this isn't true, whee!!!), 73 // which we can emit a simple matcher for. 74 // 75 // Custom Operand Parsing 76 // ---------------------- 77 // 78 // Some targets need a custom way to parse operands, some specific instructions 79 // can contain arguments that can represent processor flags and other kinds of 80 // identifiers that need to be mapped to specific values in the final encoded 81 // instructions. The target specific custom operand parsing works in the 82 // following way: 83 // 84 // 1. A operand match table is built, each entry contains a mnemonic, an 85 // operand class, a mask for all operand positions for that same 86 // class/mnemonic and target features to be checked while trying to match. 87 // 88 // 2. The operand matcher will try every possible entry with the same 89 // mnemonic and will check if the target feature for this mnemonic also 90 // matches. After that, if the operand to be matched has its index 91 // present in the mask, a successful match occurs. Otherwise, fallback 92 // to the regular operand parsing. 93 // 94 // 3. For a match success, each operand class that has a 'ParserMethod' 95 // becomes part of a switch from where the custom method is called. 96 // 97 //===----------------------------------------------------------------------===// 98 99 #include "CodeGenTarget.h" 100 #include "llvm/ADT/PointerUnion.h" 101 #include "llvm/ADT/STLExtras.h" 102 #include "llvm/ADT/SmallPtrSet.h" 103 #include "llvm/ADT/SmallVector.h" 104 #include "llvm/ADT/StringExtras.h" 105 #include "llvm/Support/CommandLine.h" 106 #include "llvm/Support/Debug.h" 107 #include "llvm/Support/ErrorHandling.h" 108 #include "llvm/TableGen/Error.h" 109 #include "llvm/TableGen/Record.h" 110 #include "llvm/TableGen/StringMatcher.h" 111 #include "llvm/TableGen/StringToOffsetTable.h" 112 #include "llvm/TableGen/TableGenBackend.h" 113 #include <cassert> 114 #include <cctype> 115 #include <forward_list> 116 #include <map> 117 #include <set> 118 119 using namespace llvm; 120 121 #define DEBUG_TYPE "asm-matcher-emitter" 122 123 static cl::opt<std::string> 124 MatchPrefix("match-prefix", cl::init(""), 125 cl::desc("Only match instructions with the given prefix")); 126 127 namespace { 128 class AsmMatcherInfo; 129 struct SubtargetFeatureInfo; 130 131 // Register sets are used as keys in some second-order sets TableGen creates 132 // when generating its data structures. This means that the order of two 133 // RegisterSets can be seen in the outputted AsmMatcher tables occasionally, and 134 // can even affect compiler output (at least seen in diagnostics produced when 135 // all matches fail). So we use a type that sorts them consistently. 136 typedef std::set<Record*, LessRecordByID> RegisterSet; 137 138 class AsmMatcherEmitter { 139 RecordKeeper &Records; 140 public: 141 AsmMatcherEmitter(RecordKeeper &R) : Records(R) {} 142 143 void run(raw_ostream &o); 144 }; 145 146 /// ClassInfo - Helper class for storing the information about a particular 147 /// class of operands which can be matched. 148 struct ClassInfo { 149 enum ClassInfoKind { 150 /// Invalid kind, for use as a sentinel value. 151 Invalid = 0, 152 153 /// The class for a particular token. 154 Token, 155 156 /// The (first) register class, subsequent register classes are 157 /// RegisterClass0+1, and so on. 158 RegisterClass0, 159 160 /// The (first) user defined class, subsequent user defined classes are 161 /// UserClass0+1, and so on. 162 UserClass0 = 1<<16 163 }; 164 165 /// Kind - The class kind, which is either a predefined kind, or (UserClass0 + 166 /// N) for the Nth user defined class. 167 unsigned Kind; 168 169 /// SuperClasses - The super classes of this class. Note that for simplicities 170 /// sake user operands only record their immediate super class, while register 171 /// operands include all superclasses. 172 std::vector<ClassInfo*> SuperClasses; 173 174 /// Name - The full class name, suitable for use in an enum. 175 std::string Name; 176 177 /// ClassName - The unadorned generic name for this class (e.g., Token). 178 std::string ClassName; 179 180 /// ValueName - The name of the value this class represents; for a token this 181 /// is the literal token string, for an operand it is the TableGen class (or 182 /// empty if this is a derived class). 183 std::string ValueName; 184 185 /// PredicateMethod - The name of the operand method to test whether the 186 /// operand matches this class; this is not valid for Token or register kinds. 187 std::string PredicateMethod; 188 189 /// RenderMethod - The name of the operand method to add this operand to an 190 /// MCInst; this is not valid for Token or register kinds. 191 std::string RenderMethod; 192 193 /// ParserMethod - The name of the operand method to do a target specific 194 /// parsing on the operand. 195 std::string ParserMethod; 196 197 /// For register classes: the records for all the registers in this class. 198 RegisterSet Registers; 199 200 /// For custom match classes: the diagnostic kind for when the predicate fails. 201 std::string DiagnosticType; 202 203 /// Is this operand optional and not always required. 204 bool IsOptional; 205 206 /// DefaultMethod - The name of the method that returns the default operand 207 /// for optional operand 208 std::string DefaultMethod; 209 210 public: 211 /// isRegisterClass() - Check if this is a register class. 212 bool isRegisterClass() const { 213 return Kind >= RegisterClass0 && Kind < UserClass0; 214 } 215 216 /// isUserClass() - Check if this is a user defined class. 217 bool isUserClass() const { 218 return Kind >= UserClass0; 219 } 220 221 /// isRelatedTo - Check whether this class is "related" to \p RHS. Classes 222 /// are related if they are in the same class hierarchy. 223 bool isRelatedTo(const ClassInfo &RHS) const { 224 // Tokens are only related to tokens. 225 if (Kind == Token || RHS.Kind == Token) 226 return Kind == Token && RHS.Kind == Token; 227 228 // Registers classes are only related to registers classes, and only if 229 // their intersection is non-empty. 230 if (isRegisterClass() || RHS.isRegisterClass()) { 231 if (!isRegisterClass() || !RHS.isRegisterClass()) 232 return false; 233 234 RegisterSet Tmp; 235 std::insert_iterator<RegisterSet> II(Tmp, Tmp.begin()); 236 std::set_intersection(Registers.begin(), Registers.end(), 237 RHS.Registers.begin(), RHS.Registers.end(), 238 II, LessRecordByID()); 239 240 return !Tmp.empty(); 241 } 242 243 // Otherwise we have two users operands; they are related if they are in the 244 // same class hierarchy. 245 // 246 // FIXME: This is an oversimplification, they should only be related if they 247 // intersect, however we don't have that information. 248 assert(isUserClass() && RHS.isUserClass() && "Unexpected class!"); 249 const ClassInfo *Root = this; 250 while (!Root->SuperClasses.empty()) 251 Root = Root->SuperClasses.front(); 252 253 const ClassInfo *RHSRoot = &RHS; 254 while (!RHSRoot->SuperClasses.empty()) 255 RHSRoot = RHSRoot->SuperClasses.front(); 256 257 return Root == RHSRoot; 258 } 259 260 /// isSubsetOf - Test whether this class is a subset of \p RHS. 261 bool isSubsetOf(const ClassInfo &RHS) const { 262 // This is a subset of RHS if it is the same class... 263 if (this == &RHS) 264 return true; 265 266 // ... or if any of its super classes are a subset of RHS. 267 for (const ClassInfo *CI : SuperClasses) 268 if (CI->isSubsetOf(RHS)) 269 return true; 270 271 return false; 272 } 273 274 int getTreeDepth() const { 275 int Depth = 0; 276 const ClassInfo *Root = this; 277 while (!Root->SuperClasses.empty()) { 278 Depth++; 279 Root = Root->SuperClasses.front(); 280 } 281 return Depth; 282 } 283 284 const ClassInfo *findRoot() const { 285 const ClassInfo *Root = this; 286 while (!Root->SuperClasses.empty()) 287 Root = Root->SuperClasses.front(); 288 return Root; 289 } 290 291 /// Compare two classes. This does not produce a total ordering, but does 292 /// guarantee that subclasses are sorted before their parents, and that the 293 /// ordering is transitive. 294 bool operator<(const ClassInfo &RHS) const { 295 if (this == &RHS) 296 return false; 297 298 // First, enforce the ordering between the three different types of class. 299 // Tokens sort before registers, which sort before user classes. 300 if (Kind == Token) { 301 if (RHS.Kind != Token) 302 return true; 303 assert(RHS.Kind == Token); 304 } else if (isRegisterClass()) { 305 if (RHS.Kind == Token) 306 return false; 307 else if (RHS.isUserClass()) 308 return true; 309 assert(RHS.isRegisterClass()); 310 } else if (isUserClass()) { 311 if (!RHS.isUserClass()) 312 return false; 313 assert(RHS.isUserClass()); 314 } else { 315 llvm_unreachable("Unknown ClassInfoKind"); 316 } 317 318 if (Kind == Token || isUserClass()) { 319 // Related tokens and user classes get sorted by depth in the inheritence 320 // tree (so that subclasses are before their parents). 321 if (isRelatedTo(RHS)) { 322 if (getTreeDepth() > RHS.getTreeDepth()) 323 return true; 324 if (getTreeDepth() < RHS.getTreeDepth()) 325 return false; 326 } else { 327 // Unrelated tokens and user classes are ordered by the name of their 328 // root nodes, so that there is a consistent ordering between 329 // unconnected trees. 330 return findRoot()->ValueName < RHS.findRoot()->ValueName; 331 } 332 } else if (isRegisterClass()) { 333 // For register sets, sort by number of registers. This guarantees that 334 // a set will always sort before all of it's strict supersets. 335 if (Registers.size() != RHS.Registers.size()) 336 return Registers.size() < RHS.Registers.size(); 337 } else { 338 llvm_unreachable("Unknown ClassInfoKind"); 339 } 340 341 // FIXME: We should be able to just return false here, as we only need a 342 // partial order (we use stable sorts, so this is deterministic) and the 343 // name of a class shouldn't be significant. However, some of the backends 344 // accidentally rely on this behaviour, so it will have to stay like this 345 // until they are fixed. 346 return ValueName < RHS.ValueName; 347 } 348 }; 349 350 class AsmVariantInfo { 351 public: 352 std::string RegisterPrefix; 353 std::string TokenizingCharacters; 354 std::string SeparatorCharacters; 355 std::string BreakCharacters; 356 std::string Name; 357 int AsmVariantNo; 358 }; 359 360 /// MatchableInfo - Helper class for storing the necessary information for an 361 /// instruction or alias which is capable of being matched. 362 struct MatchableInfo { 363 struct AsmOperand { 364 /// Token - This is the token that the operand came from. 365 StringRef Token; 366 367 /// The unique class instance this operand should match. 368 ClassInfo *Class; 369 370 /// The operand name this is, if anything. 371 StringRef SrcOpName; 372 373 /// The suboperand index within SrcOpName, or -1 for the entire operand. 374 int SubOpIdx; 375 376 /// Whether the token is "isolated", i.e., it is preceded and followed 377 /// by separators. 378 bool IsIsolatedToken; 379 380 /// Register record if this token is singleton register. 381 Record *SingletonReg; 382 383 explicit AsmOperand(bool IsIsolatedToken, StringRef T) 384 : Token(T), Class(nullptr), SubOpIdx(-1), 385 IsIsolatedToken(IsIsolatedToken), SingletonReg(nullptr) {} 386 }; 387 388 /// ResOperand - This represents a single operand in the result instruction 389 /// generated by the match. In cases (like addressing modes) where a single 390 /// assembler operand expands to multiple MCOperands, this represents the 391 /// single assembler operand, not the MCOperand. 392 struct ResOperand { 393 enum { 394 /// RenderAsmOperand - This represents an operand result that is 395 /// generated by calling the render method on the assembly operand. The 396 /// corresponding AsmOperand is specified by AsmOperandNum. 397 RenderAsmOperand, 398 399 /// TiedOperand - This represents a result operand that is a duplicate of 400 /// a previous result operand. 401 TiedOperand, 402 403 /// ImmOperand - This represents an immediate value that is dumped into 404 /// the operand. 405 ImmOperand, 406 407 /// RegOperand - This represents a fixed register that is dumped in. 408 RegOperand 409 } Kind; 410 411 union { 412 /// This is the operand # in the AsmOperands list that this should be 413 /// copied from. 414 unsigned AsmOperandNum; 415 416 /// TiedOperandNum - This is the (earlier) result operand that should be 417 /// copied from. 418 unsigned TiedOperandNum; 419 420 /// ImmVal - This is the immediate value added to the instruction. 421 int64_t ImmVal; 422 423 /// Register - This is the register record. 424 Record *Register; 425 }; 426 427 /// MINumOperands - The number of MCInst operands populated by this 428 /// operand. 429 unsigned MINumOperands; 430 431 static ResOperand getRenderedOp(unsigned AsmOpNum, unsigned NumOperands) { 432 ResOperand X; 433 X.Kind = RenderAsmOperand; 434 X.AsmOperandNum = AsmOpNum; 435 X.MINumOperands = NumOperands; 436 return X; 437 } 438 439 static ResOperand getTiedOp(unsigned TiedOperandNum) { 440 ResOperand X; 441 X.Kind = TiedOperand; 442 X.TiedOperandNum = TiedOperandNum; 443 X.MINumOperands = 1; 444 return X; 445 } 446 447 static ResOperand getImmOp(int64_t Val) { 448 ResOperand X; 449 X.Kind = ImmOperand; 450 X.ImmVal = Val; 451 X.MINumOperands = 1; 452 return X; 453 } 454 455 static ResOperand getRegOp(Record *Reg) { 456 ResOperand X; 457 X.Kind = RegOperand; 458 X.Register = Reg; 459 X.MINumOperands = 1; 460 return X; 461 } 462 }; 463 464 /// AsmVariantID - Target's assembly syntax variant no. 465 int AsmVariantID; 466 467 /// AsmString - The assembly string for this instruction (with variants 468 /// removed), e.g. "movsx $src, $dst". 469 std::string AsmString; 470 471 /// TheDef - This is the definition of the instruction or InstAlias that this 472 /// matchable came from. 473 Record *const TheDef; 474 475 /// DefRec - This is the definition that it came from. 476 PointerUnion<const CodeGenInstruction*, const CodeGenInstAlias*> DefRec; 477 478 const CodeGenInstruction *getResultInst() const { 479 if (DefRec.is<const CodeGenInstruction*>()) 480 return DefRec.get<const CodeGenInstruction*>(); 481 return DefRec.get<const CodeGenInstAlias*>()->ResultInst; 482 } 483 484 /// ResOperands - This is the operand list that should be built for the result 485 /// MCInst. 486 SmallVector<ResOperand, 8> ResOperands; 487 488 /// Mnemonic - This is the first token of the matched instruction, its 489 /// mnemonic. 490 StringRef Mnemonic; 491 492 /// AsmOperands - The textual operands that this instruction matches, 493 /// annotated with a class and where in the OperandList they were defined. 494 /// This directly corresponds to the tokenized AsmString after the mnemonic is 495 /// removed. 496 SmallVector<AsmOperand, 8> AsmOperands; 497 498 /// Predicates - The required subtarget features to match this instruction. 499 SmallVector<const SubtargetFeatureInfo *, 4> RequiredFeatures; 500 501 /// ConversionFnKind - The enum value which is passed to the generated 502 /// convertToMCInst to convert parsed operands into an MCInst for this 503 /// function. 504 std::string ConversionFnKind; 505 506 /// If this instruction is deprecated in some form. 507 bool HasDeprecation; 508 509 /// If this is an alias, this is use to determine whether or not to using 510 /// the conversion function defined by the instruction's AsmMatchConverter 511 /// or to use the function generated by the alias. 512 bool UseInstAsmMatchConverter; 513 514 MatchableInfo(const CodeGenInstruction &CGI) 515 : AsmVariantID(0), AsmString(CGI.AsmString), TheDef(CGI.TheDef), DefRec(&CGI), 516 UseInstAsmMatchConverter(true) { 517 } 518 519 MatchableInfo(std::unique_ptr<const CodeGenInstAlias> Alias) 520 : AsmVariantID(0), AsmString(Alias->AsmString), TheDef(Alias->TheDef), 521 DefRec(Alias.release()), 522 UseInstAsmMatchConverter( 523 TheDef->getValueAsBit("UseInstAsmMatchConverter")) { 524 } 525 526 // Could remove this and the dtor if PointerUnion supported unique_ptr 527 // elements with a dynamic failure/assertion (like the one below) in the case 528 // where it was copied while being in an owning state. 529 MatchableInfo(const MatchableInfo &RHS) 530 : AsmVariantID(RHS.AsmVariantID), AsmString(RHS.AsmString), 531 TheDef(RHS.TheDef), DefRec(RHS.DefRec), ResOperands(RHS.ResOperands), 532 Mnemonic(RHS.Mnemonic), AsmOperands(RHS.AsmOperands), 533 RequiredFeatures(RHS.RequiredFeatures), 534 ConversionFnKind(RHS.ConversionFnKind), 535 HasDeprecation(RHS.HasDeprecation), 536 UseInstAsmMatchConverter(RHS.UseInstAsmMatchConverter) { 537 assert(!DefRec.is<const CodeGenInstAlias *>()); 538 } 539 540 ~MatchableInfo() { 541 delete DefRec.dyn_cast<const CodeGenInstAlias*>(); 542 } 543 544 // Two-operand aliases clone from the main matchable, but mark the second 545 // operand as a tied operand of the first for purposes of the assembler. 546 void formTwoOperandAlias(StringRef Constraint); 547 548 void initialize(const AsmMatcherInfo &Info, 549 SmallPtrSetImpl<Record*> &SingletonRegisters, 550 AsmVariantInfo const &Variant, 551 bool HasMnemonicFirst); 552 553 /// validate - Return true if this matchable is a valid thing to match against 554 /// and perform a bunch of validity checking. 555 bool validate(StringRef CommentDelimiter, bool Hack) const; 556 557 /// findAsmOperand - Find the AsmOperand with the specified name and 558 /// suboperand index. 559 int findAsmOperand(StringRef N, int SubOpIdx) const { 560 auto I = find_if(AsmOperands, [&](const AsmOperand &Op) { 561 return Op.SrcOpName == N && Op.SubOpIdx == SubOpIdx; 562 }); 563 return (I != AsmOperands.end()) ? I - AsmOperands.begin() : -1; 564 } 565 566 /// findAsmOperandNamed - Find the first AsmOperand with the specified name. 567 /// This does not check the suboperand index. 568 int findAsmOperandNamed(StringRef N) const { 569 auto I = find_if(AsmOperands, 570 [&](const AsmOperand &Op) { return Op.SrcOpName == N; }); 571 return (I != AsmOperands.end()) ? I - AsmOperands.begin() : -1; 572 } 573 574 void buildInstructionResultOperands(); 575 void buildAliasResultOperands(); 576 577 /// operator< - Compare two matchables. 578 bool operator<(const MatchableInfo &RHS) const { 579 // The primary comparator is the instruction mnemonic. 580 if (int Cmp = Mnemonic.compare(RHS.Mnemonic)) 581 return Cmp == -1; 582 583 if (AsmOperands.size() != RHS.AsmOperands.size()) 584 return AsmOperands.size() < RHS.AsmOperands.size(); 585 586 // Compare lexicographically by operand. The matcher validates that other 587 // orderings wouldn't be ambiguous using \see couldMatchAmbiguouslyWith(). 588 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) { 589 if (*AsmOperands[i].Class < *RHS.AsmOperands[i].Class) 590 return true; 591 if (*RHS.AsmOperands[i].Class < *AsmOperands[i].Class) 592 return false; 593 } 594 595 // Give matches that require more features higher precedence. This is useful 596 // because we cannot define AssemblerPredicates with the negation of 597 // processor features. For example, ARM v6 "nop" may be either a HINT or 598 // MOV. With v6, we want to match HINT. The assembler has no way to 599 // predicate MOV under "NoV6", but HINT will always match first because it 600 // requires V6 while MOV does not. 601 if (RequiredFeatures.size() != RHS.RequiredFeatures.size()) 602 return RequiredFeatures.size() > RHS.RequiredFeatures.size(); 603 604 return false; 605 } 606 607 /// couldMatchAmbiguouslyWith - Check whether this matchable could 608 /// ambiguously match the same set of operands as \p RHS (without being a 609 /// strictly superior match). 610 bool couldMatchAmbiguouslyWith(const MatchableInfo &RHS) const { 611 // The primary comparator is the instruction mnemonic. 612 if (Mnemonic != RHS.Mnemonic) 613 return false; 614 615 // The number of operands is unambiguous. 616 if (AsmOperands.size() != RHS.AsmOperands.size()) 617 return false; 618 619 // Otherwise, make sure the ordering of the two instructions is unambiguous 620 // by checking that either (a) a token or operand kind discriminates them, 621 // or (b) the ordering among equivalent kinds is consistent. 622 623 // Tokens and operand kinds are unambiguous (assuming a correct target 624 // specific parser). 625 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) 626 if (AsmOperands[i].Class->Kind != RHS.AsmOperands[i].Class->Kind || 627 AsmOperands[i].Class->Kind == ClassInfo::Token) 628 if (*AsmOperands[i].Class < *RHS.AsmOperands[i].Class || 629 *RHS.AsmOperands[i].Class < *AsmOperands[i].Class) 630 return false; 631 632 // Otherwise, this operand could commute if all operands are equivalent, or 633 // there is a pair of operands that compare less than and a pair that 634 // compare greater than. 635 bool HasLT = false, HasGT = false; 636 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) { 637 if (*AsmOperands[i].Class < *RHS.AsmOperands[i].Class) 638 HasLT = true; 639 if (*RHS.AsmOperands[i].Class < *AsmOperands[i].Class) 640 HasGT = true; 641 } 642 643 return HasLT == HasGT; 644 } 645 646 void dump() const; 647 648 private: 649 void tokenizeAsmString(AsmMatcherInfo const &Info, 650 AsmVariantInfo const &Variant); 651 void addAsmOperand(StringRef Token, bool IsIsolatedToken = false); 652 }; 653 654 /// SubtargetFeatureInfo - Helper class for storing information on a subtarget 655 /// feature which participates in instruction matching. 656 struct SubtargetFeatureInfo { 657 /// \brief The predicate record for this feature. 658 Record *TheDef; 659 660 /// \brief An unique index assigned to represent this feature. 661 uint64_t Index; 662 663 SubtargetFeatureInfo(Record *D, uint64_t Idx) : TheDef(D), Index(Idx) {} 664 665 /// \brief The name of the enumerated constant identifying this feature. 666 std::string getEnumName() const { 667 return "Feature_" + TheDef->getName(); 668 } 669 670 void dump() const { 671 errs() << getEnumName() << " " << Index << "\n"; 672 TheDef->dump(); 673 } 674 }; 675 676 struct OperandMatchEntry { 677 unsigned OperandMask; 678 const MatchableInfo* MI; 679 ClassInfo *CI; 680 681 static OperandMatchEntry create(const MatchableInfo *mi, ClassInfo *ci, 682 unsigned opMask) { 683 OperandMatchEntry X; 684 X.OperandMask = opMask; 685 X.CI = ci; 686 X.MI = mi; 687 return X; 688 } 689 }; 690 691 class AsmMatcherInfo { 692 public: 693 /// Tracked Records 694 RecordKeeper &Records; 695 696 /// The tablegen AsmParser record. 697 Record *AsmParser; 698 699 /// Target - The target information. 700 CodeGenTarget &Target; 701 702 /// The classes which are needed for matching. 703 std::forward_list<ClassInfo> Classes; 704 705 /// The information on the matchables to match. 706 std::vector<std::unique_ptr<MatchableInfo>> Matchables; 707 708 /// Info for custom matching operands by user defined methods. 709 std::vector<OperandMatchEntry> OperandMatchInfo; 710 711 /// Map of Register records to their class information. 712 typedef std::map<Record*, ClassInfo*, LessRecordByID> RegisterClassesTy; 713 RegisterClassesTy RegisterClasses; 714 715 /// Map of Predicate records to their subtarget information. 716 std::map<Record *, SubtargetFeatureInfo, LessRecordByID> SubtargetFeatures; 717 718 /// Map of AsmOperandClass records to their class information. 719 std::map<Record*, ClassInfo*> AsmOperandClasses; 720 721 private: 722 /// Map of token to class information which has already been constructed. 723 std::map<std::string, ClassInfo*> TokenClasses; 724 725 /// Map of RegisterClass records to their class information. 726 std::map<Record*, ClassInfo*> RegisterClassClasses; 727 728 private: 729 /// getTokenClass - Lookup or create the class for the given token. 730 ClassInfo *getTokenClass(StringRef Token); 731 732 /// getOperandClass - Lookup or create the class for the given operand. 733 ClassInfo *getOperandClass(const CGIOperandList::OperandInfo &OI, 734 int SubOpIdx); 735 ClassInfo *getOperandClass(Record *Rec, int SubOpIdx); 736 737 /// buildRegisterClasses - Build the ClassInfo* instances for register 738 /// classes. 739 void buildRegisterClasses(SmallPtrSetImpl<Record*> &SingletonRegisters); 740 741 /// buildOperandClasses - Build the ClassInfo* instances for user defined 742 /// operand classes. 743 void buildOperandClasses(); 744 745 void buildInstructionOperandReference(MatchableInfo *II, StringRef OpName, 746 unsigned AsmOpIdx); 747 void buildAliasOperandReference(MatchableInfo *II, StringRef OpName, 748 MatchableInfo::AsmOperand &Op); 749 750 public: 751 AsmMatcherInfo(Record *AsmParser, 752 CodeGenTarget &Target, 753 RecordKeeper &Records); 754 755 /// buildInfo - Construct the various tables used during matching. 756 void buildInfo(); 757 758 /// buildOperandMatchInfo - Build the necessary information to handle user 759 /// defined operand parsing methods. 760 void buildOperandMatchInfo(); 761 762 /// getSubtargetFeature - Lookup or create the subtarget feature info for the 763 /// given operand. 764 const SubtargetFeatureInfo *getSubtargetFeature(Record *Def) const { 765 assert(Def->isSubClassOf("Predicate") && "Invalid predicate type!"); 766 const auto &I = SubtargetFeatures.find(Def); 767 return I == SubtargetFeatures.end() ? nullptr : &I->second; 768 } 769 770 RecordKeeper &getRecords() const { 771 return Records; 772 } 773 774 bool hasOptionalOperands() const { 775 return find_if(Classes, [](const ClassInfo &Class) { 776 return Class.IsOptional; 777 }) != Classes.end(); 778 } 779 }; 780 781 } // end anonymous namespace 782 783 void MatchableInfo::dump() const { 784 errs() << TheDef->getName() << " -- " << "flattened:\"" << AsmString <<"\"\n"; 785 786 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) { 787 const AsmOperand &Op = AsmOperands[i]; 788 errs() << " op[" << i << "] = " << Op.Class->ClassName << " - "; 789 errs() << '\"' << Op.Token << "\"\n"; 790 } 791 } 792 793 static std::pair<StringRef, StringRef> 794 parseTwoOperandConstraint(StringRef S, ArrayRef<SMLoc> Loc) { 795 // Split via the '='. 796 std::pair<StringRef, StringRef> Ops = S.split('='); 797 if (Ops.second == "") 798 PrintFatalError(Loc, "missing '=' in two-operand alias constraint"); 799 // Trim whitespace and the leading '$' on the operand names. 800 size_t start = Ops.first.find_first_of('$'); 801 if (start == std::string::npos) 802 PrintFatalError(Loc, "expected '$' prefix on asm operand name"); 803 Ops.first = Ops.first.slice(start + 1, std::string::npos); 804 size_t end = Ops.first.find_last_of(" \t"); 805 Ops.first = Ops.first.slice(0, end); 806 // Now the second operand. 807 start = Ops.second.find_first_of('$'); 808 if (start == std::string::npos) 809 PrintFatalError(Loc, "expected '$' prefix on asm operand name"); 810 Ops.second = Ops.second.slice(start + 1, std::string::npos); 811 end = Ops.second.find_last_of(" \t"); 812 Ops.first = Ops.first.slice(0, end); 813 return Ops; 814 } 815 816 void MatchableInfo::formTwoOperandAlias(StringRef Constraint) { 817 // Figure out which operands are aliased and mark them as tied. 818 std::pair<StringRef, StringRef> Ops = 819 parseTwoOperandConstraint(Constraint, TheDef->getLoc()); 820 821 // Find the AsmOperands that refer to the operands we're aliasing. 822 int SrcAsmOperand = findAsmOperandNamed(Ops.first); 823 int DstAsmOperand = findAsmOperandNamed(Ops.second); 824 if (SrcAsmOperand == -1) 825 PrintFatalError(TheDef->getLoc(), 826 "unknown source two-operand alias operand '" + Ops.first + 827 "'."); 828 if (DstAsmOperand == -1) 829 PrintFatalError(TheDef->getLoc(), 830 "unknown destination two-operand alias operand '" + 831 Ops.second + "'."); 832 833 // Find the ResOperand that refers to the operand we're aliasing away 834 // and update it to refer to the combined operand instead. 835 for (ResOperand &Op : ResOperands) { 836 if (Op.Kind == ResOperand::RenderAsmOperand && 837 Op.AsmOperandNum == (unsigned)SrcAsmOperand) { 838 Op.AsmOperandNum = DstAsmOperand; 839 break; 840 } 841 } 842 // Remove the AsmOperand for the alias operand. 843 AsmOperands.erase(AsmOperands.begin() + SrcAsmOperand); 844 // Adjust the ResOperand references to any AsmOperands that followed 845 // the one we just deleted. 846 for (ResOperand &Op : ResOperands) { 847 switch(Op.Kind) { 848 default: 849 // Nothing to do for operands that don't reference AsmOperands. 850 break; 851 case ResOperand::RenderAsmOperand: 852 if (Op.AsmOperandNum > (unsigned)SrcAsmOperand) 853 --Op.AsmOperandNum; 854 break; 855 case ResOperand::TiedOperand: 856 if (Op.TiedOperandNum > (unsigned)SrcAsmOperand) 857 --Op.TiedOperandNum; 858 break; 859 } 860 } 861 } 862 863 /// extractSingletonRegisterForAsmOperand - Extract singleton register, 864 /// if present, from specified token. 865 static void 866 extractSingletonRegisterForAsmOperand(MatchableInfo::AsmOperand &Op, 867 const AsmMatcherInfo &Info, 868 StringRef RegisterPrefix) { 869 StringRef Tok = Op.Token; 870 871 // If this token is not an isolated token, i.e., it isn't separated from 872 // other tokens (e.g. with whitespace), don't interpret it as a register name. 873 if (!Op.IsIsolatedToken) 874 return; 875 876 if (RegisterPrefix.empty()) { 877 std::string LoweredTok = Tok.lower(); 878 if (const CodeGenRegister *Reg = Info.Target.getRegisterByName(LoweredTok)) 879 Op.SingletonReg = Reg->TheDef; 880 return; 881 } 882 883 if (!Tok.startswith(RegisterPrefix)) 884 return; 885 886 StringRef RegName = Tok.substr(RegisterPrefix.size()); 887 if (const CodeGenRegister *Reg = Info.Target.getRegisterByName(RegName)) 888 Op.SingletonReg = Reg->TheDef; 889 890 // If there is no register prefix (i.e. "%" in "%eax"), then this may 891 // be some random non-register token, just ignore it. 892 } 893 894 void MatchableInfo::initialize(const AsmMatcherInfo &Info, 895 SmallPtrSetImpl<Record*> &SingletonRegisters, 896 AsmVariantInfo const &Variant, 897 bool HasMnemonicFirst) { 898 AsmVariantID = Variant.AsmVariantNo; 899 AsmString = 900 CodeGenInstruction::FlattenAsmStringVariants(AsmString, 901 Variant.AsmVariantNo); 902 903 tokenizeAsmString(Info, Variant); 904 905 // The first token of the instruction is the mnemonic, which must be a 906 // simple string, not a $foo variable or a singleton register. 907 if (AsmOperands.empty()) 908 PrintFatalError(TheDef->getLoc(), 909 "Instruction '" + TheDef->getName() + "' has no tokens"); 910 911 assert(!AsmOperands[0].Token.empty()); 912 if (HasMnemonicFirst) { 913 Mnemonic = AsmOperands[0].Token; 914 if (Mnemonic[0] == '$') 915 PrintFatalError(TheDef->getLoc(), 916 "Invalid instruction mnemonic '" + Mnemonic + "'!"); 917 918 // Remove the first operand, it is tracked in the mnemonic field. 919 AsmOperands.erase(AsmOperands.begin()); 920 } else if (AsmOperands[0].Token[0] != '$') 921 Mnemonic = AsmOperands[0].Token; 922 923 // Compute the require features. 924 for (Record *Predicate : TheDef->getValueAsListOfDefs("Predicates")) 925 if (const SubtargetFeatureInfo *Feature = 926 Info.getSubtargetFeature(Predicate)) 927 RequiredFeatures.push_back(Feature); 928 929 // Collect singleton registers, if used. 930 for (MatchableInfo::AsmOperand &Op : AsmOperands) { 931 extractSingletonRegisterForAsmOperand(Op, Info, Variant.RegisterPrefix); 932 if (Record *Reg = Op.SingletonReg) 933 SingletonRegisters.insert(Reg); 934 } 935 936 const RecordVal *DepMask = TheDef->getValue("DeprecatedFeatureMask"); 937 if (!DepMask) 938 DepMask = TheDef->getValue("ComplexDeprecationPredicate"); 939 940 HasDeprecation = 941 DepMask ? !DepMask->getValue()->getAsUnquotedString().empty() : false; 942 } 943 944 /// Append an AsmOperand for the given substring of AsmString. 945 void MatchableInfo::addAsmOperand(StringRef Token, bool IsIsolatedToken) { 946 AsmOperands.push_back(AsmOperand(IsIsolatedToken, Token)); 947 } 948 949 /// tokenizeAsmString - Tokenize a simplified assembly string. 950 void MatchableInfo::tokenizeAsmString(const AsmMatcherInfo &Info, 951 AsmVariantInfo const &Variant) { 952 StringRef String = AsmString; 953 size_t Prev = 0; 954 bool InTok = false; 955 bool IsIsolatedToken = true; 956 for (size_t i = 0, e = String.size(); i != e; ++i) { 957 char Char = String[i]; 958 if (Variant.BreakCharacters.find(Char) != std::string::npos) { 959 if (InTok) { 960 addAsmOperand(String.slice(Prev, i), false); 961 Prev = i; 962 IsIsolatedToken = false; 963 } 964 InTok = true; 965 continue; 966 } 967 if (Variant.TokenizingCharacters.find(Char) != std::string::npos) { 968 if (InTok) { 969 addAsmOperand(String.slice(Prev, i), IsIsolatedToken); 970 InTok = false; 971 IsIsolatedToken = false; 972 } 973 addAsmOperand(String.slice(i, i + 1), IsIsolatedToken); 974 Prev = i + 1; 975 IsIsolatedToken = true; 976 continue; 977 } 978 if (Variant.SeparatorCharacters.find(Char) != std::string::npos) { 979 if (InTok) { 980 addAsmOperand(String.slice(Prev, i), IsIsolatedToken); 981 InTok = false; 982 } 983 Prev = i + 1; 984 IsIsolatedToken = true; 985 continue; 986 } 987 988 switch (Char) { 989 case '\\': 990 if (InTok) { 991 addAsmOperand(String.slice(Prev, i), false); 992 InTok = false; 993 IsIsolatedToken = false; 994 } 995 ++i; 996 assert(i != String.size() && "Invalid quoted character"); 997 addAsmOperand(String.slice(i, i + 1), IsIsolatedToken); 998 Prev = i + 1; 999 IsIsolatedToken = false; 1000 break; 1001 1002 case '$': { 1003 if (InTok) { 1004 addAsmOperand(String.slice(Prev, i), false); 1005 InTok = false; 1006 IsIsolatedToken = false; 1007 } 1008 1009 // If this isn't "${", start new identifier looking like "$xxx" 1010 if (i + 1 == String.size() || String[i + 1] != '{') { 1011 Prev = i; 1012 break; 1013 } 1014 1015 size_t EndPos = String.find('}', i); 1016 assert(EndPos != StringRef::npos && 1017 "Missing brace in operand reference!"); 1018 addAsmOperand(String.slice(i, EndPos+1), IsIsolatedToken); 1019 Prev = EndPos + 1; 1020 i = EndPos; 1021 IsIsolatedToken = false; 1022 break; 1023 } 1024 1025 default: 1026 InTok = true; 1027 break; 1028 } 1029 } 1030 if (InTok && Prev != String.size()) 1031 addAsmOperand(String.substr(Prev), IsIsolatedToken); 1032 } 1033 1034 bool MatchableInfo::validate(StringRef CommentDelimiter, bool Hack) const { 1035 // Reject matchables with no .s string. 1036 if (AsmString.empty()) 1037 PrintFatalError(TheDef->getLoc(), "instruction with empty asm string"); 1038 1039 // Reject any matchables with a newline in them, they should be marked 1040 // isCodeGenOnly if they are pseudo instructions. 1041 if (AsmString.find('\n') != std::string::npos) 1042 PrintFatalError(TheDef->getLoc(), 1043 "multiline instruction is not valid for the asmparser, " 1044 "mark it isCodeGenOnly"); 1045 1046 // Remove comments from the asm string. We know that the asmstring only 1047 // has one line. 1048 if (!CommentDelimiter.empty() && 1049 StringRef(AsmString).find(CommentDelimiter) != StringRef::npos) 1050 PrintFatalError(TheDef->getLoc(), 1051 "asmstring for instruction has comment character in it, " 1052 "mark it isCodeGenOnly"); 1053 1054 // Reject matchables with operand modifiers, these aren't something we can 1055 // handle, the target should be refactored to use operands instead of 1056 // modifiers. 1057 // 1058 // Also, check for instructions which reference the operand multiple times; 1059 // this implies a constraint we would not honor. 1060 std::set<std::string> OperandNames; 1061 for (const AsmOperand &Op : AsmOperands) { 1062 StringRef Tok = Op.Token; 1063 if (Tok[0] == '$' && Tok.find(':') != StringRef::npos) 1064 PrintFatalError(TheDef->getLoc(), 1065 "matchable with operand modifier '" + Tok + 1066 "' not supported by asm matcher. Mark isCodeGenOnly!"); 1067 1068 // Verify that any operand is only mentioned once. 1069 // We reject aliases and ignore instructions for now. 1070 if (Tok[0] == '$' && !OperandNames.insert(Tok).second) { 1071 if (!Hack) 1072 PrintFatalError(TheDef->getLoc(), 1073 "ERROR: matchable with tied operand '" + Tok + 1074 "' can never be matched!"); 1075 // FIXME: Should reject these. The ARM backend hits this with $lane in a 1076 // bunch of instructions. It is unclear what the right answer is. 1077 DEBUG({ 1078 errs() << "warning: '" << TheDef->getName() << "': " 1079 << "ignoring instruction with tied operand '" 1080 << Tok << "'\n"; 1081 }); 1082 return false; 1083 } 1084 } 1085 1086 return true; 1087 } 1088 1089 static std::string getEnumNameForToken(StringRef Str) { 1090 std::string Res; 1091 1092 for (StringRef::iterator it = Str.begin(), ie = Str.end(); it != ie; ++it) { 1093 switch (*it) { 1094 case '*': Res += "_STAR_"; break; 1095 case '%': Res += "_PCT_"; break; 1096 case ':': Res += "_COLON_"; break; 1097 case '!': Res += "_EXCLAIM_"; break; 1098 case '.': Res += "_DOT_"; break; 1099 case '<': Res += "_LT_"; break; 1100 case '>': Res += "_GT_"; break; 1101 case '-': Res += "_MINUS_"; break; 1102 default: 1103 if ((*it >= 'A' && *it <= 'Z') || 1104 (*it >= 'a' && *it <= 'z') || 1105 (*it >= '0' && *it <= '9')) 1106 Res += *it; 1107 else 1108 Res += "_" + utostr((unsigned) *it) + "_"; 1109 } 1110 } 1111 1112 return Res; 1113 } 1114 1115 ClassInfo *AsmMatcherInfo::getTokenClass(StringRef Token) { 1116 ClassInfo *&Entry = TokenClasses[Token]; 1117 1118 if (!Entry) { 1119 Classes.emplace_front(); 1120 Entry = &Classes.front(); 1121 Entry->Kind = ClassInfo::Token; 1122 Entry->ClassName = "Token"; 1123 Entry->Name = "MCK_" + getEnumNameForToken(Token); 1124 Entry->ValueName = Token; 1125 Entry->PredicateMethod = "<invalid>"; 1126 Entry->RenderMethod = "<invalid>"; 1127 Entry->ParserMethod = ""; 1128 Entry->DiagnosticType = ""; 1129 Entry->IsOptional = false; 1130 Entry->DefaultMethod = "<invalid>"; 1131 } 1132 1133 return Entry; 1134 } 1135 1136 ClassInfo * 1137 AsmMatcherInfo::getOperandClass(const CGIOperandList::OperandInfo &OI, 1138 int SubOpIdx) { 1139 Record *Rec = OI.Rec; 1140 if (SubOpIdx != -1) 1141 Rec = cast<DefInit>(OI.MIOperandInfo->getArg(SubOpIdx))->getDef(); 1142 return getOperandClass(Rec, SubOpIdx); 1143 } 1144 1145 ClassInfo * 1146 AsmMatcherInfo::getOperandClass(Record *Rec, int SubOpIdx) { 1147 if (Rec->isSubClassOf("RegisterOperand")) { 1148 // RegisterOperand may have an associated ParserMatchClass. If it does, 1149 // use it, else just fall back to the underlying register class. 1150 const RecordVal *R = Rec->getValue("ParserMatchClass"); 1151 if (!R || !R->getValue()) 1152 PrintFatalError("Record `" + Rec->getName() + 1153 "' does not have a ParserMatchClass!\n"); 1154 1155 if (DefInit *DI= dyn_cast<DefInit>(R->getValue())) { 1156 Record *MatchClass = DI->getDef(); 1157 if (ClassInfo *CI = AsmOperandClasses[MatchClass]) 1158 return CI; 1159 } 1160 1161 // No custom match class. Just use the register class. 1162 Record *ClassRec = Rec->getValueAsDef("RegClass"); 1163 if (!ClassRec) 1164 PrintFatalError(Rec->getLoc(), "RegisterOperand `" + Rec->getName() + 1165 "' has no associated register class!\n"); 1166 if (ClassInfo *CI = RegisterClassClasses[ClassRec]) 1167 return CI; 1168 PrintFatalError(Rec->getLoc(), "register class has no class info!"); 1169 } 1170 1171 if (Rec->isSubClassOf("RegisterClass")) { 1172 if (ClassInfo *CI = RegisterClassClasses[Rec]) 1173 return CI; 1174 PrintFatalError(Rec->getLoc(), "register class has no class info!"); 1175 } 1176 1177 if (!Rec->isSubClassOf("Operand")) 1178 PrintFatalError(Rec->getLoc(), "Operand `" + Rec->getName() + 1179 "' does not derive from class Operand!\n"); 1180 Record *MatchClass = Rec->getValueAsDef("ParserMatchClass"); 1181 if (ClassInfo *CI = AsmOperandClasses[MatchClass]) 1182 return CI; 1183 1184 PrintFatalError(Rec->getLoc(), "operand has no match class!"); 1185 } 1186 1187 struct LessRegisterSet { 1188 bool operator() (const RegisterSet &LHS, const RegisterSet & RHS) const { 1189 // std::set<T> defines its own compariso "operator<", but it 1190 // performs a lexicographical comparison by T's innate comparison 1191 // for some reason. We don't want non-deterministic pointer 1192 // comparisons so use this instead. 1193 return std::lexicographical_compare(LHS.begin(), LHS.end(), 1194 RHS.begin(), RHS.end(), 1195 LessRecordByID()); 1196 } 1197 }; 1198 1199 void AsmMatcherInfo:: 1200 buildRegisterClasses(SmallPtrSetImpl<Record*> &SingletonRegisters) { 1201 const auto &Registers = Target.getRegBank().getRegisters(); 1202 auto &RegClassList = Target.getRegBank().getRegClasses(); 1203 1204 typedef std::set<RegisterSet, LessRegisterSet> RegisterSetSet; 1205 1206 // The register sets used for matching. 1207 RegisterSetSet RegisterSets; 1208 1209 // Gather the defined sets. 1210 for (const CodeGenRegisterClass &RC : RegClassList) 1211 RegisterSets.insert( 1212 RegisterSet(RC.getOrder().begin(), RC.getOrder().end())); 1213 1214 // Add any required singleton sets. 1215 for (Record *Rec : SingletonRegisters) { 1216 RegisterSets.insert(RegisterSet(&Rec, &Rec + 1)); 1217 } 1218 1219 // Introduce derived sets where necessary (when a register does not determine 1220 // a unique register set class), and build the mapping of registers to the set 1221 // they should classify to. 1222 std::map<Record*, RegisterSet> RegisterMap; 1223 for (const CodeGenRegister &CGR : Registers) { 1224 // Compute the intersection of all sets containing this register. 1225 RegisterSet ContainingSet; 1226 1227 for (const RegisterSet &RS : RegisterSets) { 1228 if (!RS.count(CGR.TheDef)) 1229 continue; 1230 1231 if (ContainingSet.empty()) { 1232 ContainingSet = RS; 1233 continue; 1234 } 1235 1236 RegisterSet Tmp; 1237 std::swap(Tmp, ContainingSet); 1238 std::insert_iterator<RegisterSet> II(ContainingSet, 1239 ContainingSet.begin()); 1240 std::set_intersection(Tmp.begin(), Tmp.end(), RS.begin(), RS.end(), II, 1241 LessRecordByID()); 1242 } 1243 1244 if (!ContainingSet.empty()) { 1245 RegisterSets.insert(ContainingSet); 1246 RegisterMap.insert(std::make_pair(CGR.TheDef, ContainingSet)); 1247 } 1248 } 1249 1250 // Construct the register classes. 1251 std::map<RegisterSet, ClassInfo*, LessRegisterSet> RegisterSetClasses; 1252 unsigned Index = 0; 1253 for (const RegisterSet &RS : RegisterSets) { 1254 Classes.emplace_front(); 1255 ClassInfo *CI = &Classes.front(); 1256 CI->Kind = ClassInfo::RegisterClass0 + Index; 1257 CI->ClassName = "Reg" + utostr(Index); 1258 CI->Name = "MCK_Reg" + utostr(Index); 1259 CI->ValueName = ""; 1260 CI->PredicateMethod = ""; // unused 1261 CI->RenderMethod = "addRegOperands"; 1262 CI->Registers = RS; 1263 // FIXME: diagnostic type. 1264 CI->DiagnosticType = ""; 1265 CI->IsOptional = false; 1266 CI->DefaultMethod = ""; // unused 1267 RegisterSetClasses.insert(std::make_pair(RS, CI)); 1268 ++Index; 1269 } 1270 1271 // Find the superclasses; we could compute only the subgroup lattice edges, 1272 // but there isn't really a point. 1273 for (const RegisterSet &RS : RegisterSets) { 1274 ClassInfo *CI = RegisterSetClasses[RS]; 1275 for (const RegisterSet &RS2 : RegisterSets) 1276 if (RS != RS2 && 1277 std::includes(RS2.begin(), RS2.end(), RS.begin(), RS.end(), 1278 LessRecordByID())) 1279 CI->SuperClasses.push_back(RegisterSetClasses[RS2]); 1280 } 1281 1282 // Name the register classes which correspond to a user defined RegisterClass. 1283 for (const CodeGenRegisterClass &RC : RegClassList) { 1284 // Def will be NULL for non-user defined register classes. 1285 Record *Def = RC.getDef(); 1286 if (!Def) 1287 continue; 1288 ClassInfo *CI = RegisterSetClasses[RegisterSet(RC.getOrder().begin(), 1289 RC.getOrder().end())]; 1290 if (CI->ValueName.empty()) { 1291 CI->ClassName = RC.getName(); 1292 CI->Name = "MCK_" + RC.getName(); 1293 CI->ValueName = RC.getName(); 1294 } else 1295 CI->ValueName = CI->ValueName + "," + RC.getName(); 1296 1297 RegisterClassClasses.insert(std::make_pair(Def, CI)); 1298 } 1299 1300 // Populate the map for individual registers. 1301 for (std::map<Record*, RegisterSet>::iterator it = RegisterMap.begin(), 1302 ie = RegisterMap.end(); it != ie; ++it) 1303 RegisterClasses[it->first] = RegisterSetClasses[it->second]; 1304 1305 // Name the register classes which correspond to singleton registers. 1306 for (Record *Rec : SingletonRegisters) { 1307 ClassInfo *CI = RegisterClasses[Rec]; 1308 assert(CI && "Missing singleton register class info!"); 1309 1310 if (CI->ValueName.empty()) { 1311 CI->ClassName = Rec->getName(); 1312 CI->Name = "MCK_" + Rec->getName(); 1313 CI->ValueName = Rec->getName(); 1314 } else 1315 CI->ValueName = CI->ValueName + "," + Rec->getName(); 1316 } 1317 } 1318 1319 void AsmMatcherInfo::buildOperandClasses() { 1320 std::vector<Record*> AsmOperands = 1321 Records.getAllDerivedDefinitions("AsmOperandClass"); 1322 1323 // Pre-populate AsmOperandClasses map. 1324 for (Record *Rec : AsmOperands) { 1325 Classes.emplace_front(); 1326 AsmOperandClasses[Rec] = &Classes.front(); 1327 } 1328 1329 unsigned Index = 0; 1330 for (Record *Rec : AsmOperands) { 1331 ClassInfo *CI = AsmOperandClasses[Rec]; 1332 CI->Kind = ClassInfo::UserClass0 + Index; 1333 1334 ListInit *Supers = Rec->getValueAsListInit("SuperClasses"); 1335 for (Init *I : Supers->getValues()) { 1336 DefInit *DI = dyn_cast<DefInit>(I); 1337 if (!DI) { 1338 PrintError(Rec->getLoc(), "Invalid super class reference!"); 1339 continue; 1340 } 1341 1342 ClassInfo *SC = AsmOperandClasses[DI->getDef()]; 1343 if (!SC) 1344 PrintError(Rec->getLoc(), "Invalid super class reference!"); 1345 else 1346 CI->SuperClasses.push_back(SC); 1347 } 1348 CI->ClassName = Rec->getValueAsString("Name"); 1349 CI->Name = "MCK_" + CI->ClassName; 1350 CI->ValueName = Rec->getName(); 1351 1352 // Get or construct the predicate method name. 1353 Init *PMName = Rec->getValueInit("PredicateMethod"); 1354 if (StringInit *SI = dyn_cast<StringInit>(PMName)) { 1355 CI->PredicateMethod = SI->getValue(); 1356 } else { 1357 assert(isa<UnsetInit>(PMName) && "Unexpected PredicateMethod field!"); 1358 CI->PredicateMethod = "is" + CI->ClassName; 1359 } 1360 1361 // Get or construct the render method name. 1362 Init *RMName = Rec->getValueInit("RenderMethod"); 1363 if (StringInit *SI = dyn_cast<StringInit>(RMName)) { 1364 CI->RenderMethod = SI->getValue(); 1365 } else { 1366 assert(isa<UnsetInit>(RMName) && "Unexpected RenderMethod field!"); 1367 CI->RenderMethod = "add" + CI->ClassName + "Operands"; 1368 } 1369 1370 // Get the parse method name or leave it as empty. 1371 Init *PRMName = Rec->getValueInit("ParserMethod"); 1372 if (StringInit *SI = dyn_cast<StringInit>(PRMName)) 1373 CI->ParserMethod = SI->getValue(); 1374 1375 // Get the diagnostic type or leave it as empty. 1376 // Get the parse method name or leave it as empty. 1377 Init *DiagnosticType = Rec->getValueInit("DiagnosticType"); 1378 if (StringInit *SI = dyn_cast<StringInit>(DiagnosticType)) 1379 CI->DiagnosticType = SI->getValue(); 1380 1381 Init *IsOptional = Rec->getValueInit("IsOptional"); 1382 if (BitInit *BI = dyn_cast<BitInit>(IsOptional)) 1383 CI->IsOptional = BI->getValue(); 1384 1385 // Get or construct the default method name. 1386 Init *DMName = Rec->getValueInit("DefaultMethod"); 1387 if (StringInit *SI = dyn_cast<StringInit>(DMName)) { 1388 CI->DefaultMethod = SI->getValue(); 1389 } else { 1390 assert(isa<UnsetInit>(DMName) && "Unexpected DefaultMethod field!"); 1391 CI->DefaultMethod = "default" + CI->ClassName + "Operands"; 1392 } 1393 1394 ++Index; 1395 } 1396 } 1397 1398 AsmMatcherInfo::AsmMatcherInfo(Record *asmParser, 1399 CodeGenTarget &target, 1400 RecordKeeper &records) 1401 : Records(records), AsmParser(asmParser), Target(target) { 1402 } 1403 1404 /// buildOperandMatchInfo - Build the necessary information to handle user 1405 /// defined operand parsing methods. 1406 void AsmMatcherInfo::buildOperandMatchInfo() { 1407 1408 /// Map containing a mask with all operands indices that can be found for 1409 /// that class inside a instruction. 1410 typedef std::map<ClassInfo *, unsigned, less_ptr<ClassInfo>> OpClassMaskTy; 1411 OpClassMaskTy OpClassMask; 1412 1413 for (const auto &MI : Matchables) { 1414 OpClassMask.clear(); 1415 1416 // Keep track of all operands of this instructions which belong to the 1417 // same class. 1418 for (unsigned i = 0, e = MI->AsmOperands.size(); i != e; ++i) { 1419 const MatchableInfo::AsmOperand &Op = MI->AsmOperands[i]; 1420 if (Op.Class->ParserMethod.empty()) 1421 continue; 1422 unsigned &OperandMask = OpClassMask[Op.Class]; 1423 OperandMask |= (1 << i); 1424 } 1425 1426 // Generate operand match info for each mnemonic/operand class pair. 1427 for (const auto &OCM : OpClassMask) { 1428 unsigned OpMask = OCM.second; 1429 ClassInfo *CI = OCM.first; 1430 OperandMatchInfo.push_back(OperandMatchEntry::create(MI.get(), CI, 1431 OpMask)); 1432 } 1433 } 1434 } 1435 1436 void AsmMatcherInfo::buildInfo() { 1437 // Build information about all of the AssemblerPredicates. 1438 std::vector<Record*> AllPredicates = 1439 Records.getAllDerivedDefinitions("Predicate"); 1440 for (Record *Pred : AllPredicates) { 1441 // Ignore predicates that are not intended for the assembler. 1442 if (!Pred->getValueAsBit("AssemblerMatcherPredicate")) 1443 continue; 1444 1445 if (Pred->getName().empty()) 1446 PrintFatalError(Pred->getLoc(), "Predicate has no name!"); 1447 1448 SubtargetFeatures.insert(std::make_pair( 1449 Pred, SubtargetFeatureInfo(Pred, SubtargetFeatures.size()))); 1450 DEBUG(SubtargetFeatures.find(Pred)->second.dump()); 1451 assert(SubtargetFeatures.size() <= 64 && "Too many subtarget features!"); 1452 } 1453 1454 bool HasMnemonicFirst = AsmParser->getValueAsBit("HasMnemonicFirst"); 1455 1456 // Parse the instructions; we need to do this first so that we can gather the 1457 // singleton register classes. 1458 SmallPtrSet<Record*, 16> SingletonRegisters; 1459 unsigned VariantCount = Target.getAsmParserVariantCount(); 1460 for (unsigned VC = 0; VC != VariantCount; ++VC) { 1461 Record *AsmVariant = Target.getAsmParserVariant(VC); 1462 std::string CommentDelimiter = 1463 AsmVariant->getValueAsString("CommentDelimiter"); 1464 AsmVariantInfo Variant; 1465 Variant.RegisterPrefix = AsmVariant->getValueAsString("RegisterPrefix"); 1466 Variant.TokenizingCharacters = 1467 AsmVariant->getValueAsString("TokenizingCharacters"); 1468 Variant.SeparatorCharacters = 1469 AsmVariant->getValueAsString("SeparatorCharacters"); 1470 Variant.BreakCharacters = 1471 AsmVariant->getValueAsString("BreakCharacters"); 1472 Variant.Name = AsmVariant->getValueAsString("Name"); 1473 Variant.AsmVariantNo = AsmVariant->getValueAsInt("Variant"); 1474 1475 for (const CodeGenInstruction *CGI : Target.getInstructionsByEnumValue()) { 1476 1477 // If the tblgen -match-prefix option is specified (for tblgen hackers), 1478 // filter the set of instructions we consider. 1479 if (!StringRef(CGI->TheDef->getName()).startswith(MatchPrefix)) 1480 continue; 1481 1482 // Ignore "codegen only" instructions. 1483 if (CGI->TheDef->getValueAsBit("isCodeGenOnly")) 1484 continue; 1485 1486 // Ignore instructions for different instructions 1487 const std::string V = CGI->TheDef->getValueAsString("AsmVariantName"); 1488 if (!V.empty() && V != Variant.Name) 1489 continue; 1490 1491 auto II = llvm::make_unique<MatchableInfo>(*CGI); 1492 1493 II->initialize(*this, SingletonRegisters, Variant, HasMnemonicFirst); 1494 1495 // Ignore instructions which shouldn't be matched and diagnose invalid 1496 // instruction definitions with an error. 1497 if (!II->validate(CommentDelimiter, true)) 1498 continue; 1499 1500 Matchables.push_back(std::move(II)); 1501 } 1502 1503 // Parse all of the InstAlias definitions and stick them in the list of 1504 // matchables. 1505 std::vector<Record*> AllInstAliases = 1506 Records.getAllDerivedDefinitions("InstAlias"); 1507 for (unsigned i = 0, e = AllInstAliases.size(); i != e; ++i) { 1508 auto Alias = llvm::make_unique<CodeGenInstAlias>(AllInstAliases[i], 1509 Variant.AsmVariantNo, 1510 Target); 1511 1512 // If the tblgen -match-prefix option is specified (for tblgen hackers), 1513 // filter the set of instruction aliases we consider, based on the target 1514 // instruction. 1515 if (!StringRef(Alias->ResultInst->TheDef->getName()) 1516 .startswith( MatchPrefix)) 1517 continue; 1518 1519 const std::string V = Alias->TheDef->getValueAsString("AsmVariantName"); 1520 if (!V.empty() && V != Variant.Name) 1521 continue; 1522 1523 auto II = llvm::make_unique<MatchableInfo>(std::move(Alias)); 1524 1525 II->initialize(*this, SingletonRegisters, Variant, HasMnemonicFirst); 1526 1527 // Validate the alias definitions. 1528 II->validate(CommentDelimiter, false); 1529 1530 Matchables.push_back(std::move(II)); 1531 } 1532 } 1533 1534 // Build info for the register classes. 1535 buildRegisterClasses(SingletonRegisters); 1536 1537 // Build info for the user defined assembly operand classes. 1538 buildOperandClasses(); 1539 1540 // Build the information about matchables, now that we have fully formed 1541 // classes. 1542 std::vector<std::unique_ptr<MatchableInfo>> NewMatchables; 1543 for (auto &II : Matchables) { 1544 // Parse the tokens after the mnemonic. 1545 // Note: buildInstructionOperandReference may insert new AsmOperands, so 1546 // don't precompute the loop bound. 1547 for (unsigned i = 0; i != II->AsmOperands.size(); ++i) { 1548 MatchableInfo::AsmOperand &Op = II->AsmOperands[i]; 1549 StringRef Token = Op.Token; 1550 1551 // Check for singleton registers. 1552 if (Record *RegRecord = Op.SingletonReg) { 1553 Op.Class = RegisterClasses[RegRecord]; 1554 assert(Op.Class && Op.Class->Registers.size() == 1 && 1555 "Unexpected class for singleton register"); 1556 continue; 1557 } 1558 1559 // Check for simple tokens. 1560 if (Token[0] != '$') { 1561 Op.Class = getTokenClass(Token); 1562 continue; 1563 } 1564 1565 if (Token.size() > 1 && isdigit(Token[1])) { 1566 Op.Class = getTokenClass(Token); 1567 continue; 1568 } 1569 1570 // Otherwise this is an operand reference. 1571 StringRef OperandName; 1572 if (Token[1] == '{') 1573 OperandName = Token.substr(2, Token.size() - 3); 1574 else 1575 OperandName = Token.substr(1); 1576 1577 if (II->DefRec.is<const CodeGenInstruction*>()) 1578 buildInstructionOperandReference(II.get(), OperandName, i); 1579 else 1580 buildAliasOperandReference(II.get(), OperandName, Op); 1581 } 1582 1583 if (II->DefRec.is<const CodeGenInstruction*>()) { 1584 II->buildInstructionResultOperands(); 1585 // If the instruction has a two-operand alias, build up the 1586 // matchable here. We'll add them in bulk at the end to avoid 1587 // confusing this loop. 1588 std::string Constraint = 1589 II->TheDef->getValueAsString("TwoOperandAliasConstraint"); 1590 if (Constraint != "") { 1591 // Start by making a copy of the original matchable. 1592 auto AliasII = llvm::make_unique<MatchableInfo>(*II); 1593 1594 // Adjust it to be a two-operand alias. 1595 AliasII->formTwoOperandAlias(Constraint); 1596 1597 // Add the alias to the matchables list. 1598 NewMatchables.push_back(std::move(AliasII)); 1599 } 1600 } else 1601 II->buildAliasResultOperands(); 1602 } 1603 if (!NewMatchables.empty()) 1604 Matchables.insert(Matchables.end(), 1605 std::make_move_iterator(NewMatchables.begin()), 1606 std::make_move_iterator(NewMatchables.end())); 1607 1608 // Process token alias definitions and set up the associated superclass 1609 // information. 1610 std::vector<Record*> AllTokenAliases = 1611 Records.getAllDerivedDefinitions("TokenAlias"); 1612 for (Record *Rec : AllTokenAliases) { 1613 ClassInfo *FromClass = getTokenClass(Rec->getValueAsString("FromToken")); 1614 ClassInfo *ToClass = getTokenClass(Rec->getValueAsString("ToToken")); 1615 if (FromClass == ToClass) 1616 PrintFatalError(Rec->getLoc(), 1617 "error: Destination value identical to source value."); 1618 FromClass->SuperClasses.push_back(ToClass); 1619 } 1620 1621 // Reorder classes so that classes precede super classes. 1622 Classes.sort(); 1623 1624 #ifndef NDEBUG 1625 // Verify that the table is now sorted 1626 for (auto I = Classes.begin(), E = Classes.end(); I != E; ++I) { 1627 for (auto J = I; J != E; ++J) { 1628 assert(!(*J < *I)); 1629 assert(I == J || !J->isSubsetOf(*I)); 1630 } 1631 } 1632 #endif // NDEBUG 1633 } 1634 1635 /// buildInstructionOperandReference - The specified operand is a reference to a 1636 /// named operand such as $src. Resolve the Class and OperandInfo pointers. 1637 void AsmMatcherInfo:: 1638 buildInstructionOperandReference(MatchableInfo *II, 1639 StringRef OperandName, 1640 unsigned AsmOpIdx) { 1641 const CodeGenInstruction &CGI = *II->DefRec.get<const CodeGenInstruction*>(); 1642 const CGIOperandList &Operands = CGI.Operands; 1643 MatchableInfo::AsmOperand *Op = &II->AsmOperands[AsmOpIdx]; 1644 1645 // Map this token to an operand. 1646 unsigned Idx; 1647 if (!Operands.hasOperandNamed(OperandName, Idx)) 1648 PrintFatalError(II->TheDef->getLoc(), 1649 "error: unable to find operand: '" + OperandName + "'"); 1650 1651 // If the instruction operand has multiple suboperands, but the parser 1652 // match class for the asm operand is still the default "ImmAsmOperand", 1653 // then handle each suboperand separately. 1654 if (Op->SubOpIdx == -1 && Operands[Idx].MINumOperands > 1) { 1655 Record *Rec = Operands[Idx].Rec; 1656 assert(Rec->isSubClassOf("Operand") && "Unexpected operand!"); 1657 Record *MatchClass = Rec->getValueAsDef("ParserMatchClass"); 1658 if (MatchClass && MatchClass->getValueAsString("Name") == "Imm") { 1659 // Insert remaining suboperands after AsmOpIdx in II->AsmOperands. 1660 StringRef Token = Op->Token; // save this in case Op gets moved 1661 for (unsigned SI = 1, SE = Operands[Idx].MINumOperands; SI != SE; ++SI) { 1662 MatchableInfo::AsmOperand NewAsmOp(/*IsIsolatedToken=*/true, Token); 1663 NewAsmOp.SubOpIdx = SI; 1664 II->AsmOperands.insert(II->AsmOperands.begin()+AsmOpIdx+SI, NewAsmOp); 1665 } 1666 // Replace Op with first suboperand. 1667 Op = &II->AsmOperands[AsmOpIdx]; // update the pointer in case it moved 1668 Op->SubOpIdx = 0; 1669 } 1670 } 1671 1672 // Set up the operand class. 1673 Op->Class = getOperandClass(Operands[Idx], Op->SubOpIdx); 1674 1675 // If the named operand is tied, canonicalize it to the untied operand. 1676 // For example, something like: 1677 // (outs GPR:$dst), (ins GPR:$src) 1678 // with an asmstring of 1679 // "inc $src" 1680 // we want to canonicalize to: 1681 // "inc $dst" 1682 // so that we know how to provide the $dst operand when filling in the result. 1683 int OITied = -1; 1684 if (Operands[Idx].MINumOperands == 1) 1685 OITied = Operands[Idx].getTiedRegister(); 1686 if (OITied != -1) { 1687 // The tied operand index is an MIOperand index, find the operand that 1688 // contains it. 1689 std::pair<unsigned, unsigned> Idx = Operands.getSubOperandNumber(OITied); 1690 OperandName = Operands[Idx.first].Name; 1691 Op->SubOpIdx = Idx.second; 1692 } 1693 1694 Op->SrcOpName = OperandName; 1695 } 1696 1697 /// buildAliasOperandReference - When parsing an operand reference out of the 1698 /// matching string (e.g. "movsx $src, $dst"), determine what the class of the 1699 /// operand reference is by looking it up in the result pattern definition. 1700 void AsmMatcherInfo::buildAliasOperandReference(MatchableInfo *II, 1701 StringRef OperandName, 1702 MatchableInfo::AsmOperand &Op) { 1703 const CodeGenInstAlias &CGA = *II->DefRec.get<const CodeGenInstAlias*>(); 1704 1705 // Set up the operand class. 1706 for (unsigned i = 0, e = CGA.ResultOperands.size(); i != e; ++i) 1707 if (CGA.ResultOperands[i].isRecord() && 1708 CGA.ResultOperands[i].getName() == OperandName) { 1709 // It's safe to go with the first one we find, because CodeGenInstAlias 1710 // validates that all operands with the same name have the same record. 1711 Op.SubOpIdx = CGA.ResultInstOperandIndex[i].second; 1712 // Use the match class from the Alias definition, not the 1713 // destination instruction, as we may have an immediate that's 1714 // being munged by the match class. 1715 Op.Class = getOperandClass(CGA.ResultOperands[i].getRecord(), 1716 Op.SubOpIdx); 1717 Op.SrcOpName = OperandName; 1718 return; 1719 } 1720 1721 PrintFatalError(II->TheDef->getLoc(), 1722 "error: unable to find operand: '" + OperandName + "'"); 1723 } 1724 1725 void MatchableInfo::buildInstructionResultOperands() { 1726 const CodeGenInstruction *ResultInst = getResultInst(); 1727 1728 // Loop over all operands of the result instruction, determining how to 1729 // populate them. 1730 for (const CGIOperandList::OperandInfo &OpInfo : ResultInst->Operands) { 1731 // If this is a tied operand, just copy from the previously handled operand. 1732 int TiedOp = -1; 1733 if (OpInfo.MINumOperands == 1) 1734 TiedOp = OpInfo.getTiedRegister(); 1735 if (TiedOp != -1) { 1736 ResOperands.push_back(ResOperand::getTiedOp(TiedOp)); 1737 continue; 1738 } 1739 1740 // Find out what operand from the asmparser this MCInst operand comes from. 1741 int SrcOperand = findAsmOperandNamed(OpInfo.Name); 1742 if (OpInfo.Name.empty() || SrcOperand == -1) { 1743 // This may happen for operands that are tied to a suboperand of a 1744 // complex operand. Simply use a dummy value here; nobody should 1745 // use this operand slot. 1746 // FIXME: The long term goal is for the MCOperand list to not contain 1747 // tied operands at all. 1748 ResOperands.push_back(ResOperand::getImmOp(0)); 1749 continue; 1750 } 1751 1752 // Check if the one AsmOperand populates the entire operand. 1753 unsigned NumOperands = OpInfo.MINumOperands; 1754 if (AsmOperands[SrcOperand].SubOpIdx == -1) { 1755 ResOperands.push_back(ResOperand::getRenderedOp(SrcOperand, NumOperands)); 1756 continue; 1757 } 1758 1759 // Add a separate ResOperand for each suboperand. 1760 for (unsigned AI = 0; AI < NumOperands; ++AI) { 1761 assert(AsmOperands[SrcOperand+AI].SubOpIdx == (int)AI && 1762 AsmOperands[SrcOperand+AI].SrcOpName == OpInfo.Name && 1763 "unexpected AsmOperands for suboperands"); 1764 ResOperands.push_back(ResOperand::getRenderedOp(SrcOperand + AI, 1)); 1765 } 1766 } 1767 } 1768 1769 void MatchableInfo::buildAliasResultOperands() { 1770 const CodeGenInstAlias &CGA = *DefRec.get<const CodeGenInstAlias*>(); 1771 const CodeGenInstruction *ResultInst = getResultInst(); 1772 1773 // Loop over all operands of the result instruction, determining how to 1774 // populate them. 1775 unsigned AliasOpNo = 0; 1776 unsigned LastOpNo = CGA.ResultInstOperandIndex.size(); 1777 for (unsigned i = 0, e = ResultInst->Operands.size(); i != e; ++i) { 1778 const CGIOperandList::OperandInfo *OpInfo = &ResultInst->Operands[i]; 1779 1780 // If this is a tied operand, just copy from the previously handled operand. 1781 int TiedOp = -1; 1782 if (OpInfo->MINumOperands == 1) 1783 TiedOp = OpInfo->getTiedRegister(); 1784 if (TiedOp != -1) { 1785 ResOperands.push_back(ResOperand::getTiedOp(TiedOp)); 1786 continue; 1787 } 1788 1789 // Handle all the suboperands for this operand. 1790 const std::string &OpName = OpInfo->Name; 1791 for ( ; AliasOpNo < LastOpNo && 1792 CGA.ResultInstOperandIndex[AliasOpNo].first == i; ++AliasOpNo) { 1793 int SubIdx = CGA.ResultInstOperandIndex[AliasOpNo].second; 1794 1795 // Find out what operand from the asmparser that this MCInst operand 1796 // comes from. 1797 switch (CGA.ResultOperands[AliasOpNo].Kind) { 1798 case CodeGenInstAlias::ResultOperand::K_Record: { 1799 StringRef Name = CGA.ResultOperands[AliasOpNo].getName(); 1800 int SrcOperand = findAsmOperand(Name, SubIdx); 1801 if (SrcOperand == -1) 1802 PrintFatalError(TheDef->getLoc(), "Instruction '" + 1803 TheDef->getName() + "' has operand '" + OpName + 1804 "' that doesn't appear in asm string!"); 1805 unsigned NumOperands = (SubIdx == -1 ? OpInfo->MINumOperands : 1); 1806 ResOperands.push_back(ResOperand::getRenderedOp(SrcOperand, 1807 NumOperands)); 1808 break; 1809 } 1810 case CodeGenInstAlias::ResultOperand::K_Imm: { 1811 int64_t ImmVal = CGA.ResultOperands[AliasOpNo].getImm(); 1812 ResOperands.push_back(ResOperand::getImmOp(ImmVal)); 1813 break; 1814 } 1815 case CodeGenInstAlias::ResultOperand::K_Reg: { 1816 Record *Reg = CGA.ResultOperands[AliasOpNo].getRegister(); 1817 ResOperands.push_back(ResOperand::getRegOp(Reg)); 1818 break; 1819 } 1820 } 1821 } 1822 } 1823 } 1824 1825 static unsigned getConverterOperandID(const std::string &Name, 1826 SmallSetVector<std::string, 16> &Table, 1827 bool &IsNew) { 1828 IsNew = Table.insert(Name); 1829 1830 unsigned ID = IsNew ? Table.size() - 1 : find(Table, Name) - Table.begin(); 1831 1832 assert(ID < Table.size()); 1833 1834 return ID; 1835 } 1836 1837 static void emitConvertFuncs(CodeGenTarget &Target, StringRef ClassName, 1838 std::vector<std::unique_ptr<MatchableInfo>> &Infos, 1839 bool HasMnemonicFirst, bool HasOptionalOperands, 1840 raw_ostream &OS) { 1841 SmallSetVector<std::string, 16> OperandConversionKinds; 1842 SmallSetVector<std::string, 16> InstructionConversionKinds; 1843 std::vector<std::vector<uint8_t> > ConversionTable; 1844 size_t MaxRowLength = 2; // minimum is custom converter plus terminator. 1845 1846 // TargetOperandClass - This is the target's operand class, like X86Operand. 1847 std::string TargetOperandClass = Target.getName() + "Operand"; 1848 1849 // Write the convert function to a separate stream, so we can drop it after 1850 // the enum. We'll build up the conversion handlers for the individual 1851 // operand types opportunistically as we encounter them. 1852 std::string ConvertFnBody; 1853 raw_string_ostream CvtOS(ConvertFnBody); 1854 // Start the unified conversion function. 1855 if (HasOptionalOperands) { 1856 CvtOS << "void " << Target.getName() << ClassName << "::\n" 1857 << "convertToMCInst(unsigned Kind, MCInst &Inst, " 1858 << "unsigned Opcode,\n" 1859 << " const OperandVector &Operands,\n" 1860 << " const SmallBitVector &OptionalOperandsMask) {\n"; 1861 } else { 1862 CvtOS << "void " << Target.getName() << ClassName << "::\n" 1863 << "convertToMCInst(unsigned Kind, MCInst &Inst, " 1864 << "unsigned Opcode,\n" 1865 << " const OperandVector &Operands) {\n"; 1866 } 1867 CvtOS << " assert(Kind < CVT_NUM_SIGNATURES && \"Invalid signature!\");\n"; 1868 CvtOS << " const uint8_t *Converter = ConversionTable[Kind];\n"; 1869 if (HasOptionalOperands) { 1870 CvtOS << " unsigned NumDefaults = 0;\n"; 1871 } 1872 CvtOS << " unsigned OpIdx;\n"; 1873 CvtOS << " Inst.setOpcode(Opcode);\n"; 1874 CvtOS << " for (const uint8_t *p = Converter; *p; p+= 2) {\n"; 1875 if (HasOptionalOperands) { 1876 CvtOS << " OpIdx = *(p + 1) - NumDefaults;\n"; 1877 } else { 1878 CvtOS << " OpIdx = *(p + 1);\n"; 1879 } 1880 CvtOS << " switch (*p) {\n"; 1881 CvtOS << " default: llvm_unreachable(\"invalid conversion entry!\");\n"; 1882 CvtOS << " case CVT_Reg:\n"; 1883 CvtOS << " static_cast<" << TargetOperandClass 1884 << "&>(*Operands[OpIdx]).addRegOperands(Inst, 1);\n"; 1885 CvtOS << " break;\n"; 1886 CvtOS << " case CVT_Tied:\n"; 1887 CvtOS << " Inst.addOperand(Inst.getOperand(OpIdx));\n"; 1888 CvtOS << " break;\n"; 1889 1890 std::string OperandFnBody; 1891 raw_string_ostream OpOS(OperandFnBody); 1892 // Start the operand number lookup function. 1893 OpOS << "void " << Target.getName() << ClassName << "::\n" 1894 << "convertToMapAndConstraints(unsigned Kind,\n"; 1895 OpOS.indent(27); 1896 OpOS << "const OperandVector &Operands) {\n" 1897 << " assert(Kind < CVT_NUM_SIGNATURES && \"Invalid signature!\");\n" 1898 << " unsigned NumMCOperands = 0;\n" 1899 << " const uint8_t *Converter = ConversionTable[Kind];\n" 1900 << " for (const uint8_t *p = Converter; *p; p+= 2) {\n" 1901 << " switch (*p) {\n" 1902 << " default: llvm_unreachable(\"invalid conversion entry!\");\n" 1903 << " case CVT_Reg:\n" 1904 << " Operands[*(p + 1)]->setMCOperandNum(NumMCOperands);\n" 1905 << " Operands[*(p + 1)]->setConstraint(\"r\");\n" 1906 << " ++NumMCOperands;\n" 1907 << " break;\n" 1908 << " case CVT_Tied:\n" 1909 << " ++NumMCOperands;\n" 1910 << " break;\n"; 1911 1912 // Pre-populate the operand conversion kinds with the standard always 1913 // available entries. 1914 OperandConversionKinds.insert("CVT_Done"); 1915 OperandConversionKinds.insert("CVT_Reg"); 1916 OperandConversionKinds.insert("CVT_Tied"); 1917 enum { CVT_Done, CVT_Reg, CVT_Tied }; 1918 1919 for (auto &II : Infos) { 1920 // Check if we have a custom match function. 1921 std::string AsmMatchConverter = 1922 II->getResultInst()->TheDef->getValueAsString("AsmMatchConverter"); 1923 if (!AsmMatchConverter.empty() && II->UseInstAsmMatchConverter) { 1924 std::string Signature = "ConvertCustom_" + AsmMatchConverter; 1925 II->ConversionFnKind = Signature; 1926 1927 // Check if we have already generated this signature. 1928 if (!InstructionConversionKinds.insert(Signature)) 1929 continue; 1930 1931 // Remember this converter for the kind enum. 1932 unsigned KindID = OperandConversionKinds.size(); 1933 OperandConversionKinds.insert("CVT_" + 1934 getEnumNameForToken(AsmMatchConverter)); 1935 1936 // Add the converter row for this instruction. 1937 ConversionTable.emplace_back(); 1938 ConversionTable.back().push_back(KindID); 1939 ConversionTable.back().push_back(CVT_Done); 1940 1941 // Add the handler to the conversion driver function. 1942 CvtOS << " case CVT_" 1943 << getEnumNameForToken(AsmMatchConverter) << ":\n" 1944 << " " << AsmMatchConverter << "(Inst, Operands);\n" 1945 << " break;\n"; 1946 1947 // FIXME: Handle the operand number lookup for custom match functions. 1948 continue; 1949 } 1950 1951 // Build the conversion function signature. 1952 std::string Signature = "Convert"; 1953 1954 std::vector<uint8_t> ConversionRow; 1955 1956 // Compute the convert enum and the case body. 1957 MaxRowLength = std::max(MaxRowLength, II->ResOperands.size()*2 + 1 ); 1958 1959 for (unsigned i = 0, e = II->ResOperands.size(); i != e; ++i) { 1960 const MatchableInfo::ResOperand &OpInfo = II->ResOperands[i]; 1961 1962 // Generate code to populate each result operand. 1963 switch (OpInfo.Kind) { 1964 case MatchableInfo::ResOperand::RenderAsmOperand: { 1965 // This comes from something we parsed. 1966 const MatchableInfo::AsmOperand &Op = 1967 II->AsmOperands[OpInfo.AsmOperandNum]; 1968 1969 // Registers are always converted the same, don't duplicate the 1970 // conversion function based on them. 1971 Signature += "__"; 1972 std::string Class; 1973 Class = Op.Class->isRegisterClass() ? "Reg" : Op.Class->ClassName; 1974 Signature += Class; 1975 Signature += utostr(OpInfo.MINumOperands); 1976 Signature += "_" + itostr(OpInfo.AsmOperandNum); 1977 1978 // Add the conversion kind, if necessary, and get the associated ID 1979 // the index of its entry in the vector). 1980 std::string Name = "CVT_" + (Op.Class->isRegisterClass() ? "Reg" : 1981 Op.Class->RenderMethod); 1982 if (Op.Class->IsOptional) { 1983 // For optional operands we must also care about DefaultMethod 1984 assert(HasOptionalOperands); 1985 Name += "_" + Op.Class->DefaultMethod; 1986 } 1987 Name = getEnumNameForToken(Name); 1988 1989 bool IsNewConverter = false; 1990 unsigned ID = getConverterOperandID(Name, OperandConversionKinds, 1991 IsNewConverter); 1992 1993 // Add the operand entry to the instruction kind conversion row. 1994 ConversionRow.push_back(ID); 1995 ConversionRow.push_back(OpInfo.AsmOperandNum + HasMnemonicFirst); 1996 1997 if (!IsNewConverter) 1998 break; 1999 2000 // This is a new operand kind. Add a handler for it to the 2001 // converter driver. 2002 CvtOS << " case " << Name << ":\n"; 2003 if (Op.Class->IsOptional) { 2004 // If optional operand is not present in actual instruction then we 2005 // should call its DefaultMethod before RenderMethod 2006 assert(HasOptionalOperands); 2007 CvtOS << " if (OptionalOperandsMask[*(p + 1) - 1]) {\n" 2008 << " " << Op.Class->DefaultMethod << "()" 2009 << "->" << Op.Class->RenderMethod << "(Inst, " 2010 << OpInfo.MINumOperands << ");\n" 2011 << " ++NumDefaults;\n" 2012 << " } else {\n" 2013 << " static_cast<" << TargetOperandClass 2014 << "&>(*Operands[OpIdx])." << Op.Class->RenderMethod 2015 << "(Inst, " << OpInfo.MINumOperands << ");\n" 2016 << " }\n"; 2017 } else { 2018 CvtOS << " static_cast<" << TargetOperandClass 2019 << "&>(*Operands[OpIdx])." << Op.Class->RenderMethod 2020 << "(Inst, " << OpInfo.MINumOperands << ");\n"; 2021 } 2022 CvtOS << " break;\n"; 2023 2024 // Add a handler for the operand number lookup. 2025 OpOS << " case " << Name << ":\n" 2026 << " Operands[*(p + 1)]->setMCOperandNum(NumMCOperands);\n"; 2027 2028 if (Op.Class->isRegisterClass()) 2029 OpOS << " Operands[*(p + 1)]->setConstraint(\"r\");\n"; 2030 else 2031 OpOS << " Operands[*(p + 1)]->setConstraint(\"m\");\n"; 2032 OpOS << " NumMCOperands += " << OpInfo.MINumOperands << ";\n" 2033 << " break;\n"; 2034 break; 2035 } 2036 case MatchableInfo::ResOperand::TiedOperand: { 2037 // If this operand is tied to a previous one, just copy the MCInst 2038 // operand from the earlier one.We can only tie single MCOperand values. 2039 assert(OpInfo.MINumOperands == 1 && "Not a singular MCOperand"); 2040 unsigned TiedOp = OpInfo.TiedOperandNum; 2041 assert(i > TiedOp && "Tied operand precedes its target!"); 2042 Signature += "__Tie" + utostr(TiedOp); 2043 ConversionRow.push_back(CVT_Tied); 2044 ConversionRow.push_back(TiedOp); 2045 break; 2046 } 2047 case MatchableInfo::ResOperand::ImmOperand: { 2048 int64_t Val = OpInfo.ImmVal; 2049 std::string Ty = "imm_" + itostr(Val); 2050 Ty = getEnumNameForToken(Ty); 2051 Signature += "__" + Ty; 2052 2053 std::string Name = "CVT_" + Ty; 2054 bool IsNewConverter = false; 2055 unsigned ID = getConverterOperandID(Name, OperandConversionKinds, 2056 IsNewConverter); 2057 // Add the operand entry to the instruction kind conversion row. 2058 ConversionRow.push_back(ID); 2059 ConversionRow.push_back(0); 2060 2061 if (!IsNewConverter) 2062 break; 2063 2064 CvtOS << " case " << Name << ":\n" 2065 << " Inst.addOperand(MCOperand::createImm(" << Val << "));\n" 2066 << " break;\n"; 2067 2068 OpOS << " case " << Name << ":\n" 2069 << " Operands[*(p + 1)]->setMCOperandNum(NumMCOperands);\n" 2070 << " Operands[*(p + 1)]->setConstraint(\"\");\n" 2071 << " ++NumMCOperands;\n" 2072 << " break;\n"; 2073 break; 2074 } 2075 case MatchableInfo::ResOperand::RegOperand: { 2076 std::string Reg, Name; 2077 if (!OpInfo.Register) { 2078 Name = "reg0"; 2079 Reg = "0"; 2080 } else { 2081 Reg = getQualifiedName(OpInfo.Register); 2082 Name = "reg" + OpInfo.Register->getName(); 2083 } 2084 Signature += "__" + Name; 2085 Name = "CVT_" + Name; 2086 bool IsNewConverter = false; 2087 unsigned ID = getConverterOperandID(Name, OperandConversionKinds, 2088 IsNewConverter); 2089 // Add the operand entry to the instruction kind conversion row. 2090 ConversionRow.push_back(ID); 2091 ConversionRow.push_back(0); 2092 2093 if (!IsNewConverter) 2094 break; 2095 CvtOS << " case " << Name << ":\n" 2096 << " Inst.addOperand(MCOperand::createReg(" << Reg << "));\n" 2097 << " break;\n"; 2098 2099 OpOS << " case " << Name << ":\n" 2100 << " Operands[*(p + 1)]->setMCOperandNum(NumMCOperands);\n" 2101 << " Operands[*(p + 1)]->setConstraint(\"m\");\n" 2102 << " ++NumMCOperands;\n" 2103 << " break;\n"; 2104 } 2105 } 2106 } 2107 2108 // If there were no operands, add to the signature to that effect 2109 if (Signature == "Convert") 2110 Signature += "_NoOperands"; 2111 2112 II->ConversionFnKind = Signature; 2113 2114 // Save the signature. If we already have it, don't add a new row 2115 // to the table. 2116 if (!InstructionConversionKinds.insert(Signature)) 2117 continue; 2118 2119 // Add the row to the table. 2120 ConversionTable.push_back(std::move(ConversionRow)); 2121 } 2122 2123 // Finish up the converter driver function. 2124 CvtOS << " }\n }\n}\n\n"; 2125 2126 // Finish up the operand number lookup function. 2127 OpOS << " }\n }\n}\n\n"; 2128 2129 OS << "namespace {\n"; 2130 2131 // Output the operand conversion kind enum. 2132 OS << "enum OperatorConversionKind {\n"; 2133 for (const std::string &Converter : OperandConversionKinds) 2134 OS << " " << Converter << ",\n"; 2135 OS << " CVT_NUM_CONVERTERS\n"; 2136 OS << "};\n\n"; 2137 2138 // Output the instruction conversion kind enum. 2139 OS << "enum InstructionConversionKind {\n"; 2140 for (const std::string &Signature : InstructionConversionKinds) 2141 OS << " " << Signature << ",\n"; 2142 OS << " CVT_NUM_SIGNATURES\n"; 2143 OS << "};\n\n"; 2144 2145 OS << "} // end anonymous namespace\n\n"; 2146 2147 // Output the conversion table. 2148 OS << "static const uint8_t ConversionTable[CVT_NUM_SIGNATURES][" 2149 << MaxRowLength << "] = {\n"; 2150 2151 for (unsigned Row = 0, ERow = ConversionTable.size(); Row != ERow; ++Row) { 2152 assert(ConversionTable[Row].size() % 2 == 0 && "bad conversion row!"); 2153 OS << " // " << InstructionConversionKinds[Row] << "\n"; 2154 OS << " { "; 2155 for (unsigned i = 0, e = ConversionTable[Row].size(); i != e; i += 2) 2156 OS << OperandConversionKinds[ConversionTable[Row][i]] << ", " 2157 << (unsigned)(ConversionTable[Row][i + 1]) << ", "; 2158 OS << "CVT_Done },\n"; 2159 } 2160 2161 OS << "};\n\n"; 2162 2163 // Spit out the conversion driver function. 2164 OS << CvtOS.str(); 2165 2166 // Spit out the operand number lookup function. 2167 OS << OpOS.str(); 2168 } 2169 2170 /// emitMatchClassEnumeration - Emit the enumeration for match class kinds. 2171 static void emitMatchClassEnumeration(CodeGenTarget &Target, 2172 std::forward_list<ClassInfo> &Infos, 2173 raw_ostream &OS) { 2174 OS << "namespace {\n\n"; 2175 2176 OS << "/// MatchClassKind - The kinds of classes which participate in\n" 2177 << "/// instruction matching.\n"; 2178 OS << "enum MatchClassKind {\n"; 2179 OS << " InvalidMatchClass = 0,\n"; 2180 OS << " OptionalMatchClass = 1,\n"; 2181 for (const auto &CI : Infos) { 2182 OS << " " << CI.Name << ", // "; 2183 if (CI.Kind == ClassInfo::Token) { 2184 OS << "'" << CI.ValueName << "'\n"; 2185 } else if (CI.isRegisterClass()) { 2186 if (!CI.ValueName.empty()) 2187 OS << "register class '" << CI.ValueName << "'\n"; 2188 else 2189 OS << "derived register class\n"; 2190 } else { 2191 OS << "user defined class '" << CI.ValueName << "'\n"; 2192 } 2193 } 2194 OS << " NumMatchClassKinds\n"; 2195 OS << "};\n\n"; 2196 2197 OS << "}\n\n"; 2198 } 2199 2200 /// emitValidateOperandClass - Emit the function to validate an operand class. 2201 static void emitValidateOperandClass(AsmMatcherInfo &Info, 2202 raw_ostream &OS) { 2203 OS << "static unsigned validateOperandClass(MCParsedAsmOperand &GOp, " 2204 << "MatchClassKind Kind) {\n"; 2205 OS << " " << Info.Target.getName() << "Operand &Operand = (" 2206 << Info.Target.getName() << "Operand&)GOp;\n"; 2207 2208 // The InvalidMatchClass is not to match any operand. 2209 OS << " if (Kind == InvalidMatchClass)\n"; 2210 OS << " return MCTargetAsmParser::Match_InvalidOperand;\n\n"; 2211 2212 // Check for Token operands first. 2213 // FIXME: Use a more specific diagnostic type. 2214 OS << " if (Operand.isToken())\n"; 2215 OS << " return isSubclass(matchTokenString(Operand.getToken()), Kind) ?\n" 2216 << " MCTargetAsmParser::Match_Success :\n" 2217 << " MCTargetAsmParser::Match_InvalidOperand;\n\n"; 2218 2219 // Check the user classes. We don't care what order since we're only 2220 // actually matching against one of them. 2221 OS << " switch (Kind) {\n" 2222 " default: break;\n"; 2223 for (const auto &CI : Info.Classes) { 2224 if (!CI.isUserClass()) 2225 continue; 2226 2227 OS << " // '" << CI.ClassName << "' class\n"; 2228 OS << " case " << CI.Name << ":\n"; 2229 OS << " if (Operand." << CI.PredicateMethod << "())\n"; 2230 OS << " return MCTargetAsmParser::Match_Success;\n"; 2231 if (!CI.DiagnosticType.empty()) 2232 OS << " return " << Info.Target.getName() << "AsmParser::Match_" 2233 << CI.DiagnosticType << ";\n"; 2234 else 2235 OS << " break;\n"; 2236 } 2237 OS << " } // end switch (Kind)\n\n"; 2238 2239 // Check for register operands, including sub-classes. 2240 OS << " if (Operand.isReg()) {\n"; 2241 OS << " MatchClassKind OpKind;\n"; 2242 OS << " switch (Operand.getReg()) {\n"; 2243 OS << " default: OpKind = InvalidMatchClass; break;\n"; 2244 for (const auto &RC : Info.RegisterClasses) 2245 OS << " case " << Info.Target.getName() << "::" 2246 << RC.first->getName() << ": OpKind = " << RC.second->Name 2247 << "; break;\n"; 2248 OS << " }\n"; 2249 OS << " return isSubclass(OpKind, Kind) ? " 2250 << "MCTargetAsmParser::Match_Success :\n " 2251 << " MCTargetAsmParser::Match_InvalidOperand;\n }\n\n"; 2252 2253 // Generic fallthrough match failure case for operands that don't have 2254 // specialized diagnostic types. 2255 OS << " return MCTargetAsmParser::Match_InvalidOperand;\n"; 2256 OS << "}\n\n"; 2257 } 2258 2259 /// emitIsSubclass - Emit the subclass predicate function. 2260 static void emitIsSubclass(CodeGenTarget &Target, 2261 std::forward_list<ClassInfo> &Infos, 2262 raw_ostream &OS) { 2263 OS << "/// isSubclass - Compute whether \\p A is a subclass of \\p B.\n"; 2264 OS << "static bool isSubclass(MatchClassKind A, MatchClassKind B) {\n"; 2265 OS << " if (A == B)\n"; 2266 OS << " return true;\n\n"; 2267 2268 bool EmittedSwitch = false; 2269 for (const auto &A : Infos) { 2270 std::vector<StringRef> SuperClasses; 2271 if (A.IsOptional) 2272 SuperClasses.push_back("OptionalMatchClass"); 2273 for (const auto &B : Infos) { 2274 if (&A != &B && A.isSubsetOf(B)) 2275 SuperClasses.push_back(B.Name); 2276 } 2277 2278 if (SuperClasses.empty()) 2279 continue; 2280 2281 // If this is the first SuperClass, emit the switch header. 2282 if (!EmittedSwitch) { 2283 OS << " switch (A) {\n"; 2284 OS << " default:\n"; 2285 OS << " return false;\n"; 2286 EmittedSwitch = true; 2287 } 2288 2289 OS << "\n case " << A.Name << ":\n"; 2290 2291 if (SuperClasses.size() == 1) { 2292 OS << " return B == " << SuperClasses.back() << ";\n"; 2293 continue; 2294 } 2295 2296 if (!SuperClasses.empty()) { 2297 OS << " switch (B) {\n"; 2298 OS << " default: return false;\n"; 2299 for (StringRef SC : SuperClasses) 2300 OS << " case " << SC << ": return true;\n"; 2301 OS << " }\n"; 2302 } else { 2303 // No case statement to emit 2304 OS << " return false;\n"; 2305 } 2306 } 2307 2308 // If there were case statements emitted into the string stream write the 2309 // default. 2310 if (EmittedSwitch) 2311 OS << " }\n"; 2312 else 2313 OS << " return false;\n"; 2314 2315 OS << "}\n\n"; 2316 } 2317 2318 /// emitMatchTokenString - Emit the function to match a token string to the 2319 /// appropriate match class value. 2320 static void emitMatchTokenString(CodeGenTarget &Target, 2321 std::forward_list<ClassInfo> &Infos, 2322 raw_ostream &OS) { 2323 // Construct the match list. 2324 std::vector<StringMatcher::StringPair> Matches; 2325 for (const auto &CI : Infos) { 2326 if (CI.Kind == ClassInfo::Token) 2327 Matches.emplace_back(CI.ValueName, "return " + CI.Name + ";"); 2328 } 2329 2330 OS << "static MatchClassKind matchTokenString(StringRef Name) {\n"; 2331 2332 StringMatcher("Name", Matches, OS).Emit(); 2333 2334 OS << " return InvalidMatchClass;\n"; 2335 OS << "}\n\n"; 2336 } 2337 2338 /// emitMatchRegisterName - Emit the function to match a string to the target 2339 /// specific register enum. 2340 static void emitMatchRegisterName(CodeGenTarget &Target, Record *AsmParser, 2341 raw_ostream &OS) { 2342 // Construct the match list. 2343 std::vector<StringMatcher::StringPair> Matches; 2344 const auto &Regs = Target.getRegBank().getRegisters(); 2345 for (const CodeGenRegister &Reg : Regs) { 2346 if (Reg.TheDef->getValueAsString("AsmName").empty()) 2347 continue; 2348 2349 Matches.emplace_back(Reg.TheDef->getValueAsString("AsmName"), 2350 "return " + utostr(Reg.EnumValue) + ";"); 2351 } 2352 2353 OS << "static unsigned MatchRegisterName(StringRef Name) {\n"; 2354 2355 StringMatcher("Name", Matches, OS).Emit(); 2356 2357 OS << " return 0;\n"; 2358 OS << "}\n\n"; 2359 } 2360 2361 /// Emit the function to match a string to the target 2362 /// specific register enum. 2363 static void emitMatchRegisterAltName(CodeGenTarget &Target, Record *AsmParser, 2364 raw_ostream &OS) { 2365 // Construct the match list. 2366 std::vector<StringMatcher::StringPair> Matches; 2367 const auto &Regs = Target.getRegBank().getRegisters(); 2368 for (const CodeGenRegister &Reg : Regs) { 2369 2370 auto AltNames = Reg.TheDef->getValueAsListOfStrings("AltNames"); 2371 2372 for (auto AltName : AltNames) { 2373 AltName = StringRef(AltName).trim(); 2374 2375 // don't handle empty alternative names 2376 if (AltName.empty()) 2377 continue; 2378 2379 Matches.emplace_back(AltName, 2380 "return " + utostr(Reg.EnumValue) + ";"); 2381 } 2382 } 2383 2384 OS << "static unsigned MatchRegisterAltName(StringRef Name) {\n"; 2385 2386 StringMatcher("Name", Matches, OS).Emit(); 2387 2388 OS << " return 0;\n"; 2389 OS << "}\n\n"; 2390 } 2391 2392 static const char *getMinimalTypeForRange(uint64_t Range) { 2393 assert(Range <= 0xFFFFFFFFFFFFFFFFULL && "Enum too large"); 2394 if (Range > 0xFFFFFFFFULL) 2395 return "uint64_t"; 2396 if (Range > 0xFFFF) 2397 return "uint32_t"; 2398 if (Range > 0xFF) 2399 return "uint16_t"; 2400 return "uint8_t"; 2401 } 2402 2403 static const char *getMinimalRequiredFeaturesType(const AsmMatcherInfo &Info) { 2404 uint64_t MaxIndex = Info.SubtargetFeatures.size(); 2405 if (MaxIndex > 0) 2406 MaxIndex--; 2407 return getMinimalTypeForRange(1ULL << MaxIndex); 2408 } 2409 2410 /// emitSubtargetFeatureFlagEnumeration - Emit the subtarget feature flag 2411 /// definitions. 2412 static void emitSubtargetFeatureFlagEnumeration(AsmMatcherInfo &Info, 2413 raw_ostream &OS) { 2414 OS << "// Flags for subtarget features that participate in " 2415 << "instruction matching.\n"; 2416 OS << "enum SubtargetFeatureFlag : " << getMinimalRequiredFeaturesType(Info) 2417 << " {\n"; 2418 for (const auto &SF : Info.SubtargetFeatures) { 2419 const SubtargetFeatureInfo &SFI = SF.second; 2420 OS << " " << SFI.getEnumName() << " = (1ULL << " << SFI.Index << "),\n"; 2421 } 2422 OS << " Feature_None = 0\n"; 2423 OS << "};\n\n"; 2424 } 2425 2426 /// emitOperandDiagnosticTypes - Emit the operand matching diagnostic types. 2427 static void emitOperandDiagnosticTypes(AsmMatcherInfo &Info, raw_ostream &OS) { 2428 // Get the set of diagnostic types from all of the operand classes. 2429 std::set<StringRef> Types; 2430 for (const auto &OpClassEntry : Info.AsmOperandClasses) { 2431 if (!OpClassEntry.second->DiagnosticType.empty()) 2432 Types.insert(OpClassEntry.second->DiagnosticType); 2433 } 2434 2435 if (Types.empty()) return; 2436 2437 // Now emit the enum entries. 2438 for (StringRef Type : Types) 2439 OS << " Match_" << Type << ",\n"; 2440 OS << " END_OPERAND_DIAGNOSTIC_TYPES\n"; 2441 } 2442 2443 /// emitGetSubtargetFeatureName - Emit the helper function to get the 2444 /// user-level name for a subtarget feature. 2445 static void emitGetSubtargetFeatureName(AsmMatcherInfo &Info, raw_ostream &OS) { 2446 OS << "// User-level names for subtarget features that participate in\n" 2447 << "// instruction matching.\n" 2448 << "static const char *getSubtargetFeatureName(uint64_t Val) {\n"; 2449 if (!Info.SubtargetFeatures.empty()) { 2450 OS << " switch(Val) {\n"; 2451 for (const auto &SF : Info.SubtargetFeatures) { 2452 const SubtargetFeatureInfo &SFI = SF.second; 2453 // FIXME: Totally just a placeholder name to get the algorithm working. 2454 OS << " case " << SFI.getEnumName() << ": return \"" 2455 << SFI.TheDef->getValueAsString("PredicateName") << "\";\n"; 2456 } 2457 OS << " default: return \"(unknown)\";\n"; 2458 OS << " }\n"; 2459 } else { 2460 // Nothing to emit, so skip the switch 2461 OS << " return \"(unknown)\";\n"; 2462 } 2463 OS << "}\n\n"; 2464 } 2465 2466 /// emitComputeAvailableFeatures - Emit the function to compute the list of 2467 /// available features given a subtarget. 2468 static void emitComputeAvailableFeatures(AsmMatcherInfo &Info, 2469 raw_ostream &OS) { 2470 std::string ClassName = 2471 Info.AsmParser->getValueAsString("AsmParserClassName"); 2472 2473 OS << "uint64_t " << Info.Target.getName() << ClassName << "::\n" 2474 << "ComputeAvailableFeatures(const FeatureBitset& FB) const {\n"; 2475 OS << " uint64_t Features = 0;\n"; 2476 for (const auto &SF : Info.SubtargetFeatures) { 2477 const SubtargetFeatureInfo &SFI = SF.second; 2478 2479 OS << " if ("; 2480 std::string CondStorage = 2481 SFI.TheDef->getValueAsString("AssemblerCondString"); 2482 StringRef Conds = CondStorage; 2483 std::pair<StringRef,StringRef> Comma = Conds.split(','); 2484 bool First = true; 2485 do { 2486 if (!First) 2487 OS << " && "; 2488 2489 bool Neg = false; 2490 StringRef Cond = Comma.first; 2491 if (Cond[0] == '!') { 2492 Neg = true; 2493 Cond = Cond.substr(1); 2494 } 2495 2496 OS << "("; 2497 if (Neg) 2498 OS << "!"; 2499 OS << "FB[" << Info.Target.getName() << "::" << Cond << "])"; 2500 2501 if (Comma.second.empty()) 2502 break; 2503 2504 First = false; 2505 Comma = Comma.second.split(','); 2506 } while (true); 2507 2508 OS << ")\n"; 2509 OS << " Features |= " << SFI.getEnumName() << ";\n"; 2510 } 2511 OS << " return Features;\n"; 2512 OS << "}\n\n"; 2513 } 2514 2515 static std::string GetAliasRequiredFeatures(Record *R, 2516 const AsmMatcherInfo &Info) { 2517 std::vector<Record*> ReqFeatures = R->getValueAsListOfDefs("Predicates"); 2518 std::string Result; 2519 unsigned NumFeatures = 0; 2520 for (unsigned i = 0, e = ReqFeatures.size(); i != e; ++i) { 2521 const SubtargetFeatureInfo *F = Info.getSubtargetFeature(ReqFeatures[i]); 2522 2523 if (!F) 2524 PrintFatalError(R->getLoc(), "Predicate '" + ReqFeatures[i]->getName() + 2525 "' is not marked as an AssemblerPredicate!"); 2526 2527 if (NumFeatures) 2528 Result += '|'; 2529 2530 Result += F->getEnumName(); 2531 ++NumFeatures; 2532 } 2533 2534 if (NumFeatures > 1) 2535 Result = '(' + Result + ')'; 2536 return Result; 2537 } 2538 2539 static void emitMnemonicAliasVariant(raw_ostream &OS,const AsmMatcherInfo &Info, 2540 std::vector<Record*> &Aliases, 2541 unsigned Indent = 0, 2542 StringRef AsmParserVariantName = StringRef()){ 2543 // Keep track of all the aliases from a mnemonic. Use an std::map so that the 2544 // iteration order of the map is stable. 2545 std::map<std::string, std::vector<Record*> > AliasesFromMnemonic; 2546 2547 for (Record *R : Aliases) { 2548 // FIXME: Allow AssemblerVariantName to be a comma separated list. 2549 std::string AsmVariantName = R->getValueAsString("AsmVariantName"); 2550 if (AsmVariantName != AsmParserVariantName) 2551 continue; 2552 AliasesFromMnemonic[R->getValueAsString("FromMnemonic")].push_back(R); 2553 } 2554 if (AliasesFromMnemonic.empty()) 2555 return; 2556 2557 // Process each alias a "from" mnemonic at a time, building the code executed 2558 // by the string remapper. 2559 std::vector<StringMatcher::StringPair> Cases; 2560 for (const auto &AliasEntry : AliasesFromMnemonic) { 2561 const std::vector<Record*> &ToVec = AliasEntry.second; 2562 2563 // Loop through each alias and emit code that handles each case. If there 2564 // are two instructions without predicates, emit an error. If there is one, 2565 // emit it last. 2566 std::string MatchCode; 2567 int AliasWithNoPredicate = -1; 2568 2569 for (unsigned i = 0, e = ToVec.size(); i != e; ++i) { 2570 Record *R = ToVec[i]; 2571 std::string FeatureMask = GetAliasRequiredFeatures(R, Info); 2572 2573 // If this unconditionally matches, remember it for later and diagnose 2574 // duplicates. 2575 if (FeatureMask.empty()) { 2576 if (AliasWithNoPredicate != -1) { 2577 // We can't have two aliases from the same mnemonic with no predicate. 2578 PrintError(ToVec[AliasWithNoPredicate]->getLoc(), 2579 "two MnemonicAliases with the same 'from' mnemonic!"); 2580 PrintFatalError(R->getLoc(), "this is the other MnemonicAlias."); 2581 } 2582 2583 AliasWithNoPredicate = i; 2584 continue; 2585 } 2586 if (R->getValueAsString("ToMnemonic") == AliasEntry.first) 2587 PrintFatalError(R->getLoc(), "MnemonicAlias to the same string"); 2588 2589 if (!MatchCode.empty()) 2590 MatchCode += "else "; 2591 MatchCode += "if ((Features & " + FeatureMask + ") == "+FeatureMask+")\n"; 2592 MatchCode += " Mnemonic = \"" +R->getValueAsString("ToMnemonic")+"\";\n"; 2593 } 2594 2595 if (AliasWithNoPredicate != -1) { 2596 Record *R = ToVec[AliasWithNoPredicate]; 2597 if (!MatchCode.empty()) 2598 MatchCode += "else\n "; 2599 MatchCode += "Mnemonic = \"" + R->getValueAsString("ToMnemonic")+"\";\n"; 2600 } 2601 2602 MatchCode += "return;"; 2603 2604 Cases.push_back(std::make_pair(AliasEntry.first, MatchCode)); 2605 } 2606 StringMatcher("Mnemonic", Cases, OS).Emit(Indent); 2607 } 2608 2609 /// emitMnemonicAliases - If the target has any MnemonicAlias<> definitions, 2610 /// emit a function for them and return true, otherwise return false. 2611 static bool emitMnemonicAliases(raw_ostream &OS, const AsmMatcherInfo &Info, 2612 CodeGenTarget &Target) { 2613 // Ignore aliases when match-prefix is set. 2614 if (!MatchPrefix.empty()) 2615 return false; 2616 2617 std::vector<Record*> Aliases = 2618 Info.getRecords().getAllDerivedDefinitions("MnemonicAlias"); 2619 if (Aliases.empty()) return false; 2620 2621 OS << "static void applyMnemonicAliases(StringRef &Mnemonic, " 2622 "uint64_t Features, unsigned VariantID) {\n"; 2623 OS << " switch (VariantID) {\n"; 2624 unsigned VariantCount = Target.getAsmParserVariantCount(); 2625 for (unsigned VC = 0; VC != VariantCount; ++VC) { 2626 Record *AsmVariant = Target.getAsmParserVariant(VC); 2627 int AsmParserVariantNo = AsmVariant->getValueAsInt("Variant"); 2628 std::string AsmParserVariantName = AsmVariant->getValueAsString("Name"); 2629 OS << " case " << AsmParserVariantNo << ":\n"; 2630 emitMnemonicAliasVariant(OS, Info, Aliases, /*Indent=*/2, 2631 AsmParserVariantName); 2632 OS << " break;\n"; 2633 } 2634 OS << " }\n"; 2635 2636 // Emit aliases that apply to all variants. 2637 emitMnemonicAliasVariant(OS, Info, Aliases); 2638 2639 OS << "}\n\n"; 2640 2641 return true; 2642 } 2643 2644 static void emitCustomOperandParsing(raw_ostream &OS, CodeGenTarget &Target, 2645 const AsmMatcherInfo &Info, StringRef ClassName, 2646 StringToOffsetTable &StringTable, 2647 unsigned MaxMnemonicIndex, bool HasMnemonicFirst) { 2648 unsigned MaxMask = 0; 2649 for (const OperandMatchEntry &OMI : Info.OperandMatchInfo) { 2650 MaxMask |= OMI.OperandMask; 2651 } 2652 2653 // Emit the static custom operand parsing table; 2654 OS << "namespace {\n"; 2655 OS << " struct OperandMatchEntry {\n"; 2656 OS << " " << getMinimalRequiredFeaturesType(Info) 2657 << " RequiredFeatures;\n"; 2658 OS << " " << getMinimalTypeForRange(MaxMnemonicIndex) 2659 << " Mnemonic;\n"; 2660 OS << " " << getMinimalTypeForRange(std::distance( 2661 Info.Classes.begin(), Info.Classes.end())) << " Class;\n"; 2662 OS << " " << getMinimalTypeForRange(MaxMask) 2663 << " OperandMask;\n\n"; 2664 OS << " StringRef getMnemonic() const {\n"; 2665 OS << " return StringRef(MnemonicTable + Mnemonic + 1,\n"; 2666 OS << " MnemonicTable[Mnemonic]);\n"; 2667 OS << " }\n"; 2668 OS << " };\n\n"; 2669 2670 OS << " // Predicate for searching for an opcode.\n"; 2671 OS << " struct LessOpcodeOperand {\n"; 2672 OS << " bool operator()(const OperandMatchEntry &LHS, StringRef RHS) {\n"; 2673 OS << " return LHS.getMnemonic() < RHS;\n"; 2674 OS << " }\n"; 2675 OS << " bool operator()(StringRef LHS, const OperandMatchEntry &RHS) {\n"; 2676 OS << " return LHS < RHS.getMnemonic();\n"; 2677 OS << " }\n"; 2678 OS << " bool operator()(const OperandMatchEntry &LHS,"; 2679 OS << " const OperandMatchEntry &RHS) {\n"; 2680 OS << " return LHS.getMnemonic() < RHS.getMnemonic();\n"; 2681 OS << " }\n"; 2682 OS << " };\n"; 2683 2684 OS << "} // end anonymous namespace.\n\n"; 2685 2686 OS << "static const OperandMatchEntry OperandMatchTable[" 2687 << Info.OperandMatchInfo.size() << "] = {\n"; 2688 2689 OS << " /* Operand List Mask, Mnemonic, Operand Class, Features */\n"; 2690 for (const OperandMatchEntry &OMI : Info.OperandMatchInfo) { 2691 const MatchableInfo &II = *OMI.MI; 2692 2693 OS << " { "; 2694 2695 // Write the required features mask. 2696 if (!II.RequiredFeatures.empty()) { 2697 for (unsigned i = 0, e = II.RequiredFeatures.size(); i != e; ++i) { 2698 if (i) OS << "|"; 2699 OS << II.RequiredFeatures[i]->getEnumName(); 2700 } 2701 } else 2702 OS << "0"; 2703 2704 // Store a pascal-style length byte in the mnemonic. 2705 std::string LenMnemonic = char(II.Mnemonic.size()) + II.Mnemonic.str(); 2706 OS << ", " << StringTable.GetOrAddStringOffset(LenMnemonic, false) 2707 << " /* " << II.Mnemonic << " */, "; 2708 2709 OS << OMI.CI->Name; 2710 2711 OS << ", " << OMI.OperandMask; 2712 OS << " /* "; 2713 bool printComma = false; 2714 for (int i = 0, e = 31; i !=e; ++i) 2715 if (OMI.OperandMask & (1 << i)) { 2716 if (printComma) 2717 OS << ", "; 2718 OS << i; 2719 printComma = true; 2720 } 2721 OS << " */"; 2722 2723 OS << " },\n"; 2724 } 2725 OS << "};\n\n"; 2726 2727 // Emit the operand class switch to call the correct custom parser for 2728 // the found operand class. 2729 OS << Target.getName() << ClassName << "::OperandMatchResultTy " 2730 << Target.getName() << ClassName << "::\n" 2731 << "tryCustomParseOperand(OperandVector" 2732 << " &Operands,\n unsigned MCK) {\n\n" 2733 << " switch(MCK) {\n"; 2734 2735 for (const auto &CI : Info.Classes) { 2736 if (CI.ParserMethod.empty()) 2737 continue; 2738 OS << " case " << CI.Name << ":\n" 2739 << " return " << CI.ParserMethod << "(Operands);\n"; 2740 } 2741 2742 OS << " default:\n"; 2743 OS << " return MatchOperand_NoMatch;\n"; 2744 OS << " }\n"; 2745 OS << " return MatchOperand_NoMatch;\n"; 2746 OS << "}\n\n"; 2747 2748 // Emit the static custom operand parser. This code is very similar with 2749 // the other matcher. Also use MatchResultTy here just in case we go for 2750 // a better error handling. 2751 OS << Target.getName() << ClassName << "::OperandMatchResultTy " 2752 << Target.getName() << ClassName << "::\n" 2753 << "MatchOperandParserImpl(OperandVector" 2754 << " &Operands,\n StringRef Mnemonic) {\n"; 2755 2756 // Emit code to get the available features. 2757 OS << " // Get the current feature set.\n"; 2758 OS << " uint64_t AvailableFeatures = getAvailableFeatures();\n\n"; 2759 2760 OS << " // Get the next operand index.\n"; 2761 OS << " unsigned NextOpNum = Operands.size()" 2762 << (HasMnemonicFirst ? " - 1" : "") << ";\n"; 2763 2764 // Emit code to search the table. 2765 OS << " // Search the table.\n"; 2766 if (HasMnemonicFirst) { 2767 OS << " auto MnemonicRange =\n"; 2768 OS << " std::equal_range(std::begin(OperandMatchTable), " 2769 "std::end(OperandMatchTable),\n"; 2770 OS << " Mnemonic, LessOpcodeOperand());\n\n"; 2771 } else { 2772 OS << " auto MnemonicRange = std::make_pair(std::begin(OperandMatchTable)," 2773 " std::end(OperandMatchTable));\n"; 2774 OS << " if (!Mnemonic.empty())\n"; 2775 OS << " MnemonicRange =\n"; 2776 OS << " std::equal_range(std::begin(OperandMatchTable), " 2777 "std::end(OperandMatchTable),\n"; 2778 OS << " Mnemonic, LessOpcodeOperand());\n\n"; 2779 } 2780 2781 OS << " if (MnemonicRange.first == MnemonicRange.second)\n"; 2782 OS << " return MatchOperand_NoMatch;\n\n"; 2783 2784 OS << " for (const OperandMatchEntry *it = MnemonicRange.first,\n" 2785 << " *ie = MnemonicRange.second; it != ie; ++it) {\n"; 2786 2787 OS << " // equal_range guarantees that instruction mnemonic matches.\n"; 2788 OS << " assert(Mnemonic == it->getMnemonic());\n\n"; 2789 2790 // Emit check that the required features are available. 2791 OS << " // check if the available features match\n"; 2792 OS << " if ((AvailableFeatures & it->RequiredFeatures) " 2793 << "!= it->RequiredFeatures) {\n"; 2794 OS << " continue;\n"; 2795 OS << " }\n\n"; 2796 2797 // Emit check to ensure the operand number matches. 2798 OS << " // check if the operand in question has a custom parser.\n"; 2799 OS << " if (!(it->OperandMask & (1 << NextOpNum)))\n"; 2800 OS << " continue;\n\n"; 2801 2802 // Emit call to the custom parser method 2803 OS << " // call custom parse method to handle the operand\n"; 2804 OS << " OperandMatchResultTy Result = "; 2805 OS << "tryCustomParseOperand(Operands, it->Class);\n"; 2806 OS << " if (Result != MatchOperand_NoMatch)\n"; 2807 OS << " return Result;\n"; 2808 OS << " }\n\n"; 2809 2810 OS << " // Okay, we had no match.\n"; 2811 OS << " return MatchOperand_NoMatch;\n"; 2812 OS << "}\n\n"; 2813 } 2814 2815 void AsmMatcherEmitter::run(raw_ostream &OS) { 2816 CodeGenTarget Target(Records); 2817 Record *AsmParser = Target.getAsmParser(); 2818 std::string ClassName = AsmParser->getValueAsString("AsmParserClassName"); 2819 2820 // Compute the information on the instructions to match. 2821 AsmMatcherInfo Info(AsmParser, Target, Records); 2822 Info.buildInfo(); 2823 2824 // Sort the instruction table using the partial order on classes. We use 2825 // stable_sort to ensure that ambiguous instructions are still 2826 // deterministically ordered. 2827 std::stable_sort(Info.Matchables.begin(), Info.Matchables.end(), 2828 [](const std::unique_ptr<MatchableInfo> &a, 2829 const std::unique_ptr<MatchableInfo> &b){ 2830 return *a < *b;}); 2831 2832 #ifndef NDEBUG 2833 // Verify that the table is now sorted 2834 for (auto I = Info.Matchables.begin(), E = Info.Matchables.end(); I != E; 2835 ++I) { 2836 for (auto J = I; J != E; ++J) { 2837 assert(!(**J < **I)); 2838 } 2839 } 2840 #endif // NDEBUG 2841 2842 DEBUG_WITH_TYPE("instruction_info", { 2843 for (const auto &MI : Info.Matchables) 2844 MI->dump(); 2845 }); 2846 2847 // Check for ambiguous matchables. 2848 DEBUG_WITH_TYPE("ambiguous_instrs", { 2849 unsigned NumAmbiguous = 0; 2850 for (auto I = Info.Matchables.begin(), E = Info.Matchables.end(); I != E; 2851 ++I) { 2852 for (auto J = std::next(I); J != E; ++J) { 2853 const MatchableInfo &A = **I; 2854 const MatchableInfo &B = **J; 2855 2856 if (A.couldMatchAmbiguouslyWith(B)) { 2857 errs() << "warning: ambiguous matchables:\n"; 2858 A.dump(); 2859 errs() << "\nis incomparable with:\n"; 2860 B.dump(); 2861 errs() << "\n\n"; 2862 ++NumAmbiguous; 2863 } 2864 } 2865 } 2866 if (NumAmbiguous) 2867 errs() << "warning: " << NumAmbiguous 2868 << " ambiguous matchables!\n"; 2869 }); 2870 2871 // Compute the information on the custom operand parsing. 2872 Info.buildOperandMatchInfo(); 2873 2874 bool HasMnemonicFirst = AsmParser->getValueAsBit("HasMnemonicFirst"); 2875 bool HasOptionalOperands = Info.hasOptionalOperands(); 2876 2877 // Write the output. 2878 2879 // Information for the class declaration. 2880 OS << "\n#ifdef GET_ASSEMBLER_HEADER\n"; 2881 OS << "#undef GET_ASSEMBLER_HEADER\n"; 2882 OS << " // This should be included into the middle of the declaration of\n"; 2883 OS << " // your subclasses implementation of MCTargetAsmParser.\n"; 2884 OS << " uint64_t ComputeAvailableFeatures(const FeatureBitset& FB) const;\n"; 2885 if (HasOptionalOperands) { 2886 OS << " void convertToMCInst(unsigned Kind, MCInst &Inst, " 2887 << "unsigned Opcode,\n" 2888 << " const OperandVector &Operands,\n" 2889 << " const SmallBitVector &OptionalOperandsMask);\n"; 2890 } else { 2891 OS << " void convertToMCInst(unsigned Kind, MCInst &Inst, " 2892 << "unsigned Opcode,\n" 2893 << " const OperandVector &Operands);\n"; 2894 } 2895 OS << " void convertToMapAndConstraints(unsigned Kind,\n "; 2896 OS << " const OperandVector &Operands) override;\n"; 2897 if (HasMnemonicFirst) 2898 OS << " bool mnemonicIsValid(StringRef Mnemonic, unsigned VariantID);\n"; 2899 OS << " unsigned MatchInstructionImpl(const OperandVector &Operands,\n" 2900 << " MCInst &Inst,\n" 2901 << " uint64_t &ErrorInfo," 2902 << " bool matchingInlineAsm,\n" 2903 << " unsigned VariantID = 0);\n"; 2904 2905 if (!Info.OperandMatchInfo.empty()) { 2906 OS << "\n enum OperandMatchResultTy {\n"; 2907 OS << " MatchOperand_Success, // operand matched successfully\n"; 2908 OS << " MatchOperand_NoMatch, // operand did not match\n"; 2909 OS << " MatchOperand_ParseFail // operand matched but had errors\n"; 2910 OS << " };\n"; 2911 OS << " OperandMatchResultTy MatchOperandParserImpl(\n"; 2912 OS << " OperandVector &Operands,\n"; 2913 OS << " StringRef Mnemonic);\n"; 2914 2915 OS << " OperandMatchResultTy tryCustomParseOperand(\n"; 2916 OS << " OperandVector &Operands,\n"; 2917 OS << " unsigned MCK);\n\n"; 2918 } 2919 2920 OS << "#endif // GET_ASSEMBLER_HEADER_INFO\n\n"; 2921 2922 // Emit the operand match diagnostic enum names. 2923 OS << "\n#ifdef GET_OPERAND_DIAGNOSTIC_TYPES\n"; 2924 OS << "#undef GET_OPERAND_DIAGNOSTIC_TYPES\n\n"; 2925 emitOperandDiagnosticTypes(Info, OS); 2926 OS << "#endif // GET_OPERAND_DIAGNOSTIC_TYPES\n\n"; 2927 2928 OS << "\n#ifdef GET_REGISTER_MATCHER\n"; 2929 OS << "#undef GET_REGISTER_MATCHER\n\n"; 2930 2931 // Emit the subtarget feature enumeration. 2932 emitSubtargetFeatureFlagEnumeration(Info, OS); 2933 2934 // Emit the function to match a register name to number. 2935 // This should be omitted for Mips target 2936 if (AsmParser->getValueAsBit("ShouldEmitMatchRegisterName")) 2937 emitMatchRegisterName(Target, AsmParser, OS); 2938 2939 if (AsmParser->getValueAsBit("ShouldEmitMatchRegisterAltName")) 2940 emitMatchRegisterAltName(Target, AsmParser, OS); 2941 2942 OS << "#endif // GET_REGISTER_MATCHER\n\n"; 2943 2944 OS << "\n#ifdef GET_SUBTARGET_FEATURE_NAME\n"; 2945 OS << "#undef GET_SUBTARGET_FEATURE_NAME\n\n"; 2946 2947 // Generate the helper function to get the names for subtarget features. 2948 emitGetSubtargetFeatureName(Info, OS); 2949 2950 OS << "#endif // GET_SUBTARGET_FEATURE_NAME\n\n"; 2951 2952 OS << "\n#ifdef GET_MATCHER_IMPLEMENTATION\n"; 2953 OS << "#undef GET_MATCHER_IMPLEMENTATION\n\n"; 2954 2955 // Generate the function that remaps for mnemonic aliases. 2956 bool HasMnemonicAliases = emitMnemonicAliases(OS, Info, Target); 2957 2958 // Generate the convertToMCInst function to convert operands into an MCInst. 2959 // Also, generate the convertToMapAndConstraints function for MS-style inline 2960 // assembly. The latter doesn't actually generate a MCInst. 2961 emitConvertFuncs(Target, ClassName, Info.Matchables, HasMnemonicFirst, 2962 HasOptionalOperands, OS); 2963 2964 // Emit the enumeration for classes which participate in matching. 2965 emitMatchClassEnumeration(Target, Info.Classes, OS); 2966 2967 // Emit the routine to match token strings to their match class. 2968 emitMatchTokenString(Target, Info.Classes, OS); 2969 2970 // Emit the subclass predicate routine. 2971 emitIsSubclass(Target, Info.Classes, OS); 2972 2973 // Emit the routine to validate an operand against a match class. 2974 emitValidateOperandClass(Info, OS); 2975 2976 // Emit the available features compute function. 2977 emitComputeAvailableFeatures(Info, OS); 2978 2979 StringToOffsetTable StringTable; 2980 2981 size_t MaxNumOperands = 0; 2982 unsigned MaxMnemonicIndex = 0; 2983 bool HasDeprecation = false; 2984 for (const auto &MI : Info.Matchables) { 2985 MaxNumOperands = std::max(MaxNumOperands, MI->AsmOperands.size()); 2986 HasDeprecation |= MI->HasDeprecation; 2987 2988 // Store a pascal-style length byte in the mnemonic. 2989 std::string LenMnemonic = char(MI->Mnemonic.size()) + MI->Mnemonic.str(); 2990 MaxMnemonicIndex = std::max(MaxMnemonicIndex, 2991 StringTable.GetOrAddStringOffset(LenMnemonic, false)); 2992 } 2993 2994 OS << "static const char *const MnemonicTable =\n"; 2995 StringTable.EmitString(OS); 2996 OS << ";\n\n"; 2997 2998 // Emit the static match table; unused classes get initalized to 0 which is 2999 // guaranteed to be InvalidMatchClass. 3000 // 3001 // FIXME: We can reduce the size of this table very easily. First, we change 3002 // it so that store the kinds in separate bit-fields for each index, which 3003 // only needs to be the max width used for classes at that index (we also need 3004 // to reject based on this during classification). If we then make sure to 3005 // order the match kinds appropriately (putting mnemonics last), then we 3006 // should only end up using a few bits for each class, especially the ones 3007 // following the mnemonic. 3008 OS << "namespace {\n"; 3009 OS << " struct MatchEntry {\n"; 3010 OS << " " << getMinimalTypeForRange(MaxMnemonicIndex) 3011 << " Mnemonic;\n"; 3012 OS << " uint16_t Opcode;\n"; 3013 OS << " " << getMinimalTypeForRange(Info.Matchables.size()) 3014 << " ConvertFn;\n"; 3015 OS << " " << getMinimalRequiredFeaturesType(Info) 3016 << " RequiredFeatures;\n"; 3017 OS << " " << getMinimalTypeForRange( 3018 std::distance(Info.Classes.begin(), Info.Classes.end())) 3019 << " Classes[" << MaxNumOperands << "];\n"; 3020 OS << " StringRef getMnemonic() const {\n"; 3021 OS << " return StringRef(MnemonicTable + Mnemonic + 1,\n"; 3022 OS << " MnemonicTable[Mnemonic]);\n"; 3023 OS << " }\n"; 3024 OS << " };\n\n"; 3025 3026 OS << " // Predicate for searching for an opcode.\n"; 3027 OS << " struct LessOpcode {\n"; 3028 OS << " bool operator()(const MatchEntry &LHS, StringRef RHS) {\n"; 3029 OS << " return LHS.getMnemonic() < RHS;\n"; 3030 OS << " }\n"; 3031 OS << " bool operator()(StringRef LHS, const MatchEntry &RHS) {\n"; 3032 OS << " return LHS < RHS.getMnemonic();\n"; 3033 OS << " }\n"; 3034 OS << " bool operator()(const MatchEntry &LHS, const MatchEntry &RHS) {\n"; 3035 OS << " return LHS.getMnemonic() < RHS.getMnemonic();\n"; 3036 OS << " }\n"; 3037 OS << " };\n"; 3038 3039 OS << "} // end anonymous namespace.\n\n"; 3040 3041 unsigned VariantCount = Target.getAsmParserVariantCount(); 3042 for (unsigned VC = 0; VC != VariantCount; ++VC) { 3043 Record *AsmVariant = Target.getAsmParserVariant(VC); 3044 int AsmVariantNo = AsmVariant->getValueAsInt("Variant"); 3045 3046 OS << "static const MatchEntry MatchTable" << VC << "[] = {\n"; 3047 3048 for (const auto &MI : Info.Matchables) { 3049 if (MI->AsmVariantID != AsmVariantNo) 3050 continue; 3051 3052 // Store a pascal-style length byte in the mnemonic. 3053 std::string LenMnemonic = char(MI->Mnemonic.size()) + MI->Mnemonic.str(); 3054 OS << " { " << StringTable.GetOrAddStringOffset(LenMnemonic, false) 3055 << " /* " << MI->Mnemonic << " */, " 3056 << Target.getName() << "::" 3057 << MI->getResultInst()->TheDef->getName() << ", " 3058 << MI->ConversionFnKind << ", "; 3059 3060 // Write the required features mask. 3061 if (!MI->RequiredFeatures.empty()) { 3062 for (unsigned i = 0, e = MI->RequiredFeatures.size(); i != e; ++i) { 3063 if (i) OS << "|"; 3064 OS << MI->RequiredFeatures[i]->getEnumName(); 3065 } 3066 } else 3067 OS << "0"; 3068 3069 OS << ", { "; 3070 for (unsigned i = 0, e = MI->AsmOperands.size(); i != e; ++i) { 3071 const MatchableInfo::AsmOperand &Op = MI->AsmOperands[i]; 3072 3073 if (i) OS << ", "; 3074 OS << Op.Class->Name; 3075 } 3076 OS << " }, },\n"; 3077 } 3078 3079 OS << "};\n\n"; 3080 } 3081 3082 // A method to determine if a mnemonic is in the list. 3083 if (HasMnemonicFirst) { 3084 OS << "bool " << Target.getName() << ClassName << "::\n" 3085 << "mnemonicIsValid(StringRef Mnemonic, unsigned VariantID) {\n"; 3086 OS << " // Find the appropriate table for this asm variant.\n"; 3087 OS << " const MatchEntry *Start, *End;\n"; 3088 OS << " switch (VariantID) {\n"; 3089 OS << " default: llvm_unreachable(\"invalid variant!\");\n"; 3090 for (unsigned VC = 0; VC != VariantCount; ++VC) { 3091 Record *AsmVariant = Target.getAsmParserVariant(VC); 3092 int AsmVariantNo = AsmVariant->getValueAsInt("Variant"); 3093 OS << " case " << AsmVariantNo << ": Start = std::begin(MatchTable" << VC 3094 << "); End = std::end(MatchTable" << VC << "); break;\n"; 3095 } 3096 OS << " }\n"; 3097 OS << " // Search the table.\n"; 3098 OS << " auto MnemonicRange = "; 3099 OS << "std::equal_range(Start, End, Mnemonic, LessOpcode());\n"; 3100 OS << " return MnemonicRange.first != MnemonicRange.second;\n"; 3101 OS << "}\n\n"; 3102 } 3103 3104 // Finally, build the match function. 3105 OS << "unsigned " << Target.getName() << ClassName << "::\n" 3106 << "MatchInstructionImpl(const OperandVector &Operands,\n"; 3107 OS << " MCInst &Inst, uint64_t &ErrorInfo,\n" 3108 << " bool matchingInlineAsm, unsigned VariantID) {\n"; 3109 3110 OS << " // Eliminate obvious mismatches.\n"; 3111 OS << " if (Operands.size() > " 3112 << (MaxNumOperands + HasMnemonicFirst) << ") {\n"; 3113 OS << " ErrorInfo = " 3114 << (MaxNumOperands + HasMnemonicFirst) << ";\n"; 3115 OS << " return Match_InvalidOperand;\n"; 3116 OS << " }\n\n"; 3117 3118 // Emit code to get the available features. 3119 OS << " // Get the current feature set.\n"; 3120 OS << " uint64_t AvailableFeatures = getAvailableFeatures();\n\n"; 3121 3122 OS << " // Get the instruction mnemonic, which is the first token.\n"; 3123 if (HasMnemonicFirst) { 3124 OS << " StringRef Mnemonic = ((" << Target.getName() 3125 << "Operand&)*Operands[0]).getToken();\n\n"; 3126 } else { 3127 OS << " StringRef Mnemonic;\n"; 3128 OS << " if (Operands[0]->isToken())\n"; 3129 OS << " Mnemonic = ((" << Target.getName() 3130 << "Operand&)*Operands[0]).getToken();\n\n"; 3131 } 3132 3133 if (HasMnemonicAliases) { 3134 OS << " // Process all MnemonicAliases to remap the mnemonic.\n"; 3135 OS << " applyMnemonicAliases(Mnemonic, AvailableFeatures, VariantID);\n\n"; 3136 } 3137 3138 // Emit code to compute the class list for this operand vector. 3139 OS << " // Some state to try to produce better error messages.\n"; 3140 OS << " bool HadMatchOtherThanFeatures = false;\n"; 3141 OS << " bool HadMatchOtherThanPredicate = false;\n"; 3142 OS << " unsigned RetCode = Match_InvalidOperand;\n"; 3143 OS << " uint64_t MissingFeatures = ~0ULL;\n"; 3144 if (HasOptionalOperands) { 3145 OS << " SmallBitVector OptionalOperandsMask(" << MaxNumOperands << ");\n"; 3146 } 3147 OS << " // Set ErrorInfo to the operand that mismatches if it is\n"; 3148 OS << " // wrong for all instances of the instruction.\n"; 3149 OS << " ErrorInfo = ~0ULL;\n"; 3150 3151 // Emit code to search the table. 3152 OS << " // Find the appropriate table for this asm variant.\n"; 3153 OS << " const MatchEntry *Start, *End;\n"; 3154 OS << " switch (VariantID) {\n"; 3155 OS << " default: llvm_unreachable(\"invalid variant!\");\n"; 3156 for (unsigned VC = 0; VC != VariantCount; ++VC) { 3157 Record *AsmVariant = Target.getAsmParserVariant(VC); 3158 int AsmVariantNo = AsmVariant->getValueAsInt("Variant"); 3159 OS << " case " << AsmVariantNo << ": Start = std::begin(MatchTable" << VC 3160 << "); End = std::end(MatchTable" << VC << "); break;\n"; 3161 } 3162 OS << " }\n"; 3163 3164 OS << " // Search the table.\n"; 3165 if (HasMnemonicFirst) { 3166 OS << " auto MnemonicRange = " 3167 "std::equal_range(Start, End, Mnemonic, LessOpcode());\n\n"; 3168 } else { 3169 OS << " auto MnemonicRange = std::make_pair(Start, End);\n"; 3170 OS << " unsigned SIndex = Mnemonic.empty() ? 0 : 1;\n"; 3171 OS << " if (!Mnemonic.empty())\n"; 3172 OS << " MnemonicRange = " 3173 "std::equal_range(Start, End, Mnemonic.lower(), LessOpcode());\n\n"; 3174 } 3175 3176 OS << " // Return a more specific error code if no mnemonics match.\n"; 3177 OS << " if (MnemonicRange.first == MnemonicRange.second)\n"; 3178 OS << " return Match_MnemonicFail;\n\n"; 3179 3180 OS << " for (const MatchEntry *it = MnemonicRange.first, " 3181 << "*ie = MnemonicRange.second;\n"; 3182 OS << " it != ie; ++it) {\n"; 3183 3184 if (HasMnemonicFirst) { 3185 OS << " // equal_range guarantees that instruction mnemonic matches.\n"; 3186 OS << " assert(Mnemonic == it->getMnemonic());\n"; 3187 } 3188 3189 // Emit check that the subclasses match. 3190 OS << " bool OperandsValid = true;\n"; 3191 if (HasOptionalOperands) { 3192 OS << " OptionalOperandsMask.reset(0, " << MaxNumOperands << ");\n"; 3193 } 3194 OS << " for (unsigned FormalIdx = " << (HasMnemonicFirst ? "0" : "SIndex") 3195 << ", ActualIdx = " << (HasMnemonicFirst ? "1" : "SIndex") 3196 << "; FormalIdx != " << MaxNumOperands << "; ++FormalIdx) {\n"; 3197 OS << " auto Formal = " 3198 << "static_cast<MatchClassKind>(it->Classes[FormalIdx]);\n"; 3199 OS << " if (ActualIdx >= Operands.size()) {\n"; 3200 OS << " OperandsValid = (Formal == " <<"InvalidMatchClass) || " 3201 "isSubclass(Formal, OptionalMatchClass);\n"; 3202 OS << " if (!OperandsValid) ErrorInfo = ActualIdx;\n"; 3203 if (HasOptionalOperands) { 3204 OS << " OptionalOperandsMask.set(FormalIdx, " << MaxNumOperands 3205 << ");\n"; 3206 } 3207 OS << " break;\n"; 3208 OS << " }\n"; 3209 OS << " MCParsedAsmOperand &Actual = *Operands[ActualIdx];\n"; 3210 OS << " unsigned Diag = validateOperandClass(Actual, Formal);\n"; 3211 OS << " if (Diag == Match_Success) {\n"; 3212 OS << " ++ActualIdx;\n"; 3213 OS << " continue;\n"; 3214 OS << " }\n"; 3215 OS << " // If the generic handler indicates an invalid operand\n"; 3216 OS << " // failure, check for a special case.\n"; 3217 OS << " if (Diag == Match_InvalidOperand) {\n"; 3218 OS << " Diag = validateTargetOperandClass(Actual, Formal);\n"; 3219 OS << " if (Diag == Match_Success) {\n"; 3220 OS << " ++ActualIdx;\n"; 3221 OS << " continue;\n"; 3222 OS << " }\n"; 3223 OS << " }\n"; 3224 OS << " // If current formal operand wasn't matched and it is optional\n" 3225 << " // then try to match next formal operand\n"; 3226 OS << " if (Diag == Match_InvalidOperand " 3227 << "&& isSubclass(Formal, OptionalMatchClass)) {\n"; 3228 if (HasOptionalOperands) { 3229 OS << " OptionalOperandsMask.set(FormalIdx);\n"; 3230 } 3231 OS << " continue;\n"; 3232 OS << " }\n"; 3233 OS << " // If this operand is broken for all of the instances of this\n"; 3234 OS << " // mnemonic, keep track of it so we can report loc info.\n"; 3235 OS << " // If we already had a match that only failed due to a\n"; 3236 OS << " // target predicate, that diagnostic is preferred.\n"; 3237 OS << " if (!HadMatchOtherThanPredicate &&\n"; 3238 OS << " (it == MnemonicRange.first || ErrorInfo <= ActualIdx)) {\n"; 3239 OS << " ErrorInfo = ActualIdx;\n"; 3240 OS << " // InvalidOperand is the default. Prefer specificity.\n"; 3241 OS << " if (Diag != Match_InvalidOperand)\n"; 3242 OS << " RetCode = Diag;\n"; 3243 OS << " }\n"; 3244 OS << " // Otherwise, just reject this instance of the mnemonic.\n"; 3245 OS << " OperandsValid = false;\n"; 3246 OS << " break;\n"; 3247 OS << " }\n\n"; 3248 3249 OS << " if (!OperandsValid) continue;\n"; 3250 3251 // Emit check that the required features are available. 3252 OS << " if ((AvailableFeatures & it->RequiredFeatures) " 3253 << "!= it->RequiredFeatures) {\n"; 3254 OS << " HadMatchOtherThanFeatures = true;\n"; 3255 OS << " uint64_t NewMissingFeatures = it->RequiredFeatures & " 3256 "~AvailableFeatures;\n"; 3257 OS << " if (countPopulation(NewMissingFeatures) <=\n" 3258 " countPopulation(MissingFeatures))\n"; 3259 OS << " MissingFeatures = NewMissingFeatures;\n"; 3260 OS << " continue;\n"; 3261 OS << " }\n"; 3262 OS << "\n"; 3263 OS << " Inst.clear();\n\n"; 3264 OS << " Inst.setOpcode(it->Opcode);\n"; 3265 // Verify the instruction with the target-specific match predicate function. 3266 OS << " // We have a potential match but have not rendered the operands.\n" 3267 << " // Check the target predicate to handle any context sensitive\n" 3268 " // constraints.\n" 3269 << " // For example, Ties that are referenced multiple times must be\n" 3270 " // checked here to ensure the input is the same for each match\n" 3271 " // constraints. If we leave it any later the ties will have been\n" 3272 " // canonicalized\n" 3273 << " unsigned MatchResult;\n" 3274 << " if ((MatchResult = checkEarlyTargetMatchPredicate(Inst, " 3275 "Operands)) != Match_Success) {\n" 3276 << " Inst.clear();\n" 3277 << " RetCode = MatchResult;\n" 3278 << " HadMatchOtherThanPredicate = true;\n" 3279 << " continue;\n" 3280 << " }\n\n"; 3281 OS << " if (matchingInlineAsm) {\n"; 3282 OS << " convertToMapAndConstraints(it->ConvertFn, Operands);\n"; 3283 OS << " return Match_Success;\n"; 3284 OS << " }\n\n"; 3285 OS << " // We have selected a definite instruction, convert the parsed\n" 3286 << " // operands into the appropriate MCInst.\n"; 3287 if (HasOptionalOperands) { 3288 OS << " convertToMCInst(it->ConvertFn, Inst, it->Opcode, Operands,\n" 3289 << " OptionalOperandsMask);\n"; 3290 } else { 3291 OS << " convertToMCInst(it->ConvertFn, Inst, it->Opcode, Operands);\n"; 3292 } 3293 OS << "\n"; 3294 3295 // Verify the instruction with the target-specific match predicate function. 3296 OS << " // We have a potential match. Check the target predicate to\n" 3297 << " // handle any context sensitive constraints.\n" 3298 << " if ((MatchResult = checkTargetMatchPredicate(Inst)) !=" 3299 << " Match_Success) {\n" 3300 << " Inst.clear();\n" 3301 << " RetCode = MatchResult;\n" 3302 << " HadMatchOtherThanPredicate = true;\n" 3303 << " continue;\n" 3304 << " }\n\n"; 3305 3306 // Call the post-processing function, if used. 3307 std::string InsnCleanupFn = 3308 AsmParser->getValueAsString("AsmParserInstCleanup"); 3309 if (!InsnCleanupFn.empty()) 3310 OS << " " << InsnCleanupFn << "(Inst);\n"; 3311 3312 if (HasDeprecation) { 3313 OS << " std::string Info;\n"; 3314 OS << " if (MII.get(Inst.getOpcode()).getDeprecatedInfo(Inst, getSTI(), Info)) {\n"; 3315 OS << " SMLoc Loc = ((" << Target.getName() 3316 << "Operand&)*Operands[0]).getStartLoc();\n"; 3317 OS << " getParser().Warning(Loc, Info, None);\n"; 3318 OS << " }\n"; 3319 } 3320 3321 OS << " return Match_Success;\n"; 3322 OS << " }\n\n"; 3323 3324 OS << " // Okay, we had no match. Try to return a useful error code.\n"; 3325 OS << " if (HadMatchOtherThanPredicate || !HadMatchOtherThanFeatures)\n"; 3326 OS << " return RetCode;\n\n"; 3327 OS << " // Missing feature matches return which features were missing\n"; 3328 OS << " ErrorInfo = MissingFeatures;\n"; 3329 OS << " return Match_MissingFeature;\n"; 3330 OS << "}\n\n"; 3331 3332 if (!Info.OperandMatchInfo.empty()) 3333 emitCustomOperandParsing(OS, Target, Info, ClassName, StringTable, 3334 MaxMnemonicIndex, HasMnemonicFirst); 3335 3336 OS << "#endif // GET_MATCHER_IMPLEMENTATION\n\n"; 3337 } 3338 3339 namespace llvm { 3340 3341 void EmitAsmMatcher(RecordKeeper &RK, raw_ostream &OS) { 3342 emitSourceFileHeader("Assembly Matcher Source Fragment", OS); 3343 AsmMatcherEmitter(RK).run(OS); 3344 } 3345 3346 } // end namespace llvm 3347