1 //===------------ FixedLenDecoderEmitter.cpp - Decoder Generator ----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // It contains the tablegen backend that emits the decoder functions for
11 // targets with fixed length instruction set.
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "decoder-emitter"
17 #include "CodeGenTarget.h"
18 #include "llvm/TableGen/Record.h"
19 #include "llvm/ADT/APInt.h"
20 #include "llvm/ADT/StringExtras.h"
21 #include "llvm/Support/DataTypes.h"
22 #include "llvm/Support/Debug.h"
23 #include "llvm/Support/raw_ostream.h"
24 #include "llvm/TableGen/TableGenBackend.h"
33 struct EncodingField {
34 unsigned Base, Width, Offset;
35 EncodingField(unsigned B, unsigned W, unsigned O)
36 : Base(B), Width(W), Offset(O) { }
38 } // End anonymous namespace
42 std::vector<EncodingField> Fields;
45 OperandInfo(std::string D)
48 void addField(unsigned Base, unsigned Width, unsigned Offset) {
49 Fields.push_back(EncodingField(Base, Width, Offset));
52 unsigned numFields() const { return Fields.size(); }
54 typedef std::vector<EncodingField>::const_iterator const_iterator;
56 const_iterator begin() const { return Fields.begin(); }
57 const_iterator end() const { return Fields.end(); }
59 } // End anonymous namespace
62 class FixedLenDecoderEmitter {
65 // Defaults preserved here for documentation, even though they aren't
66 // strictly necessary given the way that this is currently being called.
67 FixedLenDecoderEmitter(RecordKeeper &R,
68 std::string PredicateNamespace,
69 std::string GPrefix = "if (",
70 std::string GPostfix = " == MCDisassembler::Fail)"
71 " return MCDisassembler::Fail;",
72 std::string ROK = "MCDisassembler::Success",
73 std::string RFail = "MCDisassembler::Fail",
76 PredicateNamespace(PredicateNamespace),
77 GuardPrefix(GPrefix), GuardPostfix(GPostfix),
78 ReturnOK(ROK), ReturnFail(RFail), Locals(L) {}
80 // run - Output the code emitter
81 void run(raw_ostream &o);
86 std::string PredicateNamespace;
87 std::string GuardPrefix, GuardPostfix;
88 std::string ReturnOK, ReturnFail;
91 } // End anonymous namespace
93 // The set (BIT_TRUE, BIT_FALSE, BIT_UNSET) represents a ternary logic system
96 // BIT_UNFILTERED is used as the init value for a filter position. It is used
97 // only for filter processings.
102 BIT_UNFILTERED // unfiltered
105 static bool ValueSet(bit_value_t V) {
106 return (V == BIT_TRUE || V == BIT_FALSE);
108 static bool ValueNotSet(bit_value_t V) {
109 return (V == BIT_UNSET);
111 static int Value(bit_value_t V) {
112 return ValueNotSet(V) ? -1 : (V == BIT_FALSE ? 0 : 1);
114 static bit_value_t bitFromBits(const BitsInit &bits, unsigned index) {
115 if (BitInit *bit = dynamic_cast<BitInit*>(bits.getBit(index)))
116 return bit->getValue() ? BIT_TRUE : BIT_FALSE;
118 // The bit is uninitialized.
121 // Prints the bit value for each position.
122 static void dumpBits(raw_ostream &o, const BitsInit &bits) {
125 for (index = bits.getNumBits(); index > 0; index--) {
126 switch (bitFromBits(bits, index - 1)) {
137 llvm_unreachable("unexpected return value from bitFromBits");
142 static BitsInit &getBitsField(const Record &def, const char *str) {
143 BitsInit *bits = def.getValueAsBitsInit(str);
147 // Forward declaration.
150 } // End anonymous namespace
152 // Representation of the instruction to work on.
153 typedef std::vector<bit_value_t> insn_t;
155 /// Filter - Filter works with FilterChooser to produce the decoding tree for
158 /// It is useful to think of a Filter as governing the switch stmts of the
159 /// decoding tree in a certain level. Each case stmt delegates to an inferior
160 /// FilterChooser to decide what further decoding logic to employ, or in another
161 /// words, what other remaining bits to look at. The FilterChooser eventually
162 /// chooses a best Filter to do its job.
164 /// This recursive scheme ends when the number of Opcodes assigned to the
165 /// FilterChooser becomes 1 or if there is a conflict. A conflict happens when
166 /// the Filter/FilterChooser combo does not know how to distinguish among the
167 /// Opcodes assigned.
169 /// An example of a conflict is
172 /// 111101000.00........00010000....
173 /// 111101000.00........0001........
174 /// 1111010...00........0001........
175 /// 1111010...00....................
176 /// 1111010.........................
177 /// 1111............................
178 /// ................................
179 /// VST4q8a 111101000_00________00010000____
180 /// VST4q8b 111101000_00________00010000____
182 /// The Debug output shows the path that the decoding tree follows to reach the
183 /// the conclusion that there is a conflict. VST4q8a is a vst4 to double-spaced
184 /// even registers, while VST4q8b is a vst4 to double-spaced odd regsisters.
186 /// The encoding info in the .td files does not specify this meta information,
187 /// which could have been used by the decoder to resolve the conflict. The
188 /// decoder could try to decode the even/odd register numbering and assign to
189 /// VST4q8a or VST4q8b, but for the time being, the decoder chooses the "a"
190 /// version and return the Opcode since the two have the same Asm format string.
194 const FilterChooser *Owner;// points to the FilterChooser who owns this filter
195 unsigned StartBit; // the starting bit position
196 unsigned NumBits; // number of bits to filter
197 bool Mixed; // a mixed region contains both set and unset bits
199 // Map of well-known segment value to the set of uid's with that value.
200 std::map<uint64_t, std::vector<unsigned> > FilteredInstructions;
202 // Set of uid's with non-constant segment values.
203 std::vector<unsigned> VariableInstructions;
205 // Map of well-known segment value to its delegate.
206 std::map<unsigned, const FilterChooser*> FilterChooserMap;
208 // Number of instructions which fall under FilteredInstructions category.
209 unsigned NumFiltered;
211 // Keeps track of the last opcode in the filtered bucket.
212 unsigned LastOpcFiltered;
215 unsigned getNumFiltered() const { return NumFiltered; }
216 unsigned getSingletonOpc() const {
217 assert(NumFiltered == 1);
218 return LastOpcFiltered;
220 // Return the filter chooser for the group of instructions without constant
222 const FilterChooser &getVariableFC() const {
223 assert(NumFiltered == 1);
224 assert(FilterChooserMap.size() == 1);
225 return *(FilterChooserMap.find((unsigned)-1)->second);
228 Filter(const Filter &f);
229 Filter(FilterChooser &owner, unsigned startBit, unsigned numBits, bool mixed);
233 // Divides the decoding task into sub tasks and delegates them to the
234 // inferior FilterChooser's.
236 // A special case arises when there's only one entry in the filtered
237 // instructions. In order to unambiguously decode the singleton, we need to
238 // match the remaining undecoded encoding bits against the singleton.
241 // Emit code to decode instructions given a segment or segments of bits.
242 void emit(raw_ostream &o, unsigned &Indentation) const;
244 // Returns the number of fanout produced by the filter. More fanout implies
245 // the filter distinguishes more categories of instructions.
246 unsigned usefulness() const;
247 }; // End of class Filter
248 } // End anonymous namespace
250 // These are states of our finite state machines used in FilterChooser's
251 // filterProcessor() which produces the filter candidates to use.
260 /// FilterChooser - FilterChooser chooses the best filter among a set of Filters
261 /// in order to perform the decoding of instructions at the current level.
263 /// Decoding proceeds from the top down. Based on the well-known encoding bits
264 /// of instructions available, FilterChooser builds up the possible Filters that
265 /// can further the task of decoding by distinguishing among the remaining
266 /// candidate instructions.
268 /// Once a filter has been chosen, it is called upon to divide the decoding task
269 /// into sub-tasks and delegates them to its inferior FilterChoosers for further
272 /// It is useful to think of a Filter as governing the switch stmts of the
273 /// decoding tree. And each case is delegated to an inferior FilterChooser to
274 /// decide what further remaining bits to look at.
276 class FilterChooser {
280 // Vector of codegen instructions to choose our filter.
281 const std::vector<const CodeGenInstruction*> &AllInstructions;
283 // Vector of uid's for this filter chooser to work on.
284 const std::vector<unsigned> &Opcodes;
286 // Lookup table for the operand decoding of instructions.
287 const std::map<unsigned, std::vector<OperandInfo> > &Operands;
289 // Vector of candidate filters.
290 std::vector<Filter> Filters;
292 // Array of bit values passed down from our parent.
293 // Set to all BIT_UNFILTERED's for Parent == NULL.
294 std::vector<bit_value_t> FilterBitValues;
296 // Links to the FilterChooser above us in the decoding tree.
297 const FilterChooser *Parent;
299 // Index of the best filter from Filters.
302 // Width of instructions
306 const FixedLenDecoderEmitter *Emitter;
309 FilterChooser(const FilterChooser &FC)
310 : AllInstructions(FC.AllInstructions), Opcodes(FC.Opcodes),
311 Operands(FC.Operands), Filters(FC.Filters),
312 FilterBitValues(FC.FilterBitValues), Parent(FC.Parent),
313 BestIndex(FC.BestIndex), BitWidth(FC.BitWidth),
314 Emitter(FC.Emitter) { }
316 FilterChooser(const std::vector<const CodeGenInstruction*> &Insts,
317 const std::vector<unsigned> &IDs,
318 const std::map<unsigned, std::vector<OperandInfo> > &Ops,
320 const FixedLenDecoderEmitter *E)
321 : AllInstructions(Insts), Opcodes(IDs), Operands(Ops), Filters(),
322 Parent(NULL), BestIndex(-1), BitWidth(BW), Emitter(E) {
323 for (unsigned i = 0; i < BitWidth; ++i)
324 FilterBitValues.push_back(BIT_UNFILTERED);
329 FilterChooser(const std::vector<const CodeGenInstruction*> &Insts,
330 const std::vector<unsigned> &IDs,
331 const std::map<unsigned, std::vector<OperandInfo> > &Ops,
332 const std::vector<bit_value_t> &ParentFilterBitValues,
333 const FilterChooser &parent)
334 : AllInstructions(Insts), Opcodes(IDs), Operands(Ops),
335 Filters(), FilterBitValues(ParentFilterBitValues),
336 Parent(&parent), BestIndex(-1), BitWidth(parent.BitWidth),
337 Emitter(parent.Emitter) {
341 // The top level filter chooser has NULL as its parent.
342 bool isTopLevel() const { return Parent == NULL; }
344 // Emit the top level typedef and decodeInstruction() function.
345 void emitTop(raw_ostream &o, unsigned Indentation,
346 const std::string &Namespace) const;
349 // Populates the insn given the uid.
350 void insnWithID(insn_t &Insn, unsigned Opcode) const {
351 BitsInit &Bits = getBitsField(*AllInstructions[Opcode]->TheDef, "Inst");
353 // We may have a SoftFail bitmask, which specifies a mask where an encoding
354 // may differ from the value in "Inst" and yet still be valid, but the
355 // disassembler should return SoftFail instead of Success.
357 // This is used for marking UNPREDICTABLE instructions in the ARM world.
359 AllInstructions[Opcode]->TheDef->getValueAsBitsInit("SoftFail");
361 for (unsigned i = 0; i < BitWidth; ++i) {
362 if (SFBits && bitFromBits(*SFBits, i) == BIT_TRUE)
363 Insn.push_back(BIT_UNSET);
365 Insn.push_back(bitFromBits(Bits, i));
369 // Returns the record name.
370 const std::string &nameWithID(unsigned Opcode) const {
371 return AllInstructions[Opcode]->TheDef->getName();
374 // Populates the field of the insn given the start position and the number of
375 // consecutive bits to scan for.
377 // Returns false if there exists any uninitialized bit value in the range.
378 // Returns true, otherwise.
379 bool fieldFromInsn(uint64_t &Field, insn_t &Insn, unsigned StartBit,
380 unsigned NumBits) const;
382 /// dumpFilterArray - dumpFilterArray prints out debugging info for the given
383 /// filter array as a series of chars.
384 void dumpFilterArray(raw_ostream &o,
385 const std::vector<bit_value_t> & filter) const;
387 /// dumpStack - dumpStack traverses the filter chooser chain and calls
388 /// dumpFilterArray on each filter chooser up to the top level one.
389 void dumpStack(raw_ostream &o, const char *prefix) const;
391 Filter &bestFilter() {
392 assert(BestIndex != -1 && "BestIndex not set");
393 return Filters[BestIndex];
396 // Called from Filter::recurse() when singleton exists. For debug purpose.
397 void SingletonExists(unsigned Opc) const;
399 bool PositionFiltered(unsigned i) const {
400 return ValueSet(FilterBitValues[i]);
403 // Calculates the island(s) needed to decode the instruction.
404 // This returns a lit of undecoded bits of an instructions, for example,
405 // Inst{20} = 1 && Inst{3-0} == 0b1111 represents two islands of yet-to-be
406 // decoded bits in order to verify that the instruction matches the Opcode.
407 unsigned getIslands(std::vector<unsigned> &StartBits,
408 std::vector<unsigned> &EndBits,
409 std::vector<uint64_t> &FieldVals,
410 const insn_t &Insn) const;
412 // Emits code to check the Predicates member of an instruction are true.
413 // Returns true if predicate matches were emitted, false otherwise.
414 bool emitPredicateMatch(raw_ostream &o, unsigned &Indentation,
417 void emitSoftFailCheck(raw_ostream &o, unsigned Indentation,
420 // Emits code to decode the singleton. Return true if we have matched all the
422 bool emitSingletonDecoder(raw_ostream &o, unsigned &Indentation,
425 // Emits code to decode the singleton, and then to decode the rest.
426 void emitSingletonDecoder(raw_ostream &o, unsigned &Indentation,
427 const Filter &Best) const;
429 void emitBinaryParser(raw_ostream &o , unsigned &Indentation,
430 const OperandInfo &OpInfo) const;
432 // Assign a single filter and run with it.
433 void runSingleFilter(unsigned startBit, unsigned numBit, bool mixed);
435 // reportRegion is a helper function for filterProcessor to mark a region as
436 // eligible for use as a filter region.
437 void reportRegion(bitAttr_t RA, unsigned StartBit, unsigned BitIndex,
440 // FilterProcessor scans the well-known encoding bits of the instructions and
441 // builds up a list of candidate filters. It chooses the best filter and
442 // recursively descends down the decoding tree.
443 bool filterProcessor(bool AllowMixed, bool Greedy = true);
445 // Decides on the best configuration of filter(s) to use in order to decode
446 // the instructions. A conflict of instructions may occur, in which case we
447 // dump the conflict set to the standard error.
450 // Emits code to decode our share of instructions. Returns true if the
451 // emitted code causes a return, which occurs if we know how to decode
452 // the instruction at this level or the instruction is not decodeable.
453 bool emit(raw_ostream &o, unsigned &Indentation) const;
455 } // End anonymous namespace
457 ///////////////////////////
459 // Filter Implementation //
461 ///////////////////////////
463 Filter::Filter(const Filter &f)
464 : Owner(f.Owner), StartBit(f.StartBit), NumBits(f.NumBits), Mixed(f.Mixed),
465 FilteredInstructions(f.FilteredInstructions),
466 VariableInstructions(f.VariableInstructions),
467 FilterChooserMap(f.FilterChooserMap), NumFiltered(f.NumFiltered),
468 LastOpcFiltered(f.LastOpcFiltered) {
471 Filter::Filter(FilterChooser &owner, unsigned startBit, unsigned numBits,
473 : Owner(&owner), StartBit(startBit), NumBits(numBits), Mixed(mixed) {
474 assert(StartBit + NumBits - 1 < Owner->BitWidth);
479 for (unsigned i = 0, e = Owner->Opcodes.size(); i != e; ++i) {
482 // Populates the insn given the uid.
483 Owner->insnWithID(Insn, Owner->Opcodes[i]);
486 // Scans the segment for possibly well-specified encoding bits.
487 bool ok = Owner->fieldFromInsn(Field, Insn, StartBit, NumBits);
490 // The encoding bits are well-known. Lets add the uid of the
491 // instruction into the bucket keyed off the constant field value.
492 LastOpcFiltered = Owner->Opcodes[i];
493 FilteredInstructions[Field].push_back(LastOpcFiltered);
496 // Some of the encoding bit(s) are unspecified. This contributes to
497 // one additional member of "Variable" instructions.
498 VariableInstructions.push_back(Owner->Opcodes[i]);
502 assert((FilteredInstructions.size() + VariableInstructions.size() > 0)
503 && "Filter returns no instruction categories");
507 std::map<unsigned, const FilterChooser*>::iterator filterIterator;
508 for (filterIterator = FilterChooserMap.begin();
509 filterIterator != FilterChooserMap.end();
511 delete filterIterator->second;
515 // Divides the decoding task into sub tasks and delegates them to the
516 // inferior FilterChooser's.
518 // A special case arises when there's only one entry in the filtered
519 // instructions. In order to unambiguously decode the singleton, we need to
520 // match the remaining undecoded encoding bits against the singleton.
521 void Filter::recurse() {
522 std::map<uint64_t, std::vector<unsigned> >::const_iterator mapIterator;
524 // Starts by inheriting our parent filter chooser's filter bit values.
525 std::vector<bit_value_t> BitValueArray(Owner->FilterBitValues);
529 if (VariableInstructions.size()) {
530 // Conservatively marks each segment position as BIT_UNSET.
531 for (bitIndex = 0; bitIndex < NumBits; bitIndex++)
532 BitValueArray[StartBit + bitIndex] = BIT_UNSET;
534 // Delegates to an inferior filter chooser for further processing on this
535 // group of instructions whose segment values are variable.
536 FilterChooserMap.insert(std::pair<unsigned, const FilterChooser*>(
538 new FilterChooser(Owner->AllInstructions,
539 VariableInstructions,
546 // No need to recurse for a singleton filtered instruction.
547 // See also Filter::emit().
548 if (getNumFiltered() == 1) {
549 //Owner->SingletonExists(LastOpcFiltered);
550 assert(FilterChooserMap.size() == 1);
554 // Otherwise, create sub choosers.
555 for (mapIterator = FilteredInstructions.begin();
556 mapIterator != FilteredInstructions.end();
559 // Marks all the segment positions with either BIT_TRUE or BIT_FALSE.
560 for (bitIndex = 0; bitIndex < NumBits; bitIndex++) {
561 if (mapIterator->first & (1ULL << bitIndex))
562 BitValueArray[StartBit + bitIndex] = BIT_TRUE;
564 BitValueArray[StartBit + bitIndex] = BIT_FALSE;
567 // Delegates to an inferior filter chooser for further processing on this
568 // category of instructions.
569 FilterChooserMap.insert(std::pair<unsigned, const FilterChooser*>(
571 new FilterChooser(Owner->AllInstructions,
580 // Emit code to decode instructions given a segment or segments of bits.
581 void Filter::emit(raw_ostream &o, unsigned &Indentation) const {
582 o.indent(Indentation) << "// Check Inst{";
585 o << (StartBit + NumBits - 1) << '-';
587 o << StartBit << "} ...\n";
589 o.indent(Indentation) << "switch (fieldFromInstruction" << Owner->BitWidth
590 << "(insn, " << StartBit << ", "
591 << NumBits << ")) {\n";
593 std::map<unsigned, const FilterChooser*>::const_iterator filterIterator;
595 bool DefaultCase = false;
596 for (filterIterator = FilterChooserMap.begin();
597 filterIterator != FilterChooserMap.end();
600 // Field value -1 implies a non-empty set of variable instructions.
601 // See also recurse().
602 if (filterIterator->first == (unsigned)-1) {
605 o.indent(Indentation) << "default:\n";
606 o.indent(Indentation) << " break; // fallthrough\n";
608 // Closing curly brace for the switch statement.
609 // This is unconventional because we want the default processing to be
610 // performed for the fallthrough cases as well, i.e., when the "cases"
611 // did not prove a decoded instruction.
612 o.indent(Indentation) << "}\n";
615 o.indent(Indentation) << "case " << filterIterator->first << ":\n";
617 // We arrive at a category of instructions with the same segment value.
618 // Now delegate to the sub filter chooser for further decodings.
619 // The case may fallthrough, which happens if the remaining well-known
620 // encoding bits do not match exactly.
621 if (!DefaultCase) { ++Indentation; ++Indentation; }
623 filterIterator->second->emit(o, Indentation);
624 // For top level default case, there's no need for a break statement.
625 if (Owner->isTopLevel() && DefaultCase)
628 o.indent(Indentation) << "break;\n";
630 if (!DefaultCase) { --Indentation; --Indentation; }
633 // If there is no default case, we still need to supply a closing brace.
635 // Closing curly brace for the switch statement.
636 o.indent(Indentation) << "}\n";
640 // Returns the number of fanout produced by the filter. More fanout implies
641 // the filter distinguishes more categories of instructions.
642 unsigned Filter::usefulness() const {
643 if (VariableInstructions.size())
644 return FilteredInstructions.size();
646 return FilteredInstructions.size() + 1;
649 //////////////////////////////////
651 // Filterchooser Implementation //
653 //////////////////////////////////
655 // Emit the top level typedef and decodeInstruction() function.
656 void FilterChooser::emitTop(raw_ostream &o, unsigned Indentation,
657 const std::string &Namespace) const {
658 o.indent(Indentation) <<
659 "static MCDisassembler::DecodeStatus decode" << Namespace << "Instruction"
660 << BitWidth << "(MCInst &MI, uint" << BitWidth
661 << "_t insn, uint64_t Address, "
662 << "const void *Decoder, const MCSubtargetInfo &STI) {\n";
663 o.indent(Indentation) << " unsigned tmp = 0;\n";
664 o.indent(Indentation) << " (void)tmp;\n";
665 o.indent(Indentation) << Emitter->Locals << "\n";
666 o.indent(Indentation) << " uint64_t Bits = STI.getFeatureBits();\n";
667 o.indent(Indentation) << " (void)Bits;\n";
669 ++Indentation; ++Indentation;
670 // Emits code to decode the instructions.
671 emit(o, Indentation);
674 o.indent(Indentation) << "return " << Emitter->ReturnFail << ";\n";
675 --Indentation; --Indentation;
677 o.indent(Indentation) << "}\n";
682 // Populates the field of the insn given the start position and the number of
683 // consecutive bits to scan for.
685 // Returns false if and on the first uninitialized bit value encountered.
686 // Returns true, otherwise.
687 bool FilterChooser::fieldFromInsn(uint64_t &Field, insn_t &Insn,
688 unsigned StartBit, unsigned NumBits) const {
691 for (unsigned i = 0; i < NumBits; ++i) {
692 if (Insn[StartBit + i] == BIT_UNSET)
695 if (Insn[StartBit + i] == BIT_TRUE)
696 Field = Field | (1ULL << i);
702 /// dumpFilterArray - dumpFilterArray prints out debugging info for the given
703 /// filter array as a series of chars.
704 void FilterChooser::dumpFilterArray(raw_ostream &o,
705 const std::vector<bit_value_t> &filter) const {
708 for (bitIndex = BitWidth; bitIndex > 0; bitIndex--) {
709 switch (filter[bitIndex - 1]) {
726 /// dumpStack - dumpStack traverses the filter chooser chain and calls
727 /// dumpFilterArray on each filter chooser up to the top level one.
728 void FilterChooser::dumpStack(raw_ostream &o, const char *prefix) const {
729 const FilterChooser *current = this;
733 dumpFilterArray(o, current->FilterBitValues);
735 current = current->Parent;
739 // Called from Filter::recurse() when singleton exists. For debug purpose.
740 void FilterChooser::SingletonExists(unsigned Opc) const {
742 insnWithID(Insn0, Opc);
744 errs() << "Singleton exists: " << nameWithID(Opc)
745 << " with its decoding dominating ";
746 for (unsigned i = 0; i < Opcodes.size(); ++i) {
747 if (Opcodes[i] == Opc) continue;
748 errs() << nameWithID(Opcodes[i]) << ' ';
752 dumpStack(errs(), "\t\t");
753 for (unsigned i = 0; i < Opcodes.size(); ++i) {
754 const std::string &Name = nameWithID(Opcodes[i]);
756 errs() << '\t' << Name << " ";
758 getBitsField(*AllInstructions[Opcodes[i]]->TheDef, "Inst"));
763 // Calculates the island(s) needed to decode the instruction.
764 // This returns a list of undecoded bits of an instructions, for example,
765 // Inst{20} = 1 && Inst{3-0} == 0b1111 represents two islands of yet-to-be
766 // decoded bits in order to verify that the instruction matches the Opcode.
767 unsigned FilterChooser::getIslands(std::vector<unsigned> &StartBits,
768 std::vector<unsigned> &EndBits,
769 std::vector<uint64_t> &FieldVals,
770 const insn_t &Insn) const {
774 uint64_t FieldVal = 0;
777 // 1: Water (the bit value does not affect decoding)
778 // 2: Island (well-known bit value needed for decoding)
782 for (unsigned i = 0; i < BitWidth; ++i) {
783 Val = Value(Insn[i]);
784 bool Filtered = PositionFiltered(i);
786 default: llvm_unreachable("Unreachable code!");
789 if (Filtered || Val == -1)
790 State = 1; // Still in Water
792 State = 2; // Into the Island
794 StartBits.push_back(i);
799 if (Filtered || Val == -1) {
800 State = 1; // Into the Water
801 EndBits.push_back(i - 1);
802 FieldVals.push_back(FieldVal);
805 State = 2; // Still in Island
807 FieldVal = FieldVal | Val << BitNo;
812 // If we are still in Island after the loop, do some housekeeping.
814 EndBits.push_back(BitWidth - 1);
815 FieldVals.push_back(FieldVal);
819 assert(StartBits.size() == Num && EndBits.size() == Num &&
820 FieldVals.size() == Num);
824 void FilterChooser::emitBinaryParser(raw_ostream &o, unsigned &Indentation,
825 const OperandInfo &OpInfo) const {
826 const std::string &Decoder = OpInfo.Decoder;
828 if (OpInfo.numFields() == 1) {
829 OperandInfo::const_iterator OI = OpInfo.begin();
830 o.indent(Indentation) << " tmp = fieldFromInstruction" << BitWidth
831 << "(insn, " << OI->Base << ", " << OI->Width
834 o.indent(Indentation) << " tmp = 0;\n";
835 for (OperandInfo::const_iterator OI = OpInfo.begin(), OE = OpInfo.end();
837 o.indent(Indentation) << " tmp |= (fieldFromInstruction" << BitWidth
838 << "(insn, " << OI->Base << ", " << OI->Width
839 << ") << " << OI->Offset << ");\n";
844 o.indent(Indentation) << " " << Emitter->GuardPrefix << Decoder
845 << "(MI, tmp, Address, Decoder)"
846 << Emitter->GuardPostfix << "\n";
848 o.indent(Indentation) << " MI.addOperand(MCOperand::CreateImm(tmp));\n";
852 static void emitSinglePredicateMatch(raw_ostream &o, StringRef str,
853 const std::string &PredicateNamespace) {
855 o << "!(Bits & " << PredicateNamespace << "::"
856 << str.slice(1,str.size()) << ")";
858 o << "(Bits & " << PredicateNamespace << "::" << str << ")";
861 bool FilterChooser::emitPredicateMatch(raw_ostream &o, unsigned &Indentation,
862 unsigned Opc) const {
863 ListInit *Predicates =
864 AllInstructions[Opc]->TheDef->getValueAsListInit("Predicates");
865 for (unsigned i = 0; i < Predicates->getSize(); ++i) {
866 Record *Pred = Predicates->getElementAsRecord(i);
867 if (!Pred->getValue("AssemblerMatcherPredicate"))
870 std::string P = Pred->getValueAsString("AssemblerCondString");
879 std::pair<StringRef, StringRef> pairs = SR.split(',');
880 while (pairs.second.size()) {
881 emitSinglePredicateMatch(o, pairs.first, Emitter->PredicateNamespace);
883 pairs = pairs.second.split(',');
885 emitSinglePredicateMatch(o, pairs.first, Emitter->PredicateNamespace);
887 return Predicates->getSize() > 0;
890 void FilterChooser::emitSoftFailCheck(raw_ostream &o, unsigned Indentation,
891 unsigned Opc) const {
893 AllInstructions[Opc]->TheDef->getValueAsBitsInit("SoftFail");
895 BitsInit *InstBits = AllInstructions[Opc]->TheDef->getValueAsBitsInit("Inst");
897 APInt PositiveMask(BitWidth, 0ULL);
898 APInt NegativeMask(BitWidth, 0ULL);
899 for (unsigned i = 0; i < BitWidth; ++i) {
900 bit_value_t B = bitFromBits(*SFBits, i);
901 bit_value_t IB = bitFromBits(*InstBits, i);
903 if (B != BIT_TRUE) continue;
907 // The bit is meant to be false, so emit a check to see if it is true.
908 PositiveMask.setBit(i);
911 // The bit is meant to be true, so emit a check to see if it is false.
912 NegativeMask.setBit(i);
915 // The bit is not set; this must be an error!
916 StringRef Name = AllInstructions[Opc]->TheDef->getName();
917 errs() << "SoftFail Conflict: bit SoftFail{" << i << "} in "
919 << " is set but Inst{" << i <<"} is unset!\n"
920 << " - You can only mark a bit as SoftFail if it is fully defined"
921 << " (1/0 - not '?') in Inst\n";
922 o << "#error SoftFail Conflict, " << Name << "::SoftFail{" << i
923 << "} set but Inst{" << i << "} undefined!\n";
927 bool NeedPositiveMask = PositiveMask.getBoolValue();
928 bool NeedNegativeMask = NegativeMask.getBoolValue();
930 if (!NeedPositiveMask && !NeedNegativeMask)
933 std::string PositiveMaskStr = PositiveMask.toString(16, /*signed=*/false);
934 std::string NegativeMaskStr = NegativeMask.toString(16, /*signed=*/false);
935 StringRef BitExt = "";
939 o.indent(Indentation) << "if (";
940 if (NeedPositiveMask)
941 o << "insn & 0x" << PositiveMaskStr << BitExt;
942 if (NeedPositiveMask && NeedNegativeMask)
944 if (NeedNegativeMask)
945 o << "~insn & 0x" << NegativeMaskStr << BitExt;
947 o.indent(Indentation+2) << "S = MCDisassembler::SoftFail;\n";
950 // Emits code to decode the singleton. Return true if we have matched all the
952 bool FilterChooser::emitSingletonDecoder(raw_ostream &o, unsigned &Indentation,
953 unsigned Opc) const {
954 std::vector<unsigned> StartBits;
955 std::vector<unsigned> EndBits;
956 std::vector<uint64_t> FieldVals;
958 insnWithID(Insn, Opc);
960 // Look for islands of undecoded bits of the singleton.
961 getIslands(StartBits, EndBits, FieldVals, Insn);
963 unsigned Size = StartBits.size();
966 // If we have matched all the well-known bits, just issue a return.
968 o.indent(Indentation) << "if (";
969 if (!emitPredicateMatch(o, Indentation, Opc))
972 emitSoftFailCheck(o, Indentation+2, Opc);
973 o.indent(Indentation) << " MI.setOpcode(" << Opc << ");\n";
974 std::map<unsigned, std::vector<OperandInfo> >::const_iterator OpIter =
976 const std::vector<OperandInfo>& InsnOperands = OpIter->second;
977 for (std::vector<OperandInfo>::const_iterator
978 I = InsnOperands.begin(), E = InsnOperands.end(); I != E; ++I) {
979 // If a custom instruction decoder was specified, use that.
980 if (I->numFields() == 0 && I->Decoder.size()) {
981 o.indent(Indentation) << " " << Emitter->GuardPrefix << I->Decoder
982 << "(MI, insn, Address, Decoder)"
983 << Emitter->GuardPostfix << "\n";
987 emitBinaryParser(o, Indentation, *I);
990 o.indent(Indentation) << " return " << Emitter->ReturnOK << "; // "
991 << nameWithID(Opc) << '\n';
992 o.indent(Indentation) << "}\n"; // Closing predicate block.
996 // Otherwise, there are more decodings to be done!
998 // Emit code to match the island(s) for the singleton.
999 o.indent(Indentation) << "// Check ";
1001 for (I = Size; I != 0; --I) {
1002 o << "Inst{" << EndBits[I-1] << '-' << StartBits[I-1] << "} ";
1006 o << "for singleton decoding...\n";
1009 o.indent(Indentation) << "if (";
1010 if (emitPredicateMatch(o, Indentation, Opc)) {
1012 o.indent(Indentation+4);
1015 for (I = Size; I != 0; --I) {
1016 NumBits = EndBits[I-1] - StartBits[I-1] + 1;
1017 o << "fieldFromInstruction" << BitWidth << "(insn, "
1018 << StartBits[I-1] << ", " << NumBits
1019 << ") == " << FieldVals[I-1];
1025 emitSoftFailCheck(o, Indentation+2, Opc);
1026 o.indent(Indentation) << " MI.setOpcode(" << Opc << ");\n";
1027 std::map<unsigned, std::vector<OperandInfo> >::const_iterator OpIter =
1029 const std::vector<OperandInfo>& InsnOperands = OpIter->second;
1030 for (std::vector<OperandInfo>::const_iterator
1031 I = InsnOperands.begin(), E = InsnOperands.end(); I != E; ++I) {
1032 // If a custom instruction decoder was specified, use that.
1033 if (I->numFields() == 0 && I->Decoder.size()) {
1034 o.indent(Indentation) << " " << Emitter->GuardPrefix << I->Decoder
1035 << "(MI, insn, Address, Decoder)"
1036 << Emitter->GuardPostfix << "\n";
1040 emitBinaryParser(o, Indentation, *I);
1042 o.indent(Indentation) << " return " << Emitter->ReturnOK << "; // "
1043 << nameWithID(Opc) << '\n';
1044 o.indent(Indentation) << "}\n";
1049 // Emits code to decode the singleton, and then to decode the rest.
1050 void FilterChooser::emitSingletonDecoder(raw_ostream &o, unsigned &Indentation,
1051 const Filter &Best) const {
1053 unsigned Opc = Best.getSingletonOpc();
1055 emitSingletonDecoder(o, Indentation, Opc);
1057 // Emit code for the rest.
1058 o.indent(Indentation) << "else\n";
1061 Best.getVariableFC().emit(o, Indentation);
1065 // Assign a single filter and run with it. Top level API client can initialize
1066 // with a single filter to start the filtering process.
1067 void FilterChooser::runSingleFilter(unsigned startBit, unsigned numBit,
1070 Filter F(*this, startBit, numBit, true);
1071 Filters.push_back(F);
1072 BestIndex = 0; // Sole Filter instance to choose from.
1073 bestFilter().recurse();
1076 // reportRegion is a helper function for filterProcessor to mark a region as
1077 // eligible for use as a filter region.
1078 void FilterChooser::reportRegion(bitAttr_t RA, unsigned StartBit,
1079 unsigned BitIndex, bool AllowMixed) {
1080 if (RA == ATTR_MIXED && AllowMixed)
1081 Filters.push_back(Filter(*this, StartBit, BitIndex - StartBit, true));
1082 else if (RA == ATTR_ALL_SET && !AllowMixed)
1083 Filters.push_back(Filter(*this, StartBit, BitIndex - StartBit, false));
1086 // FilterProcessor scans the well-known encoding bits of the instructions and
1087 // builds up a list of candidate filters. It chooses the best filter and
1088 // recursively descends down the decoding tree.
1089 bool FilterChooser::filterProcessor(bool AllowMixed, bool Greedy) {
1092 unsigned numInstructions = Opcodes.size();
1094 assert(numInstructions && "Filter created with no instructions");
1096 // No further filtering is necessary.
1097 if (numInstructions == 1)
1100 // Heuristics. See also doFilter()'s "Heuristics" comment when num of
1101 // instructions is 3.
1102 if (AllowMixed && !Greedy) {
1103 assert(numInstructions == 3);
1105 for (unsigned i = 0; i < Opcodes.size(); ++i) {
1106 std::vector<unsigned> StartBits;
1107 std::vector<unsigned> EndBits;
1108 std::vector<uint64_t> FieldVals;
1111 insnWithID(Insn, Opcodes[i]);
1113 // Look for islands of undecoded bits of any instruction.
1114 if (getIslands(StartBits, EndBits, FieldVals, Insn) > 0) {
1115 // Found an instruction with island(s). Now just assign a filter.
1116 runSingleFilter(StartBits[0], EndBits[0] - StartBits[0] + 1, true);
1122 unsigned BitIndex, InsnIndex;
1124 // We maintain BIT_WIDTH copies of the bitAttrs automaton.
1125 // The automaton consumes the corresponding bit from each
1128 // Input symbols: 0, 1, and _ (unset).
1129 // States: NONE, FILTERED, ALL_SET, ALL_UNSET, and MIXED.
1130 // Initial state: NONE.
1132 // (NONE) ------- [01] -> (ALL_SET)
1133 // (NONE) ------- _ ----> (ALL_UNSET)
1134 // (ALL_SET) ---- [01] -> (ALL_SET)
1135 // (ALL_SET) ---- _ ----> (MIXED)
1136 // (ALL_UNSET) -- [01] -> (MIXED)
1137 // (ALL_UNSET) -- _ ----> (ALL_UNSET)
1138 // (MIXED) ------ . ----> (MIXED)
1139 // (FILTERED)---- . ----> (FILTERED)
1141 std::vector<bitAttr_t> bitAttrs;
1143 // FILTERED bit positions provide no entropy and are not worthy of pursuing.
1144 // Filter::recurse() set either BIT_TRUE or BIT_FALSE for each position.
1145 for (BitIndex = 0; BitIndex < BitWidth; ++BitIndex)
1146 if (FilterBitValues[BitIndex] == BIT_TRUE ||
1147 FilterBitValues[BitIndex] == BIT_FALSE)
1148 bitAttrs.push_back(ATTR_FILTERED);
1150 bitAttrs.push_back(ATTR_NONE);
1152 for (InsnIndex = 0; InsnIndex < numInstructions; ++InsnIndex) {
1155 insnWithID(insn, Opcodes[InsnIndex]);
1157 for (BitIndex = 0; BitIndex < BitWidth; ++BitIndex) {
1158 switch (bitAttrs[BitIndex]) {
1160 if (insn[BitIndex] == BIT_UNSET)
1161 bitAttrs[BitIndex] = ATTR_ALL_UNSET;
1163 bitAttrs[BitIndex] = ATTR_ALL_SET;
1166 if (insn[BitIndex] == BIT_UNSET)
1167 bitAttrs[BitIndex] = ATTR_MIXED;
1169 case ATTR_ALL_UNSET:
1170 if (insn[BitIndex] != BIT_UNSET)
1171 bitAttrs[BitIndex] = ATTR_MIXED;
1180 // The regionAttr automaton consumes the bitAttrs automatons' state,
1181 // lowest-to-highest.
1183 // Input symbols: F(iltered), (all_)S(et), (all_)U(nset), M(ixed)
1184 // States: NONE, ALL_SET, MIXED
1185 // Initial state: NONE
1187 // (NONE) ----- F --> (NONE)
1188 // (NONE) ----- S --> (ALL_SET) ; and set region start
1189 // (NONE) ----- U --> (NONE)
1190 // (NONE) ----- M --> (MIXED) ; and set region start
1191 // (ALL_SET) -- F --> (NONE) ; and report an ALL_SET region
1192 // (ALL_SET) -- S --> (ALL_SET)
1193 // (ALL_SET) -- U --> (NONE) ; and report an ALL_SET region
1194 // (ALL_SET) -- M --> (MIXED) ; and report an ALL_SET region
1195 // (MIXED) ---- F --> (NONE) ; and report a MIXED region
1196 // (MIXED) ---- S --> (ALL_SET) ; and report a MIXED region
1197 // (MIXED) ---- U --> (NONE) ; and report a MIXED region
1198 // (MIXED) ---- M --> (MIXED)
1200 bitAttr_t RA = ATTR_NONE;
1201 unsigned StartBit = 0;
1203 for (BitIndex = 0; BitIndex < BitWidth; BitIndex++) {
1204 bitAttr_t bitAttr = bitAttrs[BitIndex];
1206 assert(bitAttr != ATTR_NONE && "Bit without attributes");
1214 StartBit = BitIndex;
1217 case ATTR_ALL_UNSET:
1220 StartBit = BitIndex;
1224 llvm_unreachable("Unexpected bitAttr!");
1230 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1235 case ATTR_ALL_UNSET:
1236 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1240 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1241 StartBit = BitIndex;
1245 llvm_unreachable("Unexpected bitAttr!");
1251 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1252 StartBit = BitIndex;
1256 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1257 StartBit = BitIndex;
1260 case ATTR_ALL_UNSET:
1261 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1267 llvm_unreachable("Unexpected bitAttr!");
1270 case ATTR_ALL_UNSET:
1271 llvm_unreachable("regionAttr state machine has no ATTR_UNSET state");
1273 llvm_unreachable("regionAttr state machine has no ATTR_FILTERED state");
1277 // At the end, if we're still in ALL_SET or MIXED states, report a region
1284 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1286 case ATTR_ALL_UNSET:
1289 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1293 // We have finished with the filter processings. Now it's time to choose
1294 // the best performing filter.
1296 bool AllUseless = true;
1297 unsigned BestScore = 0;
1299 for (unsigned i = 0, e = Filters.size(); i != e; ++i) {
1300 unsigned Usefulness = Filters[i].usefulness();
1305 if (Usefulness > BestScore) {
1307 BestScore = Usefulness;
1312 bestFilter().recurse();
1315 } // end of FilterChooser::filterProcessor(bool)
1317 // Decides on the best configuration of filter(s) to use in order to decode
1318 // the instructions. A conflict of instructions may occur, in which case we
1319 // dump the conflict set to the standard error.
1320 void FilterChooser::doFilter() {
1321 unsigned Num = Opcodes.size();
1322 assert(Num && "FilterChooser created with no instructions");
1324 // Try regions of consecutive known bit values first.
1325 if (filterProcessor(false))
1328 // Then regions of mixed bits (both known and unitialized bit values allowed).
1329 if (filterProcessor(true))
1332 // Heuristics to cope with conflict set {t2CMPrs, t2SUBSrr, t2SUBSrs} where
1333 // no single instruction for the maximum ATTR_MIXED region Inst{14-4} has a
1334 // well-known encoding pattern. In such case, we backtrack and scan for the
1335 // the very first consecutive ATTR_ALL_SET region and assign a filter to it.
1336 if (Num == 3 && filterProcessor(true, false))
1339 // If we come to here, the instruction decoding has failed.
1340 // Set the BestIndex to -1 to indicate so.
1344 // Emits code to decode our share of instructions. Returns true if the
1345 // emitted code causes a return, which occurs if we know how to decode
1346 // the instruction at this level or the instruction is not decodeable.
1347 bool FilterChooser::emit(raw_ostream &o, unsigned &Indentation) const {
1348 if (Opcodes.size() == 1)
1349 // There is only one instruction in the set, which is great!
1350 // Call emitSingletonDecoder() to see whether there are any remaining
1352 return emitSingletonDecoder(o, Indentation, Opcodes[0]);
1354 // Choose the best filter to do the decodings!
1355 if (BestIndex != -1) {
1356 const Filter &Best = Filters[BestIndex];
1357 if (Best.getNumFiltered() == 1)
1358 emitSingletonDecoder(o, Indentation, Best);
1360 Best.emit(o, Indentation);
1364 // We don't know how to decode these instructions! Return 0 and dump the
1366 o.indent(Indentation) << "return 0;" << " // Conflict set: ";
1367 for (int i = 0, N = Opcodes.size(); i < N; ++i) {
1368 o << nameWithID(Opcodes[i]);
1375 // Print out useful conflict information for postmortem analysis.
1376 errs() << "Decoding Conflict:\n";
1378 dumpStack(errs(), "\t\t");
1380 for (unsigned i = 0; i < Opcodes.size(); ++i) {
1381 const std::string &Name = nameWithID(Opcodes[i]);
1383 errs() << '\t' << Name << " ";
1385 getBitsField(*AllInstructions[Opcodes[i]]->TheDef, "Inst"));
1392 static bool populateInstruction(const CodeGenInstruction &CGI, unsigned Opc,
1393 std::map<unsigned, std::vector<OperandInfo> > &Operands){
1394 const Record &Def = *CGI.TheDef;
1395 // If all the bit positions are not specified; do not decode this instruction.
1396 // We are bound to fail! For proper disassembly, the well-known encoding bits
1397 // of the instruction must be fully specified.
1399 // This also removes pseudo instructions from considerations of disassembly,
1400 // which is a better design and less fragile than the name matchings.
1401 // Ignore "asm parser only" instructions.
1402 if (Def.getValueAsBit("isAsmParserOnly") ||
1403 Def.getValueAsBit("isCodeGenOnly"))
1406 BitsInit &Bits = getBitsField(Def, "Inst");
1407 if (Bits.allInComplete()) return false;
1409 std::vector<OperandInfo> InsnOperands;
1411 // If the instruction has specified a custom decoding hook, use that instead
1412 // of trying to auto-generate the decoder.
1413 std::string InstDecoder = Def.getValueAsString("DecoderMethod");
1414 if (InstDecoder != "") {
1415 InsnOperands.push_back(OperandInfo(InstDecoder));
1416 Operands[Opc] = InsnOperands;
1420 // Generate a description of the operand of the instruction that we know
1421 // how to decode automatically.
1422 // FIXME: We'll need to have a way to manually override this as needed.
1424 // Gather the outputs/inputs of the instruction, so we can find their
1425 // positions in the encoding. This assumes for now that they appear in the
1426 // MCInst in the order that they're listed.
1427 std::vector<std::pair<Init*, std::string> > InOutOperands;
1428 DagInit *Out = Def.getValueAsDag("OutOperandList");
1429 DagInit *In = Def.getValueAsDag("InOperandList");
1430 for (unsigned i = 0; i < Out->getNumArgs(); ++i)
1431 InOutOperands.push_back(std::make_pair(Out->getArg(i), Out->getArgName(i)));
1432 for (unsigned i = 0; i < In->getNumArgs(); ++i)
1433 InOutOperands.push_back(std::make_pair(In->getArg(i), In->getArgName(i)));
1435 // Search for tied operands, so that we can correctly instantiate
1436 // operands that are not explicitly represented in the encoding.
1437 std::map<std::string, std::string> TiedNames;
1438 for (unsigned i = 0; i < CGI.Operands.size(); ++i) {
1439 int tiedTo = CGI.Operands[i].getTiedRegister();
1441 TiedNames[InOutOperands[i].second] = InOutOperands[tiedTo].second;
1442 TiedNames[InOutOperands[tiedTo].second] = InOutOperands[i].second;
1446 // For each operand, see if we can figure out where it is encoded.
1447 for (std::vector<std::pair<Init*, std::string> >::const_iterator
1448 NI = InOutOperands.begin(), NE = InOutOperands.end(); NI != NE; ++NI) {
1449 std::string Decoder = "";
1451 // At this point, we can locate the field, but we need to know how to
1452 // interpret it. As a first step, require the target to provide callbacks
1453 // for decoding register classes.
1454 // FIXME: This need to be extended to handle instructions with custom
1455 // decoder methods, and operands with (simple) MIOperandInfo's.
1456 TypedInit *TI = dynamic_cast<TypedInit*>(NI->first);
1457 RecordRecTy *Type = dynamic_cast<RecordRecTy*>(TI->getType());
1458 Record *TypeRecord = Type->getRecord();
1460 if (TypeRecord->isSubClassOf("RegisterOperand"))
1461 TypeRecord = TypeRecord->getValueAsDef("RegClass");
1462 if (TypeRecord->isSubClassOf("RegisterClass")) {
1463 Decoder = "Decode" + TypeRecord->getName() + "RegisterClass";
1467 RecordVal *DecoderString = TypeRecord->getValue("DecoderMethod");
1468 StringInit *String = DecoderString ?
1469 dynamic_cast<StringInit*>(DecoderString->getValue()) : 0;
1470 if (!isReg && String && String->getValue() != "")
1471 Decoder = String->getValue();
1473 OperandInfo OpInfo(Decoder);
1474 unsigned Base = ~0U;
1476 unsigned Offset = 0;
1478 for (unsigned bi = 0; bi < Bits.getNumBits(); ++bi) {
1480 VarBitInit *BI = dynamic_cast<VarBitInit*>(Bits.getBit(bi));
1482 Var = dynamic_cast<VarInit*>(BI->getVariable());
1484 Var = dynamic_cast<VarInit*>(Bits.getBit(bi));
1488 OpInfo.addField(Base, Width, Offset);
1496 if (Var->getName() != NI->second &&
1497 Var->getName() != TiedNames[NI->second]) {
1499 OpInfo.addField(Base, Width, Offset);
1510 Offset = BI ? BI->getBitNum() : 0;
1511 } else if (BI && BI->getBitNum() != Offset + Width) {
1512 OpInfo.addField(Base, Width, Offset);
1515 Offset = BI->getBitNum();
1522 OpInfo.addField(Base, Width, Offset);
1524 if (OpInfo.numFields() > 0)
1525 InsnOperands.push_back(OpInfo);
1528 Operands[Opc] = InsnOperands;
1533 // Dumps the instruction encoding bits.
1534 dumpBits(errs(), Bits);
1538 // Dumps the list of operand info.
1539 for (unsigned i = 0, e = CGI.Operands.size(); i != e; ++i) {
1540 const CGIOperandList::OperandInfo &Info = CGI.Operands[i];
1541 const std::string &OperandName = Info.Name;
1542 const Record &OperandDef = *Info.Rec;
1544 errs() << "\t" << OperandName << " (" << OperandDef.getName() << ")\n";
1552 static void emitHelper(llvm::raw_ostream &o, unsigned BitWidth) {
1553 unsigned Indentation = 0;
1554 std::string WidthStr = "uint" + utostr(BitWidth) + "_t";
1558 o.indent(Indentation) << "static " << WidthStr <<
1559 " fieldFromInstruction" << BitWidth <<
1560 "(" << WidthStr <<" insn, unsigned startBit, unsigned numBits)\n";
1562 o.indent(Indentation) << "{\n";
1564 ++Indentation; ++Indentation;
1565 o.indent(Indentation) << "assert(startBit + numBits <= " << BitWidth
1566 << " && \"Instruction field out of bounds!\");\n";
1568 o.indent(Indentation) << WidthStr << " fieldMask;\n";
1570 o.indent(Indentation) << "if (numBits == " << BitWidth << ")\n";
1572 ++Indentation; ++Indentation;
1573 o.indent(Indentation) << "fieldMask = (" << WidthStr << ")-1;\n";
1574 --Indentation; --Indentation;
1576 o.indent(Indentation) << "else\n";
1578 ++Indentation; ++Indentation;
1579 o.indent(Indentation) << "fieldMask = ((1 << numBits) - 1) << startBit;\n";
1580 --Indentation; --Indentation;
1583 o.indent(Indentation) << "return (insn & fieldMask) >> startBit;\n";
1584 --Indentation; --Indentation;
1586 o.indent(Indentation) << "}\n";
1591 // Emits disassembler code for instruction decoding.
1592 void FixedLenDecoderEmitter::run(raw_ostream &o) {
1593 o << "#include \"llvm/MC/MCInst.h\"\n";
1594 o << "#include \"llvm/Support/DataTypes.h\"\n";
1595 o << "#include <assert.h>\n";
1597 o << "namespace llvm {\n\n";
1599 // Parameterize the decoders based on namespace and instruction width.
1600 const std::vector<const CodeGenInstruction*> &NumberedInstructions =
1601 Target.getInstructionsByEnumValue();
1602 std::map<std::pair<std::string, unsigned>,
1603 std::vector<unsigned> > OpcMap;
1604 std::map<unsigned, std::vector<OperandInfo> > Operands;
1606 for (unsigned i = 0; i < NumberedInstructions.size(); ++i) {
1607 const CodeGenInstruction *Inst = NumberedInstructions[i];
1608 const Record *Def = Inst->TheDef;
1609 unsigned Size = Def->getValueAsInt("Size");
1610 if (Def->getValueAsString("Namespace") == "TargetOpcode" ||
1611 Def->getValueAsBit("isPseudo") ||
1612 Def->getValueAsBit("isAsmParserOnly") ||
1613 Def->getValueAsBit("isCodeGenOnly"))
1616 std::string DecoderNamespace = Def->getValueAsString("DecoderNamespace");
1619 if (populateInstruction(*Inst, i, Operands)) {
1620 OpcMap[std::make_pair(DecoderNamespace, Size)].push_back(i);
1625 std::set<unsigned> Sizes;
1626 for (std::map<std::pair<std::string, unsigned>,
1627 std::vector<unsigned> >::const_iterator
1628 I = OpcMap.begin(), E = OpcMap.end(); I != E; ++I) {
1629 // If we haven't visited this instruction width before, emit the
1630 // helper method to extract fields.
1631 if (!Sizes.count(I->first.second)) {
1632 emitHelper(o, 8*I->first.second);
1633 Sizes.insert(I->first.second);
1636 // Emit the decoder for this namespace+width combination.
1637 FilterChooser FC(NumberedInstructions, I->second, Operands,
1638 8*I->first.second, this);
1639 FC.emitTop(o, 0, I->first.first);
1642 o << "\n} // End llvm namespace \n";
1647 void EmitFixedLenDecoder(RecordKeeper &RK, raw_ostream &OS,
1648 std::string PredicateNamespace,
1649 std::string GPrefix,
1650 std::string GPostfix,
1654 FixedLenDecoderEmitter(RK, PredicateNamespace, GPrefix, GPostfix,
1655 ROK, RFail, L).run(OS);
1658 } // End llvm namespace