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 "FixedLenDecoderEmitter.h"
18 #include "CodeGenTarget.h"
20 #include "llvm/ADT/StringExtras.h"
21 #include "llvm/Support/Debug.h"
22 #include "llvm/Support/raw_ostream.h"
30 // The set (BIT_TRUE, BIT_FALSE, BIT_UNSET) represents a ternary logic system
33 // BIT_UNFILTERED is used as the init value for a filter position. It is used
34 // only for filter processings.
39 BIT_UNFILTERED // unfiltered
42 static bool ValueSet(bit_value_t V) {
43 return (V == BIT_TRUE || V == BIT_FALSE);
45 static bool ValueNotSet(bit_value_t V) {
46 return (V == BIT_UNSET);
48 static int Value(bit_value_t V) {
49 return ValueNotSet(V) ? -1 : (V == BIT_FALSE ? 0 : 1);
51 static bit_value_t bitFromBits(BitsInit &bits, unsigned index) {
52 if (BitInit *bit = dynamic_cast<BitInit*>(bits.getBit(index)))
53 return bit->getValue() ? BIT_TRUE : BIT_FALSE;
55 // The bit is uninitialized.
58 // Prints the bit value for each position.
59 static void dumpBits(raw_ostream &o, BitsInit &bits) {
62 for (index = bits.getNumBits(); index > 0; index--) {
63 switch (bitFromBits(bits, index - 1)) {
74 assert(0 && "unexpected return value from bitFromBits");
79 static BitsInit &getBitsField(const Record &def, const char *str) {
80 BitsInit *bits = def.getValueAsBitsInit(str);
84 // Forward declaration.
87 // Representation of the instruction to work on.
88 typedef std::vector<bit_value_t> insn_t;
90 /// Filter - Filter works with FilterChooser to produce the decoding tree for
93 /// It is useful to think of a Filter as governing the switch stmts of the
94 /// decoding tree in a certain level. Each case stmt delegates to an inferior
95 /// FilterChooser to decide what further decoding logic to employ, or in another
96 /// words, what other remaining bits to look at. The FilterChooser eventually
97 /// chooses a best Filter to do its job.
99 /// This recursive scheme ends when the number of Opcodes assigned to the
100 /// FilterChooser becomes 1 or if there is a conflict. A conflict happens when
101 /// the Filter/FilterChooser combo does not know how to distinguish among the
102 /// Opcodes assigned.
104 /// An example of a conflict is
107 /// 111101000.00........00010000....
108 /// 111101000.00........0001........
109 /// 1111010...00........0001........
110 /// 1111010...00....................
111 /// 1111010.........................
112 /// 1111............................
113 /// ................................
114 /// VST4q8a 111101000_00________00010000____
115 /// VST4q8b 111101000_00________00010000____
117 /// The Debug output shows the path that the decoding tree follows to reach the
118 /// the conclusion that there is a conflict. VST4q8a is a vst4 to double-spaced
119 /// even registers, while VST4q8b is a vst4 to double-spaced odd regsisters.
121 /// The encoding info in the .td files does not specify this meta information,
122 /// which could have been used by the decoder to resolve the conflict. The
123 /// decoder could try to decode the even/odd register numbering and assign to
124 /// VST4q8a or VST4q8b, but for the time being, the decoder chooses the "a"
125 /// version and return the Opcode since the two have the same Asm format string.
128 FilterChooser *Owner; // points to the FilterChooser who owns this filter
129 unsigned StartBit; // the starting bit position
130 unsigned NumBits; // number of bits to filter
131 bool Mixed; // a mixed region contains both set and unset bits
133 // Map of well-known segment value to the set of uid's with that value.
134 std::map<uint64_t, std::vector<unsigned> > FilteredInstructions;
136 // Set of uid's with non-constant segment values.
137 std::vector<unsigned> VariableInstructions;
139 // Map of well-known segment value to its delegate.
140 std::map<unsigned, FilterChooser*> FilterChooserMap;
142 // Number of instructions which fall under FilteredInstructions category.
143 unsigned NumFiltered;
145 // Keeps track of the last opcode in the filtered bucket.
146 unsigned LastOpcFiltered;
148 // Number of instructions which fall under VariableInstructions category.
149 unsigned NumVariable;
152 unsigned getNumFiltered() { return NumFiltered; }
153 unsigned getNumVariable() { return NumVariable; }
154 unsigned getSingletonOpc() {
155 assert(NumFiltered == 1);
156 return LastOpcFiltered;
158 // Return the filter chooser for the group of instructions without constant
160 FilterChooser &getVariableFC() {
161 assert(NumFiltered == 1);
162 assert(FilterChooserMap.size() == 1);
163 return *(FilterChooserMap.find((unsigned)-1)->second);
166 Filter(const Filter &f);
167 Filter(FilterChooser &owner, unsigned startBit, unsigned numBits, bool mixed);
171 // Divides the decoding task into sub tasks and delegates them to the
172 // inferior FilterChooser's.
174 // A special case arises when there's only one entry in the filtered
175 // instructions. In order to unambiguously decode the singleton, we need to
176 // match the remaining undecoded encoding bits against the singleton.
179 // Emit code to decode instructions given a segment or segments of bits.
180 void emit(raw_ostream &o, unsigned &Indentation);
182 // Returns the number of fanout produced by the filter. More fanout implies
183 // the filter distinguishes more categories of instructions.
184 unsigned usefulness() const;
185 }; // End of class Filter
187 // These are states of our finite state machines used in FilterChooser's
188 // filterProcessor() which produces the filter candidates to use.
197 /// FilterChooser - FilterChooser chooses the best filter among a set of Filters
198 /// in order to perform the decoding of instructions at the current level.
200 /// Decoding proceeds from the top down. Based on the well-known encoding bits
201 /// of instructions available, FilterChooser builds up the possible Filters that
202 /// can further the task of decoding by distinguishing among the remaining
203 /// candidate instructions.
205 /// Once a filter has been chosen, it is called upon to divide the decoding task
206 /// into sub-tasks and delegates them to its inferior FilterChoosers for further
209 /// It is useful to think of a Filter as governing the switch stmts of the
210 /// decoding tree. And each case is delegated to an inferior FilterChooser to
211 /// decide what further remaining bits to look at.
212 class FilterChooser {
216 // Vector of codegen instructions to choose our filter.
217 const std::vector<const CodeGenInstruction*> &AllInstructions;
219 // Vector of uid's for this filter chooser to work on.
220 const std::vector<unsigned> Opcodes;
222 // Lookup table for the operand decoding of instructions.
223 std::map<unsigned, std::vector<OperandInfo> > &Operands;
225 // Vector of candidate filters.
226 std::vector<Filter> Filters;
228 // Array of bit values passed down from our parent.
229 // Set to all BIT_UNFILTERED's for Parent == NULL.
230 std::vector<bit_value_t> FilterBitValues;
232 // Links to the FilterChooser above us in the decoding tree.
233 FilterChooser *Parent;
235 // Index of the best filter from Filters.
238 // Width of instructions
242 FilterChooser(const FilterChooser &FC) :
243 AllInstructions(FC.AllInstructions), Opcodes(FC.Opcodes),
244 Operands(FC.Operands), Filters(FC.Filters),
245 FilterBitValues(FC.FilterBitValues), Parent(FC.Parent),
246 BestIndex(FC.BestIndex), BitWidth(FC.BitWidth) { }
248 FilterChooser(const std::vector<const CodeGenInstruction*> &Insts,
249 const std::vector<unsigned> &IDs,
250 std::map<unsigned, std::vector<OperandInfo> > &Ops,
252 AllInstructions(Insts), Opcodes(IDs), Operands(Ops), Filters(),
253 Parent(NULL), BestIndex(-1), BitWidth(BW) {
254 for (unsigned i = 0; i < BitWidth; ++i)
255 FilterBitValues.push_back(BIT_UNFILTERED);
260 FilterChooser(const std::vector<const CodeGenInstruction*> &Insts,
261 const std::vector<unsigned> &IDs,
262 std::map<unsigned, std::vector<OperandInfo> > &Ops,
263 std::vector<bit_value_t> &ParentFilterBitValues,
264 FilterChooser &parent) :
265 AllInstructions(Insts), Opcodes(IDs), Operands(Ops),
266 Filters(), FilterBitValues(ParentFilterBitValues),
267 Parent(&parent), BestIndex(-1), BitWidth(parent.BitWidth) {
271 // The top level filter chooser has NULL as its parent.
272 bool isTopLevel() { return Parent == NULL; }
274 // Emit the top level typedef and decodeInstruction() function.
275 void emitTop(raw_ostream &o, unsigned Indentation, std::string Namespace);
278 // Populates the insn given the uid.
279 void insnWithID(insn_t &Insn, unsigned Opcode) const {
280 BitsInit &Bits = getBitsField(*AllInstructions[Opcode]->TheDef, "Inst");
282 for (unsigned i = 0; i < BitWidth; ++i)
283 Insn.push_back(bitFromBits(Bits, i));
286 // Returns the record name.
287 const std::string &nameWithID(unsigned Opcode) const {
288 return AllInstructions[Opcode]->TheDef->getName();
291 // Populates the field of the insn given the start position and the number of
292 // consecutive bits to scan for.
294 // Returns false if there exists any uninitialized bit value in the range.
295 // Returns true, otherwise.
296 bool fieldFromInsn(uint64_t &Field, insn_t &Insn, unsigned StartBit,
297 unsigned NumBits) const;
299 /// dumpFilterArray - dumpFilterArray prints out debugging info for the given
300 /// filter array as a series of chars.
301 void dumpFilterArray(raw_ostream &o, std::vector<bit_value_t> & filter);
303 /// dumpStack - dumpStack traverses the filter chooser chain and calls
304 /// dumpFilterArray on each filter chooser up to the top level one.
305 void dumpStack(raw_ostream &o, const char *prefix);
307 Filter &bestFilter() {
308 assert(BestIndex != -1 && "BestIndex not set");
309 return Filters[BestIndex];
312 // Called from Filter::recurse() when singleton exists. For debug purpose.
313 void SingletonExists(unsigned Opc);
315 bool PositionFiltered(unsigned i) {
316 return ValueSet(FilterBitValues[i]);
319 // Calculates the island(s) needed to decode the instruction.
320 // This returns a lit of undecoded bits of an instructions, for example,
321 // Inst{20} = 1 && Inst{3-0} == 0b1111 represents two islands of yet-to-be
322 // decoded bits in order to verify that the instruction matches the Opcode.
323 unsigned getIslands(std::vector<unsigned> &StartBits,
324 std::vector<unsigned> &EndBits, std::vector<uint64_t> &FieldVals,
327 // Emits code to decode the singleton. Return true if we have matched all the
329 bool emitSingletonDecoder(raw_ostream &o, unsigned &Indentation,unsigned Opc);
331 // Emits code to decode the singleton, and then to decode the rest.
332 void emitSingletonDecoder(raw_ostream &o, unsigned &Indentation,Filter &Best);
334 // Assign a single filter and run with it.
335 void runSingleFilter(FilterChooser &owner, unsigned startBit, unsigned numBit,
338 // reportRegion is a helper function for filterProcessor to mark a region as
339 // eligible for use as a filter region.
340 void reportRegion(bitAttr_t RA, unsigned StartBit, unsigned BitIndex,
343 // FilterProcessor scans the well-known encoding bits of the instructions and
344 // builds up a list of candidate filters. It chooses the best filter and
345 // recursively descends down the decoding tree.
346 bool filterProcessor(bool AllowMixed, bool Greedy = true);
348 // Decides on the best configuration of filter(s) to use in order to decode
349 // the instructions. A conflict of instructions may occur, in which case we
350 // dump the conflict set to the standard error.
353 // Emits code to decode our share of instructions. Returns true if the
354 // emitted code causes a return, which occurs if we know how to decode
355 // the instruction at this level or the instruction is not decodeable.
356 bool emit(raw_ostream &o, unsigned &Indentation);
359 ///////////////////////////
361 // Filter Implmenetation //
363 ///////////////////////////
365 Filter::Filter(const Filter &f) :
366 Owner(f.Owner), StartBit(f.StartBit), NumBits(f.NumBits), Mixed(f.Mixed),
367 FilteredInstructions(f.FilteredInstructions),
368 VariableInstructions(f.VariableInstructions),
369 FilterChooserMap(f.FilterChooserMap), NumFiltered(f.NumFiltered),
370 LastOpcFiltered(f.LastOpcFiltered), NumVariable(f.NumVariable) {
373 Filter::Filter(FilterChooser &owner, unsigned startBit, unsigned numBits,
374 bool mixed) : Owner(&owner), StartBit(startBit), NumBits(numBits),
376 assert(StartBit + NumBits - 1 < Owner->BitWidth);
382 for (unsigned i = 0, e = Owner->Opcodes.size(); i != e; ++i) {
385 // Populates the insn given the uid.
386 Owner->insnWithID(Insn, Owner->Opcodes[i]);
389 // Scans the segment for possibly well-specified encoding bits.
390 bool ok = Owner->fieldFromInsn(Field, Insn, StartBit, NumBits);
393 // The encoding bits are well-known. Lets add the uid of the
394 // instruction into the bucket keyed off the constant field value.
395 LastOpcFiltered = Owner->Opcodes[i];
396 FilteredInstructions[Field].push_back(LastOpcFiltered);
399 // Some of the encoding bit(s) are unspecfied. This contributes to
400 // one additional member of "Variable" instructions.
401 VariableInstructions.push_back(Owner->Opcodes[i]);
406 assert((FilteredInstructions.size() + VariableInstructions.size() > 0)
407 && "Filter returns no instruction categories");
411 std::map<unsigned, FilterChooser*>::iterator filterIterator;
412 for (filterIterator = FilterChooserMap.begin();
413 filterIterator != FilterChooserMap.end();
415 delete filterIterator->second;
419 // Divides the decoding task into sub tasks and delegates them to the
420 // inferior FilterChooser's.
422 // A special case arises when there's only one entry in the filtered
423 // instructions. In order to unambiguously decode the singleton, we need to
424 // match the remaining undecoded encoding bits against the singleton.
425 void Filter::recurse() {
426 std::map<uint64_t, std::vector<unsigned> >::const_iterator mapIterator;
428 // Starts by inheriting our parent filter chooser's filter bit values.
429 std::vector<bit_value_t> BitValueArray(Owner->FilterBitValues);
433 if (VariableInstructions.size()) {
434 // Conservatively marks each segment position as BIT_UNSET.
435 for (bitIndex = 0; bitIndex < NumBits; bitIndex++)
436 BitValueArray[StartBit + bitIndex] = BIT_UNSET;
438 // Delegates to an inferior filter chooser for further processing on this
439 // group of instructions whose segment values are variable.
440 FilterChooserMap.insert(std::pair<unsigned, FilterChooser*>(
442 new FilterChooser(Owner->AllInstructions,
443 VariableInstructions,
450 // No need to recurse for a singleton filtered instruction.
451 // See also Filter::emit().
452 if (getNumFiltered() == 1) {
453 //Owner->SingletonExists(LastOpcFiltered);
454 assert(FilterChooserMap.size() == 1);
458 // Otherwise, create sub choosers.
459 for (mapIterator = FilteredInstructions.begin();
460 mapIterator != FilteredInstructions.end();
463 // Marks all the segment positions with either BIT_TRUE or BIT_FALSE.
464 for (bitIndex = 0; bitIndex < NumBits; bitIndex++) {
465 if (mapIterator->first & (1ULL << bitIndex))
466 BitValueArray[StartBit + bitIndex] = BIT_TRUE;
468 BitValueArray[StartBit + bitIndex] = BIT_FALSE;
471 // Delegates to an inferior filter chooser for further processing on this
472 // category of instructions.
473 FilterChooserMap.insert(std::pair<unsigned, FilterChooser*>(
475 new FilterChooser(Owner->AllInstructions,
484 // Emit code to decode instructions given a segment or segments of bits.
485 void Filter::emit(raw_ostream &o, unsigned &Indentation) {
486 o.indent(Indentation) << "// Check Inst{";
489 o << (StartBit + NumBits - 1) << '-';
491 o << StartBit << "} ...\n";
493 o.indent(Indentation) << "switch (fieldFromInstruction" << Owner->BitWidth
494 << "(insn, " << StartBit << ", "
495 << NumBits << ")) {\n";
497 std::map<unsigned, FilterChooser*>::iterator filterIterator;
499 bool DefaultCase = false;
500 for (filterIterator = FilterChooserMap.begin();
501 filterIterator != FilterChooserMap.end();
504 // Field value -1 implies a non-empty set of variable instructions.
505 // See also recurse().
506 if (filterIterator->first == (unsigned)-1) {
509 o.indent(Indentation) << "default:\n";
510 o.indent(Indentation) << " break; // fallthrough\n";
512 // Closing curly brace for the switch statement.
513 // This is unconventional because we want the default processing to be
514 // performed for the fallthrough cases as well, i.e., when the "cases"
515 // did not prove a decoded instruction.
516 o.indent(Indentation) << "}\n";
519 o.indent(Indentation) << "case " << filterIterator->first << ":\n";
521 // We arrive at a category of instructions with the same segment value.
522 // Now delegate to the sub filter chooser for further decodings.
523 // The case may fallthrough, which happens if the remaining well-known
524 // encoding bits do not match exactly.
525 if (!DefaultCase) { ++Indentation; ++Indentation; }
527 bool finished = filterIterator->second->emit(o, Indentation);
528 // For top level default case, there's no need for a break statement.
529 if (Owner->isTopLevel() && DefaultCase)
532 o.indent(Indentation) << "break;\n";
534 if (!DefaultCase) { --Indentation; --Indentation; }
537 // If there is no default case, we still need to supply a closing brace.
539 // Closing curly brace for the switch statement.
540 o.indent(Indentation) << "}\n";
544 // Returns the number of fanout produced by the filter. More fanout implies
545 // the filter distinguishes more categories of instructions.
546 unsigned Filter::usefulness() const {
547 if (VariableInstructions.size())
548 return FilteredInstructions.size();
550 return FilteredInstructions.size() + 1;
553 //////////////////////////////////
555 // Filterchooser Implementation //
557 //////////////////////////////////
559 // Emit the top level typedef and decodeInstruction() function.
560 void FilterChooser::emitTop(raw_ostream &o, unsigned Indentation,
561 std::string Namespace) {
562 o.indent(Indentation) <<
563 "static bool decode" << Namespace << "Instruction" << BitWidth
564 << "(MCInst &MI, uint" << BitWidth << "_t insn, uint64_t Address, "
565 << "const void *Decoder) {\n";
566 o.indent(Indentation) << " unsigned tmp = 0;\n";
568 ++Indentation; ++Indentation;
569 // Emits code to decode the instructions.
570 emit(o, Indentation);
573 o.indent(Indentation) << "return false;\n";
574 --Indentation; --Indentation;
576 o.indent(Indentation) << "}\n";
581 // Populates the field of the insn given the start position and the number of
582 // consecutive bits to scan for.
584 // Returns false if and on the first uninitialized bit value encountered.
585 // Returns true, otherwise.
586 bool FilterChooser::fieldFromInsn(uint64_t &Field, insn_t &Insn,
587 unsigned StartBit, unsigned NumBits) const {
590 for (unsigned i = 0; i < NumBits; ++i) {
591 if (Insn[StartBit + i] == BIT_UNSET)
594 if (Insn[StartBit + i] == BIT_TRUE)
595 Field = Field | (1ULL << i);
601 /// dumpFilterArray - dumpFilterArray prints out debugging info for the given
602 /// filter array as a series of chars.
603 void FilterChooser::dumpFilterArray(raw_ostream &o,
604 std::vector<bit_value_t> &filter) {
607 for (bitIndex = BitWidth; bitIndex > 0; bitIndex--) {
608 switch (filter[bitIndex - 1]) {
625 /// dumpStack - dumpStack traverses the filter chooser chain and calls
626 /// dumpFilterArray on each filter chooser up to the top level one.
627 void FilterChooser::dumpStack(raw_ostream &o, const char *prefix) {
628 FilterChooser *current = this;
632 dumpFilterArray(o, current->FilterBitValues);
634 current = current->Parent;
638 // Called from Filter::recurse() when singleton exists. For debug purpose.
639 void FilterChooser::SingletonExists(unsigned Opc) {
641 insnWithID(Insn0, Opc);
643 errs() << "Singleton exists: " << nameWithID(Opc)
644 << " with its decoding dominating ";
645 for (unsigned i = 0; i < Opcodes.size(); ++i) {
646 if (Opcodes[i] == Opc) continue;
647 errs() << nameWithID(Opcodes[i]) << ' ';
651 dumpStack(errs(), "\t\t");
652 for (unsigned i = 0; i < Opcodes.size(); i++) {
653 const std::string &Name = nameWithID(Opcodes[i]);
655 errs() << '\t' << Name << " ";
657 getBitsField(*AllInstructions[Opcodes[i]]->TheDef, "Inst"));
662 // Calculates the island(s) needed to decode the instruction.
663 // This returns a list of undecoded bits of an instructions, for example,
664 // Inst{20} = 1 && Inst{3-0} == 0b1111 represents two islands of yet-to-be
665 // decoded bits in order to verify that the instruction matches the Opcode.
666 unsigned FilterChooser::getIslands(std::vector<unsigned> &StartBits,
667 std::vector<unsigned> &EndBits, std::vector<uint64_t> &FieldVals,
672 uint64_t FieldVal = 0;
675 // 1: Water (the bit value does not affect decoding)
676 // 2: Island (well-known bit value needed for decoding)
680 for (unsigned i = 0; i < BitWidth; ++i) {
681 Val = Value(Insn[i]);
682 bool Filtered = PositionFiltered(i);
685 assert(0 && "Unreachable code!");
689 if (Filtered || Val == -1)
690 State = 1; // Still in Water
692 State = 2; // Into the Island
694 StartBits.push_back(i);
699 if (Filtered || Val == -1) {
700 State = 1; // Into the Water
701 EndBits.push_back(i - 1);
702 FieldVals.push_back(FieldVal);
705 State = 2; // Still in Island
707 FieldVal = FieldVal | Val << BitNo;
712 // If we are still in Island after the loop, do some housekeeping.
714 EndBits.push_back(BitWidth - 1);
715 FieldVals.push_back(FieldVal);
719 assert(StartBits.size() == Num && EndBits.size() == Num &&
720 FieldVals.size() == Num);
724 // Emits code to decode the singleton. Return true if we have matched all the
726 bool FilterChooser::emitSingletonDecoder(raw_ostream &o, unsigned &Indentation,
728 std::vector<unsigned> StartBits;
729 std::vector<unsigned> EndBits;
730 std::vector<uint64_t> FieldVals;
732 insnWithID(Insn, Opc);
734 // Look for islands of undecoded bits of the singleton.
735 getIslands(StartBits, EndBits, FieldVals, Insn);
737 unsigned Size = StartBits.size();
740 // If we have matched all the well-known bits, just issue a return.
742 o.indent(Indentation) << "{\n";
743 o.indent(Indentation) << " MI.setOpcode(" << Opc << ");\n";
744 std::vector<OperandInfo>& InsnOperands = Operands[Opc];
745 for (std::vector<OperandInfo>::iterator
746 I = InsnOperands.begin(), E = InsnOperands.end(); I != E; ++I) {
747 // If a custom instruction decoder was specified, use that.
748 if (I->FieldBase == ~0U && I->FieldLength == ~0U) {
749 o.indent(Indentation) << " " << I->Decoder
750 << "(MI, insn, Address, Decoder);\n";
754 o.indent(Indentation)
755 << " tmp = fieldFromInstruction" << BitWidth
756 << "(insn, " << I->FieldBase << ", " << I->FieldLength << ");\n";
757 if (I->Decoder != "") {
758 o.indent(Indentation) << " " << I->Decoder
759 << "(MI, tmp, Address, Decoder);\n";
761 o.indent(Indentation)
762 << " MI.addOperand(MCOperand::CreateImm(tmp));\n";
766 o.indent(Indentation) << " return true; // " << nameWithID(Opc)
768 o.indent(Indentation) << "}\n";
772 // Otherwise, there are more decodings to be done!
774 // Emit code to match the island(s) for the singleton.
775 o.indent(Indentation) << "// Check ";
777 for (I = Size; I != 0; --I) {
778 o << "Inst{" << EndBits[I-1] << '-' << StartBits[I-1] << "} ";
782 o << "for singleton decoding...\n";
785 o.indent(Indentation) << "if (";
787 for (I = Size; I != 0; --I) {
788 NumBits = EndBits[I-1] - StartBits[I-1] + 1;
789 o << "fieldFromInstruction" << BitWidth << "(insn, "
790 << StartBits[I-1] << ", " << NumBits
791 << ") == " << FieldVals[I-1];
797 o.indent(Indentation) << " MI.setOpcode(" << Opc << ");\n";
798 std::vector<OperandInfo>& InsnOperands = Operands[Opc];
799 for (std::vector<OperandInfo>::iterator
800 I = InsnOperands.begin(), E = InsnOperands.end(); I != E; ++I) {
801 // If a custom instruction decoder was specified, use that.
802 if (I->FieldBase == ~0U && I->FieldLength == ~0U) {
803 o.indent(Indentation) << " " << I->Decoder
804 << "(MI, insn, Address, Decoder);\n";
808 o.indent(Indentation)
809 << " tmp = fieldFromInstruction" << BitWidth
810 << "(insn, " << I->FieldBase
811 << ", " << I->FieldLength << ");\n";
812 if (I->Decoder != "") {
813 o.indent(Indentation) << " " << I->Decoder
814 << "(MI, tmp, Address, Decoder);\n";
816 o.indent(Indentation)
817 << " MI.addOperand(MCOperand::CreateImm(tmp));\n";
820 o.indent(Indentation) << " return true; // " << nameWithID(Opc)
822 o.indent(Indentation) << "}\n";
827 // Emits code to decode the singleton, and then to decode the rest.
828 void FilterChooser::emitSingletonDecoder(raw_ostream &o, unsigned &Indentation,
831 unsigned Opc = Best.getSingletonOpc();
833 emitSingletonDecoder(o, Indentation, Opc);
835 // Emit code for the rest.
836 o.indent(Indentation) << "else\n";
839 Best.getVariableFC().emit(o, Indentation);
843 // Assign a single filter and run with it. Top level API client can initialize
844 // with a single filter to start the filtering process.
845 void FilterChooser::runSingleFilter(FilterChooser &owner, unsigned startBit,
846 unsigned numBit, bool mixed) {
848 Filter F(*this, startBit, numBit, true);
849 Filters.push_back(F);
850 BestIndex = 0; // Sole Filter instance to choose from.
851 bestFilter().recurse();
854 // reportRegion is a helper function for filterProcessor to mark a region as
855 // eligible for use as a filter region.
856 void FilterChooser::reportRegion(bitAttr_t RA, unsigned StartBit,
857 unsigned BitIndex, bool AllowMixed) {
858 if (RA == ATTR_MIXED && AllowMixed)
859 Filters.push_back(Filter(*this, StartBit, BitIndex - StartBit, true));
860 else if (RA == ATTR_ALL_SET && !AllowMixed)
861 Filters.push_back(Filter(*this, StartBit, BitIndex - StartBit, false));
864 // FilterProcessor scans the well-known encoding bits of the instructions and
865 // builds up a list of candidate filters. It chooses the best filter and
866 // recursively descends down the decoding tree.
867 bool FilterChooser::filterProcessor(bool AllowMixed, bool Greedy) {
870 unsigned numInstructions = Opcodes.size();
872 assert(numInstructions && "Filter created with no instructions");
874 // No further filtering is necessary.
875 if (numInstructions == 1)
878 // Heuristics. See also doFilter()'s "Heuristics" comment when num of
879 // instructions is 3.
880 if (AllowMixed && !Greedy) {
881 assert(numInstructions == 3);
883 for (unsigned i = 0; i < Opcodes.size(); ++i) {
884 std::vector<unsigned> StartBits;
885 std::vector<unsigned> EndBits;
886 std::vector<uint64_t> FieldVals;
889 insnWithID(Insn, Opcodes[i]);
891 // Look for islands of undecoded bits of any instruction.
892 if (getIslands(StartBits, EndBits, FieldVals, Insn) > 0) {
893 // Found an instruction with island(s). Now just assign a filter.
894 runSingleFilter(*this, StartBits[0], EndBits[0] - StartBits[0] + 1,
901 unsigned BitIndex, InsnIndex;
903 // We maintain BIT_WIDTH copies of the bitAttrs automaton.
904 // The automaton consumes the corresponding bit from each
907 // Input symbols: 0, 1, and _ (unset).
908 // States: NONE, FILTERED, ALL_SET, ALL_UNSET, and MIXED.
909 // Initial state: NONE.
911 // (NONE) ------- [01] -> (ALL_SET)
912 // (NONE) ------- _ ----> (ALL_UNSET)
913 // (ALL_SET) ---- [01] -> (ALL_SET)
914 // (ALL_SET) ---- _ ----> (MIXED)
915 // (ALL_UNSET) -- [01] -> (MIXED)
916 // (ALL_UNSET) -- _ ----> (ALL_UNSET)
917 // (MIXED) ------ . ----> (MIXED)
918 // (FILTERED)---- . ----> (FILTERED)
920 std::vector<bitAttr_t> bitAttrs;
922 // FILTERED bit positions provide no entropy and are not worthy of pursuing.
923 // Filter::recurse() set either BIT_TRUE or BIT_FALSE for each position.
924 for (BitIndex = 0; BitIndex < BitWidth; ++BitIndex)
925 if (FilterBitValues[BitIndex] == BIT_TRUE ||
926 FilterBitValues[BitIndex] == BIT_FALSE)
927 bitAttrs.push_back(ATTR_FILTERED);
929 bitAttrs.push_back(ATTR_NONE);
931 for (InsnIndex = 0; InsnIndex < numInstructions; ++InsnIndex) {
934 insnWithID(insn, Opcodes[InsnIndex]);
936 for (BitIndex = 0; BitIndex < BitWidth; ++BitIndex) {
937 switch (bitAttrs[BitIndex]) {
939 if (insn[BitIndex] == BIT_UNSET)
940 bitAttrs[BitIndex] = ATTR_ALL_UNSET;
942 bitAttrs[BitIndex] = ATTR_ALL_SET;
945 if (insn[BitIndex] == BIT_UNSET)
946 bitAttrs[BitIndex] = ATTR_MIXED;
949 if (insn[BitIndex] != BIT_UNSET)
950 bitAttrs[BitIndex] = ATTR_MIXED;
959 // The regionAttr automaton consumes the bitAttrs automatons' state,
960 // lowest-to-highest.
962 // Input symbols: F(iltered), (all_)S(et), (all_)U(nset), M(ixed)
963 // States: NONE, ALL_SET, MIXED
964 // Initial state: NONE
966 // (NONE) ----- F --> (NONE)
967 // (NONE) ----- S --> (ALL_SET) ; and set region start
968 // (NONE) ----- U --> (NONE)
969 // (NONE) ----- M --> (MIXED) ; and set region start
970 // (ALL_SET) -- F --> (NONE) ; and report an ALL_SET region
971 // (ALL_SET) -- S --> (ALL_SET)
972 // (ALL_SET) -- U --> (NONE) ; and report an ALL_SET region
973 // (ALL_SET) -- M --> (MIXED) ; and report an ALL_SET region
974 // (MIXED) ---- F --> (NONE) ; and report a MIXED region
975 // (MIXED) ---- S --> (ALL_SET) ; and report a MIXED region
976 // (MIXED) ---- U --> (NONE) ; and report a MIXED region
977 // (MIXED) ---- M --> (MIXED)
979 bitAttr_t RA = ATTR_NONE;
980 unsigned StartBit = 0;
982 for (BitIndex = 0; BitIndex < BitWidth; BitIndex++) {
983 bitAttr_t bitAttr = bitAttrs[BitIndex];
985 assert(bitAttr != ATTR_NONE && "Bit without attributes");
1003 assert(0 && "Unexpected bitAttr!");
1009 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1014 case ATTR_ALL_UNSET:
1015 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1019 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1020 StartBit = BitIndex;
1024 assert(0 && "Unexpected bitAttr!");
1030 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1031 StartBit = BitIndex;
1035 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1036 StartBit = BitIndex;
1039 case ATTR_ALL_UNSET:
1040 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1046 assert(0 && "Unexpected bitAttr!");
1049 case ATTR_ALL_UNSET:
1050 assert(0 && "regionAttr state machine has no ATTR_UNSET state");
1052 assert(0 && "regionAttr state machine has no ATTR_FILTERED state");
1056 // At the end, if we're still in ALL_SET or MIXED states, report a region
1063 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1065 case ATTR_ALL_UNSET:
1068 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1072 // We have finished with the filter processings. Now it's time to choose
1073 // the best performing filter.
1075 bool AllUseless = true;
1076 unsigned BestScore = 0;
1078 for (unsigned i = 0, e = Filters.size(); i != e; ++i) {
1079 unsigned Usefulness = Filters[i].usefulness();
1084 if (Usefulness > BestScore) {
1086 BestScore = Usefulness;
1091 bestFilter().recurse();
1094 } // end of FilterChooser::filterProcessor(bool)
1096 // Decides on the best configuration of filter(s) to use in order to decode
1097 // the instructions. A conflict of instructions may occur, in which case we
1098 // dump the conflict set to the standard error.
1099 void FilterChooser::doFilter() {
1100 unsigned Num = Opcodes.size();
1101 assert(Num && "FilterChooser created with no instructions");
1103 // Try regions of consecutive known bit values first.
1104 if (filterProcessor(false))
1107 // Then regions of mixed bits (both known and unitialized bit values allowed).
1108 if (filterProcessor(true))
1111 // Heuristics to cope with conflict set {t2CMPrs, t2SUBSrr, t2SUBSrs} where
1112 // no single instruction for the maximum ATTR_MIXED region Inst{14-4} has a
1113 // well-known encoding pattern. In such case, we backtrack and scan for the
1114 // the very first consecutive ATTR_ALL_SET region and assign a filter to it.
1115 if (Num == 3 && filterProcessor(true, false))
1118 // If we come to here, the instruction decoding has failed.
1119 // Set the BestIndex to -1 to indicate so.
1123 // Emits code to decode our share of instructions. Returns true if the
1124 // emitted code causes a return, which occurs if we know how to decode
1125 // the instruction at this level or the instruction is not decodeable.
1126 bool FilterChooser::emit(raw_ostream &o, unsigned &Indentation) {
1127 if (Opcodes.size() == 1)
1128 // There is only one instruction in the set, which is great!
1129 // Call emitSingletonDecoder() to see whether there are any remaining
1131 return emitSingletonDecoder(o, Indentation, Opcodes[0]);
1133 // Choose the best filter to do the decodings!
1134 if (BestIndex != -1) {
1135 Filter &Best = bestFilter();
1136 if (Best.getNumFiltered() == 1)
1137 emitSingletonDecoder(o, Indentation, Best);
1139 bestFilter().emit(o, Indentation);
1143 // We don't know how to decode these instructions! Return 0 and dump the
1145 o.indent(Indentation) << "return 0;" << " // Conflict set: ";
1146 for (int i = 0, N = Opcodes.size(); i < N; ++i) {
1147 o << nameWithID(Opcodes[i]);
1154 // Print out useful conflict information for postmortem analysis.
1155 errs() << "Decoding Conflict:\n";
1157 dumpStack(errs(), "\t\t");
1159 for (unsigned i = 0; i < Opcodes.size(); i++) {
1160 const std::string &Name = nameWithID(Opcodes[i]);
1162 errs() << '\t' << Name << " ";
1164 getBitsField(*AllInstructions[Opcodes[i]]->TheDef, "Inst"));
1171 static bool populateInstruction(const CodeGenInstruction &CGI,
1173 std::map<unsigned, std::vector<OperandInfo> >& Operands){
1174 const Record &Def = *CGI.TheDef;
1175 // If all the bit positions are not specified; do not decode this instruction.
1176 // We are bound to fail! For proper disassembly, the well-known encoding bits
1177 // of the instruction must be fully specified.
1179 // This also removes pseudo instructions from considerations of disassembly,
1180 // which is a better design and less fragile than the name matchings.
1181 // Ignore "asm parser only" instructions.
1182 if (Def.getValueAsBit("isAsmParserOnly") ||
1183 Def.getValueAsBit("isCodeGenOnly"))
1186 BitsInit &Bits = getBitsField(Def, "Inst");
1187 if (Bits.allInComplete()) return false;
1189 std::vector<OperandInfo> InsnOperands;
1191 // If the instruction has specified a custom decoding hook, use that instead
1192 // of trying to auto-generate the decoder.
1193 std::string InstDecoder = Def.getValueAsString("DecoderMethod");
1194 if (InstDecoder != "") {
1195 InsnOperands.push_back(OperandInfo(~0U, ~0U, InstDecoder));
1196 Operands[Opc] = InsnOperands;
1200 // Generate a description of the operand of the instruction that we know
1201 // how to decode automatically.
1202 // FIXME: We'll need to have a way to manually override this as needed.
1204 // Gather the outputs/inputs of the instruction, so we can find their
1205 // positions in the encoding. This assumes for now that they appear in the
1206 // MCInst in the order that they're listed.
1207 std::vector<std::pair<Init*, std::string> > InOutOperands;
1208 DagInit *Out = Def.getValueAsDag("OutOperandList");
1209 DagInit *In = Def.getValueAsDag("InOperandList");
1210 for (unsigned i = 0; i < Out->getNumArgs(); ++i)
1211 InOutOperands.push_back(std::make_pair(Out->getArg(i), Out->getArgName(i)));
1212 for (unsigned i = 0; i < In->getNumArgs(); ++i)
1213 InOutOperands.push_back(std::make_pair(In->getArg(i), In->getArgName(i)));
1215 // For each operand, see if we can figure out where it is encoded.
1216 for (std::vector<std::pair<Init*, std::string> >::iterator
1217 NI = InOutOperands.begin(), NE = InOutOperands.end(); NI != NE; ++NI) {
1218 unsigned PrevBit = ~0;
1220 unsigned PrevPos = ~0;
1221 std::string Decoder = "";
1223 for (unsigned bi = 0; bi < Bits.getNumBits(); ++bi) {
1224 VarBitInit *BI = dynamic_cast<VarBitInit*>(Bits.getBit(bi));
1227 VarInit *Var = dynamic_cast<VarInit*>(BI->getVariable());
1229 unsigned CurrBit = BI->getBitNum();
1230 if (Var->getName() != NI->second) continue;
1232 // Figure out the lowest bit of the value, and the width of the field.
1233 // Deliberately don't try to handle cases where the field is scattered,
1234 // or where not all bits of the the field are explicit.
1235 if (Base == ~0U && PrevBit == ~0U && PrevPos == ~0U) {
1242 if ((PrevPos != ~0U && bi-1 != PrevPos) ||
1243 (CurrBit != ~0U && CurrBit-1 != PrevBit)) {
1252 // At this point, we can locate the field, but we need to know how to
1253 // interpret it. As a first step, require the target to provide callbacks
1254 // for decoding register classes.
1255 // FIXME: This need to be extended to handle instructions with custom
1256 // decoder methods, and operands with (simple) MIOperandInfo's.
1257 TypedInit *TI = dynamic_cast<TypedInit*>(NI->first);
1258 RecordRecTy *Type = dynamic_cast<RecordRecTy*>(TI->getType());
1259 Record *TypeRecord = Type->getRecord();
1261 if (TypeRecord->isSubClassOf("RegisterOperand"))
1262 TypeRecord = TypeRecord->getValueAsDef("RegClass");
1263 if (TypeRecord->isSubClassOf("RegisterClass")) {
1264 Decoder = "Decode" + TypeRecord->getName() + "RegisterClass";
1268 RecordVal *DecoderString = TypeRecord->getValue("DecoderMethod");
1269 StringInit *String = DecoderString ?
1270 dynamic_cast<StringInit*>(DecoderString->getValue()) :
1272 if (!isReg && String && String->getValue() != "")
1273 Decoder = String->getValue();
1277 InsnOperands.push_back(OperandInfo(Base, PrevBit+1, Decoder));
1278 DEBUG(errs() << "ENCODED OPERAND: $" << NI->second << " @ ("
1279 << utostr(Base+PrevBit) << ", " << utostr(Base) << ")\n");
1283 Operands[Opc] = InsnOperands;
1288 // Dumps the instruction encoding bits.
1289 dumpBits(errs(), Bits);
1293 // Dumps the list of operand info.
1294 for (unsigned i = 0, e = CGI.Operands.size(); i != e; ++i) {
1295 const CGIOperandList::OperandInfo &Info = CGI.Operands[i];
1296 const std::string &OperandName = Info.Name;
1297 const Record &OperandDef = *Info.Rec;
1299 errs() << "\t" << OperandName << " (" << OperandDef.getName() << ")\n";
1307 static void emitHelper(llvm::raw_ostream &o, unsigned BitWidth) {
1308 unsigned Indentation = 0;
1309 std::string WidthStr = "uint" + utostr(BitWidth) + "_t";
1313 o.indent(Indentation) << "static " << WidthStr <<
1314 " fieldFromInstruction" << BitWidth <<
1315 "(" << WidthStr <<" insn, unsigned startBit, unsigned numBits)\n";
1317 o.indent(Indentation) << "{\n";
1319 ++Indentation; ++Indentation;
1320 o.indent(Indentation) << "assert(startBit + numBits <= " << BitWidth
1321 << " && \"Instruction field out of bounds!\");\n";
1323 o.indent(Indentation) << WidthStr << " fieldMask;\n";
1325 o.indent(Indentation) << "if (numBits == " << BitWidth << ")\n";
1327 ++Indentation; ++Indentation;
1328 o.indent(Indentation) << "fieldMask = (" << WidthStr << ")-1;\n";
1329 --Indentation; --Indentation;
1331 o.indent(Indentation) << "else\n";
1333 ++Indentation; ++Indentation;
1334 o.indent(Indentation) << "fieldMask = ((1 << numBits) - 1) << startBit;\n";
1335 --Indentation; --Indentation;
1338 o.indent(Indentation) << "return (insn & fieldMask) >> startBit;\n";
1339 --Indentation; --Indentation;
1341 o.indent(Indentation) << "}\n";
1346 // Emits disassembler code for instruction decoding.
1347 void FixedLenDecoderEmitter::run(raw_ostream &o)
1349 o << "#include \"llvm/MC/MCInst.h\"\n";
1350 o << "#include \"llvm/Support/DataTypes.h\"\n";
1351 o << "#include <assert.h>\n";
1353 o << "namespace llvm {\n\n";
1355 // Parameterize the decoders based on namespace and instruction width.
1356 NumberedInstructions = Target.getInstructionsByEnumValue();
1357 std::map<std::pair<std::string, unsigned>,
1358 std::vector<unsigned> > OpcMap;
1359 std::map<unsigned, std::vector<OperandInfo> > Operands;
1361 for (unsigned i = 0; i < NumberedInstructions.size(); ++i) {
1362 const CodeGenInstruction *Inst = NumberedInstructions[i];
1363 Record *Def = Inst->TheDef;
1364 unsigned Size = Def->getValueAsInt("Size");
1365 if (Def->getValueAsString("Namespace") == "TargetOpcode" ||
1366 Def->getValueAsBit("isPseudo") ||
1367 Def->getValueAsBit("isAsmParserOnly") ||
1368 Def->getValueAsBit("isCodeGenOnly"))
1371 std::string DecoderNamespace = Def->getValueAsString("DecoderNamespace");
1374 if (populateInstruction(*Inst, i, Operands)) {
1375 OpcMap[std::make_pair(DecoderNamespace, Size)].push_back(i);
1380 std::set<unsigned> Sizes;
1381 for (std::map<std::pair<std::string, unsigned>,
1382 std::vector<unsigned> >::iterator
1383 I = OpcMap.begin(), E = OpcMap.end(); I != E; ++I) {
1384 // If we haven't visited this instruction width before, emit the
1385 // helper method to extract fields.
1386 if (!Sizes.count(I->first.second)) {
1387 emitHelper(o, 8*I->first.second);
1388 Sizes.insert(I->first.second);
1391 // Emit the decoder for this namespace+width combination.
1392 FilterChooser FC(NumberedInstructions, I->second, Operands,
1394 FC.emitTop(o, 0, I->first.first);
1397 o << "\n} // End llvm namespace \n";