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