1 //===------------ FixedLenDecoderEmitter.cpp - Decoder Generator ----------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // It contains the tablegen backend that emits the decoder functions for 10 // targets with fixed length instruction set. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "CodeGenInstruction.h" 15 #include "CodeGenTarget.h" 16 #include "InfoByHwMode.h" 17 #include "llvm/ADT/APInt.h" 18 #include "llvm/ADT/ArrayRef.h" 19 #include "llvm/ADT/CachedHashString.h" 20 #include "llvm/ADT/STLExtras.h" 21 #include "llvm/ADT/SetVector.h" 22 #include "llvm/ADT/SmallString.h" 23 #include "llvm/ADT/Statistic.h" 24 #include "llvm/ADT/StringExtras.h" 25 #include "llvm/ADT/StringRef.h" 26 #include "llvm/MC/MCFixedLenDisassembler.h" 27 #include "llvm/Support/Casting.h" 28 #include "llvm/Support/Debug.h" 29 #include "llvm/Support/ErrorHandling.h" 30 #include "llvm/Support/FormattedStream.h" 31 #include "llvm/Support/LEB128.h" 32 #include "llvm/Support/raw_ostream.h" 33 #include "llvm/TableGen/Error.h" 34 #include "llvm/TableGen/Record.h" 35 #include <algorithm> 36 #include <cassert> 37 #include <cstddef> 38 #include <cstdint> 39 #include <map> 40 #include <memory> 41 #include <set> 42 #include <string> 43 #include <utility> 44 #include <vector> 45 46 using namespace llvm; 47 48 #define DEBUG_TYPE "decoder-emitter" 49 50 namespace { 51 52 STATISTIC(NumEncodings, "Number of encodings considered"); 53 STATISTIC(NumEncodingsLackingDisasm, "Number of encodings without disassembler info"); 54 STATISTIC(NumInstructions, "Number of instructions considered"); 55 STATISTIC(NumEncodingsSupported, "Number of encodings supported"); 56 STATISTIC(NumEncodingsOmitted, "Number of encodings omitted"); 57 58 struct EncodingField { 59 unsigned Base, Width, Offset; 60 EncodingField(unsigned B, unsigned W, unsigned O) 61 : Base(B), Width(W), Offset(O) { } 62 }; 63 64 struct OperandInfo { 65 std::vector<EncodingField> Fields; 66 std::string Decoder; 67 bool HasCompleteDecoder; 68 uint64_t InitValue; 69 70 OperandInfo(std::string D, bool HCD) 71 : Decoder(std::move(D)), HasCompleteDecoder(HCD), InitValue(0) {} 72 73 void addField(unsigned Base, unsigned Width, unsigned Offset) { 74 Fields.push_back(EncodingField(Base, Width, Offset)); 75 } 76 77 unsigned numFields() const { return Fields.size(); } 78 79 typedef std::vector<EncodingField>::const_iterator const_iterator; 80 81 const_iterator begin() const { return Fields.begin(); } 82 const_iterator end() const { return Fields.end(); } 83 }; 84 85 typedef std::vector<uint8_t> DecoderTable; 86 typedef uint32_t DecoderFixup; 87 typedef std::vector<DecoderFixup> FixupList; 88 typedef std::vector<FixupList> FixupScopeList; 89 typedef SmallSetVector<CachedHashString, 16> PredicateSet; 90 typedef SmallSetVector<CachedHashString, 16> DecoderSet; 91 struct DecoderTableInfo { 92 DecoderTable Table; 93 FixupScopeList FixupStack; 94 PredicateSet Predicates; 95 DecoderSet Decoders; 96 }; 97 98 struct EncodingAndInst { 99 const Record *EncodingDef; 100 const CodeGenInstruction *Inst; 101 StringRef HwModeName; 102 103 EncodingAndInst(const Record *EncodingDef, const CodeGenInstruction *Inst, 104 StringRef HwModeName = "") 105 : EncodingDef(EncodingDef), Inst(Inst), HwModeName(HwModeName) {} 106 }; 107 108 struct EncodingIDAndOpcode { 109 unsigned EncodingID; 110 unsigned Opcode; 111 112 EncodingIDAndOpcode() : EncodingID(0), Opcode(0) {} 113 EncodingIDAndOpcode(unsigned EncodingID, unsigned Opcode) 114 : EncodingID(EncodingID), Opcode(Opcode) {} 115 }; 116 117 raw_ostream &operator<<(raw_ostream &OS, const EncodingAndInst &Value) { 118 if (Value.EncodingDef != Value.Inst->TheDef) 119 OS << Value.EncodingDef->getName() << ":"; 120 OS << Value.Inst->TheDef->getName(); 121 return OS; 122 } 123 124 class FixedLenDecoderEmitter { 125 RecordKeeper &RK; 126 std::vector<EncodingAndInst> NumberedEncodings; 127 128 public: 129 // Defaults preserved here for documentation, even though they aren't 130 // strictly necessary given the way that this is currently being called. 131 FixedLenDecoderEmitter(RecordKeeper &R, std::string PredicateNamespace, 132 std::string GPrefix = "if (", 133 std::string GPostfix = " == MCDisassembler::Fail)", 134 std::string ROK = "MCDisassembler::Success", 135 std::string RFail = "MCDisassembler::Fail", 136 std::string L = "") 137 : RK(R), Target(R), PredicateNamespace(std::move(PredicateNamespace)), 138 GuardPrefix(std::move(GPrefix)), GuardPostfix(std::move(GPostfix)), 139 ReturnOK(std::move(ROK)), ReturnFail(std::move(RFail)), 140 Locals(std::move(L)) {} 141 142 // Emit the decoder state machine table. 143 void emitTable(formatted_raw_ostream &o, DecoderTable &Table, 144 unsigned Indentation, unsigned BitWidth, 145 StringRef Namespace) const; 146 void emitPredicateFunction(formatted_raw_ostream &OS, 147 PredicateSet &Predicates, 148 unsigned Indentation) const; 149 void emitDecoderFunction(formatted_raw_ostream &OS, 150 DecoderSet &Decoders, 151 unsigned Indentation) const; 152 153 // run - Output the code emitter 154 void run(raw_ostream &o); 155 156 private: 157 CodeGenTarget Target; 158 159 public: 160 std::string PredicateNamespace; 161 std::string GuardPrefix, GuardPostfix; 162 std::string ReturnOK, ReturnFail; 163 std::string Locals; 164 }; 165 166 } // end anonymous namespace 167 168 // The set (BIT_TRUE, BIT_FALSE, BIT_UNSET) represents a ternary logic system 169 // for a bit value. 170 // 171 // BIT_UNFILTERED is used as the init value for a filter position. It is used 172 // only for filter processings. 173 typedef enum { 174 BIT_TRUE, // '1' 175 BIT_FALSE, // '0' 176 BIT_UNSET, // '?' 177 BIT_UNFILTERED // unfiltered 178 } bit_value_t; 179 180 static bool ValueSet(bit_value_t V) { 181 return (V == BIT_TRUE || V == BIT_FALSE); 182 } 183 184 static bool ValueNotSet(bit_value_t V) { 185 return (V == BIT_UNSET); 186 } 187 188 static int Value(bit_value_t V) { 189 return ValueNotSet(V) ? -1 : (V == BIT_FALSE ? 0 : 1); 190 } 191 192 static bit_value_t bitFromBits(const BitsInit &bits, unsigned index) { 193 if (BitInit *bit = dyn_cast<BitInit>(bits.getBit(index))) 194 return bit->getValue() ? BIT_TRUE : BIT_FALSE; 195 196 // The bit is uninitialized. 197 return BIT_UNSET; 198 } 199 200 // Prints the bit value for each position. 201 static void dumpBits(raw_ostream &o, const BitsInit &bits) { 202 for (unsigned index = bits.getNumBits(); index > 0; --index) { 203 switch (bitFromBits(bits, index - 1)) { 204 case BIT_TRUE: 205 o << "1"; 206 break; 207 case BIT_FALSE: 208 o << "0"; 209 break; 210 case BIT_UNSET: 211 o << "_"; 212 break; 213 default: 214 llvm_unreachable("unexpected return value from bitFromBits"); 215 } 216 } 217 } 218 219 static BitsInit &getBitsField(const Record &def, StringRef str) { 220 BitsInit *bits = def.getValueAsBitsInit(str); 221 return *bits; 222 } 223 224 // Representation of the instruction to work on. 225 typedef std::vector<bit_value_t> insn_t; 226 227 namespace { 228 229 static const uint64_t NO_FIXED_SEGMENTS_SENTINEL = -1ULL; 230 231 class FilterChooser; 232 233 /// Filter - Filter works with FilterChooser to produce the decoding tree for 234 /// the ISA. 235 /// 236 /// It is useful to think of a Filter as governing the switch stmts of the 237 /// decoding tree in a certain level. Each case stmt delegates to an inferior 238 /// FilterChooser to decide what further decoding logic to employ, or in another 239 /// words, what other remaining bits to look at. The FilterChooser eventually 240 /// chooses a best Filter to do its job. 241 /// 242 /// This recursive scheme ends when the number of Opcodes assigned to the 243 /// FilterChooser becomes 1 or if there is a conflict. A conflict happens when 244 /// the Filter/FilterChooser combo does not know how to distinguish among the 245 /// Opcodes assigned. 246 /// 247 /// An example of a conflict is 248 /// 249 /// Conflict: 250 /// 111101000.00........00010000.... 251 /// 111101000.00........0001........ 252 /// 1111010...00........0001........ 253 /// 1111010...00.................... 254 /// 1111010......................... 255 /// 1111............................ 256 /// ................................ 257 /// VST4q8a 111101000_00________00010000____ 258 /// VST4q8b 111101000_00________00010000____ 259 /// 260 /// The Debug output shows the path that the decoding tree follows to reach the 261 /// the conclusion that there is a conflict. VST4q8a is a vst4 to double-spaced 262 /// even registers, while VST4q8b is a vst4 to double-spaced odd registers. 263 /// 264 /// The encoding info in the .td files does not specify this meta information, 265 /// which could have been used by the decoder to resolve the conflict. The 266 /// decoder could try to decode the even/odd register numbering and assign to 267 /// VST4q8a or VST4q8b, but for the time being, the decoder chooses the "a" 268 /// version and return the Opcode since the two have the same Asm format string. 269 class Filter { 270 protected: 271 const FilterChooser *Owner;// points to the FilterChooser who owns this filter 272 unsigned StartBit; // the starting bit position 273 unsigned NumBits; // number of bits to filter 274 bool Mixed; // a mixed region contains both set and unset bits 275 276 // Map of well-known segment value to the set of uid's with that value. 277 std::map<uint64_t, std::vector<EncodingIDAndOpcode>> 278 FilteredInstructions; 279 280 // Set of uid's with non-constant segment values. 281 std::vector<EncodingIDAndOpcode> VariableInstructions; 282 283 // Map of well-known segment value to its delegate. 284 std::map<uint64_t, std::unique_ptr<const FilterChooser>> FilterChooserMap; 285 286 // Number of instructions which fall under FilteredInstructions category. 287 unsigned NumFiltered; 288 289 // Keeps track of the last opcode in the filtered bucket. 290 EncodingIDAndOpcode LastOpcFiltered; 291 292 public: 293 Filter(Filter &&f); 294 Filter(FilterChooser &owner, unsigned startBit, unsigned numBits, bool mixed); 295 296 ~Filter() = default; 297 298 unsigned getNumFiltered() const { return NumFiltered; } 299 300 EncodingIDAndOpcode getSingletonOpc() const { 301 assert(NumFiltered == 1); 302 return LastOpcFiltered; 303 } 304 305 // Return the filter chooser for the group of instructions without constant 306 // segment values. 307 const FilterChooser &getVariableFC() const { 308 assert(NumFiltered == 1); 309 assert(FilterChooserMap.size() == 1); 310 return *(FilterChooserMap.find(NO_FIXED_SEGMENTS_SENTINEL)->second); 311 } 312 313 // Divides the decoding task into sub tasks and delegates them to the 314 // inferior FilterChooser's. 315 // 316 // A special case arises when there's only one entry in the filtered 317 // instructions. In order to unambiguously decode the singleton, we need to 318 // match the remaining undecoded encoding bits against the singleton. 319 void recurse(); 320 321 // Emit table entries to decode instructions given a segment or segments of 322 // bits. 323 void emitTableEntry(DecoderTableInfo &TableInfo) const; 324 325 // Returns the number of fanout produced by the filter. More fanout implies 326 // the filter distinguishes more categories of instructions. 327 unsigned usefulness() const; 328 }; // end class Filter 329 330 } // end anonymous namespace 331 332 // These are states of our finite state machines used in FilterChooser's 333 // filterProcessor() which produces the filter candidates to use. 334 typedef enum { 335 ATTR_NONE, 336 ATTR_FILTERED, 337 ATTR_ALL_SET, 338 ATTR_ALL_UNSET, 339 ATTR_MIXED 340 } bitAttr_t; 341 342 /// FilterChooser - FilterChooser chooses the best filter among a set of Filters 343 /// in order to perform the decoding of instructions at the current level. 344 /// 345 /// Decoding proceeds from the top down. Based on the well-known encoding bits 346 /// of instructions available, FilterChooser builds up the possible Filters that 347 /// can further the task of decoding by distinguishing among the remaining 348 /// candidate instructions. 349 /// 350 /// Once a filter has been chosen, it is called upon to divide the decoding task 351 /// into sub-tasks and delegates them to its inferior FilterChoosers for further 352 /// processings. 353 /// 354 /// It is useful to think of a Filter as governing the switch stmts of the 355 /// decoding tree. And each case is delegated to an inferior FilterChooser to 356 /// decide what further remaining bits to look at. 357 namespace { 358 359 class FilterChooser { 360 protected: 361 friend class Filter; 362 363 // Vector of codegen instructions to choose our filter. 364 ArrayRef<EncodingAndInst> AllInstructions; 365 366 // Vector of uid's for this filter chooser to work on. 367 // The first member of the pair is the opcode id being decoded, the second is 368 // the opcode id that should be emitted. 369 const std::vector<EncodingIDAndOpcode> &Opcodes; 370 371 // Lookup table for the operand decoding of instructions. 372 const std::map<unsigned, std::vector<OperandInfo>> &Operands; 373 374 // Vector of candidate filters. 375 std::vector<Filter> Filters; 376 377 // Array of bit values passed down from our parent. 378 // Set to all BIT_UNFILTERED's for Parent == NULL. 379 std::vector<bit_value_t> FilterBitValues; 380 381 // Links to the FilterChooser above us in the decoding tree. 382 const FilterChooser *Parent; 383 384 // Index of the best filter from Filters. 385 int BestIndex; 386 387 // Width of instructions 388 unsigned BitWidth; 389 390 // Parent emitter 391 const FixedLenDecoderEmitter *Emitter; 392 393 public: 394 FilterChooser(ArrayRef<EncodingAndInst> Insts, 395 const std::vector<EncodingIDAndOpcode> &IDs, 396 const std::map<unsigned, std::vector<OperandInfo>> &Ops, 397 unsigned BW, const FixedLenDecoderEmitter *E) 398 : AllInstructions(Insts), Opcodes(IDs), Operands(Ops), 399 FilterBitValues(BW, BIT_UNFILTERED), Parent(nullptr), BestIndex(-1), 400 BitWidth(BW), Emitter(E) { 401 doFilter(); 402 } 403 404 FilterChooser(ArrayRef<EncodingAndInst> Insts, 405 const std::vector<EncodingIDAndOpcode> &IDs, 406 const std::map<unsigned, std::vector<OperandInfo>> &Ops, 407 const std::vector<bit_value_t> &ParentFilterBitValues, 408 const FilterChooser &parent) 409 : AllInstructions(Insts), Opcodes(IDs), Operands(Ops), 410 FilterBitValues(ParentFilterBitValues), Parent(&parent), BestIndex(-1), 411 BitWidth(parent.BitWidth), Emitter(parent.Emitter) { 412 doFilter(); 413 } 414 415 FilterChooser(const FilterChooser &) = delete; 416 void operator=(const FilterChooser &) = delete; 417 418 unsigned getBitWidth() const { return BitWidth; } 419 420 protected: 421 // Populates the insn given the uid. 422 void insnWithID(insn_t &Insn, unsigned Opcode) const { 423 BitsInit &Bits = getBitsField(*AllInstructions[Opcode].EncodingDef, "Inst"); 424 425 // We may have a SoftFail bitmask, which specifies a mask where an encoding 426 // may differ from the value in "Inst" and yet still be valid, but the 427 // disassembler should return SoftFail instead of Success. 428 // 429 // This is used for marking UNPREDICTABLE instructions in the ARM world. 430 BitsInit *SFBits = 431 AllInstructions[Opcode].EncodingDef->getValueAsBitsInit("SoftFail"); 432 433 for (unsigned i = 0; i < BitWidth; ++i) { 434 if (SFBits && bitFromBits(*SFBits, i) == BIT_TRUE) 435 Insn.push_back(BIT_UNSET); 436 else 437 Insn.push_back(bitFromBits(Bits, i)); 438 } 439 } 440 441 // Emit the name of the encoding/instruction pair. 442 void emitNameWithID(raw_ostream &OS, unsigned Opcode) const { 443 const Record *EncodingDef = AllInstructions[Opcode].EncodingDef; 444 const Record *InstDef = AllInstructions[Opcode].Inst->TheDef; 445 if (EncodingDef != InstDef) 446 OS << EncodingDef->getName() << ":"; 447 OS << InstDef->getName(); 448 } 449 450 // Populates the field of the insn given the start position and the number of 451 // consecutive bits to scan for. 452 // 453 // Returns false if there exists any uninitialized bit value in the range. 454 // Returns true, otherwise. 455 bool fieldFromInsn(uint64_t &Field, insn_t &Insn, unsigned StartBit, 456 unsigned NumBits) const; 457 458 /// dumpFilterArray - dumpFilterArray prints out debugging info for the given 459 /// filter array as a series of chars. 460 void dumpFilterArray(raw_ostream &o, 461 const std::vector<bit_value_t> & filter) const; 462 463 /// dumpStack - dumpStack traverses the filter chooser chain and calls 464 /// dumpFilterArray on each filter chooser up to the top level one. 465 void dumpStack(raw_ostream &o, const char *prefix) const; 466 467 Filter &bestFilter() { 468 assert(BestIndex != -1 && "BestIndex not set"); 469 return Filters[BestIndex]; 470 } 471 472 bool PositionFiltered(unsigned i) const { 473 return ValueSet(FilterBitValues[i]); 474 } 475 476 // Calculates the island(s) needed to decode the instruction. 477 // This returns a lit of undecoded bits of an instructions, for example, 478 // Inst{20} = 1 && Inst{3-0} == 0b1111 represents two islands of yet-to-be 479 // decoded bits in order to verify that the instruction matches the Opcode. 480 unsigned getIslands(std::vector<unsigned> &StartBits, 481 std::vector<unsigned> &EndBits, 482 std::vector<uint64_t> &FieldVals, 483 const insn_t &Insn) const; 484 485 // Emits code to check the Predicates member of an instruction are true. 486 // Returns true if predicate matches were emitted, false otherwise. 487 bool emitPredicateMatch(raw_ostream &o, unsigned &Indentation, 488 unsigned Opc) const; 489 490 bool doesOpcodeNeedPredicate(unsigned Opc) const; 491 unsigned getPredicateIndex(DecoderTableInfo &TableInfo, StringRef P) const; 492 void emitPredicateTableEntry(DecoderTableInfo &TableInfo, 493 unsigned Opc) const; 494 495 void emitSoftFailTableEntry(DecoderTableInfo &TableInfo, 496 unsigned Opc) const; 497 498 // Emits table entries to decode the singleton. 499 void emitSingletonTableEntry(DecoderTableInfo &TableInfo, 500 EncodingIDAndOpcode Opc) const; 501 502 // Emits code to decode the singleton, and then to decode the rest. 503 void emitSingletonTableEntry(DecoderTableInfo &TableInfo, 504 const Filter &Best) const; 505 506 void emitBinaryParser(raw_ostream &o, unsigned &Indentation, 507 const OperandInfo &OpInfo, 508 bool &OpHasCompleteDecoder) const; 509 510 void emitDecoder(raw_ostream &OS, unsigned Indentation, unsigned Opc, 511 bool &HasCompleteDecoder) const; 512 unsigned getDecoderIndex(DecoderSet &Decoders, unsigned Opc, 513 bool &HasCompleteDecoder) const; 514 515 // Assign a single filter and run with it. 516 void runSingleFilter(unsigned startBit, unsigned numBit, bool mixed); 517 518 // reportRegion is a helper function for filterProcessor to mark a region as 519 // eligible for use as a filter region. 520 void reportRegion(bitAttr_t RA, unsigned StartBit, unsigned BitIndex, 521 bool AllowMixed); 522 523 // FilterProcessor scans the well-known encoding bits of the instructions and 524 // builds up a list of candidate filters. It chooses the best filter and 525 // recursively descends down the decoding tree. 526 bool filterProcessor(bool AllowMixed, bool Greedy = true); 527 528 // Decides on the best configuration of filter(s) to use in order to decode 529 // the instructions. A conflict of instructions may occur, in which case we 530 // dump the conflict set to the standard error. 531 void doFilter(); 532 533 public: 534 // emitTableEntries - Emit state machine entries to decode our share of 535 // instructions. 536 void emitTableEntries(DecoderTableInfo &TableInfo) const; 537 }; 538 539 } // end anonymous namespace 540 541 /////////////////////////// 542 // // 543 // Filter Implementation // 544 // // 545 /////////////////////////// 546 547 Filter::Filter(Filter &&f) 548 : Owner(f.Owner), StartBit(f.StartBit), NumBits(f.NumBits), Mixed(f.Mixed), 549 FilteredInstructions(std::move(f.FilteredInstructions)), 550 VariableInstructions(std::move(f.VariableInstructions)), 551 FilterChooserMap(std::move(f.FilterChooserMap)), NumFiltered(f.NumFiltered), 552 LastOpcFiltered(f.LastOpcFiltered) { 553 } 554 555 Filter::Filter(FilterChooser &owner, unsigned startBit, unsigned numBits, 556 bool mixed) 557 : Owner(&owner), StartBit(startBit), NumBits(numBits), Mixed(mixed) { 558 assert(StartBit + NumBits - 1 < Owner->BitWidth); 559 560 NumFiltered = 0; 561 LastOpcFiltered = {0, 0}; 562 563 for (unsigned i = 0, e = Owner->Opcodes.size(); i != e; ++i) { 564 insn_t Insn; 565 566 // Populates the insn given the uid. 567 Owner->insnWithID(Insn, Owner->Opcodes[i].EncodingID); 568 569 uint64_t Field; 570 // Scans the segment for possibly well-specified encoding bits. 571 bool ok = Owner->fieldFromInsn(Field, Insn, StartBit, NumBits); 572 573 if (ok) { 574 // The encoding bits are well-known. Lets add the uid of the 575 // instruction into the bucket keyed off the constant field value. 576 LastOpcFiltered = Owner->Opcodes[i]; 577 FilteredInstructions[Field].push_back(LastOpcFiltered); 578 ++NumFiltered; 579 } else { 580 // Some of the encoding bit(s) are unspecified. This contributes to 581 // one additional member of "Variable" instructions. 582 VariableInstructions.push_back(Owner->Opcodes[i]); 583 } 584 } 585 586 assert((FilteredInstructions.size() + VariableInstructions.size() > 0) 587 && "Filter returns no instruction categories"); 588 } 589 590 // Divides the decoding task into sub tasks and delegates them to the 591 // inferior FilterChooser's. 592 // 593 // A special case arises when there's only one entry in the filtered 594 // instructions. In order to unambiguously decode the singleton, we need to 595 // match the remaining undecoded encoding bits against the singleton. 596 void Filter::recurse() { 597 // Starts by inheriting our parent filter chooser's filter bit values. 598 std::vector<bit_value_t> BitValueArray(Owner->FilterBitValues); 599 600 if (!VariableInstructions.empty()) { 601 // Conservatively marks each segment position as BIT_UNSET. 602 for (unsigned bitIndex = 0; bitIndex < NumBits; ++bitIndex) 603 BitValueArray[StartBit + bitIndex] = BIT_UNSET; 604 605 // Delegates to an inferior filter chooser for further processing on this 606 // group of instructions whose segment values are variable. 607 FilterChooserMap.insert(std::make_pair(NO_FIXED_SEGMENTS_SENTINEL, 608 std::make_unique<FilterChooser>(Owner->AllInstructions, 609 VariableInstructions, Owner->Operands, BitValueArray, *Owner))); 610 } 611 612 // No need to recurse for a singleton filtered instruction. 613 // See also Filter::emit*(). 614 if (getNumFiltered() == 1) { 615 assert(FilterChooserMap.size() == 1); 616 return; 617 } 618 619 // Otherwise, create sub choosers. 620 for (const auto &Inst : FilteredInstructions) { 621 622 // Marks all the segment positions with either BIT_TRUE or BIT_FALSE. 623 for (unsigned bitIndex = 0; bitIndex < NumBits; ++bitIndex) { 624 if (Inst.first & (1ULL << bitIndex)) 625 BitValueArray[StartBit + bitIndex] = BIT_TRUE; 626 else 627 BitValueArray[StartBit + bitIndex] = BIT_FALSE; 628 } 629 630 // Delegates to an inferior filter chooser for further processing on this 631 // category of instructions. 632 FilterChooserMap.insert(std::make_pair( 633 Inst.first, std::make_unique<FilterChooser>( 634 Owner->AllInstructions, Inst.second, 635 Owner->Operands, BitValueArray, *Owner))); 636 } 637 } 638 639 static void resolveTableFixups(DecoderTable &Table, const FixupList &Fixups, 640 uint32_t DestIdx) { 641 // Any NumToSkip fixups in the current scope can resolve to the 642 // current location. 643 for (FixupList::const_reverse_iterator I = Fixups.rbegin(), 644 E = Fixups.rend(); 645 I != E; ++I) { 646 // Calculate the distance from the byte following the fixup entry byte 647 // to the destination. The Target is calculated from after the 16-bit 648 // NumToSkip entry itself, so subtract two from the displacement here 649 // to account for that. 650 uint32_t FixupIdx = *I; 651 uint32_t Delta = DestIdx - FixupIdx - 3; 652 // Our NumToSkip entries are 24-bits. Make sure our table isn't too 653 // big. 654 assert(Delta < (1u << 24)); 655 Table[FixupIdx] = (uint8_t)Delta; 656 Table[FixupIdx + 1] = (uint8_t)(Delta >> 8); 657 Table[FixupIdx + 2] = (uint8_t)(Delta >> 16); 658 } 659 } 660 661 // Emit table entries to decode instructions given a segment or segments 662 // of bits. 663 void Filter::emitTableEntry(DecoderTableInfo &TableInfo) const { 664 TableInfo.Table.push_back(MCD::OPC_ExtractField); 665 TableInfo.Table.push_back(StartBit); 666 TableInfo.Table.push_back(NumBits); 667 668 // A new filter entry begins a new scope for fixup resolution. 669 TableInfo.FixupStack.emplace_back(); 670 671 DecoderTable &Table = TableInfo.Table; 672 673 size_t PrevFilter = 0; 674 bool HasFallthrough = false; 675 for (auto &Filter : FilterChooserMap) { 676 // Field value -1 implies a non-empty set of variable instructions. 677 // See also recurse(). 678 if (Filter.first == NO_FIXED_SEGMENTS_SENTINEL) { 679 HasFallthrough = true; 680 681 // Each scope should always have at least one filter value to check 682 // for. 683 assert(PrevFilter != 0 && "empty filter set!"); 684 FixupList &CurScope = TableInfo.FixupStack.back(); 685 // Resolve any NumToSkip fixups in the current scope. 686 resolveTableFixups(Table, CurScope, Table.size()); 687 CurScope.clear(); 688 PrevFilter = 0; // Don't re-process the filter's fallthrough. 689 } else { 690 Table.push_back(MCD::OPC_FilterValue); 691 // Encode and emit the value to filter against. 692 uint8_t Buffer[16]; 693 unsigned Len = encodeULEB128(Filter.first, Buffer); 694 Table.insert(Table.end(), Buffer, Buffer + Len); 695 // Reserve space for the NumToSkip entry. We'll backpatch the value 696 // later. 697 PrevFilter = Table.size(); 698 Table.push_back(0); 699 Table.push_back(0); 700 Table.push_back(0); 701 } 702 703 // We arrive at a category of instructions with the same segment value. 704 // Now delegate to the sub filter chooser for further decodings. 705 // The case may fallthrough, which happens if the remaining well-known 706 // encoding bits do not match exactly. 707 Filter.second->emitTableEntries(TableInfo); 708 709 // Now that we've emitted the body of the handler, update the NumToSkip 710 // of the filter itself to be able to skip forward when false. Subtract 711 // two as to account for the width of the NumToSkip field itself. 712 if (PrevFilter) { 713 uint32_t NumToSkip = Table.size() - PrevFilter - 3; 714 assert(NumToSkip < (1u << 24) && "disassembler decoding table too large!"); 715 Table[PrevFilter] = (uint8_t)NumToSkip; 716 Table[PrevFilter + 1] = (uint8_t)(NumToSkip >> 8); 717 Table[PrevFilter + 2] = (uint8_t)(NumToSkip >> 16); 718 } 719 } 720 721 // Any remaining unresolved fixups bubble up to the parent fixup scope. 722 assert(TableInfo.FixupStack.size() > 1 && "fixup stack underflow!"); 723 FixupScopeList::iterator Source = TableInfo.FixupStack.end() - 1; 724 FixupScopeList::iterator Dest = Source - 1; 725 llvm::append_range(*Dest, *Source); 726 TableInfo.FixupStack.pop_back(); 727 728 // If there is no fallthrough, then the final filter should get fixed 729 // up according to the enclosing scope rather than the current position. 730 if (!HasFallthrough) 731 TableInfo.FixupStack.back().push_back(PrevFilter); 732 } 733 734 // Returns the number of fanout produced by the filter. More fanout implies 735 // the filter distinguishes more categories of instructions. 736 unsigned Filter::usefulness() const { 737 if (!VariableInstructions.empty()) 738 return FilteredInstructions.size(); 739 else 740 return FilteredInstructions.size() + 1; 741 } 742 743 ////////////////////////////////// 744 // // 745 // Filterchooser Implementation // 746 // // 747 ////////////////////////////////// 748 749 // Emit the decoder state machine table. 750 void FixedLenDecoderEmitter::emitTable(formatted_raw_ostream &OS, 751 DecoderTable &Table, 752 unsigned Indentation, 753 unsigned BitWidth, 754 StringRef Namespace) const { 755 OS.indent(Indentation) << "static const uint8_t DecoderTable" << Namespace 756 << BitWidth << "[] = {\n"; 757 758 Indentation += 2; 759 760 // FIXME: We may be able to use the NumToSkip values to recover 761 // appropriate indentation levels. 762 DecoderTable::const_iterator I = Table.begin(); 763 DecoderTable::const_iterator E = Table.end(); 764 while (I != E) { 765 assert (I < E && "incomplete decode table entry!"); 766 767 uint64_t Pos = I - Table.begin(); 768 OS << "/* " << Pos << " */"; 769 OS.PadToColumn(12); 770 771 switch (*I) { 772 default: 773 PrintFatalError("invalid decode table opcode"); 774 case MCD::OPC_ExtractField: { 775 ++I; 776 unsigned Start = *I++; 777 unsigned Len = *I++; 778 OS.indent(Indentation) << "MCD::OPC_ExtractField, " << Start << ", " 779 << Len << ", // Inst{"; 780 if (Len > 1) 781 OS << (Start + Len - 1) << "-"; 782 OS << Start << "} ...\n"; 783 break; 784 } 785 case MCD::OPC_FilterValue: { 786 ++I; 787 OS.indent(Indentation) << "MCD::OPC_FilterValue, "; 788 // The filter value is ULEB128 encoded. 789 while (*I >= 128) 790 OS << (unsigned)*I++ << ", "; 791 OS << (unsigned)*I++ << ", "; 792 793 // 24-bit numtoskip value. 794 uint8_t Byte = *I++; 795 uint32_t NumToSkip = Byte; 796 OS << (unsigned)Byte << ", "; 797 Byte = *I++; 798 OS << (unsigned)Byte << ", "; 799 NumToSkip |= Byte << 8; 800 Byte = *I++; 801 OS << utostr(Byte) << ", "; 802 NumToSkip |= Byte << 16; 803 OS << "// Skip to: " << ((I - Table.begin()) + NumToSkip) << "\n"; 804 break; 805 } 806 case MCD::OPC_CheckField: { 807 ++I; 808 unsigned Start = *I++; 809 unsigned Len = *I++; 810 OS.indent(Indentation) << "MCD::OPC_CheckField, " << Start << ", " 811 << Len << ", ";// << Val << ", " << NumToSkip << ",\n"; 812 // ULEB128 encoded field value. 813 for (; *I >= 128; ++I) 814 OS << (unsigned)*I << ", "; 815 OS << (unsigned)*I++ << ", "; 816 // 24-bit numtoskip value. 817 uint8_t Byte = *I++; 818 uint32_t NumToSkip = Byte; 819 OS << (unsigned)Byte << ", "; 820 Byte = *I++; 821 OS << (unsigned)Byte << ", "; 822 NumToSkip |= Byte << 8; 823 Byte = *I++; 824 OS << utostr(Byte) << ", "; 825 NumToSkip |= Byte << 16; 826 OS << "// Skip to: " << ((I - Table.begin()) + NumToSkip) << "\n"; 827 break; 828 } 829 case MCD::OPC_CheckPredicate: { 830 ++I; 831 OS.indent(Indentation) << "MCD::OPC_CheckPredicate, "; 832 for (; *I >= 128; ++I) 833 OS << (unsigned)*I << ", "; 834 OS << (unsigned)*I++ << ", "; 835 836 // 24-bit numtoskip value. 837 uint8_t Byte = *I++; 838 uint32_t NumToSkip = Byte; 839 OS << (unsigned)Byte << ", "; 840 Byte = *I++; 841 OS << (unsigned)Byte << ", "; 842 NumToSkip |= Byte << 8; 843 Byte = *I++; 844 OS << utostr(Byte) << ", "; 845 NumToSkip |= Byte << 16; 846 OS << "// Skip to: " << ((I - Table.begin()) + NumToSkip) << "\n"; 847 break; 848 } 849 case MCD::OPC_Decode: 850 case MCD::OPC_TryDecode: { 851 bool IsTry = *I == MCD::OPC_TryDecode; 852 ++I; 853 // Extract the ULEB128 encoded Opcode to a buffer. 854 uint8_t Buffer[16], *p = Buffer; 855 while ((*p++ = *I++) >= 128) 856 assert((p - Buffer) <= (ptrdiff_t)sizeof(Buffer) 857 && "ULEB128 value too large!"); 858 // Decode the Opcode value. 859 unsigned Opc = decodeULEB128(Buffer); 860 OS.indent(Indentation) << "MCD::OPC_" << (IsTry ? "Try" : "") 861 << "Decode, "; 862 for (p = Buffer; *p >= 128; ++p) 863 OS << (unsigned)*p << ", "; 864 OS << (unsigned)*p << ", "; 865 866 // Decoder index. 867 for (; *I >= 128; ++I) 868 OS << (unsigned)*I << ", "; 869 OS << (unsigned)*I++ << ", "; 870 871 if (!IsTry) { 872 OS << "// Opcode: " << NumberedEncodings[Opc] << "\n"; 873 break; 874 } 875 876 // Fallthrough for OPC_TryDecode. 877 878 // 24-bit numtoskip value. 879 uint8_t Byte = *I++; 880 uint32_t NumToSkip = Byte; 881 OS << (unsigned)Byte << ", "; 882 Byte = *I++; 883 OS << (unsigned)Byte << ", "; 884 NumToSkip |= Byte << 8; 885 Byte = *I++; 886 OS << utostr(Byte) << ", "; 887 NumToSkip |= Byte << 16; 888 889 OS << "// Opcode: " << NumberedEncodings[Opc] 890 << ", skip to: " << ((I - Table.begin()) + NumToSkip) << "\n"; 891 break; 892 } 893 case MCD::OPC_SoftFail: { 894 ++I; 895 OS.indent(Indentation) << "MCD::OPC_SoftFail"; 896 // Positive mask 897 uint64_t Value = 0; 898 unsigned Shift = 0; 899 do { 900 OS << ", " << (unsigned)*I; 901 Value += (*I & 0x7f) << Shift; 902 Shift += 7; 903 } while (*I++ >= 128); 904 if (Value > 127) { 905 OS << " /* 0x"; 906 OS.write_hex(Value); 907 OS << " */"; 908 } 909 // Negative mask 910 Value = 0; 911 Shift = 0; 912 do { 913 OS << ", " << (unsigned)*I; 914 Value += (*I & 0x7f) << Shift; 915 Shift += 7; 916 } while (*I++ >= 128); 917 if (Value > 127) { 918 OS << " /* 0x"; 919 OS.write_hex(Value); 920 OS << " */"; 921 } 922 OS << ",\n"; 923 break; 924 } 925 case MCD::OPC_Fail: { 926 ++I; 927 OS.indent(Indentation) << "MCD::OPC_Fail,\n"; 928 break; 929 } 930 } 931 } 932 OS.indent(Indentation) << "0\n"; 933 934 Indentation -= 2; 935 936 OS.indent(Indentation) << "};\n\n"; 937 } 938 939 void FixedLenDecoderEmitter:: 940 emitPredicateFunction(formatted_raw_ostream &OS, PredicateSet &Predicates, 941 unsigned Indentation) const { 942 // The predicate function is just a big switch statement based on the 943 // input predicate index. 944 OS.indent(Indentation) << "static bool checkDecoderPredicate(unsigned Idx, " 945 << "const FeatureBitset &Bits) {\n"; 946 Indentation += 2; 947 if (!Predicates.empty()) { 948 OS.indent(Indentation) << "switch (Idx) {\n"; 949 OS.indent(Indentation) << "default: llvm_unreachable(\"Invalid index!\");\n"; 950 unsigned Index = 0; 951 for (const auto &Predicate : Predicates) { 952 OS.indent(Indentation) << "case " << Index++ << ":\n"; 953 OS.indent(Indentation+2) << "return (" << Predicate << ");\n"; 954 } 955 OS.indent(Indentation) << "}\n"; 956 } else { 957 // No case statement to emit 958 OS.indent(Indentation) << "llvm_unreachable(\"Invalid index!\");\n"; 959 } 960 Indentation -= 2; 961 OS.indent(Indentation) << "}\n\n"; 962 } 963 964 void FixedLenDecoderEmitter:: 965 emitDecoderFunction(formatted_raw_ostream &OS, DecoderSet &Decoders, 966 unsigned Indentation) const { 967 // The decoder function is just a big switch statement based on the 968 // input decoder index. 969 OS.indent(Indentation) << "template <typename InsnType>\n"; 970 OS.indent(Indentation) << "static DecodeStatus decodeToMCInst(DecodeStatus S," 971 << " unsigned Idx, InsnType insn, MCInst &MI,\n"; 972 OS.indent(Indentation) << " uint64_t " 973 << "Address, const void *Decoder, bool &DecodeComplete) {\n"; 974 Indentation += 2; 975 OS.indent(Indentation) << "DecodeComplete = true;\n"; 976 OS.indent(Indentation) << "InsnType tmp;\n"; 977 OS.indent(Indentation) << "switch (Idx) {\n"; 978 OS.indent(Indentation) << "default: llvm_unreachable(\"Invalid index!\");\n"; 979 unsigned Index = 0; 980 for (const auto &Decoder : Decoders) { 981 OS.indent(Indentation) << "case " << Index++ << ":\n"; 982 OS << Decoder; 983 OS.indent(Indentation+2) << "return S;\n"; 984 } 985 OS.indent(Indentation) << "}\n"; 986 Indentation -= 2; 987 OS.indent(Indentation) << "}\n\n"; 988 } 989 990 // Populates the field of the insn given the start position and the number of 991 // consecutive bits to scan for. 992 // 993 // Returns false if and on the first uninitialized bit value encountered. 994 // Returns true, otherwise. 995 bool FilterChooser::fieldFromInsn(uint64_t &Field, insn_t &Insn, 996 unsigned StartBit, unsigned NumBits) const { 997 Field = 0; 998 999 for (unsigned i = 0; i < NumBits; ++i) { 1000 if (Insn[StartBit + i] == BIT_UNSET) 1001 return false; 1002 1003 if (Insn[StartBit + i] == BIT_TRUE) 1004 Field = Field | (1ULL << i); 1005 } 1006 1007 return true; 1008 } 1009 1010 /// dumpFilterArray - dumpFilterArray prints out debugging info for the given 1011 /// filter array as a series of chars. 1012 void FilterChooser::dumpFilterArray(raw_ostream &o, 1013 const std::vector<bit_value_t> &filter) const { 1014 for (unsigned bitIndex = BitWidth; bitIndex > 0; bitIndex--) { 1015 switch (filter[bitIndex - 1]) { 1016 case BIT_UNFILTERED: 1017 o << "."; 1018 break; 1019 case BIT_UNSET: 1020 o << "_"; 1021 break; 1022 case BIT_TRUE: 1023 o << "1"; 1024 break; 1025 case BIT_FALSE: 1026 o << "0"; 1027 break; 1028 } 1029 } 1030 } 1031 1032 /// dumpStack - dumpStack traverses the filter chooser chain and calls 1033 /// dumpFilterArray on each filter chooser up to the top level one. 1034 void FilterChooser::dumpStack(raw_ostream &o, const char *prefix) const { 1035 const FilterChooser *current = this; 1036 1037 while (current) { 1038 o << prefix; 1039 dumpFilterArray(o, current->FilterBitValues); 1040 o << '\n'; 1041 current = current->Parent; 1042 } 1043 } 1044 1045 // Calculates the island(s) needed to decode the instruction. 1046 // This returns a list of undecoded bits of an instructions, for example, 1047 // Inst{20} = 1 && Inst{3-0} == 0b1111 represents two islands of yet-to-be 1048 // decoded bits in order to verify that the instruction matches the Opcode. 1049 unsigned FilterChooser::getIslands(std::vector<unsigned> &StartBits, 1050 std::vector<unsigned> &EndBits, 1051 std::vector<uint64_t> &FieldVals, 1052 const insn_t &Insn) const { 1053 unsigned Num, BitNo; 1054 Num = BitNo = 0; 1055 1056 uint64_t FieldVal = 0; 1057 1058 // 0: Init 1059 // 1: Water (the bit value does not affect decoding) 1060 // 2: Island (well-known bit value needed for decoding) 1061 int State = 0; 1062 1063 for (unsigned i = 0; i < BitWidth; ++i) { 1064 int64_t Val = Value(Insn[i]); 1065 bool Filtered = PositionFiltered(i); 1066 switch (State) { 1067 default: llvm_unreachable("Unreachable code!"); 1068 case 0: 1069 case 1: 1070 if (Filtered || Val == -1) 1071 State = 1; // Still in Water 1072 else { 1073 State = 2; // Into the Island 1074 BitNo = 0; 1075 StartBits.push_back(i); 1076 FieldVal = Val; 1077 } 1078 break; 1079 case 2: 1080 if (Filtered || Val == -1) { 1081 State = 1; // Into the Water 1082 EndBits.push_back(i - 1); 1083 FieldVals.push_back(FieldVal); 1084 ++Num; 1085 } else { 1086 State = 2; // Still in Island 1087 ++BitNo; 1088 FieldVal = FieldVal | Val << BitNo; 1089 } 1090 break; 1091 } 1092 } 1093 // If we are still in Island after the loop, do some housekeeping. 1094 if (State == 2) { 1095 EndBits.push_back(BitWidth - 1); 1096 FieldVals.push_back(FieldVal); 1097 ++Num; 1098 } 1099 1100 assert(StartBits.size() == Num && EndBits.size() == Num && 1101 FieldVals.size() == Num); 1102 return Num; 1103 } 1104 1105 void FilterChooser::emitBinaryParser(raw_ostream &o, unsigned &Indentation, 1106 const OperandInfo &OpInfo, 1107 bool &OpHasCompleteDecoder) const { 1108 const std::string &Decoder = OpInfo.Decoder; 1109 1110 if (OpInfo.numFields() != 1 || OpInfo.InitValue != 0) { 1111 o.indent(Indentation) << "tmp = 0x"; 1112 o.write_hex(OpInfo.InitValue); 1113 o << ";\n"; 1114 } 1115 1116 for (const EncodingField &EF : OpInfo) { 1117 o.indent(Indentation) << "tmp "; 1118 if (OpInfo.numFields() != 1 || OpInfo.InitValue != 0) o << '|'; 1119 o << "= fieldFromInstruction" 1120 << "(insn, " << EF.Base << ", " << EF.Width << ')'; 1121 if (OpInfo.numFields() != 1 || EF.Offset != 0) 1122 o << " << " << EF.Offset; 1123 o << ";\n"; 1124 } 1125 1126 if (Decoder != "") { 1127 OpHasCompleteDecoder = OpInfo.HasCompleteDecoder; 1128 o.indent(Indentation) << Emitter->GuardPrefix << Decoder 1129 << "(MI, tmp, Address, Decoder)" 1130 << Emitter->GuardPostfix 1131 << " { " << (OpHasCompleteDecoder ? "" : "DecodeComplete = false; ") 1132 << "return MCDisassembler::Fail; }\n"; 1133 } else { 1134 OpHasCompleteDecoder = true; 1135 o.indent(Indentation) << "MI.addOperand(MCOperand::createImm(tmp));\n"; 1136 } 1137 } 1138 1139 void FilterChooser::emitDecoder(raw_ostream &OS, unsigned Indentation, 1140 unsigned Opc, bool &HasCompleteDecoder) const { 1141 HasCompleteDecoder = true; 1142 1143 for (const auto &Op : Operands.find(Opc)->second) { 1144 // If a custom instruction decoder was specified, use that. 1145 if (Op.numFields() == 0 && !Op.Decoder.empty()) { 1146 HasCompleteDecoder = Op.HasCompleteDecoder; 1147 OS.indent(Indentation) << Emitter->GuardPrefix << Op.Decoder 1148 << "(MI, insn, Address, Decoder)" 1149 << Emitter->GuardPostfix 1150 << " { " << (HasCompleteDecoder ? "" : "DecodeComplete = false; ") 1151 << "return MCDisassembler::Fail; }\n"; 1152 break; 1153 } 1154 1155 bool OpHasCompleteDecoder; 1156 emitBinaryParser(OS, Indentation, Op, OpHasCompleteDecoder); 1157 if (!OpHasCompleteDecoder) 1158 HasCompleteDecoder = false; 1159 } 1160 } 1161 1162 unsigned FilterChooser::getDecoderIndex(DecoderSet &Decoders, 1163 unsigned Opc, 1164 bool &HasCompleteDecoder) const { 1165 // Build up the predicate string. 1166 SmallString<256> Decoder; 1167 // FIXME: emitDecoder() function can take a buffer directly rather than 1168 // a stream. 1169 raw_svector_ostream S(Decoder); 1170 unsigned I = 4; 1171 emitDecoder(S, I, Opc, HasCompleteDecoder); 1172 1173 // Using the full decoder string as the key value here is a bit 1174 // heavyweight, but is effective. If the string comparisons become a 1175 // performance concern, we can implement a mangling of the predicate 1176 // data easily enough with a map back to the actual string. That's 1177 // overkill for now, though. 1178 1179 // Make sure the predicate is in the table. 1180 Decoders.insert(CachedHashString(Decoder)); 1181 // Now figure out the index for when we write out the table. 1182 DecoderSet::const_iterator P = find(Decoders, Decoder.str()); 1183 return (unsigned)(P - Decoders.begin()); 1184 } 1185 1186 bool FilterChooser::emitPredicateMatch(raw_ostream &o, unsigned &Indentation, 1187 unsigned Opc) const { 1188 ListInit *Predicates = 1189 AllInstructions[Opc].EncodingDef->getValueAsListInit("Predicates"); 1190 bool IsFirstEmission = true; 1191 for (unsigned i = 0; i < Predicates->size(); ++i) { 1192 Record *Pred = Predicates->getElementAsRecord(i); 1193 if (!Pred->getValue("AssemblerMatcherPredicate")) 1194 continue; 1195 1196 if (!isa<DagInit>(Pred->getValue("AssemblerCondDag")->getValue())) 1197 continue; 1198 1199 const DagInit *D = Pred->getValueAsDag("AssemblerCondDag"); 1200 std::string CombineType = D->getOperator()->getAsString(); 1201 if (CombineType != "any_of" && CombineType != "all_of") 1202 PrintFatalError(Pred->getLoc(), "Invalid AssemblerCondDag!"); 1203 if (D->getNumArgs() == 0) 1204 PrintFatalError(Pred->getLoc(), "Invalid AssemblerCondDag!"); 1205 bool IsOr = CombineType == "any_of"; 1206 1207 if (!IsFirstEmission) 1208 o << " && "; 1209 1210 if (IsOr) 1211 o << "("; 1212 1213 bool First = true; 1214 for (auto *Arg : D->getArgs()) { 1215 if (!First) { 1216 if (IsOr) 1217 o << " || "; 1218 else 1219 o << " && "; 1220 } 1221 if (auto *NotArg = dyn_cast<DagInit>(Arg)) { 1222 if (NotArg->getOperator()->getAsString() != "not" || 1223 NotArg->getNumArgs() != 1) 1224 PrintFatalError(Pred->getLoc(), "Invalid AssemblerCondDag!"); 1225 Arg = NotArg->getArg(0); 1226 o << "!"; 1227 } 1228 if (!isa<DefInit>(Arg) || 1229 !cast<DefInit>(Arg)->getDef()->isSubClassOf("SubtargetFeature")) 1230 PrintFatalError(Pred->getLoc(), "Invalid AssemblerCondDag!"); 1231 o << "Bits[" << Emitter->PredicateNamespace << "::" << Arg->getAsString() 1232 << "]"; 1233 1234 First = false; 1235 } 1236 1237 if (IsOr) 1238 o << ")"; 1239 1240 IsFirstEmission = false; 1241 } 1242 return !Predicates->empty(); 1243 } 1244 1245 bool FilterChooser::doesOpcodeNeedPredicate(unsigned Opc) const { 1246 ListInit *Predicates = 1247 AllInstructions[Opc].EncodingDef->getValueAsListInit("Predicates"); 1248 for (unsigned i = 0; i < Predicates->size(); ++i) { 1249 Record *Pred = Predicates->getElementAsRecord(i); 1250 if (!Pred->getValue("AssemblerMatcherPredicate")) 1251 continue; 1252 1253 if (dyn_cast<DagInit>(Pred->getValue("AssemblerCondDag")->getValue())) 1254 return true; 1255 } 1256 return false; 1257 } 1258 1259 unsigned FilterChooser::getPredicateIndex(DecoderTableInfo &TableInfo, 1260 StringRef Predicate) const { 1261 // Using the full predicate string as the key value here is a bit 1262 // heavyweight, but is effective. If the string comparisons become a 1263 // performance concern, we can implement a mangling of the predicate 1264 // data easily enough with a map back to the actual string. That's 1265 // overkill for now, though. 1266 1267 // Make sure the predicate is in the table. 1268 TableInfo.Predicates.insert(CachedHashString(Predicate)); 1269 // Now figure out the index for when we write out the table. 1270 PredicateSet::const_iterator P = find(TableInfo.Predicates, Predicate); 1271 return (unsigned)(P - TableInfo.Predicates.begin()); 1272 } 1273 1274 void FilterChooser::emitPredicateTableEntry(DecoderTableInfo &TableInfo, 1275 unsigned Opc) const { 1276 if (!doesOpcodeNeedPredicate(Opc)) 1277 return; 1278 1279 // Build up the predicate string. 1280 SmallString<256> Predicate; 1281 // FIXME: emitPredicateMatch() functions can take a buffer directly rather 1282 // than a stream. 1283 raw_svector_ostream PS(Predicate); 1284 unsigned I = 0; 1285 emitPredicateMatch(PS, I, Opc); 1286 1287 // Figure out the index into the predicate table for the predicate just 1288 // computed. 1289 unsigned PIdx = getPredicateIndex(TableInfo, PS.str()); 1290 SmallString<16> PBytes; 1291 raw_svector_ostream S(PBytes); 1292 encodeULEB128(PIdx, S); 1293 1294 TableInfo.Table.push_back(MCD::OPC_CheckPredicate); 1295 // Predicate index 1296 for (unsigned i = 0, e = PBytes.size(); i != e; ++i) 1297 TableInfo.Table.push_back(PBytes[i]); 1298 // Push location for NumToSkip backpatching. 1299 TableInfo.FixupStack.back().push_back(TableInfo.Table.size()); 1300 TableInfo.Table.push_back(0); 1301 TableInfo.Table.push_back(0); 1302 TableInfo.Table.push_back(0); 1303 } 1304 1305 void FilterChooser::emitSoftFailTableEntry(DecoderTableInfo &TableInfo, 1306 unsigned Opc) const { 1307 BitsInit *SFBits = 1308 AllInstructions[Opc].EncodingDef->getValueAsBitsInit("SoftFail"); 1309 if (!SFBits) return; 1310 BitsInit *InstBits = 1311 AllInstructions[Opc].EncodingDef->getValueAsBitsInit("Inst"); 1312 1313 APInt PositiveMask(BitWidth, 0ULL); 1314 APInt NegativeMask(BitWidth, 0ULL); 1315 for (unsigned i = 0; i < BitWidth; ++i) { 1316 bit_value_t B = bitFromBits(*SFBits, i); 1317 bit_value_t IB = bitFromBits(*InstBits, i); 1318 1319 if (B != BIT_TRUE) continue; 1320 1321 switch (IB) { 1322 case BIT_FALSE: 1323 // The bit is meant to be false, so emit a check to see if it is true. 1324 PositiveMask.setBit(i); 1325 break; 1326 case BIT_TRUE: 1327 // The bit is meant to be true, so emit a check to see if it is false. 1328 NegativeMask.setBit(i); 1329 break; 1330 default: 1331 // The bit is not set; this must be an error! 1332 errs() << "SoftFail Conflict: bit SoftFail{" << i << "} in " 1333 << AllInstructions[Opc] << " is set but Inst{" << i 1334 << "} is unset!\n" 1335 << " - You can only mark a bit as SoftFail if it is fully defined" 1336 << " (1/0 - not '?') in Inst\n"; 1337 return; 1338 } 1339 } 1340 1341 bool NeedPositiveMask = PositiveMask.getBoolValue(); 1342 bool NeedNegativeMask = NegativeMask.getBoolValue(); 1343 1344 if (!NeedPositiveMask && !NeedNegativeMask) 1345 return; 1346 1347 TableInfo.Table.push_back(MCD::OPC_SoftFail); 1348 1349 SmallString<16> MaskBytes; 1350 raw_svector_ostream S(MaskBytes); 1351 if (NeedPositiveMask) { 1352 encodeULEB128(PositiveMask.getZExtValue(), S); 1353 for (unsigned i = 0, e = MaskBytes.size(); i != e; ++i) 1354 TableInfo.Table.push_back(MaskBytes[i]); 1355 } else 1356 TableInfo.Table.push_back(0); 1357 if (NeedNegativeMask) { 1358 MaskBytes.clear(); 1359 encodeULEB128(NegativeMask.getZExtValue(), S); 1360 for (unsigned i = 0, e = MaskBytes.size(); i != e; ++i) 1361 TableInfo.Table.push_back(MaskBytes[i]); 1362 } else 1363 TableInfo.Table.push_back(0); 1364 } 1365 1366 // Emits table entries to decode the singleton. 1367 void FilterChooser::emitSingletonTableEntry(DecoderTableInfo &TableInfo, 1368 EncodingIDAndOpcode Opc) const { 1369 std::vector<unsigned> StartBits; 1370 std::vector<unsigned> EndBits; 1371 std::vector<uint64_t> FieldVals; 1372 insn_t Insn; 1373 insnWithID(Insn, Opc.EncodingID); 1374 1375 // Look for islands of undecoded bits of the singleton. 1376 getIslands(StartBits, EndBits, FieldVals, Insn); 1377 1378 unsigned Size = StartBits.size(); 1379 1380 // Emit the predicate table entry if one is needed. 1381 emitPredicateTableEntry(TableInfo, Opc.EncodingID); 1382 1383 // Check any additional encoding fields needed. 1384 for (unsigned I = Size; I != 0; --I) { 1385 unsigned NumBits = EndBits[I-1] - StartBits[I-1] + 1; 1386 TableInfo.Table.push_back(MCD::OPC_CheckField); 1387 TableInfo.Table.push_back(StartBits[I-1]); 1388 TableInfo.Table.push_back(NumBits); 1389 uint8_t Buffer[16], *p; 1390 encodeULEB128(FieldVals[I-1], Buffer); 1391 for (p = Buffer; *p >= 128 ; ++p) 1392 TableInfo.Table.push_back(*p); 1393 TableInfo.Table.push_back(*p); 1394 // Push location for NumToSkip backpatching. 1395 TableInfo.FixupStack.back().push_back(TableInfo.Table.size()); 1396 // The fixup is always 24-bits, so go ahead and allocate the space 1397 // in the table so all our relative position calculations work OK even 1398 // before we fully resolve the real value here. 1399 TableInfo.Table.push_back(0); 1400 TableInfo.Table.push_back(0); 1401 TableInfo.Table.push_back(0); 1402 } 1403 1404 // Check for soft failure of the match. 1405 emitSoftFailTableEntry(TableInfo, Opc.EncodingID); 1406 1407 bool HasCompleteDecoder; 1408 unsigned DIdx = 1409 getDecoderIndex(TableInfo.Decoders, Opc.EncodingID, HasCompleteDecoder); 1410 1411 // Produce OPC_Decode or OPC_TryDecode opcode based on the information 1412 // whether the instruction decoder is complete or not. If it is complete 1413 // then it handles all possible values of remaining variable/unfiltered bits 1414 // and for any value can determine if the bitpattern is a valid instruction 1415 // or not. This means OPC_Decode will be the final step in the decoding 1416 // process. If it is not complete, then the Fail return code from the 1417 // decoder method indicates that additional processing should be done to see 1418 // if there is any other instruction that also matches the bitpattern and 1419 // can decode it. 1420 TableInfo.Table.push_back(HasCompleteDecoder ? MCD::OPC_Decode : 1421 MCD::OPC_TryDecode); 1422 NumEncodingsSupported++; 1423 uint8_t Buffer[16], *p; 1424 encodeULEB128(Opc.Opcode, Buffer); 1425 for (p = Buffer; *p >= 128 ; ++p) 1426 TableInfo.Table.push_back(*p); 1427 TableInfo.Table.push_back(*p); 1428 1429 SmallString<16> Bytes; 1430 raw_svector_ostream S(Bytes); 1431 encodeULEB128(DIdx, S); 1432 1433 // Decoder index 1434 for (unsigned i = 0, e = Bytes.size(); i != e; ++i) 1435 TableInfo.Table.push_back(Bytes[i]); 1436 1437 if (!HasCompleteDecoder) { 1438 // Push location for NumToSkip backpatching. 1439 TableInfo.FixupStack.back().push_back(TableInfo.Table.size()); 1440 // Allocate the space for the fixup. 1441 TableInfo.Table.push_back(0); 1442 TableInfo.Table.push_back(0); 1443 TableInfo.Table.push_back(0); 1444 } 1445 } 1446 1447 // Emits table entries to decode the singleton, and then to decode the rest. 1448 void FilterChooser::emitSingletonTableEntry(DecoderTableInfo &TableInfo, 1449 const Filter &Best) const { 1450 EncodingIDAndOpcode Opc = Best.getSingletonOpc(); 1451 1452 // complex singletons need predicate checks from the first singleton 1453 // to refer forward to the variable filterchooser that follows. 1454 TableInfo.FixupStack.emplace_back(); 1455 1456 emitSingletonTableEntry(TableInfo, Opc); 1457 1458 resolveTableFixups(TableInfo.Table, TableInfo.FixupStack.back(), 1459 TableInfo.Table.size()); 1460 TableInfo.FixupStack.pop_back(); 1461 1462 Best.getVariableFC().emitTableEntries(TableInfo); 1463 } 1464 1465 // Assign a single filter and run with it. Top level API client can initialize 1466 // with a single filter to start the filtering process. 1467 void FilterChooser::runSingleFilter(unsigned startBit, unsigned numBit, 1468 bool mixed) { 1469 Filters.clear(); 1470 Filters.emplace_back(*this, startBit, numBit, true); 1471 BestIndex = 0; // Sole Filter instance to choose from. 1472 bestFilter().recurse(); 1473 } 1474 1475 // reportRegion is a helper function for filterProcessor to mark a region as 1476 // eligible for use as a filter region. 1477 void FilterChooser::reportRegion(bitAttr_t RA, unsigned StartBit, 1478 unsigned BitIndex, bool AllowMixed) { 1479 if (RA == ATTR_MIXED && AllowMixed) 1480 Filters.emplace_back(*this, StartBit, BitIndex - StartBit, true); 1481 else if (RA == ATTR_ALL_SET && !AllowMixed) 1482 Filters.emplace_back(*this, StartBit, BitIndex - StartBit, false); 1483 } 1484 1485 // FilterProcessor scans the well-known encoding bits of the instructions and 1486 // builds up a list of candidate filters. It chooses the best filter and 1487 // recursively descends down the decoding tree. 1488 bool FilterChooser::filterProcessor(bool AllowMixed, bool Greedy) { 1489 Filters.clear(); 1490 BestIndex = -1; 1491 unsigned numInstructions = Opcodes.size(); 1492 1493 assert(numInstructions && "Filter created with no instructions"); 1494 1495 // No further filtering is necessary. 1496 if (numInstructions == 1) 1497 return true; 1498 1499 // Heuristics. See also doFilter()'s "Heuristics" comment when num of 1500 // instructions is 3. 1501 if (AllowMixed && !Greedy) { 1502 assert(numInstructions == 3); 1503 1504 for (unsigned i = 0; i < Opcodes.size(); ++i) { 1505 std::vector<unsigned> StartBits; 1506 std::vector<unsigned> EndBits; 1507 std::vector<uint64_t> FieldVals; 1508 insn_t Insn; 1509 1510 insnWithID(Insn, Opcodes[i].EncodingID); 1511 1512 // Look for islands of undecoded bits of any instruction. 1513 if (getIslands(StartBits, EndBits, FieldVals, Insn) > 0) { 1514 // Found an instruction with island(s). Now just assign a filter. 1515 runSingleFilter(StartBits[0], EndBits[0] - StartBits[0] + 1, true); 1516 return true; 1517 } 1518 } 1519 } 1520 1521 unsigned BitIndex; 1522 1523 // We maintain BIT_WIDTH copies of the bitAttrs automaton. 1524 // The automaton consumes the corresponding bit from each 1525 // instruction. 1526 // 1527 // Input symbols: 0, 1, and _ (unset). 1528 // States: NONE, FILTERED, ALL_SET, ALL_UNSET, and MIXED. 1529 // Initial state: NONE. 1530 // 1531 // (NONE) ------- [01] -> (ALL_SET) 1532 // (NONE) ------- _ ----> (ALL_UNSET) 1533 // (ALL_SET) ---- [01] -> (ALL_SET) 1534 // (ALL_SET) ---- _ ----> (MIXED) 1535 // (ALL_UNSET) -- [01] -> (MIXED) 1536 // (ALL_UNSET) -- _ ----> (ALL_UNSET) 1537 // (MIXED) ------ . ----> (MIXED) 1538 // (FILTERED)---- . ----> (FILTERED) 1539 1540 std::vector<bitAttr_t> bitAttrs; 1541 1542 // FILTERED bit positions provide no entropy and are not worthy of pursuing. 1543 // Filter::recurse() set either BIT_TRUE or BIT_FALSE for each position. 1544 for (BitIndex = 0; BitIndex < BitWidth; ++BitIndex) 1545 if (FilterBitValues[BitIndex] == BIT_TRUE || 1546 FilterBitValues[BitIndex] == BIT_FALSE) 1547 bitAttrs.push_back(ATTR_FILTERED); 1548 else 1549 bitAttrs.push_back(ATTR_NONE); 1550 1551 for (unsigned InsnIndex = 0; InsnIndex < numInstructions; ++InsnIndex) { 1552 insn_t insn; 1553 1554 insnWithID(insn, Opcodes[InsnIndex].EncodingID); 1555 1556 for (BitIndex = 0; BitIndex < BitWidth; ++BitIndex) { 1557 switch (bitAttrs[BitIndex]) { 1558 case ATTR_NONE: 1559 if (insn[BitIndex] == BIT_UNSET) 1560 bitAttrs[BitIndex] = ATTR_ALL_UNSET; 1561 else 1562 bitAttrs[BitIndex] = ATTR_ALL_SET; 1563 break; 1564 case ATTR_ALL_SET: 1565 if (insn[BitIndex] == BIT_UNSET) 1566 bitAttrs[BitIndex] = ATTR_MIXED; 1567 break; 1568 case ATTR_ALL_UNSET: 1569 if (insn[BitIndex] != BIT_UNSET) 1570 bitAttrs[BitIndex] = ATTR_MIXED; 1571 break; 1572 case ATTR_MIXED: 1573 case ATTR_FILTERED: 1574 break; 1575 } 1576 } 1577 } 1578 1579 // The regionAttr automaton consumes the bitAttrs automatons' state, 1580 // lowest-to-highest. 1581 // 1582 // Input symbols: F(iltered), (all_)S(et), (all_)U(nset), M(ixed) 1583 // States: NONE, ALL_SET, MIXED 1584 // Initial state: NONE 1585 // 1586 // (NONE) ----- F --> (NONE) 1587 // (NONE) ----- S --> (ALL_SET) ; and set region start 1588 // (NONE) ----- U --> (NONE) 1589 // (NONE) ----- M --> (MIXED) ; and set region start 1590 // (ALL_SET) -- F --> (NONE) ; and report an ALL_SET region 1591 // (ALL_SET) -- S --> (ALL_SET) 1592 // (ALL_SET) -- U --> (NONE) ; and report an ALL_SET region 1593 // (ALL_SET) -- M --> (MIXED) ; and report an ALL_SET region 1594 // (MIXED) ---- F --> (NONE) ; and report a MIXED region 1595 // (MIXED) ---- S --> (ALL_SET) ; and report a MIXED region 1596 // (MIXED) ---- U --> (NONE) ; and report a MIXED region 1597 // (MIXED) ---- M --> (MIXED) 1598 1599 bitAttr_t RA = ATTR_NONE; 1600 unsigned StartBit = 0; 1601 1602 for (BitIndex = 0; BitIndex < BitWidth; ++BitIndex) { 1603 bitAttr_t bitAttr = bitAttrs[BitIndex]; 1604 1605 assert(bitAttr != ATTR_NONE && "Bit without attributes"); 1606 1607 switch (RA) { 1608 case ATTR_NONE: 1609 switch (bitAttr) { 1610 case ATTR_FILTERED: 1611 break; 1612 case ATTR_ALL_SET: 1613 StartBit = BitIndex; 1614 RA = ATTR_ALL_SET; 1615 break; 1616 case ATTR_ALL_UNSET: 1617 break; 1618 case ATTR_MIXED: 1619 StartBit = BitIndex; 1620 RA = ATTR_MIXED; 1621 break; 1622 default: 1623 llvm_unreachable("Unexpected bitAttr!"); 1624 } 1625 break; 1626 case ATTR_ALL_SET: 1627 switch (bitAttr) { 1628 case ATTR_FILTERED: 1629 reportRegion(RA, StartBit, BitIndex, AllowMixed); 1630 RA = ATTR_NONE; 1631 break; 1632 case ATTR_ALL_SET: 1633 break; 1634 case ATTR_ALL_UNSET: 1635 reportRegion(RA, StartBit, BitIndex, AllowMixed); 1636 RA = ATTR_NONE; 1637 break; 1638 case ATTR_MIXED: 1639 reportRegion(RA, StartBit, BitIndex, AllowMixed); 1640 StartBit = BitIndex; 1641 RA = ATTR_MIXED; 1642 break; 1643 default: 1644 llvm_unreachable("Unexpected bitAttr!"); 1645 } 1646 break; 1647 case ATTR_MIXED: 1648 switch (bitAttr) { 1649 case ATTR_FILTERED: 1650 reportRegion(RA, StartBit, BitIndex, AllowMixed); 1651 StartBit = BitIndex; 1652 RA = ATTR_NONE; 1653 break; 1654 case ATTR_ALL_SET: 1655 reportRegion(RA, StartBit, BitIndex, AllowMixed); 1656 StartBit = BitIndex; 1657 RA = ATTR_ALL_SET; 1658 break; 1659 case ATTR_ALL_UNSET: 1660 reportRegion(RA, StartBit, BitIndex, AllowMixed); 1661 RA = ATTR_NONE; 1662 break; 1663 case ATTR_MIXED: 1664 break; 1665 default: 1666 llvm_unreachable("Unexpected bitAttr!"); 1667 } 1668 break; 1669 case ATTR_ALL_UNSET: 1670 llvm_unreachable("regionAttr state machine has no ATTR_UNSET state"); 1671 case ATTR_FILTERED: 1672 llvm_unreachable("regionAttr state machine has no ATTR_FILTERED state"); 1673 } 1674 } 1675 1676 // At the end, if we're still in ALL_SET or MIXED states, report a region 1677 switch (RA) { 1678 case ATTR_NONE: 1679 break; 1680 case ATTR_FILTERED: 1681 break; 1682 case ATTR_ALL_SET: 1683 reportRegion(RA, StartBit, BitIndex, AllowMixed); 1684 break; 1685 case ATTR_ALL_UNSET: 1686 break; 1687 case ATTR_MIXED: 1688 reportRegion(RA, StartBit, BitIndex, AllowMixed); 1689 break; 1690 } 1691 1692 // We have finished with the filter processings. Now it's time to choose 1693 // the best performing filter. 1694 BestIndex = 0; 1695 bool AllUseless = true; 1696 unsigned BestScore = 0; 1697 1698 for (unsigned i = 0, e = Filters.size(); i != e; ++i) { 1699 unsigned Usefulness = Filters[i].usefulness(); 1700 1701 if (Usefulness) 1702 AllUseless = false; 1703 1704 if (Usefulness > BestScore) { 1705 BestIndex = i; 1706 BestScore = Usefulness; 1707 } 1708 } 1709 1710 if (!AllUseless) 1711 bestFilter().recurse(); 1712 1713 return !AllUseless; 1714 } // end of FilterChooser::filterProcessor(bool) 1715 1716 // Decides on the best configuration of filter(s) to use in order to decode 1717 // the instructions. A conflict of instructions may occur, in which case we 1718 // dump the conflict set to the standard error. 1719 void FilterChooser::doFilter() { 1720 unsigned Num = Opcodes.size(); 1721 assert(Num && "FilterChooser created with no instructions"); 1722 1723 // Try regions of consecutive known bit values first. 1724 if (filterProcessor(false)) 1725 return; 1726 1727 // Then regions of mixed bits (both known and unitialized bit values allowed). 1728 if (filterProcessor(true)) 1729 return; 1730 1731 // Heuristics to cope with conflict set {t2CMPrs, t2SUBSrr, t2SUBSrs} where 1732 // no single instruction for the maximum ATTR_MIXED region Inst{14-4} has a 1733 // well-known encoding pattern. In such case, we backtrack and scan for the 1734 // the very first consecutive ATTR_ALL_SET region and assign a filter to it. 1735 if (Num == 3 && filterProcessor(true, false)) 1736 return; 1737 1738 // If we come to here, the instruction decoding has failed. 1739 // Set the BestIndex to -1 to indicate so. 1740 BestIndex = -1; 1741 } 1742 1743 // emitTableEntries - Emit state machine entries to decode our share of 1744 // instructions. 1745 void FilterChooser::emitTableEntries(DecoderTableInfo &TableInfo) const { 1746 if (Opcodes.size() == 1) { 1747 // There is only one instruction in the set, which is great! 1748 // Call emitSingletonDecoder() to see whether there are any remaining 1749 // encodings bits. 1750 emitSingletonTableEntry(TableInfo, Opcodes[0]); 1751 return; 1752 } 1753 1754 // Choose the best filter to do the decodings! 1755 if (BestIndex != -1) { 1756 const Filter &Best = Filters[BestIndex]; 1757 if (Best.getNumFiltered() == 1) 1758 emitSingletonTableEntry(TableInfo, Best); 1759 else 1760 Best.emitTableEntry(TableInfo); 1761 return; 1762 } 1763 1764 // We don't know how to decode these instructions! Dump the 1765 // conflict set and bail. 1766 1767 // Print out useful conflict information for postmortem analysis. 1768 errs() << "Decoding Conflict:\n"; 1769 1770 dumpStack(errs(), "\t\t"); 1771 1772 for (unsigned i = 0; i < Opcodes.size(); ++i) { 1773 errs() << '\t'; 1774 emitNameWithID(errs(), Opcodes[i].EncodingID); 1775 errs() << " "; 1776 dumpBits( 1777 errs(), 1778 getBitsField(*AllInstructions[Opcodes[i].EncodingID].EncodingDef, "Inst")); 1779 errs() << '\n'; 1780 } 1781 } 1782 1783 static std::string findOperandDecoderMethod(TypedInit *TI) { 1784 std::string Decoder; 1785 1786 Record *Record = cast<DefInit>(TI)->getDef(); 1787 1788 RecordVal *DecoderString = Record->getValue("DecoderMethod"); 1789 StringInit *String = DecoderString ? 1790 dyn_cast<StringInit>(DecoderString->getValue()) : nullptr; 1791 if (String) { 1792 Decoder = std::string(String->getValue()); 1793 if (!Decoder.empty()) 1794 return Decoder; 1795 } 1796 1797 if (Record->isSubClassOf("RegisterOperand")) 1798 Record = Record->getValueAsDef("RegClass"); 1799 1800 if (Record->isSubClassOf("RegisterClass")) { 1801 Decoder = "Decode" + Record->getName().str() + "RegisterClass"; 1802 } else if (Record->isSubClassOf("PointerLikeRegClass")) { 1803 Decoder = "DecodePointerLikeRegClass" + 1804 utostr(Record->getValueAsInt("RegClassKind")); 1805 } 1806 1807 return Decoder; 1808 } 1809 1810 static bool 1811 populateInstruction(CodeGenTarget &Target, const Record &EncodingDef, 1812 const CodeGenInstruction &CGI, unsigned Opc, 1813 std::map<unsigned, std::vector<OperandInfo>> &Operands) { 1814 const Record &Def = *CGI.TheDef; 1815 // If all the bit positions are not specified; do not decode this instruction. 1816 // We are bound to fail! For proper disassembly, the well-known encoding bits 1817 // of the instruction must be fully specified. 1818 1819 BitsInit &Bits = getBitsField(EncodingDef, "Inst"); 1820 if (Bits.allInComplete()) return false; 1821 1822 std::vector<OperandInfo> InsnOperands; 1823 1824 // If the instruction has specified a custom decoding hook, use that instead 1825 // of trying to auto-generate the decoder. 1826 StringRef InstDecoder = EncodingDef.getValueAsString("DecoderMethod"); 1827 if (InstDecoder != "") { 1828 bool HasCompleteInstDecoder = EncodingDef.getValueAsBit("hasCompleteDecoder"); 1829 InsnOperands.push_back( 1830 OperandInfo(std::string(InstDecoder), HasCompleteInstDecoder)); 1831 Operands[Opc] = InsnOperands; 1832 return true; 1833 } 1834 1835 // Generate a description of the operand of the instruction that we know 1836 // how to decode automatically. 1837 // FIXME: We'll need to have a way to manually override this as needed. 1838 1839 // Gather the outputs/inputs of the instruction, so we can find their 1840 // positions in the encoding. This assumes for now that they appear in the 1841 // MCInst in the order that they're listed. 1842 std::vector<std::pair<Init*, StringRef>> InOutOperands; 1843 DagInit *Out = Def.getValueAsDag("OutOperandList"); 1844 DagInit *In = Def.getValueAsDag("InOperandList"); 1845 for (unsigned i = 0; i < Out->getNumArgs(); ++i) 1846 InOutOperands.push_back(std::make_pair(Out->getArg(i), 1847 Out->getArgNameStr(i))); 1848 for (unsigned i = 0; i < In->getNumArgs(); ++i) 1849 InOutOperands.push_back(std::make_pair(In->getArg(i), 1850 In->getArgNameStr(i))); 1851 1852 // Search for tied operands, so that we can correctly instantiate 1853 // operands that are not explicitly represented in the encoding. 1854 std::map<std::string, std::string> TiedNames; 1855 for (unsigned i = 0; i < CGI.Operands.size(); ++i) { 1856 int tiedTo = CGI.Operands[i].getTiedRegister(); 1857 if (tiedTo != -1) { 1858 std::pair<unsigned, unsigned> SO = 1859 CGI.Operands.getSubOperandNumber(tiedTo); 1860 TiedNames[std::string(InOutOperands[i].second)] = 1861 std::string(InOutOperands[SO.first].second); 1862 TiedNames[std::string(InOutOperands[SO.first].second)] = 1863 std::string(InOutOperands[i].second); 1864 } 1865 } 1866 1867 std::map<std::string, std::vector<OperandInfo>> NumberedInsnOperands; 1868 std::set<std::string> NumberedInsnOperandsNoTie; 1869 if (Target.getInstructionSet()-> 1870 getValueAsBit("decodePositionallyEncodedOperands")) { 1871 const std::vector<RecordVal> &Vals = Def.getValues(); 1872 unsigned NumberedOp = 0; 1873 1874 std::set<unsigned> NamedOpIndices; 1875 if (Target.getInstructionSet()-> 1876 getValueAsBit("noNamedPositionallyEncodedOperands")) 1877 // Collect the set of operand indices that might correspond to named 1878 // operand, and skip these when assigning operands based on position. 1879 for (unsigned i = 0, e = Vals.size(); i != e; ++i) { 1880 unsigned OpIdx; 1881 if (!CGI.Operands.hasOperandNamed(Vals[i].getName(), OpIdx)) 1882 continue; 1883 1884 NamedOpIndices.insert(OpIdx); 1885 } 1886 1887 for (unsigned i = 0, e = Vals.size(); i != e; ++i) { 1888 // Ignore fixed fields in the record, we're looking for values like: 1889 // bits<5> RST = { ?, ?, ?, ?, ? }; 1890 if (Vals[i].isNonconcreteOK() || Vals[i].getValue()->isComplete()) 1891 continue; 1892 1893 // Determine if Vals[i] actually contributes to the Inst encoding. 1894 unsigned bi = 0; 1895 for (; bi < Bits.getNumBits(); ++bi) { 1896 VarInit *Var = nullptr; 1897 VarBitInit *BI = dyn_cast<VarBitInit>(Bits.getBit(bi)); 1898 if (BI) 1899 Var = dyn_cast<VarInit>(BI->getBitVar()); 1900 else 1901 Var = dyn_cast<VarInit>(Bits.getBit(bi)); 1902 1903 if (Var && Var->getName() == Vals[i].getName()) 1904 break; 1905 } 1906 1907 if (bi == Bits.getNumBits()) 1908 continue; 1909 1910 // Skip variables that correspond to explicitly-named operands. 1911 unsigned OpIdx; 1912 if (CGI.Operands.hasOperandNamed(Vals[i].getName(), OpIdx)) 1913 continue; 1914 1915 // Get the bit range for this operand: 1916 unsigned bitStart = bi++, bitWidth = 1; 1917 for (; bi < Bits.getNumBits(); ++bi) { 1918 VarInit *Var = nullptr; 1919 VarBitInit *BI = dyn_cast<VarBitInit>(Bits.getBit(bi)); 1920 if (BI) 1921 Var = dyn_cast<VarInit>(BI->getBitVar()); 1922 else 1923 Var = dyn_cast<VarInit>(Bits.getBit(bi)); 1924 1925 if (!Var) 1926 break; 1927 1928 if (Var->getName() != Vals[i].getName()) 1929 break; 1930 1931 ++bitWidth; 1932 } 1933 1934 unsigned NumberOps = CGI.Operands.size(); 1935 while (NumberedOp < NumberOps && 1936 (CGI.Operands.isFlatOperandNotEmitted(NumberedOp) || 1937 (!NamedOpIndices.empty() && NamedOpIndices.count( 1938 CGI.Operands.getSubOperandNumber(NumberedOp).first)))) 1939 ++NumberedOp; 1940 1941 OpIdx = NumberedOp++; 1942 1943 // OpIdx now holds the ordered operand number of Vals[i]. 1944 std::pair<unsigned, unsigned> SO = 1945 CGI.Operands.getSubOperandNumber(OpIdx); 1946 const std::string &Name = CGI.Operands[SO.first].Name; 1947 1948 LLVM_DEBUG(dbgs() << "Numbered operand mapping for " << Def.getName() 1949 << ": " << Name << "(" << SO.first << ", " << SO.second 1950 << ") => " << Vals[i].getName() << "\n"); 1951 1952 std::string Decoder; 1953 Record *TypeRecord = CGI.Operands[SO.first].Rec; 1954 1955 RecordVal *DecoderString = TypeRecord->getValue("DecoderMethod"); 1956 StringInit *String = DecoderString ? 1957 dyn_cast<StringInit>(DecoderString->getValue()) : nullptr; 1958 if (String && String->getValue() != "") 1959 Decoder = std::string(String->getValue()); 1960 1961 if (Decoder == "" && 1962 CGI.Operands[SO.first].MIOperandInfo && 1963 CGI.Operands[SO.first].MIOperandInfo->getNumArgs()) { 1964 Init *Arg = CGI.Operands[SO.first].MIOperandInfo-> 1965 getArg(SO.second); 1966 if (DefInit *DI = cast<DefInit>(Arg)) 1967 TypeRecord = DI->getDef(); 1968 } 1969 1970 bool isReg = false; 1971 if (TypeRecord->isSubClassOf("RegisterOperand")) 1972 TypeRecord = TypeRecord->getValueAsDef("RegClass"); 1973 if (TypeRecord->isSubClassOf("RegisterClass")) { 1974 Decoder = "Decode" + TypeRecord->getName().str() + "RegisterClass"; 1975 isReg = true; 1976 } else if (TypeRecord->isSubClassOf("PointerLikeRegClass")) { 1977 Decoder = "DecodePointerLikeRegClass" + 1978 utostr(TypeRecord->getValueAsInt("RegClassKind")); 1979 isReg = true; 1980 } 1981 1982 DecoderString = TypeRecord->getValue("DecoderMethod"); 1983 String = DecoderString ? 1984 dyn_cast<StringInit>(DecoderString->getValue()) : nullptr; 1985 if (!isReg && String && String->getValue() != "") 1986 Decoder = std::string(String->getValue()); 1987 1988 RecordVal *HasCompleteDecoderVal = 1989 TypeRecord->getValue("hasCompleteDecoder"); 1990 BitInit *HasCompleteDecoderBit = HasCompleteDecoderVal ? 1991 dyn_cast<BitInit>(HasCompleteDecoderVal->getValue()) : nullptr; 1992 bool HasCompleteDecoder = HasCompleteDecoderBit ? 1993 HasCompleteDecoderBit->getValue() : true; 1994 1995 OperandInfo OpInfo(Decoder, HasCompleteDecoder); 1996 OpInfo.addField(bitStart, bitWidth, 0); 1997 1998 NumberedInsnOperands[Name].push_back(OpInfo); 1999 2000 // FIXME: For complex operands with custom decoders we can't handle tied 2001 // sub-operands automatically. Skip those here and assume that this is 2002 // fixed up elsewhere. 2003 if (CGI.Operands[SO.first].MIOperandInfo && 2004 CGI.Operands[SO.first].MIOperandInfo->getNumArgs() > 1 && 2005 String && String->getValue() != "") 2006 NumberedInsnOperandsNoTie.insert(Name); 2007 } 2008 } 2009 2010 // For each operand, see if we can figure out where it is encoded. 2011 for (const auto &Op : InOutOperands) { 2012 if (!NumberedInsnOperands[std::string(Op.second)].empty()) { 2013 llvm::append_range(InsnOperands, 2014 NumberedInsnOperands[std::string(Op.second)]); 2015 continue; 2016 } 2017 if (!NumberedInsnOperands[TiedNames[std::string(Op.second)]].empty()) { 2018 if (!NumberedInsnOperandsNoTie.count(TiedNames[std::string(Op.second)])) { 2019 // Figure out to which (sub)operand we're tied. 2020 unsigned i = 2021 CGI.Operands.getOperandNamed(TiedNames[std::string(Op.second)]); 2022 int tiedTo = CGI.Operands[i].getTiedRegister(); 2023 if (tiedTo == -1) { 2024 i = CGI.Operands.getOperandNamed(Op.second); 2025 tiedTo = CGI.Operands[i].getTiedRegister(); 2026 } 2027 2028 if (tiedTo != -1) { 2029 std::pair<unsigned, unsigned> SO = 2030 CGI.Operands.getSubOperandNumber(tiedTo); 2031 2032 InsnOperands.push_back( 2033 NumberedInsnOperands[TiedNames[std::string(Op.second)]] 2034 [SO.second]); 2035 } 2036 } 2037 continue; 2038 } 2039 2040 TypedInit *TI = cast<TypedInit>(Op.first); 2041 2042 // At this point, we can locate the decoder field, but we need to know how 2043 // to interpret it. As a first step, require the target to provide 2044 // callbacks for decoding register classes. 2045 std::string Decoder = findOperandDecoderMethod(TI); 2046 Record *TypeRecord = cast<DefInit>(TI)->getDef(); 2047 2048 RecordVal *HasCompleteDecoderVal = 2049 TypeRecord->getValue("hasCompleteDecoder"); 2050 BitInit *HasCompleteDecoderBit = HasCompleteDecoderVal ? 2051 dyn_cast<BitInit>(HasCompleteDecoderVal->getValue()) : nullptr; 2052 bool HasCompleteDecoder = HasCompleteDecoderBit ? 2053 HasCompleteDecoderBit->getValue() : true; 2054 2055 OperandInfo OpInfo(Decoder, HasCompleteDecoder); 2056 2057 // Some bits of the operand may be required to be 1 depending on the 2058 // instruction's encoding. Collect those bits. 2059 if (const RecordVal *EncodedValue = EncodingDef.getValue(Op.second)) 2060 if (const BitsInit *OpBits = dyn_cast<BitsInit>(EncodedValue->getValue())) 2061 for (unsigned I = 0; I < OpBits->getNumBits(); ++I) 2062 if (const BitInit *OpBit = dyn_cast<BitInit>(OpBits->getBit(I))) 2063 if (OpBit->getValue()) 2064 OpInfo.InitValue |= 1ULL << I; 2065 2066 unsigned Base = ~0U; 2067 unsigned Width = 0; 2068 unsigned Offset = 0; 2069 2070 for (unsigned bi = 0; bi < Bits.getNumBits(); ++bi) { 2071 VarInit *Var = nullptr; 2072 VarBitInit *BI = dyn_cast<VarBitInit>(Bits.getBit(bi)); 2073 if (BI) 2074 Var = dyn_cast<VarInit>(BI->getBitVar()); 2075 else 2076 Var = dyn_cast<VarInit>(Bits.getBit(bi)); 2077 2078 if (!Var) { 2079 if (Base != ~0U) { 2080 OpInfo.addField(Base, Width, Offset); 2081 Base = ~0U; 2082 Width = 0; 2083 Offset = 0; 2084 } 2085 continue; 2086 } 2087 2088 if (Var->getName() != Op.second && 2089 Var->getName() != TiedNames[std::string(Op.second)]) { 2090 if (Base != ~0U) { 2091 OpInfo.addField(Base, Width, Offset); 2092 Base = ~0U; 2093 Width = 0; 2094 Offset = 0; 2095 } 2096 continue; 2097 } 2098 2099 if (Base == ~0U) { 2100 Base = bi; 2101 Width = 1; 2102 Offset = BI ? BI->getBitNum() : 0; 2103 } else if (BI && BI->getBitNum() != Offset + Width) { 2104 OpInfo.addField(Base, Width, Offset); 2105 Base = bi; 2106 Width = 1; 2107 Offset = BI->getBitNum(); 2108 } else { 2109 ++Width; 2110 } 2111 } 2112 2113 if (Base != ~0U) 2114 OpInfo.addField(Base, Width, Offset); 2115 2116 if (OpInfo.numFields() > 0) 2117 InsnOperands.push_back(OpInfo); 2118 } 2119 2120 Operands[Opc] = InsnOperands; 2121 2122 #if 0 2123 LLVM_DEBUG({ 2124 // Dumps the instruction encoding bits. 2125 dumpBits(errs(), Bits); 2126 2127 errs() << '\n'; 2128 2129 // Dumps the list of operand info. 2130 for (unsigned i = 0, e = CGI.Operands.size(); i != e; ++i) { 2131 const CGIOperandList::OperandInfo &Info = CGI.Operands[i]; 2132 const std::string &OperandName = Info.Name; 2133 const Record &OperandDef = *Info.Rec; 2134 2135 errs() << "\t" << OperandName << " (" << OperandDef.getName() << ")\n"; 2136 } 2137 }); 2138 #endif 2139 2140 return true; 2141 } 2142 2143 // emitFieldFromInstruction - Emit the templated helper function 2144 // fieldFromInstruction(). 2145 // On Windows we make sure that this function is not inlined when 2146 // using the VS compiler. It has a bug which causes the function 2147 // to be optimized out in some circustances. See llvm.org/pr38292 2148 static void emitFieldFromInstruction(formatted_raw_ostream &OS) { 2149 OS << "// Helper functions for extracting fields from encoded instructions.\n" 2150 << "// InsnType must either be integral or an APInt-like object that " 2151 "must:\n" 2152 << "// * Have a static const max_size_in_bits equal to the number of bits " 2153 "in the\n" 2154 << "// encoding.\n" 2155 << "// * be default-constructible and copy-constructible\n" 2156 << "// * be constructible from a uint64_t\n" 2157 << "// * be constructible from an APInt (this can be private)\n" 2158 << "// * Support getBitsSet(loBit, hiBit)\n" 2159 << "// * be convertible to uint64_t\n" 2160 << "// * Support the ~, &, ==, !=, and |= operators with other objects of " 2161 "the same type\n" 2162 << "// * Support shift (<<, >>) with signed and unsigned integers on the " 2163 "RHS\n" 2164 << "// * Support put (<<) to raw_ostream&\n" 2165 << "template <typename InsnType>\n" 2166 << "#if defined(_MSC_VER) && !defined(__clang__)\n" 2167 << "__declspec(noinline)\n" 2168 << "#endif\n" 2169 << "static InsnType fieldFromInstruction(InsnType insn, unsigned " 2170 "startBit,\n" 2171 << " unsigned numBits, " 2172 "std::true_type) {\n" 2173 << " assert(startBit + numBits <= 64 && \"Cannot support >64-bit " 2174 "extractions!\");\n" 2175 << " assert(startBit + numBits <= (sizeof(InsnType) * 8) &&\n" 2176 << " \"Instruction field out of bounds!\");\n" 2177 << " InsnType fieldMask;\n" 2178 << " if (numBits == sizeof(InsnType) * 8)\n" 2179 << " fieldMask = (InsnType)(-1LL);\n" 2180 << " else\n" 2181 << " fieldMask = (((InsnType)1 << numBits) - 1) << startBit;\n" 2182 << " return (insn & fieldMask) >> startBit;\n" 2183 << "}\n" 2184 << "\n" 2185 << "template <typename InsnType>\n" 2186 << "static InsnType fieldFromInstruction(InsnType insn, unsigned " 2187 "startBit,\n" 2188 << " unsigned numBits, " 2189 "std::false_type) {\n" 2190 << " assert(startBit + numBits <= InsnType::max_size_in_bits && " 2191 "\"Instruction field out of bounds!\");\n" 2192 << " InsnType fieldMask = InsnType::getBitsSet(0, numBits);\n" 2193 << " return (insn >> startBit) & fieldMask;\n" 2194 << "}\n" 2195 << "\n" 2196 << "template <typename InsnType>\n" 2197 << "static InsnType fieldFromInstruction(InsnType insn, unsigned " 2198 "startBit,\n" 2199 << " unsigned numBits) {\n" 2200 << " return fieldFromInstruction(insn, startBit, numBits, " 2201 "std::is_integral<InsnType>());\n" 2202 << "}\n\n"; 2203 } 2204 2205 // emitDecodeInstruction - Emit the templated helper function 2206 // decodeInstruction(). 2207 static void emitDecodeInstruction(formatted_raw_ostream &OS) { 2208 OS << "template <typename InsnType>\n" 2209 << "static DecodeStatus decodeInstruction(const uint8_t DecodeTable[], " 2210 "MCInst &MI,\n" 2211 << " InsnType insn, uint64_t " 2212 "Address,\n" 2213 << " const void *DisAsm,\n" 2214 << " const MCSubtargetInfo &STI) {\n" 2215 << " const FeatureBitset &Bits = STI.getFeatureBits();\n" 2216 << "\n" 2217 << " const uint8_t *Ptr = DecodeTable;\n" 2218 << " InsnType CurFieldValue = 0;\n" 2219 << " DecodeStatus S = MCDisassembler::Success;\n" 2220 << " while (true) {\n" 2221 << " ptrdiff_t Loc = Ptr - DecodeTable;\n" 2222 << " switch (*Ptr) {\n" 2223 << " default:\n" 2224 << " errs() << Loc << \": Unexpected decode table opcode!\\n\";\n" 2225 << " return MCDisassembler::Fail;\n" 2226 << " case MCD::OPC_ExtractField: {\n" 2227 << " unsigned Start = *++Ptr;\n" 2228 << " unsigned Len = *++Ptr;\n" 2229 << " ++Ptr;\n" 2230 << " CurFieldValue = fieldFromInstruction(insn, Start, Len);\n" 2231 << " LLVM_DEBUG(dbgs() << Loc << \": OPC_ExtractField(\" << Start << " 2232 "\", \"\n" 2233 << " << Len << \"): \" << CurFieldValue << \"\\n\");\n" 2234 << " break;\n" 2235 << " }\n" 2236 << " case MCD::OPC_FilterValue: {\n" 2237 << " // Decode the field value.\n" 2238 << " unsigned Len;\n" 2239 << " InsnType Val = decodeULEB128(++Ptr, &Len);\n" 2240 << " Ptr += Len;\n" 2241 << " // NumToSkip is a plain 24-bit integer.\n" 2242 << " unsigned NumToSkip = *Ptr++;\n" 2243 << " NumToSkip |= (*Ptr++) << 8;\n" 2244 << " NumToSkip |= (*Ptr++) << 16;\n" 2245 << "\n" 2246 << " // Perform the filter operation.\n" 2247 << " if (Val != CurFieldValue)\n" 2248 << " Ptr += NumToSkip;\n" 2249 << " LLVM_DEBUG(dbgs() << Loc << \": OPC_FilterValue(\" << Val << " 2250 "\", \" << NumToSkip\n" 2251 << " << \"): \" << ((Val != CurFieldValue) ? \"FAIL:\" " 2252 ": \"PASS:\")\n" 2253 << " << \" continuing at \" << (Ptr - DecodeTable) << " 2254 "\"\\n\");\n" 2255 << "\n" 2256 << " break;\n" 2257 << " }\n" 2258 << " case MCD::OPC_CheckField: {\n" 2259 << " unsigned Start = *++Ptr;\n" 2260 << " unsigned Len = *++Ptr;\n" 2261 << " InsnType FieldValue = fieldFromInstruction(insn, Start, Len);\n" 2262 << " // Decode the field value.\n" 2263 << " InsnType ExpectedValue = decodeULEB128(++Ptr, &Len);\n" 2264 << " Ptr += Len;\n" 2265 << " // NumToSkip is a plain 24-bit integer.\n" 2266 << " unsigned NumToSkip = *Ptr++;\n" 2267 << " NumToSkip |= (*Ptr++) << 8;\n" 2268 << " NumToSkip |= (*Ptr++) << 16;\n" 2269 << "\n" 2270 << " // If the actual and expected values don't match, skip.\n" 2271 << " if (ExpectedValue != FieldValue)\n" 2272 << " Ptr += NumToSkip;\n" 2273 << " LLVM_DEBUG(dbgs() << Loc << \": OPC_CheckField(\" << Start << " 2274 "\", \"\n" 2275 << " << Len << \", \" << ExpectedValue << \", \" << " 2276 "NumToSkip\n" 2277 << " << \"): FieldValue = \" << FieldValue << \", " 2278 "ExpectedValue = \"\n" 2279 << " << ExpectedValue << \": \"\n" 2280 << " << ((ExpectedValue == FieldValue) ? \"PASS\\n\" : " 2281 "\"FAIL\\n\"));\n" 2282 << " break;\n" 2283 << " }\n" 2284 << " case MCD::OPC_CheckPredicate: {\n" 2285 << " unsigned Len;\n" 2286 << " // Decode the Predicate Index value.\n" 2287 << " unsigned PIdx = decodeULEB128(++Ptr, &Len);\n" 2288 << " Ptr += Len;\n" 2289 << " // NumToSkip is a plain 24-bit integer.\n" 2290 << " unsigned NumToSkip = *Ptr++;\n" 2291 << " NumToSkip |= (*Ptr++) << 8;\n" 2292 << " NumToSkip |= (*Ptr++) << 16;\n" 2293 << " // Check the predicate.\n" 2294 << " bool Pred;\n" 2295 << " if (!(Pred = checkDecoderPredicate(PIdx, Bits)))\n" 2296 << " Ptr += NumToSkip;\n" 2297 << " (void)Pred;\n" 2298 << " LLVM_DEBUG(dbgs() << Loc << \": OPC_CheckPredicate(\" << PIdx " 2299 "<< \"): \"\n" 2300 << " << (Pred ? \"PASS\\n\" : \"FAIL\\n\"));\n" 2301 << "\n" 2302 << " break;\n" 2303 << " }\n" 2304 << " case MCD::OPC_Decode: {\n" 2305 << " unsigned Len;\n" 2306 << " // Decode the Opcode value.\n" 2307 << " unsigned Opc = decodeULEB128(++Ptr, &Len);\n" 2308 << " Ptr += Len;\n" 2309 << " unsigned DecodeIdx = decodeULEB128(Ptr, &Len);\n" 2310 << " Ptr += Len;\n" 2311 << "\n" 2312 << " MI.clear();\n" 2313 << " MI.setOpcode(Opc);\n" 2314 << " bool DecodeComplete;\n" 2315 << " S = decodeToMCInst(S, DecodeIdx, insn, MI, Address, DisAsm, " 2316 "DecodeComplete);\n" 2317 << " assert(DecodeComplete);\n" 2318 << "\n" 2319 << " LLVM_DEBUG(dbgs() << Loc << \": OPC_Decode: opcode \" << Opc\n" 2320 << " << \", using decoder \" << DecodeIdx << \": \"\n" 2321 << " << (S != MCDisassembler::Fail ? \"PASS\" : " 2322 "\"FAIL\") << \"\\n\");\n" 2323 << " return S;\n" 2324 << " }\n" 2325 << " case MCD::OPC_TryDecode: {\n" 2326 << " unsigned Len;\n" 2327 << " // Decode the Opcode value.\n" 2328 << " unsigned Opc = decodeULEB128(++Ptr, &Len);\n" 2329 << " Ptr += Len;\n" 2330 << " unsigned DecodeIdx = decodeULEB128(Ptr, &Len);\n" 2331 << " Ptr += Len;\n" 2332 << " // NumToSkip is a plain 24-bit integer.\n" 2333 << " unsigned NumToSkip = *Ptr++;\n" 2334 << " NumToSkip |= (*Ptr++) << 8;\n" 2335 << " NumToSkip |= (*Ptr++) << 16;\n" 2336 << "\n" 2337 << " // Perform the decode operation.\n" 2338 << " MCInst TmpMI;\n" 2339 << " TmpMI.setOpcode(Opc);\n" 2340 << " bool DecodeComplete;\n" 2341 << " S = decodeToMCInst(S, DecodeIdx, insn, TmpMI, Address, DisAsm, " 2342 "DecodeComplete);\n" 2343 << " LLVM_DEBUG(dbgs() << Loc << \": OPC_TryDecode: opcode \" << " 2344 "Opc\n" 2345 << " << \", using decoder \" << DecodeIdx << \": \");\n" 2346 << "\n" 2347 << " if (DecodeComplete) {\n" 2348 << " // Decoding complete.\n" 2349 << " LLVM_DEBUG(dbgs() << (S != MCDisassembler::Fail ? \"PASS\" : " 2350 "\"FAIL\") << \"\\n\");\n" 2351 << " MI = TmpMI;\n" 2352 << " return S;\n" 2353 << " } else {\n" 2354 << " assert(S == MCDisassembler::Fail);\n" 2355 << " // If the decoding was incomplete, skip.\n" 2356 << " Ptr += NumToSkip;\n" 2357 << " LLVM_DEBUG(dbgs() << \"FAIL: continuing at \" << (Ptr - " 2358 "DecodeTable) << \"\\n\");\n" 2359 << " // Reset decode status. This also drops a SoftFail status " 2360 "that could be\n" 2361 << " // set before the decode attempt.\n" 2362 << " S = MCDisassembler::Success;\n" 2363 << " }\n" 2364 << " break;\n" 2365 << " }\n" 2366 << " case MCD::OPC_SoftFail: {\n" 2367 << " // Decode the mask values.\n" 2368 << " unsigned Len;\n" 2369 << " InsnType PositiveMask = decodeULEB128(++Ptr, &Len);\n" 2370 << " Ptr += Len;\n" 2371 << " InsnType NegativeMask = decodeULEB128(Ptr, &Len);\n" 2372 << " Ptr += Len;\n" 2373 << " bool Fail = (insn & PositiveMask) || (~insn & NegativeMask);\n" 2374 << " if (Fail)\n" 2375 << " S = MCDisassembler::SoftFail;\n" 2376 << " LLVM_DEBUG(dbgs() << Loc << \": OPC_SoftFail: \" << (Fail ? " 2377 "\"FAIL\\n\" : \"PASS\\n\"));\n" 2378 << " break;\n" 2379 << " }\n" 2380 << " case MCD::OPC_Fail: {\n" 2381 << " LLVM_DEBUG(dbgs() << Loc << \": OPC_Fail\\n\");\n" 2382 << " return MCDisassembler::Fail;\n" 2383 << " }\n" 2384 << " }\n" 2385 << " }\n" 2386 << " llvm_unreachable(\"bogosity detected in disassembler state " 2387 "machine!\");\n" 2388 << "}\n\n"; 2389 } 2390 2391 // Emits disassembler code for instruction decoding. 2392 void FixedLenDecoderEmitter::run(raw_ostream &o) { 2393 formatted_raw_ostream OS(o); 2394 OS << "#include \"llvm/MC/MCInst.h\"\n"; 2395 OS << "#include \"llvm/Support/DataTypes.h\"\n"; 2396 OS << "#include \"llvm/Support/Debug.h\"\n"; 2397 OS << "#include \"llvm/Support/LEB128.h\"\n"; 2398 OS << "#include \"llvm/Support/raw_ostream.h\"\n"; 2399 OS << "#include <assert.h>\n"; 2400 OS << '\n'; 2401 OS << "namespace llvm {\n\n"; 2402 2403 emitFieldFromInstruction(OS); 2404 2405 Target.reverseBitsForLittleEndianEncoding(); 2406 2407 // Parameterize the decoders based on namespace and instruction width. 2408 std::set<StringRef> HwModeNames; 2409 const auto &NumberedInstructions = Target.getInstructionsByEnumValue(); 2410 NumberedEncodings.reserve(NumberedInstructions.size()); 2411 DenseMap<Record *, unsigned> IndexOfInstruction; 2412 // First, collect all HwModes referenced by the target. 2413 for (const auto &NumberedInstruction : NumberedInstructions) { 2414 IndexOfInstruction[NumberedInstruction->TheDef] = NumberedEncodings.size(); 2415 2416 if (const RecordVal *RV = 2417 NumberedInstruction->TheDef->getValue("EncodingInfos")) { 2418 if (auto *DI = dyn_cast_or_null<DefInit>(RV->getValue())) { 2419 const CodeGenHwModes &HWM = Target.getHwModes(); 2420 EncodingInfoByHwMode EBM(DI->getDef(), HWM); 2421 for (auto &KV : EBM.Map) 2422 HwModeNames.insert(HWM.getMode(KV.first).Name); 2423 } 2424 } 2425 } 2426 2427 // If HwModeNames is empty, add the empty string so we always have one HwMode. 2428 if (HwModeNames.empty()) 2429 HwModeNames.insert(""); 2430 2431 for (const auto &NumberedInstruction : NumberedInstructions) { 2432 IndexOfInstruction[NumberedInstruction->TheDef] = NumberedEncodings.size(); 2433 2434 if (const RecordVal *RV = 2435 NumberedInstruction->TheDef->getValue("EncodingInfos")) { 2436 if (DefInit *DI = dyn_cast_or_null<DefInit>(RV->getValue())) { 2437 const CodeGenHwModes &HWM = Target.getHwModes(); 2438 EncodingInfoByHwMode EBM(DI->getDef(), HWM); 2439 for (auto &KV : EBM.Map) { 2440 NumberedEncodings.emplace_back(KV.second, NumberedInstruction, 2441 HWM.getMode(KV.first).Name); 2442 HwModeNames.insert(HWM.getMode(KV.first).Name); 2443 } 2444 continue; 2445 } 2446 } 2447 // This instruction is encoded the same on all HwModes. Emit it for all 2448 // HwModes. 2449 for (StringRef HwModeName : HwModeNames) 2450 NumberedEncodings.emplace_back(NumberedInstruction->TheDef, 2451 NumberedInstruction, HwModeName); 2452 } 2453 for (const auto &NumberedAlias : RK.getAllDerivedDefinitions("AdditionalEncoding")) 2454 NumberedEncodings.emplace_back( 2455 NumberedAlias, 2456 &Target.getInstruction(NumberedAlias->getValueAsDef("AliasOf"))); 2457 2458 std::map<std::pair<std::string, unsigned>, std::vector<EncodingIDAndOpcode>> 2459 OpcMap; 2460 std::map<unsigned, std::vector<OperandInfo>> Operands; 2461 2462 for (unsigned i = 0; i < NumberedEncodings.size(); ++i) { 2463 const Record *EncodingDef = NumberedEncodings[i].EncodingDef; 2464 const CodeGenInstruction *Inst = NumberedEncodings[i].Inst; 2465 const Record *Def = Inst->TheDef; 2466 unsigned Size = EncodingDef->getValueAsInt("Size"); 2467 if (Def->getValueAsString("Namespace") == "TargetOpcode" || 2468 Def->getValueAsBit("isPseudo") || 2469 Def->getValueAsBit("isAsmParserOnly") || 2470 Def->getValueAsBit("isCodeGenOnly")) { 2471 NumEncodingsLackingDisasm++; 2472 continue; 2473 } 2474 2475 if (i < NumberedInstructions.size()) 2476 NumInstructions++; 2477 NumEncodings++; 2478 2479 if (!Size) 2480 continue; 2481 2482 if (populateInstruction(Target, *EncodingDef, *Inst, i, Operands)) { 2483 std::string DecoderNamespace = 2484 std::string(EncodingDef->getValueAsString("DecoderNamespace")); 2485 if (!NumberedEncodings[i].HwModeName.empty()) 2486 DecoderNamespace += 2487 std::string("_") + NumberedEncodings[i].HwModeName.str(); 2488 OpcMap[std::make_pair(DecoderNamespace, Size)].emplace_back( 2489 i, IndexOfInstruction.find(Def)->second); 2490 } else { 2491 NumEncodingsOmitted++; 2492 } 2493 } 2494 2495 DecoderTableInfo TableInfo; 2496 for (const auto &Opc : OpcMap) { 2497 // Emit the decoder for this namespace+width combination. 2498 ArrayRef<EncodingAndInst> NumberedEncodingsRef( 2499 NumberedEncodings.data(), NumberedEncodings.size()); 2500 FilterChooser FC(NumberedEncodingsRef, Opc.second, Operands, 2501 8 * Opc.first.second, this); 2502 2503 // The decode table is cleared for each top level decoder function. The 2504 // predicates and decoders themselves, however, are shared across all 2505 // decoders to give more opportunities for uniqueing. 2506 TableInfo.Table.clear(); 2507 TableInfo.FixupStack.clear(); 2508 TableInfo.Table.reserve(16384); 2509 TableInfo.FixupStack.emplace_back(); 2510 FC.emitTableEntries(TableInfo); 2511 // Any NumToSkip fixups in the top level scope can resolve to the 2512 // OPC_Fail at the end of the table. 2513 assert(TableInfo.FixupStack.size() == 1 && "fixup stack phasing error!"); 2514 // Resolve any NumToSkip fixups in the current scope. 2515 resolveTableFixups(TableInfo.Table, TableInfo.FixupStack.back(), 2516 TableInfo.Table.size()); 2517 TableInfo.FixupStack.clear(); 2518 2519 TableInfo.Table.push_back(MCD::OPC_Fail); 2520 2521 // Print the table to the output stream. 2522 emitTable(OS, TableInfo.Table, 0, FC.getBitWidth(), Opc.first.first); 2523 OS.flush(); 2524 } 2525 2526 // Emit the predicate function. 2527 emitPredicateFunction(OS, TableInfo.Predicates, 0); 2528 2529 // Emit the decoder function. 2530 emitDecoderFunction(OS, TableInfo.Decoders, 0); 2531 2532 // Emit the main entry point for the decoder, decodeInstruction(). 2533 emitDecodeInstruction(OS); 2534 2535 OS << "\n} // end namespace llvm\n"; 2536 } 2537 2538 namespace llvm { 2539 2540 void EmitFixedLenDecoder(RecordKeeper &RK, raw_ostream &OS, 2541 const std::string &PredicateNamespace, 2542 const std::string &GPrefix, 2543 const std::string &GPostfix, const std::string &ROK, 2544 const std::string &RFail, const std::string &L) { 2545 FixedLenDecoderEmitter(RK, PredicateNamespace, GPrefix, GPostfix, 2546 ROK, RFail, L).run(OS); 2547 } 2548 2549 } // end namespace llvm 2550