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