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"
19 #include "llvm/TableGen/Record.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 const FixedLenDecoderEmitter *Emitter;
245 FilterChooser(const FilterChooser &FC) :
246 AllInstructions(FC.AllInstructions), Opcodes(FC.Opcodes),
247 Operands(FC.Operands), Filters(FC.Filters),
248 FilterBitValues(FC.FilterBitValues), Parent(FC.Parent),
249 BestIndex(FC.BestIndex), BitWidth(FC.BitWidth),
250 Emitter(FC.Emitter) { }
252 FilterChooser(const std::vector<const CodeGenInstruction*> &Insts,
253 const std::vector<unsigned> &IDs,
254 std::map<unsigned, std::vector<OperandInfo> > &Ops,
256 const FixedLenDecoderEmitter *E) :
257 AllInstructions(Insts), Opcodes(IDs), Operands(Ops), Filters(),
258 Parent(NULL), BestIndex(-1), BitWidth(BW), Emitter(E) {
259 for (unsigned i = 0; i < BitWidth; ++i)
260 FilterBitValues.push_back(BIT_UNFILTERED);
265 FilterChooser(const std::vector<const CodeGenInstruction*> &Insts,
266 const std::vector<unsigned> &IDs,
267 std::map<unsigned, std::vector<OperandInfo> > &Ops,
268 std::vector<bit_value_t> &ParentFilterBitValues,
269 FilterChooser &parent) :
270 AllInstructions(Insts), Opcodes(IDs), Operands(Ops),
271 Filters(), FilterBitValues(ParentFilterBitValues),
272 Parent(&parent), BestIndex(-1), BitWidth(parent.BitWidth),
273 Emitter(parent.Emitter) {
277 // The top level filter chooser has NULL as its parent.
278 bool isTopLevel() { return Parent == NULL; }
280 // Emit the top level typedef and decodeInstruction() function.
281 void emitTop(raw_ostream &o, unsigned Indentation, std::string Namespace);
284 // Populates the insn given the uid.
285 void insnWithID(insn_t &Insn, unsigned Opcode) const {
286 BitsInit &Bits = getBitsField(*AllInstructions[Opcode]->TheDef, "Inst");
288 for (unsigned i = 0; i < BitWidth; ++i)
289 Insn.push_back(bitFromBits(Bits, i));
292 // Returns the record name.
293 const std::string &nameWithID(unsigned Opcode) const {
294 return AllInstructions[Opcode]->TheDef->getName();
297 // Populates the field of the insn given the start position and the number of
298 // consecutive bits to scan for.
300 // Returns false if there exists any uninitialized bit value in the range.
301 // Returns true, otherwise.
302 bool fieldFromInsn(uint64_t &Field, insn_t &Insn, unsigned StartBit,
303 unsigned NumBits) const;
305 /// dumpFilterArray - dumpFilterArray prints out debugging info for the given
306 /// filter array as a series of chars.
307 void dumpFilterArray(raw_ostream &o, std::vector<bit_value_t> & filter);
309 /// dumpStack - dumpStack traverses the filter chooser chain and calls
310 /// dumpFilterArray on each filter chooser up to the top level one.
311 void dumpStack(raw_ostream &o, const char *prefix);
313 Filter &bestFilter() {
314 assert(BestIndex != -1 && "BestIndex not set");
315 return Filters[BestIndex];
318 // Called from Filter::recurse() when singleton exists. For debug purpose.
319 void SingletonExists(unsigned Opc);
321 bool PositionFiltered(unsigned i) {
322 return ValueSet(FilterBitValues[i]);
325 // Calculates the island(s) needed to decode the instruction.
326 // This returns a lit of undecoded bits of an instructions, for example,
327 // Inst{20} = 1 && Inst{3-0} == 0b1111 represents two islands of yet-to-be
328 // decoded bits in order to verify that the instruction matches the Opcode.
329 unsigned getIslands(std::vector<unsigned> &StartBits,
330 std::vector<unsigned> &EndBits, std::vector<uint64_t> &FieldVals,
333 // Emits code to check the Predicates member of an instruction are true.
334 // Returns true if predicate matches were emitted, false otherwise.
335 bool emitPredicateMatch(raw_ostream &o, unsigned &Indentation,unsigned Opc);
337 // Emits code to decode the singleton. Return true if we have matched all the
339 bool emitSingletonDecoder(raw_ostream &o, unsigned &Indentation,unsigned Opc);
341 // Emits code to decode the singleton, and then to decode the rest.
342 void emitSingletonDecoder(raw_ostream &o, unsigned &Indentation,Filter &Best);
344 void emitBinaryParser(raw_ostream &o , unsigned &Indentation,
345 OperandInfo &OpInfo);
347 // Assign a single filter and run with it.
348 void runSingleFilter(FilterChooser &owner, unsigned startBit, unsigned numBit,
351 // reportRegion is a helper function for filterProcessor to mark a region as
352 // eligible for use as a filter region.
353 void reportRegion(bitAttr_t RA, unsigned StartBit, unsigned BitIndex,
356 // FilterProcessor scans the well-known encoding bits of the instructions and
357 // builds up a list of candidate filters. It chooses the best filter and
358 // recursively descends down the decoding tree.
359 bool filterProcessor(bool AllowMixed, bool Greedy = true);
361 // Decides on the best configuration of filter(s) to use in order to decode
362 // the instructions. A conflict of instructions may occur, in which case we
363 // dump the conflict set to the standard error.
366 // Emits code to decode our share of instructions. Returns true if the
367 // emitted code causes a return, which occurs if we know how to decode
368 // the instruction at this level or the instruction is not decodeable.
369 bool emit(raw_ostream &o, unsigned &Indentation);
372 ///////////////////////////
374 // Filter Implmenetation //
376 ///////////////////////////
378 Filter::Filter(const Filter &f) :
379 Owner(f.Owner), StartBit(f.StartBit), NumBits(f.NumBits), Mixed(f.Mixed),
380 FilteredInstructions(f.FilteredInstructions),
381 VariableInstructions(f.VariableInstructions),
382 FilterChooserMap(f.FilterChooserMap), NumFiltered(f.NumFiltered),
383 LastOpcFiltered(f.LastOpcFiltered), NumVariable(f.NumVariable) {
386 Filter::Filter(FilterChooser &owner, unsigned startBit, unsigned numBits,
387 bool mixed) : Owner(&owner), StartBit(startBit), NumBits(numBits),
389 assert(StartBit + NumBits - 1 < Owner->BitWidth);
395 for (unsigned i = 0, e = Owner->Opcodes.size(); i != e; ++i) {
398 // Populates the insn given the uid.
399 Owner->insnWithID(Insn, Owner->Opcodes[i]);
402 // Scans the segment for possibly well-specified encoding bits.
403 bool ok = Owner->fieldFromInsn(Field, Insn, StartBit, NumBits);
406 // The encoding bits are well-known. Lets add the uid of the
407 // instruction into the bucket keyed off the constant field value.
408 LastOpcFiltered = Owner->Opcodes[i];
409 FilteredInstructions[Field].push_back(LastOpcFiltered);
412 // Some of the encoding bit(s) are unspecfied. This contributes to
413 // one additional member of "Variable" instructions.
414 VariableInstructions.push_back(Owner->Opcodes[i]);
419 assert((FilteredInstructions.size() + VariableInstructions.size() > 0)
420 && "Filter returns no instruction categories");
424 std::map<unsigned, FilterChooser*>::iterator filterIterator;
425 for (filterIterator = FilterChooserMap.begin();
426 filterIterator != FilterChooserMap.end();
428 delete filterIterator->second;
432 // Divides the decoding task into sub tasks and delegates them to the
433 // inferior FilterChooser's.
435 // A special case arises when there's only one entry in the filtered
436 // instructions. In order to unambiguously decode the singleton, we need to
437 // match the remaining undecoded encoding bits against the singleton.
438 void Filter::recurse() {
439 std::map<uint64_t, std::vector<unsigned> >::const_iterator mapIterator;
441 // Starts by inheriting our parent filter chooser's filter bit values.
442 std::vector<bit_value_t> BitValueArray(Owner->FilterBitValues);
446 if (VariableInstructions.size()) {
447 // Conservatively marks each segment position as BIT_UNSET.
448 for (bitIndex = 0; bitIndex < NumBits; bitIndex++)
449 BitValueArray[StartBit + bitIndex] = BIT_UNSET;
451 // Delegates to an inferior filter chooser for further processing on this
452 // group of instructions whose segment values are variable.
453 FilterChooserMap.insert(std::pair<unsigned, FilterChooser*>(
455 new FilterChooser(Owner->AllInstructions,
456 VariableInstructions,
463 // No need to recurse for a singleton filtered instruction.
464 // See also Filter::emit().
465 if (getNumFiltered() == 1) {
466 //Owner->SingletonExists(LastOpcFiltered);
467 assert(FilterChooserMap.size() == 1);
471 // Otherwise, create sub choosers.
472 for (mapIterator = FilteredInstructions.begin();
473 mapIterator != FilteredInstructions.end();
476 // Marks all the segment positions with either BIT_TRUE or BIT_FALSE.
477 for (bitIndex = 0; bitIndex < NumBits; bitIndex++) {
478 if (mapIterator->first & (1ULL << bitIndex))
479 BitValueArray[StartBit + bitIndex] = BIT_TRUE;
481 BitValueArray[StartBit + bitIndex] = BIT_FALSE;
484 // Delegates to an inferior filter chooser for further processing on this
485 // category of instructions.
486 FilterChooserMap.insert(std::pair<unsigned, FilterChooser*>(
488 new FilterChooser(Owner->AllInstructions,
497 // Emit code to decode instructions given a segment or segments of bits.
498 void Filter::emit(raw_ostream &o, unsigned &Indentation) {
499 o.indent(Indentation) << "// Check Inst{";
502 o << (StartBit + NumBits - 1) << '-';
504 o << StartBit << "} ...\n";
506 o.indent(Indentation) << "switch (fieldFromInstruction" << Owner->BitWidth
507 << "(insn, " << StartBit << ", "
508 << NumBits << ")) {\n";
510 std::map<unsigned, FilterChooser*>::iterator filterIterator;
512 bool DefaultCase = false;
513 for (filterIterator = FilterChooserMap.begin();
514 filterIterator != FilterChooserMap.end();
517 // Field value -1 implies a non-empty set of variable instructions.
518 // See also recurse().
519 if (filterIterator->first == (unsigned)-1) {
522 o.indent(Indentation) << "default:\n";
523 o.indent(Indentation) << " break; // fallthrough\n";
525 // Closing curly brace for the switch statement.
526 // This is unconventional because we want the default processing to be
527 // performed for the fallthrough cases as well, i.e., when the "cases"
528 // did not prove a decoded instruction.
529 o.indent(Indentation) << "}\n";
532 o.indent(Indentation) << "case " << filterIterator->first << ":\n";
534 // We arrive at a category of instructions with the same segment value.
535 // Now delegate to the sub filter chooser for further decodings.
536 // The case may fallthrough, which happens if the remaining well-known
537 // encoding bits do not match exactly.
538 if (!DefaultCase) { ++Indentation; ++Indentation; }
540 bool finished = filterIterator->second->emit(o, Indentation);
541 // For top level default case, there's no need for a break statement.
542 if (Owner->isTopLevel() && DefaultCase)
545 o.indent(Indentation) << "break;\n";
547 if (!DefaultCase) { --Indentation; --Indentation; }
550 // If there is no default case, we still need to supply a closing brace.
552 // Closing curly brace for the switch statement.
553 o.indent(Indentation) << "}\n";
557 // Returns the number of fanout produced by the filter. More fanout implies
558 // the filter distinguishes more categories of instructions.
559 unsigned Filter::usefulness() const {
560 if (VariableInstructions.size())
561 return FilteredInstructions.size();
563 return FilteredInstructions.size() + 1;
566 //////////////////////////////////
568 // Filterchooser Implementation //
570 //////////////////////////////////
572 // Emit the top level typedef and decodeInstruction() function.
573 void FilterChooser::emitTop(raw_ostream &o, unsigned Indentation,
574 std::string Namespace) {
575 o.indent(Indentation) <<
576 "static MCDisassembler::DecodeStatus decode" << Namespace << "Instruction" << BitWidth
577 << "(MCInst &MI, uint" << BitWidth << "_t insn, uint64_t Address, "
578 << "const void *Decoder, const MCSubtargetInfo &STI) {\n";
579 o.indent(Indentation) << " unsigned tmp = 0;\n";
580 o.indent(Indentation) << " (void)tmp;\n";
581 o.indent(Indentation) << Emitter->Locals << "\n";
582 o.indent(Indentation) << " uint64_t Bits = STI.getFeatureBits();\n";
583 o.indent(Indentation) << " (void)Bits;\n";
585 ++Indentation; ++Indentation;
586 // Emits code to decode the instructions.
587 emit(o, Indentation);
590 o.indent(Indentation) << "return " << Emitter->ReturnFail << ";\n";
591 --Indentation; --Indentation;
593 o.indent(Indentation) << "}\n";
598 // Populates the field of the insn given the start position and the number of
599 // consecutive bits to scan for.
601 // Returns false if and on the first uninitialized bit value encountered.
602 // Returns true, otherwise.
603 bool FilterChooser::fieldFromInsn(uint64_t &Field, insn_t &Insn,
604 unsigned StartBit, unsigned NumBits) const {
607 for (unsigned i = 0; i < NumBits; ++i) {
608 if (Insn[StartBit + i] == BIT_UNSET)
611 if (Insn[StartBit + i] == BIT_TRUE)
612 Field = Field | (1ULL << i);
618 /// dumpFilterArray - dumpFilterArray prints out debugging info for the given
619 /// filter array as a series of chars.
620 void FilterChooser::dumpFilterArray(raw_ostream &o,
621 std::vector<bit_value_t> &filter) {
624 for (bitIndex = BitWidth; bitIndex > 0; bitIndex--) {
625 switch (filter[bitIndex - 1]) {
642 /// dumpStack - dumpStack traverses the filter chooser chain and calls
643 /// dumpFilterArray on each filter chooser up to the top level one.
644 void FilterChooser::dumpStack(raw_ostream &o, const char *prefix) {
645 FilterChooser *current = this;
649 dumpFilterArray(o, current->FilterBitValues);
651 current = current->Parent;
655 // Called from Filter::recurse() when singleton exists. For debug purpose.
656 void FilterChooser::SingletonExists(unsigned Opc) {
658 insnWithID(Insn0, Opc);
660 errs() << "Singleton exists: " << nameWithID(Opc)
661 << " with its decoding dominating ";
662 for (unsigned i = 0; i < Opcodes.size(); ++i) {
663 if (Opcodes[i] == Opc) continue;
664 errs() << nameWithID(Opcodes[i]) << ' ';
668 dumpStack(errs(), "\t\t");
669 for (unsigned i = 0; i < Opcodes.size(); i++) {
670 const std::string &Name = nameWithID(Opcodes[i]);
672 errs() << '\t' << Name << " ";
674 getBitsField(*AllInstructions[Opcodes[i]]->TheDef, "Inst"));
679 // Calculates the island(s) needed to decode the instruction.
680 // This returns a list of undecoded bits of an instructions, for example,
681 // Inst{20} = 1 && Inst{3-0} == 0b1111 represents two islands of yet-to-be
682 // decoded bits in order to verify that the instruction matches the Opcode.
683 unsigned FilterChooser::getIslands(std::vector<unsigned> &StartBits,
684 std::vector<unsigned> &EndBits, std::vector<uint64_t> &FieldVals,
689 uint64_t FieldVal = 0;
692 // 1: Water (the bit value does not affect decoding)
693 // 2: Island (well-known bit value needed for decoding)
697 for (unsigned i = 0; i < BitWidth; ++i) {
698 Val = Value(Insn[i]);
699 bool Filtered = PositionFiltered(i);
702 assert(0 && "Unreachable code!");
706 if (Filtered || Val == -1)
707 State = 1; // Still in Water
709 State = 2; // Into the Island
711 StartBits.push_back(i);
716 if (Filtered || Val == -1) {
717 State = 1; // Into the Water
718 EndBits.push_back(i - 1);
719 FieldVals.push_back(FieldVal);
722 State = 2; // Still in Island
724 FieldVal = FieldVal | Val << BitNo;
729 // If we are still in Island after the loop, do some housekeeping.
731 EndBits.push_back(BitWidth - 1);
732 FieldVals.push_back(FieldVal);
736 assert(StartBits.size() == Num && EndBits.size() == Num &&
737 FieldVals.size() == Num);
741 void FilterChooser::emitBinaryParser(raw_ostream &o, unsigned &Indentation,
742 OperandInfo &OpInfo) {
743 std::string &Decoder = OpInfo.Decoder;
745 if (OpInfo.numFields() == 1) {
746 OperandInfo::iterator OI = OpInfo.begin();
747 o.indent(Indentation) << " tmp = fieldFromInstruction" << BitWidth
748 << "(insn, " << OI->Base << ", " << OI->Width
751 o.indent(Indentation) << " tmp = 0;\n";
752 for (OperandInfo::iterator OI = OpInfo.begin(), OE = OpInfo.end();
754 o.indent(Indentation) << " tmp |= (fieldFromInstruction" << BitWidth
755 << "(insn, " << OI->Base << ", " << OI->Width
756 << ") << " << OI->Offset << ");\n";
761 o.indent(Indentation) << " " << Emitter->GuardPrefix << Decoder
762 << "(MI, tmp, Address, Decoder)" << Emitter->GuardPostfix << "\n";
764 o.indent(Indentation) << " MI.addOperand(MCOperand::CreateImm(tmp));\n";
768 static void emitSinglePredicateMatch(raw_ostream &o, StringRef str,
769 std::string PredicateNamespace) {
771 o << "!(Bits & " << PredicateNamespace << "::"
772 << str.slice(1,str.size()) << ")";
774 o << "(Bits & " << PredicateNamespace << "::" << str << ")";
777 bool FilterChooser::emitPredicateMatch(raw_ostream &o, unsigned &Indentation,
779 ListInit *Predicates = AllInstructions[Opc]->TheDef->getValueAsListInit("Predicates");
780 for (unsigned i = 0; i < Predicates->getSize(); ++i) {
781 Record *Pred = Predicates->getElementAsRecord(i);
782 if (!Pred->getValue("AssemblerMatcherPredicate"))
785 std::string P = Pred->getValueAsString("AssemblerCondString");
794 std::pair<StringRef, StringRef> pairs = SR.split(',');
795 while (pairs.second.size()) {
796 emitSinglePredicateMatch(o, pairs.first, Emitter->PredicateNamespace);
798 pairs = pairs.second.split(',');
800 emitSinglePredicateMatch(o, pairs.first, Emitter->PredicateNamespace);
802 return Predicates->getSize() > 0;
805 // Emits code to decode the singleton. Return true if we have matched all the
807 bool FilterChooser::emitSingletonDecoder(raw_ostream &o, unsigned &Indentation,
809 std::vector<unsigned> StartBits;
810 std::vector<unsigned> EndBits;
811 std::vector<uint64_t> FieldVals;
813 insnWithID(Insn, Opc);
815 // Look for islands of undecoded bits of the singleton.
816 getIslands(StartBits, EndBits, FieldVals, Insn);
818 unsigned Size = StartBits.size();
821 // If we have matched all the well-known bits, just issue a return.
823 o.indent(Indentation) << "if (";
824 if (!emitPredicateMatch(o, Indentation, Opc))
827 o.indent(Indentation) << " MI.setOpcode(" << Opc << ");\n";
828 std::vector<OperandInfo>& InsnOperands = Operands[Opc];
829 for (std::vector<OperandInfo>::iterator
830 I = InsnOperands.begin(), E = InsnOperands.end(); I != E; ++I) {
831 // If a custom instruction decoder was specified, use that.
832 if (I->numFields() == 0 && I->Decoder.size()) {
833 o.indent(Indentation) << " " << Emitter->GuardPrefix << I->Decoder
834 << "(MI, insn, Address, Decoder)" << Emitter->GuardPostfix << "\n";
838 emitBinaryParser(o, Indentation, *I);
841 o.indent(Indentation) << " return " << Emitter->ReturnOK << "; // " << nameWithID(Opc)
843 o.indent(Indentation) << "}\n"; // Closing predicate block.
847 // Otherwise, there are more decodings to be done!
849 // Emit code to match the island(s) for the singleton.
850 o.indent(Indentation) << "// Check ";
852 for (I = Size; I != 0; --I) {
853 o << "Inst{" << EndBits[I-1] << '-' << StartBits[I-1] << "} ";
857 o << "for singleton decoding...\n";
860 o.indent(Indentation) << "if (";
861 if (emitPredicateMatch(o, Indentation, Opc)) {
863 o.indent(Indentation+4);
866 for (I = Size; I != 0; --I) {
867 NumBits = EndBits[I-1] - StartBits[I-1] + 1;
868 o << "fieldFromInstruction" << BitWidth << "(insn, "
869 << StartBits[I-1] << ", " << NumBits
870 << ") == " << FieldVals[I-1];
876 o.indent(Indentation) << " MI.setOpcode(" << Opc << ");\n";
877 std::vector<OperandInfo>& InsnOperands = Operands[Opc];
878 for (std::vector<OperandInfo>::iterator
879 I = InsnOperands.begin(), E = InsnOperands.end(); I != E; ++I) {
880 // If a custom instruction decoder was specified, use that.
881 if (I->numFields() == 0 && I->Decoder.size()) {
882 o.indent(Indentation) << " " << Emitter->GuardPrefix << I->Decoder
883 << "(MI, insn, Address, Decoder)" << Emitter->GuardPostfix << "\n";
887 emitBinaryParser(o, Indentation, *I);
889 o.indent(Indentation) << " return " << Emitter->ReturnOK << "; // " << nameWithID(Opc)
891 o.indent(Indentation) << "}\n";
896 // Emits code to decode the singleton, and then to decode the rest.
897 void FilterChooser::emitSingletonDecoder(raw_ostream &o, unsigned &Indentation,
900 unsigned Opc = Best.getSingletonOpc();
902 emitSingletonDecoder(o, Indentation, Opc);
904 // Emit code for the rest.
905 o.indent(Indentation) << "else\n";
908 Best.getVariableFC().emit(o, Indentation);
912 // Assign a single filter and run with it. Top level API client can initialize
913 // with a single filter to start the filtering process.
914 void FilterChooser::runSingleFilter(FilterChooser &owner, unsigned startBit,
915 unsigned numBit, bool mixed) {
917 Filter F(*this, startBit, numBit, true);
918 Filters.push_back(F);
919 BestIndex = 0; // Sole Filter instance to choose from.
920 bestFilter().recurse();
923 // reportRegion is a helper function for filterProcessor to mark a region as
924 // eligible for use as a filter region.
925 void FilterChooser::reportRegion(bitAttr_t RA, unsigned StartBit,
926 unsigned BitIndex, bool AllowMixed) {
927 if (RA == ATTR_MIXED && AllowMixed)
928 Filters.push_back(Filter(*this, StartBit, BitIndex - StartBit, true));
929 else if (RA == ATTR_ALL_SET && !AllowMixed)
930 Filters.push_back(Filter(*this, StartBit, BitIndex - StartBit, false));
933 // FilterProcessor scans the well-known encoding bits of the instructions and
934 // builds up a list of candidate filters. It chooses the best filter and
935 // recursively descends down the decoding tree.
936 bool FilterChooser::filterProcessor(bool AllowMixed, bool Greedy) {
939 unsigned numInstructions = Opcodes.size();
941 assert(numInstructions && "Filter created with no instructions");
943 // No further filtering is necessary.
944 if (numInstructions == 1)
947 // Heuristics. See also doFilter()'s "Heuristics" comment when num of
948 // instructions is 3.
949 if (AllowMixed && !Greedy) {
950 assert(numInstructions == 3);
952 for (unsigned i = 0; i < Opcodes.size(); ++i) {
953 std::vector<unsigned> StartBits;
954 std::vector<unsigned> EndBits;
955 std::vector<uint64_t> FieldVals;
958 insnWithID(Insn, Opcodes[i]);
960 // Look for islands of undecoded bits of any instruction.
961 if (getIslands(StartBits, EndBits, FieldVals, Insn) > 0) {
962 // Found an instruction with island(s). Now just assign a filter.
963 runSingleFilter(*this, StartBits[0], EndBits[0] - StartBits[0] + 1,
970 unsigned BitIndex, InsnIndex;
972 // We maintain BIT_WIDTH copies of the bitAttrs automaton.
973 // The automaton consumes the corresponding bit from each
976 // Input symbols: 0, 1, and _ (unset).
977 // States: NONE, FILTERED, ALL_SET, ALL_UNSET, and MIXED.
978 // Initial state: NONE.
980 // (NONE) ------- [01] -> (ALL_SET)
981 // (NONE) ------- _ ----> (ALL_UNSET)
982 // (ALL_SET) ---- [01] -> (ALL_SET)
983 // (ALL_SET) ---- _ ----> (MIXED)
984 // (ALL_UNSET) -- [01] -> (MIXED)
985 // (ALL_UNSET) -- _ ----> (ALL_UNSET)
986 // (MIXED) ------ . ----> (MIXED)
987 // (FILTERED)---- . ----> (FILTERED)
989 std::vector<bitAttr_t> bitAttrs;
991 // FILTERED bit positions provide no entropy and are not worthy of pursuing.
992 // Filter::recurse() set either BIT_TRUE or BIT_FALSE for each position.
993 for (BitIndex = 0; BitIndex < BitWidth; ++BitIndex)
994 if (FilterBitValues[BitIndex] == BIT_TRUE ||
995 FilterBitValues[BitIndex] == BIT_FALSE)
996 bitAttrs.push_back(ATTR_FILTERED);
998 bitAttrs.push_back(ATTR_NONE);
1000 for (InsnIndex = 0; InsnIndex < numInstructions; ++InsnIndex) {
1003 insnWithID(insn, Opcodes[InsnIndex]);
1005 for (BitIndex = 0; BitIndex < BitWidth; ++BitIndex) {
1006 switch (bitAttrs[BitIndex]) {
1008 if (insn[BitIndex] == BIT_UNSET)
1009 bitAttrs[BitIndex] = ATTR_ALL_UNSET;
1011 bitAttrs[BitIndex] = ATTR_ALL_SET;
1014 if (insn[BitIndex] == BIT_UNSET)
1015 bitAttrs[BitIndex] = ATTR_MIXED;
1017 case ATTR_ALL_UNSET:
1018 if (insn[BitIndex] != BIT_UNSET)
1019 bitAttrs[BitIndex] = ATTR_MIXED;
1028 // The regionAttr automaton consumes the bitAttrs automatons' state,
1029 // lowest-to-highest.
1031 // Input symbols: F(iltered), (all_)S(et), (all_)U(nset), M(ixed)
1032 // States: NONE, ALL_SET, MIXED
1033 // Initial state: NONE
1035 // (NONE) ----- F --> (NONE)
1036 // (NONE) ----- S --> (ALL_SET) ; and set region start
1037 // (NONE) ----- U --> (NONE)
1038 // (NONE) ----- M --> (MIXED) ; and set region start
1039 // (ALL_SET) -- F --> (NONE) ; and report an ALL_SET region
1040 // (ALL_SET) -- S --> (ALL_SET)
1041 // (ALL_SET) -- U --> (NONE) ; and report an ALL_SET region
1042 // (ALL_SET) -- M --> (MIXED) ; and report an ALL_SET region
1043 // (MIXED) ---- F --> (NONE) ; and report a MIXED region
1044 // (MIXED) ---- S --> (ALL_SET) ; and report a MIXED region
1045 // (MIXED) ---- U --> (NONE) ; and report a MIXED region
1046 // (MIXED) ---- M --> (MIXED)
1048 bitAttr_t RA = ATTR_NONE;
1049 unsigned StartBit = 0;
1051 for (BitIndex = 0; BitIndex < BitWidth; BitIndex++) {
1052 bitAttr_t bitAttr = bitAttrs[BitIndex];
1054 assert(bitAttr != ATTR_NONE && "Bit without attributes");
1062 StartBit = BitIndex;
1065 case ATTR_ALL_UNSET:
1068 StartBit = BitIndex;
1072 assert(0 && "Unexpected bitAttr!");
1078 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1083 case ATTR_ALL_UNSET:
1084 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1088 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1089 StartBit = BitIndex;
1093 assert(0 && "Unexpected bitAttr!");
1099 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1100 StartBit = BitIndex;
1104 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1105 StartBit = BitIndex;
1108 case ATTR_ALL_UNSET:
1109 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1115 assert(0 && "Unexpected bitAttr!");
1118 case ATTR_ALL_UNSET:
1119 assert(0 && "regionAttr state machine has no ATTR_UNSET state");
1121 assert(0 && "regionAttr state machine has no ATTR_FILTERED state");
1125 // At the end, if we're still in ALL_SET or MIXED states, report a region
1132 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1134 case ATTR_ALL_UNSET:
1137 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1141 // We have finished with the filter processings. Now it's time to choose
1142 // the best performing filter.
1144 bool AllUseless = true;
1145 unsigned BestScore = 0;
1147 for (unsigned i = 0, e = Filters.size(); i != e; ++i) {
1148 unsigned Usefulness = Filters[i].usefulness();
1153 if (Usefulness > BestScore) {
1155 BestScore = Usefulness;
1160 bestFilter().recurse();
1163 } // end of FilterChooser::filterProcessor(bool)
1165 // Decides on the best configuration of filter(s) to use in order to decode
1166 // the instructions. A conflict of instructions may occur, in which case we
1167 // dump the conflict set to the standard error.
1168 void FilterChooser::doFilter() {
1169 unsigned Num = Opcodes.size();
1170 assert(Num && "FilterChooser created with no instructions");
1172 // Try regions of consecutive known bit values first.
1173 if (filterProcessor(false))
1176 // Then regions of mixed bits (both known and unitialized bit values allowed).
1177 if (filterProcessor(true))
1180 // Heuristics to cope with conflict set {t2CMPrs, t2SUBSrr, t2SUBSrs} where
1181 // no single instruction for the maximum ATTR_MIXED region Inst{14-4} has a
1182 // well-known encoding pattern. In such case, we backtrack and scan for the
1183 // the very first consecutive ATTR_ALL_SET region and assign a filter to it.
1184 if (Num == 3 && filterProcessor(true, false))
1187 // If we come to here, the instruction decoding has failed.
1188 // Set the BestIndex to -1 to indicate so.
1192 // Emits code to decode our share of instructions. Returns true if the
1193 // emitted code causes a return, which occurs if we know how to decode
1194 // the instruction at this level or the instruction is not decodeable.
1195 bool FilterChooser::emit(raw_ostream &o, unsigned &Indentation) {
1196 if (Opcodes.size() == 1)
1197 // There is only one instruction in the set, which is great!
1198 // Call emitSingletonDecoder() to see whether there are any remaining
1200 return emitSingletonDecoder(o, Indentation, Opcodes[0]);
1202 // Choose the best filter to do the decodings!
1203 if (BestIndex != -1) {
1204 Filter &Best = bestFilter();
1205 if (Best.getNumFiltered() == 1)
1206 emitSingletonDecoder(o, Indentation, Best);
1208 bestFilter().emit(o, Indentation);
1212 // We don't know how to decode these instructions! Return 0 and dump the
1214 o.indent(Indentation) << "return 0;" << " // Conflict set: ";
1215 for (int i = 0, N = Opcodes.size(); i < N; ++i) {
1216 o << nameWithID(Opcodes[i]);
1223 // Print out useful conflict information for postmortem analysis.
1224 errs() << "Decoding Conflict:\n";
1226 dumpStack(errs(), "\t\t");
1228 for (unsigned i = 0; i < Opcodes.size(); i++) {
1229 const std::string &Name = nameWithID(Opcodes[i]);
1231 errs() << '\t' << Name << " ";
1233 getBitsField(*AllInstructions[Opcodes[i]]->TheDef, "Inst"));
1240 static bool populateInstruction(const CodeGenInstruction &CGI,
1242 std::map<unsigned, std::vector<OperandInfo> >& Operands){
1243 const Record &Def = *CGI.TheDef;
1244 // If all the bit positions are not specified; do not decode this instruction.
1245 // We are bound to fail! For proper disassembly, the well-known encoding bits
1246 // of the instruction must be fully specified.
1248 // This also removes pseudo instructions from considerations of disassembly,
1249 // which is a better design and less fragile than the name matchings.
1250 // Ignore "asm parser only" instructions.
1251 if (Def.getValueAsBit("isAsmParserOnly") ||
1252 Def.getValueAsBit("isCodeGenOnly"))
1255 BitsInit &Bits = getBitsField(Def, "Inst");
1256 if (Bits.allInComplete()) return false;
1258 std::vector<OperandInfo> InsnOperands;
1260 // If the instruction has specified a custom decoding hook, use that instead
1261 // of trying to auto-generate the decoder.
1262 std::string InstDecoder = Def.getValueAsString("DecoderMethod");
1263 if (InstDecoder != "") {
1264 InsnOperands.push_back(OperandInfo(InstDecoder));
1265 Operands[Opc] = InsnOperands;
1269 // Generate a description of the operand of the instruction that we know
1270 // how to decode automatically.
1271 // FIXME: We'll need to have a way to manually override this as needed.
1273 // Gather the outputs/inputs of the instruction, so we can find their
1274 // positions in the encoding. This assumes for now that they appear in the
1275 // MCInst in the order that they're listed.
1276 std::vector<std::pair<Init*, std::string> > InOutOperands;
1277 DagInit *Out = Def.getValueAsDag("OutOperandList");
1278 DagInit *In = Def.getValueAsDag("InOperandList");
1279 for (unsigned i = 0; i < Out->getNumArgs(); ++i)
1280 InOutOperands.push_back(std::make_pair(Out->getArg(i), Out->getArgName(i)));
1281 for (unsigned i = 0; i < In->getNumArgs(); ++i)
1282 InOutOperands.push_back(std::make_pair(In->getArg(i), In->getArgName(i)));
1284 // Search for tied operands, so that we can correctly instantiate
1285 // operands that are not explicitly represented in the encoding.
1286 std::map<std::string, std::string> TiedNames;
1287 for (unsigned i = 0; i < CGI.Operands.size(); ++i) {
1288 int tiedTo = CGI.Operands[i].getTiedRegister();
1290 TiedNames[InOutOperands[i].second] = InOutOperands[tiedTo].second;
1291 TiedNames[InOutOperands[tiedTo].second] = InOutOperands[i].second;
1295 // For each operand, see if we can figure out where it is encoded.
1296 for (std::vector<std::pair<Init*, std::string> >::iterator
1297 NI = InOutOperands.begin(), NE = InOutOperands.end(); NI != NE; ++NI) {
1298 std::string Decoder = "";
1300 // At this point, we can locate the field, but we need to know how to
1301 // interpret it. As a first step, require the target to provide callbacks
1302 // for decoding register classes.
1303 // FIXME: This need to be extended to handle instructions with custom
1304 // decoder methods, and operands with (simple) MIOperandInfo's.
1305 TypedInit *TI = dynamic_cast<TypedInit*>(NI->first);
1306 RecordRecTy *Type = dynamic_cast<RecordRecTy*>(TI->getType());
1307 Record *TypeRecord = Type->getRecord();
1309 if (TypeRecord->isSubClassOf("RegisterOperand"))
1310 TypeRecord = TypeRecord->getValueAsDef("RegClass");
1311 if (TypeRecord->isSubClassOf("RegisterClass")) {
1312 Decoder = "Decode" + TypeRecord->getName() + "RegisterClass";
1316 RecordVal *DecoderString = TypeRecord->getValue("DecoderMethod");
1317 StringInit *String = DecoderString ?
1318 dynamic_cast<StringInit*>(DecoderString->getValue()) : 0;
1319 if (!isReg && String && String->getValue() != "")
1320 Decoder = String->getValue();
1322 OperandInfo OpInfo(Decoder);
1323 unsigned Base = ~0U;
1325 unsigned Offset = 0;
1327 for (unsigned bi = 0; bi < Bits.getNumBits(); ++bi) {
1329 VarBitInit *BI = dynamic_cast<VarBitInit*>(Bits.getBit(bi));
1331 Var = dynamic_cast<VarInit*>(BI->getVariable());
1333 Var = dynamic_cast<VarInit*>(Bits.getBit(bi));
1337 OpInfo.addField(Base, Width, Offset);
1345 if (Var->getName() != NI->second &&
1346 Var->getName() != TiedNames[NI->second]) {
1348 OpInfo.addField(Base, Width, Offset);
1359 Offset = BI ? BI->getBitNum() : 0;
1360 } else if (BI && BI->getBitNum() != Offset + Width) {
1361 OpInfo.addField(Base, Width, Offset);
1364 Offset = BI->getBitNum();
1371 OpInfo.addField(Base, Width, Offset);
1373 if (OpInfo.numFields() > 0)
1374 InsnOperands.push_back(OpInfo);
1377 Operands[Opc] = InsnOperands;
1382 // Dumps the instruction encoding bits.
1383 dumpBits(errs(), Bits);
1387 // Dumps the list of operand info.
1388 for (unsigned i = 0, e = CGI.Operands.size(); i != e; ++i) {
1389 const CGIOperandList::OperandInfo &Info = CGI.Operands[i];
1390 const std::string &OperandName = Info.Name;
1391 const Record &OperandDef = *Info.Rec;
1393 errs() << "\t" << OperandName << " (" << OperandDef.getName() << ")\n";
1401 static void emitHelper(llvm::raw_ostream &o, unsigned BitWidth) {
1402 unsigned Indentation = 0;
1403 std::string WidthStr = "uint" + utostr(BitWidth) + "_t";
1407 o.indent(Indentation) << "static " << WidthStr <<
1408 " fieldFromInstruction" << BitWidth <<
1409 "(" << WidthStr <<" insn, unsigned startBit, unsigned numBits)\n";
1411 o.indent(Indentation) << "{\n";
1413 ++Indentation; ++Indentation;
1414 o.indent(Indentation) << "assert(startBit + numBits <= " << BitWidth
1415 << " && \"Instruction field out of bounds!\");\n";
1417 o.indent(Indentation) << WidthStr << " fieldMask;\n";
1419 o.indent(Indentation) << "if (numBits == " << BitWidth << ")\n";
1421 ++Indentation; ++Indentation;
1422 o.indent(Indentation) << "fieldMask = (" << WidthStr << ")-1;\n";
1423 --Indentation; --Indentation;
1425 o.indent(Indentation) << "else\n";
1427 ++Indentation; ++Indentation;
1428 o.indent(Indentation) << "fieldMask = ((1 << numBits) - 1) << startBit;\n";
1429 --Indentation; --Indentation;
1432 o.indent(Indentation) << "return (insn & fieldMask) >> startBit;\n";
1433 --Indentation; --Indentation;
1435 o.indent(Indentation) << "}\n";
1440 // Emits disassembler code for instruction decoding.
1441 void FixedLenDecoderEmitter::run(raw_ostream &o)
1443 o << "#include \"llvm/MC/MCInst.h\"\n";
1444 o << "#include \"llvm/Support/DataTypes.h\"\n";
1445 o << "#include <assert.h>\n";
1447 o << "namespace llvm {\n\n";
1449 // Parameterize the decoders based on namespace and instruction width.
1450 NumberedInstructions = Target.getInstructionsByEnumValue();
1451 std::map<std::pair<std::string, unsigned>,
1452 std::vector<unsigned> > OpcMap;
1453 std::map<unsigned, std::vector<OperandInfo> > Operands;
1455 for (unsigned i = 0; i < NumberedInstructions.size(); ++i) {
1456 const CodeGenInstruction *Inst = NumberedInstructions[i];
1457 Record *Def = Inst->TheDef;
1458 unsigned Size = Def->getValueAsInt("Size");
1459 if (Def->getValueAsString("Namespace") == "TargetOpcode" ||
1460 Def->getValueAsBit("isPseudo") ||
1461 Def->getValueAsBit("isAsmParserOnly") ||
1462 Def->getValueAsBit("isCodeGenOnly"))
1465 std::string DecoderNamespace = Def->getValueAsString("DecoderNamespace");
1468 if (populateInstruction(*Inst, i, Operands)) {
1469 OpcMap[std::make_pair(DecoderNamespace, Size)].push_back(i);
1474 std::set<unsigned> Sizes;
1475 for (std::map<std::pair<std::string, unsigned>,
1476 std::vector<unsigned> >::iterator
1477 I = OpcMap.begin(), E = OpcMap.end(); I != E; ++I) {
1478 // If we haven't visited this instruction width before, emit the
1479 // helper method to extract fields.
1480 if (!Sizes.count(I->first.second)) {
1481 emitHelper(o, 8*I->first.second);
1482 Sizes.insert(I->first.second);
1485 // Emit the decoder for this namespace+width combination.
1486 FilterChooser FC(NumberedInstructions, I->second, Operands,
1487 8*I->first.second, this);
1488 FC.emitTop(o, 0, I->first.first);
1491 o << "\n} // End llvm namespace \n";