1 //===------------ ARMDecoderEmitter.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 // This file is part of the ARM Disassembler.
11 // It contains the tablegen backend that emits the decoder functions for ARM and
12 // Thumb. The disassembler core includes the auto-generated file, invokes the
13 // decoder functions, and builds up the MCInst based on the decoded Opcode.
15 //===----------------------------------------------------------------------===//
17 #define DEBUG_TYPE "arm-decoder-emitter"
19 #include "ARMDecoderEmitter.h"
20 #include "CodeGenTarget.h"
22 #include "llvm/ADT/StringExtras.h"
23 #include "llvm/Support/Debug.h"
24 #include "llvm/Support/raw_ostream.h"
32 /////////////////////////////////////////////////////
34 // Enums and Utilities for ARM Instruction Format //
36 /////////////////////////////////////////////////////
39 ENTRY(ARM_FORMAT_PSEUDO, 0) \
40 ENTRY(ARM_FORMAT_MULFRM, 1) \
41 ENTRY(ARM_FORMAT_BRFRM, 2) \
42 ENTRY(ARM_FORMAT_BRMISCFRM, 3) \
43 ENTRY(ARM_FORMAT_DPFRM, 4) \
44 ENTRY(ARM_FORMAT_DPSOREGFRM, 5) \
45 ENTRY(ARM_FORMAT_LDFRM, 6) \
46 ENTRY(ARM_FORMAT_STFRM, 7) \
47 ENTRY(ARM_FORMAT_LDMISCFRM, 8) \
48 ENTRY(ARM_FORMAT_STMISCFRM, 9) \
49 ENTRY(ARM_FORMAT_LDSTMULFRM, 10) \
50 ENTRY(ARM_FORMAT_LDSTEXFRM, 11) \
51 ENTRY(ARM_FORMAT_ARITHMISCFRM, 12) \
52 ENTRY(ARM_FORMAT_EXTFRM, 13) \
53 ENTRY(ARM_FORMAT_VFPUNARYFRM, 14) \
54 ENTRY(ARM_FORMAT_VFPBINARYFRM, 15) \
55 ENTRY(ARM_FORMAT_VFPCONV1FRM, 16) \
56 ENTRY(ARM_FORMAT_VFPCONV2FRM, 17) \
57 ENTRY(ARM_FORMAT_VFPCONV3FRM, 18) \
58 ENTRY(ARM_FORMAT_VFPCONV4FRM, 19) \
59 ENTRY(ARM_FORMAT_VFPCONV5FRM, 20) \
60 ENTRY(ARM_FORMAT_VFPLDSTFRM, 21) \
61 ENTRY(ARM_FORMAT_VFPLDSTMULFRM, 22) \
62 ENTRY(ARM_FORMAT_VFPMISCFRM, 23) \
63 ENTRY(ARM_FORMAT_THUMBFRM, 24) \
64 ENTRY(ARM_FORMAT_NEONFRM, 25) \
65 ENTRY(ARM_FORMAT_NEONGETLNFRM, 26) \
66 ENTRY(ARM_FORMAT_NEONSETLNFRM, 27) \
67 ENTRY(ARM_FORMAT_NEONDUPFRM, 28) \
68 ENTRY(ARM_FORMAT_MISCFRM, 29) \
69 ENTRY(ARM_FORMAT_THUMBMISCFRM, 30) \
70 ENTRY(ARM_FORMAT_NLdSt, 31) \
71 ENTRY(ARM_FORMAT_N1RegModImm, 32) \
72 ENTRY(ARM_FORMAT_N2Reg, 33) \
73 ENTRY(ARM_FORMAT_NVCVT, 34) \
74 ENTRY(ARM_FORMAT_NVecDupLn, 35) \
75 ENTRY(ARM_FORMAT_N2RegVecShL, 36) \
76 ENTRY(ARM_FORMAT_N2RegVecShR, 37) \
77 ENTRY(ARM_FORMAT_N3Reg, 38) \
78 ENTRY(ARM_FORMAT_N3RegVecSh, 39) \
79 ENTRY(ARM_FORMAT_NVecExtract, 40) \
80 ENTRY(ARM_FORMAT_NVecMulScalar, 41) \
81 ENTRY(ARM_FORMAT_NVTBL, 42)
83 // ARM instruction format specifies the encoding used by the instruction.
84 #define ENTRY(n, v) n = v,
91 // Converts enum to const char*.
92 static const char *stringForARMFormat(ARMFormat form) {
93 #define ENTRY(n, v) case n: return #n;
110 /////////////////////////
112 // Utility functions //
114 /////////////////////////
116 /// byteFromBitsInit - Return the byte value from a BitsInit.
117 /// Called from getByteField().
118 static uint8_t byteFromBitsInit(BitsInit &init) {
119 int width = init.getNumBits();
121 assert(width <= 8 && "Field is too large for uint8_t!");
128 for (index = 0; index < width; index++) {
129 if (static_cast<BitInit*>(init.getBit(index))->getValue())
138 static uint8_t getByteField(const Record &def, const char *str) {
139 BitsInit *bits = def.getValueAsBitsInit(str);
140 return byteFromBitsInit(*bits);
143 static BitsInit &getBitsField(const Record &def, const char *str) {
144 BitsInit *bits = def.getValueAsBitsInit(str);
148 /// sameStringExceptSuffix - Return true if the two strings differ only in RHS's
149 /// suffix. ("VST4d8", "VST4d8_UPD", "_UPD") as input returns true.
151 bool sameStringExceptSuffix(const StringRef LHS, const StringRef RHS,
152 const StringRef Suffix) {
154 if (RHS.startswith(LHS) && RHS.endswith(Suffix))
155 return RHS.size() == LHS.size() + Suffix.size();
160 /// thumbInstruction - Determine whether we have a Thumb instruction.
161 /// See also ARMInstrFormats.td.
162 static bool thumbInstruction(uint8_t Form) {
163 return Form == ARM_FORMAT_THUMBFRM;
166 // The set (BIT_TRUE, BIT_FALSE, BIT_UNSET) represents a ternary logic system
169 // BIT_UNFILTERED is used as the init value for a filter position. It is used
170 // only for filter processings.
175 BIT_UNFILTERED // unfiltered
178 static bool ValueSet(bit_value_t V) {
179 return (V == BIT_TRUE || V == BIT_FALSE);
181 static bool ValueNotSet(bit_value_t V) {
182 return (V == BIT_UNSET);
184 static int Value(bit_value_t V) {
185 return ValueNotSet(V) ? -1 : (V == BIT_FALSE ? 0 : 1);
187 static bit_value_t bitFromBits(BitsInit &bits, unsigned index) {
188 if (BitInit *bit = dynamic_cast<BitInit*>(bits.getBit(index)))
189 return bit->getValue() ? BIT_TRUE : BIT_FALSE;
191 // The bit is uninitialized.
194 // Prints the bit value for each position.
195 static void dumpBits(raw_ostream &o, BitsInit &bits) {
198 for (index = bits.getNumBits(); index > 0; index--) {
199 switch (bitFromBits(bits, index - 1)) {
210 assert(0 && "unexpected return value from bitFromBits");
215 // Enums for the available target names.
221 // FIXME: Possibly auto-detected?
224 // Forward declaration.
227 // Representation of the instruction to work on.
228 typedef bit_value_t insn_t[BIT_WIDTH];
230 /// Filter - Filter works with FilterChooser to produce the decoding tree for
233 /// It is useful to think of a Filter as governing the switch stmts of the
234 /// decoding tree in a certain level. Each case stmt delegates to an inferior
235 /// FilterChooser to decide what further decoding logic to employ, or in another
236 /// words, what other remaining bits to look at. The FilterChooser eventually
237 /// chooses a best Filter to do its job.
239 /// This recursive scheme ends when the number of Opcodes assigned to the
240 /// FilterChooser becomes 1 or if there is a conflict. A conflict happens when
241 /// the Filter/FilterChooser combo does not know how to distinguish among the
242 /// Opcodes assigned.
244 /// An example of a conflcit is
247 /// 111101000.00........00010000....
248 /// 111101000.00........0001........
249 /// 1111010...00........0001........
250 /// 1111010...00....................
251 /// 1111010.........................
252 /// 1111............................
253 /// ................................
254 /// VST4q8a 111101000_00________00010000____
255 /// VST4q8b 111101000_00________00010000____
257 /// The Debug output shows the path that the decoding tree follows to reach the
258 /// the conclusion that there is a conflict. VST4q8a is a vst4 to double-spaced
259 /// even registers, while VST4q8b is a vst4 to double-spaced odd regsisters.
261 /// The encoding info in the .td files does not specify this meta information,
262 /// which could have been used by the decoder to resolve the conflict. The
263 /// decoder could try to decode the even/odd register numbering and assign to
264 /// VST4q8a or VST4q8b, but for the time being, the decoder chooses the "a"
265 /// version and return the Opcode since the two have the same Asm format string.
268 FilterChooser *Owner; // points to the FilterChooser who owns this filter
269 unsigned StartBit; // the starting bit position
270 unsigned NumBits; // number of bits to filter
271 bool Mixed; // a mixed region contains both set and unset bits
273 // Map of well-known segment value to the set of uid's with that value.
274 std::map<uint64_t, std::vector<unsigned> > FilteredInstructions;
276 // Set of uid's with non-constant segment values.
277 std::vector<unsigned> VariableInstructions;
279 // Map of well-known segment value to its delegate.
280 std::map<unsigned, FilterChooser*> FilterChooserMap;
282 // Number of instructions which fall under FilteredInstructions category.
283 unsigned NumFiltered;
285 // Keeps track of the last opcode in the filtered bucket.
286 unsigned LastOpcFiltered;
288 // Number of instructions which fall under VariableInstructions category.
289 unsigned NumVariable;
292 unsigned getNumFiltered() { return NumFiltered; }
293 unsigned getNumVariable() { return NumVariable; }
294 unsigned getSingletonOpc() {
295 assert(NumFiltered == 1);
296 return LastOpcFiltered;
298 // Return the filter chooser for the group of instructions without constant
300 FilterChooser &getVariableFC() {
301 assert(NumFiltered == 1);
302 assert(FilterChooserMap.size() == 1);
303 return *(FilterChooserMap.find((unsigned)-1)->second);
306 Filter(const Filter &f);
307 Filter(FilterChooser &owner, unsigned startBit, unsigned numBits, bool mixed);
311 // Divides the decoding task into sub tasks and delegates them to the
312 // inferior FilterChooser's.
314 // A special case arises when there's only one entry in the filtered
315 // instructions. In order to unambiguously decode the singleton, we need to
316 // match the remaining undecoded encoding bits against the singleton.
319 // Emit code to decode instructions given a segment or segments of bits.
320 void emit(raw_ostream &o, unsigned &Indentation);
322 // Returns the number of fanout produced by the filter. More fanout implies
323 // the filter distinguishes more categories of instructions.
324 unsigned usefulness() const;
325 }; // End of class Filter
327 // These are states of our finite state machines used in FilterChooser's
328 // filterProcessor() which produces the filter candidates to use.
337 /// FilterChooser - FilterChooser chooses the best filter among a set of Filters
338 /// in order to perform the decoding of instructions at the current level.
340 /// Decoding proceeds from the top down. Based on the well-known encoding bits
341 /// of instructions available, FilterChooser builds up the possible Filters that
342 /// can further the task of decoding by distinguishing among the remaining
343 /// candidate instructions.
345 /// Once a filter has been chosen, it is called upon to divide the decoding task
346 /// into sub-tasks and delegates them to its inferior FilterChoosers for further
349 /// It is useful to think of a Filter as governing the switch stmts of the
350 /// decoding tree. And each case is delegated to an inferior FilterChooser to
351 /// decide what further remaining bits to look at.
352 class FilterChooser {
353 static TARGET_NAME_t TargetName;
358 // Vector of codegen instructions to choose our filter.
359 const std::vector<const CodeGenInstruction*> &AllInstructions;
361 // Vector of uid's for this filter chooser to work on.
362 const std::vector<unsigned> Opcodes;
364 // Vector of candidate filters.
365 std::vector<Filter> Filters;
367 // Array of bit values passed down from our parent.
368 // Set to all BIT_UNFILTERED's for Parent == NULL.
369 bit_value_t FilterBitValues[BIT_WIDTH];
371 // Links to the FilterChooser above us in the decoding tree.
372 FilterChooser *Parent;
374 // Index of the best filter from Filters.
378 static void setTargetName(TARGET_NAME_t tn) { TargetName = tn; }
380 FilterChooser(const FilterChooser &FC) :
381 AllInstructions(FC.AllInstructions), Opcodes(FC.Opcodes),
382 Filters(FC.Filters), Parent(FC.Parent), BestIndex(FC.BestIndex) {
383 memcpy(FilterBitValues, FC.FilterBitValues, sizeof(FilterBitValues));
386 FilterChooser(const std::vector<const CodeGenInstruction*> &Insts,
387 const std::vector<unsigned> &IDs) :
388 AllInstructions(Insts), Opcodes(IDs), Filters(), Parent(NULL),
390 for (unsigned i = 0; i < BIT_WIDTH; ++i)
391 FilterBitValues[i] = BIT_UNFILTERED;
396 FilterChooser(const std::vector<const CodeGenInstruction*> &Insts,
397 const std::vector<unsigned> &IDs,
398 bit_value_t (&ParentFilterBitValues)[BIT_WIDTH],
399 FilterChooser &parent) :
400 AllInstructions(Insts), Opcodes(IDs), Filters(), Parent(&parent),
402 for (unsigned i = 0; i < BIT_WIDTH; ++i)
403 FilterBitValues[i] = ParentFilterBitValues[i];
408 // The top level filter chooser has NULL as its parent.
409 bool isTopLevel() { return Parent == NULL; }
411 // This provides an opportunity for target specific code emission.
412 void emitTopHook(raw_ostream &o);
414 // Emit the top level typedef and decodeInstruction() function.
415 void emitTop(raw_ostream &o, unsigned &Indentation);
417 // This provides an opportunity for target specific code emission after
419 void emitBot(raw_ostream &o, unsigned &Indentation);
422 // Populates the insn given the uid.
423 void insnWithID(insn_t &Insn, unsigned Opcode) const {
424 BitsInit &Bits = getBitsField(*AllInstructions[Opcode]->TheDef, "Inst");
426 for (unsigned i = 0; i < BIT_WIDTH; ++i)
427 Insn[i] = bitFromBits(Bits, i);
429 // Set Inst{21} to 1 (wback) when IndexModeBits == IndexModeUpd.
430 if (getByteField(*AllInstructions[Opcode]->TheDef, "IndexModeBits")
435 // Returns the record name.
436 const std::string &nameWithID(unsigned Opcode) const {
437 return AllInstructions[Opcode]->TheDef->getName();
440 // Populates the field of the insn given the start position and the number of
441 // consecutive bits to scan for.
443 // Returns false if there exists any uninitialized bit value in the range.
444 // Returns true, otherwise.
445 bool fieldFromInsn(uint64_t &Field, insn_t &Insn, unsigned StartBit,
446 unsigned NumBits) const;
448 /// dumpFilterArray - dumpFilterArray prints out debugging info for the given
449 /// filter array as a series of chars.
450 void dumpFilterArray(raw_ostream &o, bit_value_t (&filter)[BIT_WIDTH]);
452 /// dumpStack - dumpStack traverses the filter chooser chain and calls
453 /// dumpFilterArray on each filter chooser up to the top level one.
454 void dumpStack(raw_ostream &o, const char *prefix);
456 Filter &bestFilter() {
457 assert(BestIndex != -1 && "BestIndex not set");
458 return Filters[BestIndex];
461 // Called from Filter::recurse() when singleton exists. For debug purpose.
462 void SingletonExists(unsigned Opc);
464 bool PositionFiltered(unsigned i) {
465 return ValueSet(FilterBitValues[i]);
468 // Calculates the island(s) needed to decode the instruction.
469 // This returns a lit of undecoded bits of an instructions, for example,
470 // Inst{20} = 1 && Inst{3-0} == 0b1111 represents two islands of yet-to-be
471 // decoded bits in order to verify that the instruction matches the Opcode.
472 unsigned getIslands(std::vector<unsigned> &StartBits,
473 std::vector<unsigned> &EndBits, std::vector<uint64_t> &FieldVals,
476 // The purpose of this function is for the API client to detect possible
477 // Load/Store Coprocessor instructions. If the coprocessor number is of
478 // the instruction is either 10 or 11, the decoder should not report the
479 // instruction as LDC/LDC2/STC/STC2, but should match against Advanced SIMD or
481 bool LdStCopEncoding1(unsigned Opc) {
482 const std::string &Name = nameWithID(Opc);
483 if (Name == "LDC_OFFSET" || Name == "LDC_OPTION" ||
484 Name == "LDC_POST" || Name == "LDC_PRE" ||
485 Name == "LDCL_OFFSET" || Name == "LDCL_OPTION" ||
486 Name == "LDCL_POST" || Name == "LDCL_PRE" ||
487 Name == "STC_OFFSET" || Name == "STC_OPTION" ||
488 Name == "STC_POST" || Name == "STC_PRE" ||
489 Name == "STCL_OFFSET" || Name == "STCL_OPTION" ||
490 Name == "STCL_POST" || Name == "STCL_PRE")
496 // Emits code to decode the singleton. Return true if we have matched all the
498 bool emitSingletonDecoder(raw_ostream &o, unsigned &Indentation,unsigned Opc);
500 // Emits code to decode the singleton, and then to decode the rest.
501 void emitSingletonDecoder(raw_ostream &o, unsigned &Indentation,Filter &Best);
503 // Assign a single filter and run with it.
504 void runSingleFilter(FilterChooser &owner, unsigned startBit, unsigned numBit,
507 // reportRegion is a helper function for filterProcessor to mark a region as
508 // eligible for use as a filter region.
509 void reportRegion(bitAttr_t RA, unsigned StartBit, unsigned BitIndex,
512 // FilterProcessor scans the well-known encoding bits of the instructions and
513 // builds up a list of candidate filters. It chooses the best filter and
514 // recursively descends down the decoding tree.
515 bool filterProcessor(bool AllowMixed, bool Greedy = true);
517 // Decides on the best configuration of filter(s) to use in order to decode
518 // the instructions. A conflict of instructions may occur, in which case we
519 // dump the conflict set to the standard error.
522 // Emits code to decode our share of instructions. Returns true if the
523 // emitted code causes a return, which occurs if we know how to decode
524 // the instruction at this level or the instruction is not decodeable.
525 bool emit(raw_ostream &o, unsigned &Indentation);
528 ///////////////////////////
530 // Filter Implmenetation //
532 ///////////////////////////
534 Filter::Filter(const Filter &f) :
535 Owner(f.Owner), StartBit(f.StartBit), NumBits(f.NumBits), Mixed(f.Mixed),
536 FilteredInstructions(f.FilteredInstructions),
537 VariableInstructions(f.VariableInstructions),
538 FilterChooserMap(f.FilterChooserMap), NumFiltered(f.NumFiltered),
539 LastOpcFiltered(f.LastOpcFiltered), NumVariable(f.NumVariable) {
542 Filter::Filter(FilterChooser &owner, unsigned startBit, unsigned numBits,
543 bool mixed) : Owner(&owner), StartBit(startBit), NumBits(numBits),
545 assert(StartBit + NumBits - 1 < BIT_WIDTH);
551 for (unsigned i = 0, e = Owner->Opcodes.size(); i != e; ++i) {
554 // Populates the insn given the uid.
555 Owner->insnWithID(Insn, Owner->Opcodes[i]);
558 // Scans the segment for possibly well-specified encoding bits.
559 bool ok = Owner->fieldFromInsn(Field, Insn, StartBit, NumBits);
562 // The encoding bits are well-known. Lets add the uid of the
563 // instruction into the bucket keyed off the constant field value.
564 LastOpcFiltered = Owner->Opcodes[i];
565 FilteredInstructions[Field].push_back(LastOpcFiltered);
568 // Some of the encoding bit(s) are unspecfied. This contributes to
569 // one additional member of "Variable" instructions.
570 VariableInstructions.push_back(Owner->Opcodes[i]);
575 assert((FilteredInstructions.size() + VariableInstructions.size() > 0)
576 && "Filter returns no instruction categories");
580 std::map<unsigned, FilterChooser*>::iterator filterIterator;
581 for (filterIterator = FilterChooserMap.begin();
582 filterIterator != FilterChooserMap.end();
584 delete filterIterator->second;
588 // Divides the decoding task into sub tasks and delegates them to the
589 // inferior FilterChooser's.
591 // A special case arises when there's only one entry in the filtered
592 // instructions. In order to unambiguously decode the singleton, we need to
593 // match the remaining undecoded encoding bits against the singleton.
594 void Filter::recurse() {
595 std::map<uint64_t, std::vector<unsigned> >::const_iterator mapIterator;
597 bit_value_t BitValueArray[BIT_WIDTH];
598 // Starts by inheriting our parent filter chooser's filter bit values.
599 memcpy(BitValueArray, Owner->FilterBitValues, sizeof(BitValueArray));
603 if (VariableInstructions.size()) {
604 // Conservatively marks each segment position as BIT_UNSET.
605 for (bitIndex = 0; bitIndex < NumBits; bitIndex++)
606 BitValueArray[StartBit + bitIndex] = BIT_UNSET;
608 // Delegates to an inferior filter chooser for futher processing on this
609 // group of instructions whose segment values are variable.
610 FilterChooserMap.insert(std::pair<unsigned, FilterChooser*>(
612 new FilterChooser(Owner->AllInstructions,
613 VariableInstructions,
619 // No need to recurse for a singleton filtered instruction.
620 // See also Filter::emit().
621 if (getNumFiltered() == 1) {
622 //Owner->SingletonExists(LastOpcFiltered);
623 assert(FilterChooserMap.size() == 1);
627 // Otherwise, create sub choosers.
628 for (mapIterator = FilteredInstructions.begin();
629 mapIterator != FilteredInstructions.end();
632 // Marks all the segment positions with either BIT_TRUE or BIT_FALSE.
633 for (bitIndex = 0; bitIndex < NumBits; bitIndex++) {
634 if (mapIterator->first & (1ULL << bitIndex))
635 BitValueArray[StartBit + bitIndex] = BIT_TRUE;
637 BitValueArray[StartBit + bitIndex] = BIT_FALSE;
640 // Delegates to an inferior filter chooser for futher processing on this
641 // category of instructions.
642 FilterChooserMap.insert(std::pair<unsigned, FilterChooser*>(
644 new FilterChooser(Owner->AllInstructions,
652 // Emit code to decode instructions given a segment or segments of bits.
653 void Filter::emit(raw_ostream &o, unsigned &Indentation) {
654 o.indent(Indentation) << "// Check Inst{";
657 o << (StartBit + NumBits - 1) << '-';
659 o << StartBit << "} ...\n";
661 o.indent(Indentation) << "switch (fieldFromInstruction(insn, "
662 << StartBit << ", " << NumBits << ")) {\n";
664 std::map<unsigned, FilterChooser*>::iterator filterIterator;
666 bool DefaultCase = false;
667 for (filterIterator = FilterChooserMap.begin();
668 filterIterator != FilterChooserMap.end();
671 // Field value -1 implies a non-empty set of variable instructions.
672 // See also recurse().
673 if (filterIterator->first == (unsigned)-1) {
676 o.indent(Indentation) << "default:\n";
677 o.indent(Indentation) << " break; // fallthrough\n";
679 // Closing curly brace for the switch statement.
680 // This is unconventional because we want the default processing to be
681 // performed for the fallthrough cases as well, i.e., when the "cases"
682 // did not prove a decoded instruction.
683 o.indent(Indentation) << "}\n";
686 o.indent(Indentation) << "case " << filterIterator->first << ":\n";
688 // We arrive at a category of instructions with the same segment value.
689 // Now delegate to the sub filter chooser for further decodings.
690 // The case may fallthrough, which happens if the remaining well-known
691 // encoding bits do not match exactly.
692 if (!DefaultCase) { ++Indentation; ++Indentation; }
694 bool finished = filterIterator->second->emit(o, Indentation);
695 // For top level default case, there's no need for a break statement.
696 if (Owner->isTopLevel() && DefaultCase)
699 o.indent(Indentation) << "break;\n";
701 if (!DefaultCase) { --Indentation; --Indentation; }
704 // If there is no default case, we still need to supply a closing brace.
706 // Closing curly brace for the switch statement.
707 o.indent(Indentation) << "}\n";
711 // Returns the number of fanout produced by the filter. More fanout implies
712 // the filter distinguishes more categories of instructions.
713 unsigned Filter::usefulness() const {
714 if (VariableInstructions.size())
715 return FilteredInstructions.size();
717 return FilteredInstructions.size() + 1;
720 //////////////////////////////////
722 // Filterchooser Implementation //
724 //////////////////////////////////
726 // Define the symbol here.
727 TARGET_NAME_t FilterChooser::TargetName;
729 // This provides an opportunity for target specific code emission.
730 void FilterChooser::emitTopHook(raw_ostream &o) {
731 if (TargetName == TARGET_ARM) {
732 // Emit code that references the ARMFormat data type.
733 o << "static const ARMFormat ARMFormats[] = {\n";
734 for (unsigned i = 0, e = AllInstructions.size(); i != e; ++i) {
735 const Record &Def = *(AllInstructions[i]->TheDef);
736 const std::string &Name = Def.getName();
737 if (Def.isSubClassOf("InstARM") || Def.isSubClassOf("InstThumb"))
739 stringForARMFormat((ARMFormat)getByteField(Def, "Form"));
741 o << " ARM_FORMAT_NA";
743 o << ",\t// Inst #" << i << " = " << Name << '\n';
745 o << " ARM_FORMAT_NA\t// Unreachable.\n";
750 // Emit the top level typedef and decodeInstruction() function.
751 void FilterChooser::emitTop(raw_ostream &o, unsigned &Indentation) {
752 // Run the target specific emit hook.
757 o.indent(Indentation) << "typedef uint8_t field_t;\n";
760 o.indent(Indentation) << "typedef uint16_t field_t;\n";
763 o.indent(Indentation) << "typedef uint32_t field_t;\n";
766 o.indent(Indentation) << "typedef uint64_t field_t;\n";
769 assert(0 && "Unexpected instruction size!");
774 o.indent(Indentation) << "static field_t " <<
775 "fieldFromInstruction(field_t insn, unsigned startBit, unsigned numBits)\n";
777 o.indent(Indentation) << "{\n";
779 ++Indentation; ++Indentation;
780 o.indent(Indentation) << "assert(startBit + numBits <= " << BIT_WIDTH
781 << " && \"Instruction field out of bounds!\");\n";
783 o.indent(Indentation) << "field_t fieldMask;\n";
785 o.indent(Indentation) << "if (numBits == " << BIT_WIDTH << ")\n";
787 ++Indentation; ++Indentation;
788 o.indent(Indentation) << "fieldMask = (field_t)-1;\n";
789 --Indentation; --Indentation;
791 o.indent(Indentation) << "else\n";
793 ++Indentation; ++Indentation;
794 o.indent(Indentation) << "fieldMask = ((1 << numBits) - 1) << startBit;\n";
795 --Indentation; --Indentation;
798 o.indent(Indentation) << "return (insn & fieldMask) >> startBit;\n";
799 --Indentation; --Indentation;
801 o.indent(Indentation) << "}\n";
805 o.indent(Indentation) << "static uint16_t decodeInstruction(field_t insn) {\n";
807 ++Indentation; ++Indentation;
808 // Emits code to decode the instructions.
809 emit(o, Indentation);
812 o.indent(Indentation) << "return 0;\n";
813 --Indentation; --Indentation;
815 o.indent(Indentation) << "}\n";
820 // This provides an opportunity for target specific code emission after
822 void FilterChooser::emitBot(raw_ostream &o, unsigned &Indentation) {
823 if (TargetName != TARGET_THUMB) return;
825 // Emit code that decodes the Thumb ISA.
826 o.indent(Indentation)
827 << "static uint16_t decodeThumbInstruction(field_t insn) {\n";
829 ++Indentation; ++Indentation;
831 // Emits code to decode the instructions.
832 emit(o, Indentation);
835 o.indent(Indentation) << "return 0;\n";
837 --Indentation; --Indentation;
839 o.indent(Indentation) << "}\n";
842 // Populates the field of the insn given the start position and the number of
843 // consecutive bits to scan for.
845 // Returns false if and on the first uninitialized bit value encountered.
846 // Returns true, otherwise.
847 bool FilterChooser::fieldFromInsn(uint64_t &Field, insn_t &Insn,
848 unsigned StartBit, unsigned NumBits) const {
851 for (unsigned i = 0; i < NumBits; ++i) {
852 if (Insn[StartBit + i] == BIT_UNSET)
855 if (Insn[StartBit + i] == BIT_TRUE)
856 Field = Field | (1ULL << i);
862 /// dumpFilterArray - dumpFilterArray prints out debugging info for the given
863 /// filter array as a series of chars.
864 void FilterChooser::dumpFilterArray(raw_ostream &o,
865 bit_value_t (&filter)[BIT_WIDTH]) {
868 for (bitIndex = BIT_WIDTH; bitIndex > 0; bitIndex--) {
869 switch (filter[bitIndex - 1]) {
886 /// dumpStack - dumpStack traverses the filter chooser chain and calls
887 /// dumpFilterArray on each filter chooser up to the top level one.
888 void FilterChooser::dumpStack(raw_ostream &o, const char *prefix) {
889 FilterChooser *current = this;
893 dumpFilterArray(o, current->FilterBitValues);
895 current = current->Parent;
899 // Called from Filter::recurse() when singleton exists. For debug purpose.
900 void FilterChooser::SingletonExists(unsigned Opc) {
902 insnWithID(Insn0, Opc);
904 errs() << "Singleton exists: " << nameWithID(Opc)
905 << " with its decoding dominating ";
906 for (unsigned i = 0; i < Opcodes.size(); ++i) {
907 if (Opcodes[i] == Opc) continue;
908 errs() << nameWithID(Opcodes[i]) << ' ';
912 dumpStack(errs(), "\t\t");
913 for (unsigned i = 0; i < Opcodes.size(); i++) {
914 const std::string &Name = nameWithID(Opcodes[i]);
916 errs() << '\t' << Name << " ";
918 getBitsField(*AllInstructions[Opcodes[i]]->TheDef, "Inst"));
923 // Calculates the island(s) needed to decode the instruction.
924 // This returns a list of undecoded bits of an instructions, for example,
925 // Inst{20} = 1 && Inst{3-0} == 0b1111 represents two islands of yet-to-be
926 // decoded bits in order to verify that the instruction matches the Opcode.
927 unsigned FilterChooser::getIslands(std::vector<unsigned> &StartBits,
928 std::vector<unsigned> &EndBits, std::vector<uint64_t> &FieldVals,
933 uint64_t FieldVal = 0;
936 // 1: Water (the bit value does not affect decoding)
937 // 2: Island (well-known bit value needed for decoding)
941 for (unsigned i = 0; i < BIT_WIDTH; ++i) {
942 Val = Value(Insn[i]);
943 bool Filtered = PositionFiltered(i);
946 assert(0 && "Unreachable code!");
950 if (Filtered || Val == -1)
951 State = 1; // Still in Water
953 State = 2; // Into the Island
955 StartBits.push_back(i);
960 if (Filtered || Val == -1) {
961 State = 1; // Into the Water
962 EndBits.push_back(i - 1);
963 FieldVals.push_back(FieldVal);
966 State = 2; // Still in Island
968 FieldVal = FieldVal | Val << BitNo;
973 // If we are still in Island after the loop, do some housekeeping.
975 EndBits.push_back(BIT_WIDTH - 1);
976 FieldVals.push_back(FieldVal);
980 assert(StartBits.size() == Num && EndBits.size() == Num &&
981 FieldVals.size() == Num);
985 // Emits code to decode the singleton. Return true if we have matched all the
987 bool FilterChooser::emitSingletonDecoder(raw_ostream &o, unsigned &Indentation,
989 std::vector<unsigned> StartBits;
990 std::vector<unsigned> EndBits;
991 std::vector<uint64_t> FieldVals;
993 insnWithID(Insn, Opc);
995 // This provides a good opportunity to check for possible Ld/St Coprocessor
996 // Opcode and escapes if the coproc # is either 10 or 11. It is a NEON/VFP
997 // instruction is disguise.
998 if (TargetName == TARGET_ARM && LdStCopEncoding1(Opc)) {
999 o.indent(Indentation);
1000 // A8.6.51 & A8.6.188
1001 // If coproc = 0b101?, i.e, slice(insn, 11, 8) = 10 or 11, escape.
1002 o << "if (fieldFromInstruction(insn, 9, 3) == 5) break; // fallthrough\n";
1005 // Look for islands of undecoded bits of the singleton.
1006 getIslands(StartBits, EndBits, FieldVals, Insn);
1008 unsigned Size = StartBits.size();
1009 unsigned I, NumBits;
1011 // If we have matched all the well-known bits, just issue a return.
1013 o.indent(Indentation) << "return " << Opc << "; // " << nameWithID(Opc)
1018 // Otherwise, there are more decodings to be done!
1020 // Emit code to match the island(s) for the singleton.
1021 o.indent(Indentation) << "// Check ";
1023 for (I = Size; I != 0; --I) {
1024 o << "Inst{" << EndBits[I-1] << '-' << StartBits[I-1] << "} ";
1028 o << "for singleton decoding...\n";
1031 o.indent(Indentation) << "if (";
1033 for (I = Size; I != 0; --I) {
1034 NumBits = EndBits[I-1] - StartBits[I-1] + 1;
1035 o << "fieldFromInstruction(insn, " << StartBits[I-1] << ", " << NumBits
1036 << ") == " << FieldVals[I-1];
1043 o.indent(Indentation) << " return " << Opc << "; // " << nameWithID(Opc)
1049 // Emits code to decode the singleton, and then to decode the rest.
1050 void FilterChooser::emitSingletonDecoder(raw_ostream &o, unsigned &Indentation,
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(FilterChooser &owner, unsigned startBit,
1068 unsigned numBit, bool mixed) {
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(*this, StartBits[0], EndBits[0] - StartBits[0] + 1,
1123 unsigned BitIndex, InsnIndex;
1125 // We maintain BIT_WIDTH copies of the bitAttrs automaton.
1126 // The automaton consumes the corresponding bit from each
1129 // Input symbols: 0, 1, and _ (unset).
1130 // States: NONE, FILTERED, ALL_SET, ALL_UNSET, and MIXED.
1131 // Initial state: NONE.
1133 // (NONE) ------- [01] -> (ALL_SET)
1134 // (NONE) ------- _ ----> (ALL_UNSET)
1135 // (ALL_SET) ---- [01] -> (ALL_SET)
1136 // (ALL_SET) ---- _ ----> (MIXED)
1137 // (ALL_UNSET) -- [01] -> (MIXED)
1138 // (ALL_UNSET) -- _ ----> (ALL_UNSET)
1139 // (MIXED) ------ . ----> (MIXED)
1140 // (FILTERED)---- . ----> (FILTERED)
1142 bitAttr_t bitAttrs[BIT_WIDTH];
1144 // FILTERED bit positions provide no entropy and are not worthy of pursuing.
1145 // Filter::recurse() set either BIT_TRUE or BIT_FALSE for each position.
1146 for (BitIndex = 0; BitIndex < BIT_WIDTH; ++BitIndex)
1147 if (FilterBitValues[BitIndex] == BIT_TRUE ||
1148 FilterBitValues[BitIndex] == BIT_FALSE)
1149 bitAttrs[BitIndex] = ATTR_FILTERED;
1151 bitAttrs[BitIndex] = ATTR_NONE;
1153 for (InsnIndex = 0; InsnIndex < numInstructions; ++InsnIndex) {
1156 insnWithID(insn, Opcodes[InsnIndex]);
1158 for (BitIndex = 0; BitIndex < BIT_WIDTH; ++BitIndex) {
1159 switch (bitAttrs[BitIndex]) {
1161 if (insn[BitIndex] == BIT_UNSET)
1162 bitAttrs[BitIndex] = ATTR_ALL_UNSET;
1164 bitAttrs[BitIndex] = ATTR_ALL_SET;
1167 if (insn[BitIndex] == BIT_UNSET)
1168 bitAttrs[BitIndex] = ATTR_MIXED;
1170 case ATTR_ALL_UNSET:
1171 if (insn[BitIndex] != BIT_UNSET)
1172 bitAttrs[BitIndex] = ATTR_MIXED;
1181 // The regionAttr automaton consumes the bitAttrs automatons' state,
1182 // lowest-to-highest.
1184 // Input symbols: F(iltered), (all_)S(et), (all_)U(nset), M(ixed)
1185 // States: NONE, ALL_SET, MIXED
1186 // Initial state: NONE
1188 // (NONE) ----- F --> (NONE)
1189 // (NONE) ----- S --> (ALL_SET) ; and set region start
1190 // (NONE) ----- U --> (NONE)
1191 // (NONE) ----- M --> (MIXED) ; and set region start
1192 // (ALL_SET) -- F --> (NONE) ; and report an ALL_SET region
1193 // (ALL_SET) -- S --> (ALL_SET)
1194 // (ALL_SET) -- U --> (NONE) ; and report an ALL_SET region
1195 // (ALL_SET) -- M --> (MIXED) ; and report an ALL_SET region
1196 // (MIXED) ---- F --> (NONE) ; and report a MIXED region
1197 // (MIXED) ---- S --> (ALL_SET) ; and report a MIXED region
1198 // (MIXED) ---- U --> (NONE) ; and report a MIXED region
1199 // (MIXED) ---- M --> (MIXED)
1201 bitAttr_t RA = ATTR_NONE;
1202 unsigned StartBit = 0;
1204 for (BitIndex = 0; BitIndex < BIT_WIDTH; BitIndex++) {
1205 bitAttr_t bitAttr = bitAttrs[BitIndex];
1207 assert(bitAttr != ATTR_NONE && "Bit without attributes");
1215 StartBit = BitIndex;
1218 case ATTR_ALL_UNSET:
1221 StartBit = BitIndex;
1225 assert(0 && "Unexpected bitAttr!");
1231 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1236 case ATTR_ALL_UNSET:
1237 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1241 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1242 StartBit = BitIndex;
1246 assert(0 && "Unexpected bitAttr!");
1252 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1253 StartBit = BitIndex;
1257 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1258 StartBit = BitIndex;
1261 case ATTR_ALL_UNSET:
1262 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1268 assert(0 && "Unexpected bitAttr!");
1271 case ATTR_ALL_UNSET:
1272 assert(0 && "regionAttr state machine has no ATTR_UNSET state");
1274 assert(0 && "regionAttr state machine has no ATTR_FILTERED state");
1278 // At the end, if we're still in ALL_SET or MIXED states, report a region
1285 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1287 case ATTR_ALL_UNSET:
1290 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1294 // We have finished with the filter processings. Now it's time to choose
1295 // the best performing filter.
1297 bool AllUseless = true;
1298 unsigned BestScore = 0;
1300 for (unsigned i = 0, e = Filters.size(); i != e; ++i) {
1301 unsigned Usefulness = Filters[i].usefulness();
1306 if (Usefulness > BestScore) {
1308 BestScore = Usefulness;
1313 bestFilter().recurse();
1316 } // end of FilterChooser::filterProcessor(bool)
1318 // Decides on the best configuration of filter(s) to use in order to decode
1319 // the instructions. A conflict of instructions may occur, in which case we
1320 // dump the conflict set to the standard error.
1321 void FilterChooser::doFilter() {
1322 unsigned Num = Opcodes.size();
1323 assert(Num && "FilterChooser created with no instructions");
1325 // Heuristics: Use Inst{31-28} as the top level filter for ARM ISA.
1326 if (TargetName == TARGET_ARM && Parent == NULL) {
1327 runSingleFilter(*this, 28, 4, false);
1331 // Try regions of consecutive known bit values first.
1332 if (filterProcessor(false))
1335 // Then regions of mixed bits (both known and unitialized bit values allowed).
1336 if (filterProcessor(true))
1339 // Heuristics to cope with conflict set {t2CMPrs, t2SUBSrr, t2SUBSrs} where
1340 // no single instruction for the maximum ATTR_MIXED region Inst{14-4} has a
1341 // well-known encoding pattern. In such case, we backtrack and scan for the
1342 // the very first consecutive ATTR_ALL_SET region and assign a filter to it.
1343 if (Num == 3 && filterProcessor(true, false))
1346 // If we come to here, the instruction decoding has failed.
1347 // Print out the instructions in the conflict set...
1351 errs() << "Conflict:\n";
1353 dumpStack(errs(), "\t\t");
1355 for (unsigned i = 0; i < Num; i++) {
1356 const std::string &Name = nameWithID(Opcodes[i]);
1358 errs() << '\t' << Name << " ";
1360 getBitsField(*AllInstructions[Opcodes[i]]->TheDef, "Inst"));
1366 // Emits code to decode our share of instructions. Returns true if the
1367 // emitted code causes a return, which occurs if we know how to decode
1368 // the instruction at this level or the instruction is not decodeable.
1369 bool FilterChooser::emit(raw_ostream &o, unsigned &Indentation) {
1370 if (Opcodes.size() == 1)
1371 // There is only one instruction in the set, which is great!
1372 // Call emitSingletonDecoder() to see whether there are any remaining
1374 return emitSingletonDecoder(o, Indentation, Opcodes[0]);
1376 // Choose the best filter to do the decodings!
1377 if (BestIndex != -1) {
1378 Filter &Best = bestFilter();
1379 if (Best.getNumFiltered() == 1)
1380 emitSingletonDecoder(o, Indentation, Best);
1382 bestFilter().emit(o, Indentation);
1386 // If we reach here, there is a conflict in decoding. Let's resolve the known
1388 if ((TargetName == TARGET_ARM || TargetName == TARGET_THUMB) &&
1389 Opcodes.size() == 2) {
1390 // Resolve the known conflict sets:
1392 // 1. source registers are identical => VMOVDneon; otherwise => VORRd
1393 // 2. source registers are identical => VMOVQ; otherwise => VORRq
1394 // 3. LDR, LDRcp => return LDR for now.
1395 // FIXME: How can we distinguish between LDR and LDRcp? Do we need to?
1396 // 4. tLDM, tLDM_UPD => Rn = Inst{10-8}, reglist = Inst{7-0},
1397 // wback = registers<Rn> = 0
1398 // NOTE: (tLDM, tLDM_UPD) resolution must come before Advanced SIMD
1399 // addressing mode resolution!!!
1400 // 5. VLD[234]LN*/VST[234]LN* vs. VLD[234]LN*_UPD/VST[234]LN*_UPD conflicts
1401 // are resolved returning the non-UPD versions of the instructions if the
1402 // Rm field, i.e., Inst{3-0} is 0b1111. This is specified in A7.7.1
1403 // Advanced SIMD addressing mode.
1404 const std::string &name1 = nameWithID(Opcodes[0]);
1405 const std::string &name2 = nameWithID(Opcodes[1]);
1406 if ((name1 == "VMOVDneon" && name2 == "VORRd") ||
1407 (name1 == "VMOVQ" && name2 == "VORRq")) {
1408 // Inserting the opening curly brace for this case block.
1409 --Indentation; --Indentation;
1410 o.indent(Indentation) << "{\n";
1411 ++Indentation; ++Indentation;
1413 o.indent(Indentation)
1414 << "field_t N = fieldFromInstruction(insn, 7, 1), "
1415 << "M = fieldFromInstruction(insn, 5, 1);\n";
1416 o.indent(Indentation)
1417 << "field_t Vn = fieldFromInstruction(insn, 16, 4), "
1418 << "Vm = fieldFromInstruction(insn, 0, 4);\n";
1419 o.indent(Indentation)
1420 << "return (N == M && Vn == Vm) ? "
1421 << Opcodes[0] << " /* " << name1 << " */ : "
1422 << Opcodes[1] << " /* " << name2 << " */ ;\n";
1424 // Inserting the closing curly brace for this case block.
1425 --Indentation; --Indentation;
1426 o.indent(Indentation) << "}\n";
1427 ++Indentation; ++Indentation;
1431 if (name1 == "LDR" && name2 == "LDRcp") {
1432 o.indent(Indentation)
1433 << "return " << Opcodes[0]
1434 << "; // Returning LDR for {LDR, LDRcp}\n";
1437 if (name1 == "tLDM" && name2 == "tLDM_UPD") {
1438 // Inserting the opening curly brace for this case block.
1439 --Indentation; --Indentation;
1440 o.indent(Indentation) << "{\n";
1441 ++Indentation; ++Indentation;
1443 o.indent(Indentation)
1444 << "unsigned Rn = fieldFromInstruction(insn, 8, 3), "
1445 << "list = fieldFromInstruction(insn, 0, 8);\n";
1446 o.indent(Indentation)
1447 << "return ((list >> Rn) & 1) == 0 ? "
1448 << Opcodes[1] << " /* " << name2 << " */ : "
1449 << Opcodes[0] << " /* " << name1 << " */ ;\n";
1451 // Inserting the closing curly brace for this case block.
1452 --Indentation; --Indentation;
1453 o.indent(Indentation) << "}\n";
1454 ++Indentation; ++Indentation;
1458 if (sameStringExceptSuffix(name1, name2, "_UPD")) {
1459 o.indent(Indentation)
1460 << "return fieldFromInstruction(insn, 0, 4) == 15 ? " << Opcodes[0]
1461 << " /* " << name1 << " */ : " << Opcodes[1] << "/* " << name2
1462 << " */ ; // Advanced SIMD addressing mode\n";
1466 // Otherwise, it does not belong to the known conflict sets.
1468 // We don't know how to decode these instructions! Dump the conflict set!
1469 o.indent(Indentation) << "return 0;" << " // Conflict set: ";
1470 for (int i = 0, N = Opcodes.size(); i < N; ++i) {
1471 o << nameWithID(Opcodes[i]);
1481 ////////////////////////////////////////////
1484 // (Helper class for ARMDecoderEmitter) //
1486 ////////////////////////////////////////////
1488 class ARMDecoderEmitter::ARMDEBackend {
1490 ARMDEBackend(ARMDecoderEmitter &frontend) :
1491 NumberedInstructions(),
1497 if (Target.getName() == "ARM")
1498 TargetName = TARGET_ARM;
1500 errs() << "Target name " << Target.getName() << " not recognized\n";
1501 assert(0 && "Unknown target");
1504 // Populate the instructions for our TargetName.
1505 populateInstructions();
1515 void getInstructionsByEnumValue(std::vector<const CodeGenInstruction*>
1516 &NumberedInstructions) {
1517 // We must emit the PHI opcode first...
1518 std::string Namespace = Target.getInstNamespace();
1519 assert(!Namespace.empty() && "No instructions defined.");
1521 NumberedInstructions = Target.getInstructionsByEnumValue();
1524 bool populateInstruction(const CodeGenInstruction &CGI, TARGET_NAME_t TN);
1526 void populateInstructions();
1528 // Emits disassembler code for instruction decoding. This delegates to the
1529 // FilterChooser instance to do the heavy lifting.
1530 void emit(raw_ostream &o);
1533 std::vector<const CodeGenInstruction*> NumberedInstructions;
1534 std::vector<unsigned> Opcodes;
1535 // Special case for the ARM chip, which supports ARM and Thumb ISAs.
1536 // Opcodes2 will be populated with the Thumb opcodes.
1537 std::vector<unsigned> Opcodes2;
1538 ARMDecoderEmitter &Frontend;
1539 CodeGenTarget Target;
1542 TARGET_NAME_t TargetName;
1545 bool ARMDecoderEmitter::ARMDEBackend::populateInstruction(
1546 const CodeGenInstruction &CGI, TARGET_NAME_t TN) {
1547 const Record &Def = *CGI.TheDef;
1548 const StringRef Name = Def.getName();
1549 uint8_t Form = getByteField(Def, "Form");
1551 if (TN == TARGET_ARM) {
1552 // FIXME: what about Int_MemBarrierV6 and Int_SyncBarrierV6?
1553 if ((Name != "Int_MemBarrierV7" && Name != "Int_SyncBarrierV7") &&
1554 Form == ARM_FORMAT_PSEUDO)
1556 if (thumbInstruction(Form))
1558 if (Name.find("CMPz") != std::string::npos /* ||
1559 Name.find("CMNz") != std::string::npos */)
1562 // Ignore pseudo instructions.
1563 if (Name == "BXr9" || Name == "BMOVPCRX" || Name == "BMOVPCRXr9")
1566 // VLDMQ/VSTMQ can be hanlded with the more generic VLDMD/VSTMD.
1567 if (Name == "VLDMQ" || Name == "VLDMQ_UPD" ||
1568 Name == "VSTMQ" || Name == "VSTMQ_UPD")
1572 // The following special cases are for conflict resolutions.
1575 // NEON NLdStFrm conflict resolutions:
1577 // 1. Ignore suffix "odd" and "odd_UPD", prefer the "even" register-
1578 // numbered ones which have the same Asm format string.
1579 // 2. Ignore VST2d64_UPD, which conflicts with VST1q64_UPD.
1580 // 3. Ignore VLD2d64_UPD, which conflicts with VLD1q64_UPD.
1581 // 4. Ignore VLD1q[_UPD], which conflicts with VLD1q64[_UPD].
1582 // 5. Ignore VST1q[_UPD], which conflicts with VST1q64[_UPD].
1583 if (Name.endswith("odd") || Name.endswith("odd_UPD") ||
1584 Name == "VST2d64_UPD" || Name == "VLD2d64_UPD" ||
1585 Name == "VLD1q" || Name == "VLD1q_UPD" ||
1586 Name == "VST1q" || Name == "VST1q_UPD")
1589 // RSCSri and RSCSrs set the 's' bit, but are not predicated. We are
1590 // better off using the generic RSCri and RSCrs instructions.
1591 if (Name == "RSCSri" || Name == "RSCSrs") return false;
1593 // MOVCCr, MOVCCs, MOVCCi, FCYPScc, FCYPDcc, FNEGScc, and FNEGDcc are used
1594 // in the compiler to implement conditional moves. We can ignore them in
1595 // favor of their more generic versions of instructions.
1596 // See also SDNode *ARMDAGToDAGISel::Select(SDValue Op).
1597 if (Name == "MOVCCr" || Name == "MOVCCs" || Name == "MOVCCi" ||
1598 Name == "FCPYScc" || Name == "FCPYDcc" ||
1599 Name == "FNEGScc" || Name == "FNEGDcc")
1602 // Ditto for VMOVDcc, VMOVScc, VNEGDcc, and VNEGScc.
1603 if (Name == "VMOVDcc" || Name == "VMOVScc" || Name == "VNEGDcc" ||
1607 // Ignore the *_sfp instructions when decoding. They are used by the
1608 // compiler to implement scalar floating point operations using vector
1609 // operations in order to work around some performance issues.
1610 if (Name.find("_sfp") != std::string::npos) return false;
1612 // LDM_RET is a special case of LDM (Load Multiple) where the registers
1613 // loaded include the PC, causing a branch to a loaded address. Ignore
1614 // the LDM_RET instruction when decoding.
1615 if (Name == "LDM_RET") return false;
1617 // Bcc is in a more generic form than B. Ignore B when decoding.
1618 if (Name == "B") return false;
1620 // Ignore the non-Darwin BL instructions and the TPsoft (TLS) instruction.
1621 if (Name == "BL" || Name == "BL_pred" || Name == "BLX" || Name == "BX" ||
1625 // Ignore VDUPf[d|q] instructions known to conflict with VDUP32[d-q] for
1626 // decoding. The instruction duplicates an element from an ARM core
1627 // register into every element of the destination vector. There is no
1628 // distinction between data types.
1629 if (Name == "VDUPfd" || Name == "VDUPfq") return false;
1632 // Vector Extract extracts elements from the bottom end of the second
1633 // operand vector and the top end of the first, concatenates them and
1634 // places the result in the destination vector. The elements of the
1635 // vectors are treated as being 8-bit bitfields. There is no distinction
1636 // between data types. The size of the operation can be specified in
1637 // assembler as vext.size. If the value is 16, 32, or 64, the syntax is
1638 // a pseudo-instruction for a VEXT instruction specifying the equivalent
1641 // Variants VEXTd16, VEXTd32, VEXTd8, and VEXTdf are reduced to VEXTd8;
1642 // variants VEXTq16, VEXTq32, VEXTq8, and VEXTqf are reduced to VEXTq8.
1643 if (Name == "VEXTd16" || Name == "VEXTd32" || Name == "VEXTdf" ||
1644 Name == "VEXTq16" || Name == "VEXTq32" || Name == "VEXTqf")
1647 // Vector Reverse is similar to Vector Extract. There is no distinction
1648 // between data types, other than size.
1650 // VREV64df is equivalent to VREV64d32.
1651 // VREV64qf is equivalent to VREV64q32.
1652 if (Name == "VREV64df" || Name == "VREV64qf") return false;
1654 // VDUPLNfd is equivalent to VDUPLN32d; VDUPfdf is specialized VDUPLN32d.
1655 // VDUPLNfq is equivalent to VDUPLN32q; VDUPfqf is specialized VDUPLN32q.
1656 // VLD1df is equivalent to VLD1d32.
1657 // VLD1qf is equivalent to VLD1q32.
1658 // VLD2d64 is equivalent to VLD1q64.
1659 // VST1df is equivalent to VST1d32.
1660 // VST1qf is equivalent to VST1q32.
1661 // VST2d64 is equivalent to VST1q64.
1662 if (Name == "VDUPLNfd" || Name == "VDUPfdf" ||
1663 Name == "VDUPLNfq" || Name == "VDUPfqf" ||
1664 Name == "VLD1df" || Name == "VLD1qf" || Name == "VLD2d64" ||
1665 Name == "VST1df" || Name == "VST1qf" || Name == "VST2d64")
1667 } else if (TN == TARGET_THUMB) {
1668 if (!thumbInstruction(Form))
1671 // Ignore pseudo instructions.
1672 if (Name == "tInt_eh_sjlj_setjmp" || Name == "t2Int_eh_sjlj_setjmp" ||
1673 Name == "t2MOVi32imm" || Name == "tBX" || Name == "tBXr9")
1676 // On Darwin R9 is call-clobbered. Ignore the non-Darwin counterparts.
1677 if (Name == "tBL" || Name == "tBLXi" || Name == "tBLXr")
1680 // Ignore the TPsoft (TLS) instructions, which conflict with tBLr9.
1681 if (Name == "tTPsoft" || Name == "t2TPsoft")
1684 // Ignore tLEApcrel and tLEApcrelJT, prefer tADDrPCi.
1685 if (Name == "tLEApcrel" || Name == "tLEApcrelJT")
1688 // Ignore t2LEApcrel, prefer the generic t2ADD* for disassembly printing.
1689 if (Name == "t2LEApcrel")
1692 // Ignore tADDrSP, tADDspr, and tPICADD, prefer the generic tADDhirr.
1693 // Ignore t2SUBrSPs, prefer the t2SUB[S]r[r|s].
1694 // Ignore t2ADDrSPs, prefer the t2ADD[S]r[r|s].
1695 if (Name == "tADDrSP" || Name == "tADDspr" || Name == "tPICADD" ||
1696 Name == "t2SUBrSPs" || Name == "t2ADDrSPs")
1699 // Ignore t2LDRDpci, prefer the generic t2LDRDi8, t2LDRD_PRE, t2LDRD_POST.
1700 if (Name == "t2LDRDpci")
1703 // Ignore t2TBB, t2TBH and prefer the generic t2TBBgen, t2TBHgen.
1704 if (Name == "t2TBB" || Name == "t2TBH")
1707 // Resolve conflicts:
1709 // tBfar conflicts with tBLr9
1710 // tCMNz conflicts with tCMN (with assembly format strings being equal)
1711 // tPOP_RET/t2LDM_RET conflict with tPOP/t2LDM (ditto)
1712 // tMOVCCi conflicts with tMOVi8
1713 // tMOVCCr conflicts with tMOVgpr2gpr
1714 // tBR_JTr conflicts with tBRIND
1715 // tSpill conflicts with tSTRspi
1716 // tLDRcp conflicts with tLDRspi
1717 // tRestore conflicts with tLDRspi
1718 // t2LEApcrelJT conflicts with t2LEApcrel
1719 // t2ADDrSPi/t2SUBrSPi have more generic couterparts
1720 if (Name == "tBfar" ||
1721 /* Name == "tCMNz" || */ Name == "tCMPzi8" || Name == "tCMPzr" ||
1722 Name == "tCMPzhir" || /* Name == "t2CMNzrr" || Name == "t2CMNzrs" ||
1723 Name == "t2CMNzri" || */ Name == "t2CMPzrr" || Name == "t2CMPzrs" ||
1724 Name == "t2CMPzri" || Name == "tPOP_RET" || Name == "t2LDM_RET" ||
1725 Name == "tMOVCCi" || Name == "tMOVCCr" || Name == "tBR_JTr" ||
1726 Name == "tSpill" || Name == "tLDRcp" || Name == "tRestore" ||
1727 Name == "t2LEApcrelJT" || Name == "t2ADDrSPi" || Name == "t2SUBrSPi")
1731 // Dumps the instruction encoding format.
1732 switch (TargetName) {
1735 DEBUG(errs() << Name << " " << stringForARMFormat((ARMFormat)Form));
1740 BitsInit &Bits = getBitsField(Def, "Inst");
1744 // Dumps the instruction encoding bits.
1745 dumpBits(errs(), Bits);
1749 // Dumps the list of operand info.
1750 for (unsigned i = 0, e = CGI.OperandList.size(); i != e; ++i) {
1751 CodeGenInstruction::OperandInfo Info = CGI.OperandList[i];
1752 const std::string &OperandName = Info.Name;
1753 const Record &OperandDef = *Info.Rec;
1755 errs() << "\t" << OperandName << " (" << OperandDef.getName() << ")\n";
1762 void ARMDecoderEmitter::ARMDEBackend::populateInstructions() {
1763 getInstructionsByEnumValue(NumberedInstructions);
1765 uint16_t numUIDs = NumberedInstructions.size();
1768 const char *instClass = NULL;
1770 switch (TargetName) {
1772 instClass = "InstARM";
1775 assert(0 && "Unreachable code!");
1778 for (uid = 0; uid < numUIDs; uid++) {
1779 // filter out intrinsics
1780 if (!NumberedInstructions[uid]->TheDef->isSubClassOf(instClass))
1783 if (populateInstruction(*NumberedInstructions[uid], TargetName))
1784 Opcodes.push_back(uid);
1787 // Special handling for the ARM chip, which supports two modes of execution.
1788 // This branch handles the Thumb opcodes.
1789 if (TargetName == TARGET_ARM) {
1790 for (uid = 0; uid < numUIDs; uid++) {
1791 // filter out intrinsics
1792 if (!NumberedInstructions[uid]->TheDef->isSubClassOf("InstARM")
1793 && !NumberedInstructions[uid]->TheDef->isSubClassOf("InstThumb"))
1796 if (populateInstruction(*NumberedInstructions[uid], TARGET_THUMB))
1797 Opcodes2.push_back(uid);
1802 // Emits disassembler code for instruction decoding. This delegates to the
1803 // FilterChooser instance to do the heavy lifting.
1804 void ARMDecoderEmitter::ARMDEBackend::emit(raw_ostream &o) {
1805 switch (TargetName) {
1807 Frontend.EmitSourceFileHeader("ARM/Thumb Decoders", o);
1810 assert(0 && "Unreachable code!");
1813 o << "#include \"llvm/System/DataTypes.h\"\n";
1814 o << "#include <assert.h>\n";
1816 o << "namespace llvm {\n\n";
1818 FilterChooser::setTargetName(TargetName);
1820 switch (TargetName) {
1822 // Emit common utility and ARM ISA decoder.
1823 FC = new FilterChooser(NumberedInstructions, Opcodes);
1824 // Reset indentation level.
1825 unsigned Indentation = 0;
1826 FC->emitTop(o, Indentation);
1829 // Emit Thumb ISA decoder as well.
1830 FilterChooser::setTargetName(TARGET_THUMB);
1831 FC = new FilterChooser(NumberedInstructions, Opcodes2);
1832 // Reset indentation level.
1834 FC->emitBot(o, Indentation);
1838 assert(0 && "Unreachable code!");
1841 o << "\n} // End llvm namespace \n";
1844 /////////////////////////
1845 // Backend interface //
1846 /////////////////////////
1848 void ARMDecoderEmitter::initBackend()
1850 Backend = new ARMDEBackend(*this);
1853 void ARMDecoderEmitter::run(raw_ostream &o)
1858 void ARMDecoderEmitter::shutdownBackend()