blob: 64796a02ff4ecbc97e60b0bcf4a78104afea9d13 [file] [log] [blame]
Owen Anderson4e818902011-02-18 21:51:29 +00001//===------------ FixedLenDecoderEmitter.cpp - Decoder Generator ----------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// It contains the tablegen backend that emits the decoder functions for
11// targets with fixed length instruction set.
12//
13//===----------------------------------------------------------------------===//
14
15#define DEBUG_TYPE "decoder-emitter"
16
Owen Anderson4e818902011-02-18 21:51:29 +000017#include "CodeGenTarget.h"
James Molloyd9ba4fd2012-02-09 10:56:31 +000018#include "llvm/ADT/APInt.h"
Jim Grosbachecaef492012-08-14 19:06:05 +000019#include "llvm/ADT/SmallString.h"
Owen Anderson4e818902011-02-18 21:51:29 +000020#include "llvm/ADT/StringExtras.h"
Jim Grosbachecaef492012-08-14 19:06:05 +000021#include "llvm/ADT/StringRef.h"
22#include "llvm/ADT/Twine.h"
23#include "llvm/MC/MCFixedLenDisassembler.h"
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +000024#include "llvm/Support/DataTypes.h"
Owen Anderson4e818902011-02-18 21:51:29 +000025#include "llvm/Support/Debug.h"
Jim Grosbachecaef492012-08-14 19:06:05 +000026#include "llvm/Support/FormattedStream.h"
27#include "llvm/Support/LEB128.h"
Owen Anderson4e818902011-02-18 21:51:29 +000028#include "llvm/Support/raw_ostream.h"
Chandler Carruth91d19d82012-12-04 10:37:14 +000029#include "llvm/TableGen/Error.h"
30#include "llvm/TableGen/Record.h"
Owen Anderson4e818902011-02-18 21:51:29 +000031#include <map>
32#include <string>
Chandler Carruth91d19d82012-12-04 10:37:14 +000033#include <vector>
Owen Anderson4e818902011-02-18 21:51:29 +000034
35using namespace llvm;
36
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +000037namespace {
38struct EncodingField {
39 unsigned Base, Width, Offset;
40 EncodingField(unsigned B, unsigned W, unsigned O)
41 : Base(B), Width(W), Offset(O) { }
42};
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +000043
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +000044struct OperandInfo {
45 std::vector<EncodingField> Fields;
46 std::string Decoder;
47
48 OperandInfo(std::string D)
49 : Decoder(D) { }
50
51 void addField(unsigned Base, unsigned Width, unsigned Offset) {
52 Fields.push_back(EncodingField(Base, Width, Offset));
53 }
54
55 unsigned numFields() const { return Fields.size(); }
56
57 typedef std::vector<EncodingField>::const_iterator const_iterator;
58
59 const_iterator begin() const { return Fields.begin(); }
60 const_iterator end() const { return Fields.end(); }
61};
Jim Grosbachecaef492012-08-14 19:06:05 +000062
63typedef std::vector<uint8_t> DecoderTable;
64typedef uint32_t DecoderFixup;
65typedef std::vector<DecoderFixup> FixupList;
66typedef std::vector<FixupList> FixupScopeList;
67typedef SetVector<std::string> PredicateSet;
68typedef SetVector<std::string> DecoderSet;
69struct DecoderTableInfo {
70 DecoderTable Table;
71 FixupScopeList FixupStack;
72 PredicateSet Predicates;
73 DecoderSet Decoders;
74};
75
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +000076} // End anonymous namespace
77
78namespace {
79class FixedLenDecoderEmitter {
Jim Grosbachecaef492012-08-14 19:06:05 +000080 const std::vector<const CodeGenInstruction*> *NumberedInstructions;
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +000081public:
82
83 // Defaults preserved here for documentation, even though they aren't
84 // strictly necessary given the way that this is currently being called.
85 FixedLenDecoderEmitter(RecordKeeper &R,
86 std::string PredicateNamespace,
87 std::string GPrefix = "if (",
88 std::string GPostfix = " == MCDisassembler::Fail)"
89 " return MCDisassembler::Fail;",
90 std::string ROK = "MCDisassembler::Success",
91 std::string RFail = "MCDisassembler::Fail",
92 std::string L = "") :
93 Target(R),
94 PredicateNamespace(PredicateNamespace),
95 GuardPrefix(GPrefix), GuardPostfix(GPostfix),
96 ReturnOK(ROK), ReturnFail(RFail), Locals(L) {}
97
Jim Grosbachecaef492012-08-14 19:06:05 +000098 // Emit the decoder state machine table.
99 void emitTable(formatted_raw_ostream &o, DecoderTable &Table,
100 unsigned Indentation, unsigned BitWidth,
101 StringRef Namespace) const;
102 void emitPredicateFunction(formatted_raw_ostream &OS,
103 PredicateSet &Predicates,
104 unsigned Indentation) const;
105 void emitDecoderFunction(formatted_raw_ostream &OS,
106 DecoderSet &Decoders,
107 unsigned Indentation) const;
108
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +0000109 // run - Output the code emitter
110 void run(raw_ostream &o);
111
112private:
113 CodeGenTarget Target;
114public:
115 std::string PredicateNamespace;
116 std::string GuardPrefix, GuardPostfix;
117 std::string ReturnOK, ReturnFail;
118 std::string Locals;
119};
120} // End anonymous namespace
121
Owen Anderson4e818902011-02-18 21:51:29 +0000122// The set (BIT_TRUE, BIT_FALSE, BIT_UNSET) represents a ternary logic system
123// for a bit value.
124//
125// BIT_UNFILTERED is used as the init value for a filter position. It is used
126// only for filter processings.
127typedef enum {
128 BIT_TRUE, // '1'
129 BIT_FALSE, // '0'
130 BIT_UNSET, // '?'
131 BIT_UNFILTERED // unfiltered
132} bit_value_t;
133
134static bool ValueSet(bit_value_t V) {
135 return (V == BIT_TRUE || V == BIT_FALSE);
136}
137static bool ValueNotSet(bit_value_t V) {
138 return (V == BIT_UNSET);
139}
140static int Value(bit_value_t V) {
141 return ValueNotSet(V) ? -1 : (V == BIT_FALSE ? 0 : 1);
142}
Craig Topper48c112b2012-03-16 05:58:09 +0000143static bit_value_t bitFromBits(const BitsInit &bits, unsigned index) {
Sean Silvafb509ed2012-10-10 20:24:43 +0000144 if (BitInit *bit = dyn_cast<BitInit>(bits.getBit(index)))
Owen Anderson4e818902011-02-18 21:51:29 +0000145 return bit->getValue() ? BIT_TRUE : BIT_FALSE;
146
147 // The bit is uninitialized.
148 return BIT_UNSET;
149}
150// Prints the bit value for each position.
Craig Topper48c112b2012-03-16 05:58:09 +0000151static void dumpBits(raw_ostream &o, const BitsInit &bits) {
Craig Topper29688ab2012-08-17 05:42:16 +0000152 for (unsigned index = bits.getNumBits(); index > 0; --index) {
Owen Anderson4e818902011-02-18 21:51:29 +0000153 switch (bitFromBits(bits, index - 1)) {
154 case BIT_TRUE:
155 o << "1";
156 break;
157 case BIT_FALSE:
158 o << "0";
159 break;
160 case BIT_UNSET:
161 o << "_";
162 break;
163 default:
Craig Topperc4965bc2012-02-05 07:21:30 +0000164 llvm_unreachable("unexpected return value from bitFromBits");
Owen Anderson4e818902011-02-18 21:51:29 +0000165 }
166 }
167}
168
David Greeneaf8ee2c2011-07-29 22:43:06 +0000169static BitsInit &getBitsField(const Record &def, const char *str) {
170 BitsInit *bits = def.getValueAsBitsInit(str);
Owen Anderson4e818902011-02-18 21:51:29 +0000171 return *bits;
172}
173
174// Forward declaration.
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +0000175namespace {
Owen Anderson4e818902011-02-18 21:51:29 +0000176class FilterChooser;
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +0000177} // End anonymous namespace
Owen Anderson4e818902011-02-18 21:51:29 +0000178
Owen Anderson4e818902011-02-18 21:51:29 +0000179// Representation of the instruction to work on.
Owen Andersonc78e03c2011-07-19 21:06:00 +0000180typedef std::vector<bit_value_t> insn_t;
Owen Anderson4e818902011-02-18 21:51:29 +0000181
182/// Filter - Filter works with FilterChooser to produce the decoding tree for
183/// the ISA.
184///
185/// It is useful to think of a Filter as governing the switch stmts of the
186/// decoding tree in a certain level. Each case stmt delegates to an inferior
187/// FilterChooser to decide what further decoding logic to employ, or in another
188/// words, what other remaining bits to look at. The FilterChooser eventually
189/// chooses a best Filter to do its job.
190///
191/// This recursive scheme ends when the number of Opcodes assigned to the
192/// FilterChooser becomes 1 or if there is a conflict. A conflict happens when
193/// the Filter/FilterChooser combo does not know how to distinguish among the
194/// Opcodes assigned.
195///
196/// An example of a conflict is
197///
198/// Conflict:
199/// 111101000.00........00010000....
200/// 111101000.00........0001........
201/// 1111010...00........0001........
202/// 1111010...00....................
203/// 1111010.........................
204/// 1111............................
205/// ................................
206/// VST4q8a 111101000_00________00010000____
207/// VST4q8b 111101000_00________00010000____
208///
209/// The Debug output shows the path that the decoding tree follows to reach the
210/// the conclusion that there is a conflict. VST4q8a is a vst4 to double-spaced
211/// even registers, while VST4q8b is a vst4 to double-spaced odd regsisters.
212///
213/// The encoding info in the .td files does not specify this meta information,
214/// which could have been used by the decoder to resolve the conflict. The
215/// decoder could try to decode the even/odd register numbering and assign to
216/// VST4q8a or VST4q8b, but for the time being, the decoder chooses the "a"
217/// version and return the Opcode since the two have the same Asm format string.
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +0000218namespace {
Owen Anderson4e818902011-02-18 21:51:29 +0000219class Filter {
220protected:
Craig Topper501d95c2012-03-16 06:52:56 +0000221 const FilterChooser *Owner;// points to the FilterChooser who owns this filter
Owen Anderson4e818902011-02-18 21:51:29 +0000222 unsigned StartBit; // the starting bit position
223 unsigned NumBits; // number of bits to filter
224 bool Mixed; // a mixed region contains both set and unset bits
225
226 // Map of well-known segment value to the set of uid's with that value.
227 std::map<uint64_t, std::vector<unsigned> > FilteredInstructions;
228
229 // Set of uid's with non-constant segment values.
230 std::vector<unsigned> VariableInstructions;
231
232 // Map of well-known segment value to its delegate.
Craig Topper48c112b2012-03-16 05:58:09 +0000233 std::map<unsigned, const FilterChooser*> FilterChooserMap;
Owen Anderson4e818902011-02-18 21:51:29 +0000234
235 // Number of instructions which fall under FilteredInstructions category.
236 unsigned NumFiltered;
237
238 // Keeps track of the last opcode in the filtered bucket.
239 unsigned LastOpcFiltered;
240
Owen Anderson4e818902011-02-18 21:51:29 +0000241public:
Craig Topper48c112b2012-03-16 05:58:09 +0000242 unsigned getNumFiltered() const { return NumFiltered; }
243 unsigned getSingletonOpc() const {
Owen Anderson4e818902011-02-18 21:51:29 +0000244 assert(NumFiltered == 1);
245 return LastOpcFiltered;
246 }
247 // Return the filter chooser for the group of instructions without constant
248 // segment values.
Craig Topper48c112b2012-03-16 05:58:09 +0000249 const FilterChooser &getVariableFC() const {
Owen Anderson4e818902011-02-18 21:51:29 +0000250 assert(NumFiltered == 1);
251 assert(FilterChooserMap.size() == 1);
252 return *(FilterChooserMap.find((unsigned)-1)->second);
253 }
254
255 Filter(const Filter &f);
256 Filter(FilterChooser &owner, unsigned startBit, unsigned numBits, bool mixed);
257
258 ~Filter();
259
260 // Divides the decoding task into sub tasks and delegates them to the
261 // inferior FilterChooser's.
262 //
263 // A special case arises when there's only one entry in the filtered
264 // instructions. In order to unambiguously decode the singleton, we need to
265 // match the remaining undecoded encoding bits against the singleton.
266 void recurse();
267
Jim Grosbachecaef492012-08-14 19:06:05 +0000268 // Emit table entries to decode instructions given a segment or segments of
269 // bits.
270 void emitTableEntry(DecoderTableInfo &TableInfo) const;
Owen Anderson4e818902011-02-18 21:51:29 +0000271
272 // Returns the number of fanout produced by the filter. More fanout implies
273 // the filter distinguishes more categories of instructions.
274 unsigned usefulness() const;
275}; // End of class Filter
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +0000276} // End anonymous namespace
Owen Anderson4e818902011-02-18 21:51:29 +0000277
278// These are states of our finite state machines used in FilterChooser's
279// filterProcessor() which produces the filter candidates to use.
280typedef enum {
281 ATTR_NONE,
282 ATTR_FILTERED,
283 ATTR_ALL_SET,
284 ATTR_ALL_UNSET,
285 ATTR_MIXED
286} bitAttr_t;
287
288/// FilterChooser - FilterChooser chooses the best filter among a set of Filters
289/// in order to perform the decoding of instructions at the current level.
290///
291/// Decoding proceeds from the top down. Based on the well-known encoding bits
292/// of instructions available, FilterChooser builds up the possible Filters that
293/// can further the task of decoding by distinguishing among the remaining
294/// candidate instructions.
295///
296/// Once a filter has been chosen, it is called upon to divide the decoding task
297/// into sub-tasks and delegates them to its inferior FilterChoosers for further
298/// processings.
299///
300/// It is useful to think of a Filter as governing the switch stmts of the
301/// decoding tree. And each case is delegated to an inferior FilterChooser to
302/// decide what further remaining bits to look at.
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +0000303namespace {
Owen Anderson4e818902011-02-18 21:51:29 +0000304class FilterChooser {
305protected:
306 friend class Filter;
307
308 // Vector of codegen instructions to choose our filter.
309 const std::vector<const CodeGenInstruction*> &AllInstructions;
310
311 // Vector of uid's for this filter chooser to work on.
Craig Topper501d95c2012-03-16 06:52:56 +0000312 const std::vector<unsigned> &Opcodes;
Owen Anderson4e818902011-02-18 21:51:29 +0000313
314 // Lookup table for the operand decoding of instructions.
Craig Topper501d95c2012-03-16 06:52:56 +0000315 const std::map<unsigned, std::vector<OperandInfo> > &Operands;
Owen Anderson4e818902011-02-18 21:51:29 +0000316
317 // Vector of candidate filters.
318 std::vector<Filter> Filters;
319
320 // Array of bit values passed down from our parent.
321 // Set to all BIT_UNFILTERED's for Parent == NULL.
Owen Andersonc78e03c2011-07-19 21:06:00 +0000322 std::vector<bit_value_t> FilterBitValues;
Owen Anderson4e818902011-02-18 21:51:29 +0000323
324 // Links to the FilterChooser above us in the decoding tree.
Craig Topper501d95c2012-03-16 06:52:56 +0000325 const FilterChooser *Parent;
Owen Anderson4e818902011-02-18 21:51:29 +0000326
327 // Index of the best filter from Filters.
328 int BestIndex;
329
Owen Andersonc78e03c2011-07-19 21:06:00 +0000330 // Width of instructions
331 unsigned BitWidth;
332
Owen Andersona4043c42011-08-17 17:44:15 +0000333 // Parent emitter
334 const FixedLenDecoderEmitter *Emitter;
335
Owen Anderson4e818902011-02-18 21:51:29 +0000336public:
Craig Topper82d0d5f2012-03-16 01:19:24 +0000337 FilterChooser(const FilterChooser &FC)
338 : AllInstructions(FC.AllInstructions), Opcodes(FC.Opcodes),
Owen Andersonc78e03c2011-07-19 21:06:00 +0000339 Operands(FC.Operands), Filters(FC.Filters),
340 FilterBitValues(FC.FilterBitValues), Parent(FC.Parent),
Craig Topper82d0d5f2012-03-16 01:19:24 +0000341 BestIndex(FC.BestIndex), BitWidth(FC.BitWidth),
342 Emitter(FC.Emitter) { }
Owen Anderson4e818902011-02-18 21:51:29 +0000343
344 FilterChooser(const std::vector<const CodeGenInstruction*> &Insts,
345 const std::vector<unsigned> &IDs,
Craig Topper501d95c2012-03-16 06:52:56 +0000346 const std::map<unsigned, std::vector<OperandInfo> > &Ops,
Owen Andersona4043c42011-08-17 17:44:15 +0000347 unsigned BW,
Craig Topper82d0d5f2012-03-16 01:19:24 +0000348 const FixedLenDecoderEmitter *E)
349 : AllInstructions(Insts), Opcodes(IDs), Operands(Ops), Filters(),
Craig Topper24064772014-04-15 07:20:03 +0000350 Parent(nullptr), BestIndex(-1), BitWidth(BW), Emitter(E) {
Owen Andersonc78e03c2011-07-19 21:06:00 +0000351 for (unsigned i = 0; i < BitWidth; ++i)
352 FilterBitValues.push_back(BIT_UNFILTERED);
Owen Anderson4e818902011-02-18 21:51:29 +0000353
354 doFilter();
355 }
356
357 FilterChooser(const std::vector<const CodeGenInstruction*> &Insts,
358 const std::vector<unsigned> &IDs,
Craig Topper501d95c2012-03-16 06:52:56 +0000359 const std::map<unsigned, std::vector<OperandInfo> > &Ops,
360 const std::vector<bit_value_t> &ParentFilterBitValues,
361 const FilterChooser &parent)
Craig Topper82d0d5f2012-03-16 01:19:24 +0000362 : AllInstructions(Insts), Opcodes(IDs), Operands(Ops),
Owen Andersonc78e03c2011-07-19 21:06:00 +0000363 Filters(), FilterBitValues(ParentFilterBitValues),
Owen Andersona4043c42011-08-17 17:44:15 +0000364 Parent(&parent), BestIndex(-1), BitWidth(parent.BitWidth),
365 Emitter(parent.Emitter) {
Owen Anderson4e818902011-02-18 21:51:29 +0000366 doFilter();
367 }
368
Jim Grosbachecaef492012-08-14 19:06:05 +0000369 unsigned getBitWidth() const { return BitWidth; }
Owen Anderson4e818902011-02-18 21:51:29 +0000370
371protected:
372 // Populates the insn given the uid.
373 void insnWithID(insn_t &Insn, unsigned Opcode) const {
David Greeneaf8ee2c2011-07-29 22:43:06 +0000374 BitsInit &Bits = getBitsField(*AllInstructions[Opcode]->TheDef, "Inst");
Owen Anderson4e818902011-02-18 21:51:29 +0000375
James Molloyd9ba4fd2012-02-09 10:56:31 +0000376 // We may have a SoftFail bitmask, which specifies a mask where an encoding
377 // may differ from the value in "Inst" and yet still be valid, but the
378 // disassembler should return SoftFail instead of Success.
379 //
380 // This is used for marking UNPREDICTABLE instructions in the ARM world.
Jim Grosbach3f4b2392012-02-29 22:07:56 +0000381 BitsInit *SFBits =
382 AllInstructions[Opcode]->TheDef->getValueAsBitsInit("SoftFail");
James Molloyd9ba4fd2012-02-09 10:56:31 +0000383
384 for (unsigned i = 0; i < BitWidth; ++i) {
385 if (SFBits && bitFromBits(*SFBits, i) == BIT_TRUE)
386 Insn.push_back(BIT_UNSET);
387 else
388 Insn.push_back(bitFromBits(Bits, i));
389 }
Owen Anderson4e818902011-02-18 21:51:29 +0000390 }
391
392 // Returns the record name.
393 const std::string &nameWithID(unsigned Opcode) const {
394 return AllInstructions[Opcode]->TheDef->getName();
395 }
396
397 // Populates the field of the insn given the start position and the number of
398 // consecutive bits to scan for.
399 //
400 // Returns false if there exists any uninitialized bit value in the range.
401 // Returns true, otherwise.
402 bool fieldFromInsn(uint64_t &Field, insn_t &Insn, unsigned StartBit,
Craig Topper82d0d5f2012-03-16 01:19:24 +0000403 unsigned NumBits) const;
Owen Anderson4e818902011-02-18 21:51:29 +0000404
405 /// dumpFilterArray - dumpFilterArray prints out debugging info for the given
406 /// filter array as a series of chars.
Craig Topper48c112b2012-03-16 05:58:09 +0000407 void dumpFilterArray(raw_ostream &o,
408 const std::vector<bit_value_t> & filter) const;
Owen Anderson4e818902011-02-18 21:51:29 +0000409
410 /// dumpStack - dumpStack traverses the filter chooser chain and calls
411 /// dumpFilterArray on each filter chooser up to the top level one.
Craig Topper48c112b2012-03-16 05:58:09 +0000412 void dumpStack(raw_ostream &o, const char *prefix) const;
Owen Anderson4e818902011-02-18 21:51:29 +0000413
414 Filter &bestFilter() {
415 assert(BestIndex != -1 && "BestIndex not set");
416 return Filters[BestIndex];
417 }
418
419 // Called from Filter::recurse() when singleton exists. For debug purpose.
Craig Topper48c112b2012-03-16 05:58:09 +0000420 void SingletonExists(unsigned Opc) const;
Owen Anderson4e818902011-02-18 21:51:29 +0000421
Craig Topper48c112b2012-03-16 05:58:09 +0000422 bool PositionFiltered(unsigned i) const {
Owen Anderson4e818902011-02-18 21:51:29 +0000423 return ValueSet(FilterBitValues[i]);
424 }
425
426 // Calculates the island(s) needed to decode the instruction.
427 // This returns a lit of undecoded bits of an instructions, for example,
428 // Inst{20} = 1 && Inst{3-0} == 0b1111 represents two islands of yet-to-be
429 // decoded bits in order to verify that the instruction matches the Opcode.
430 unsigned getIslands(std::vector<unsigned> &StartBits,
Craig Topper82d0d5f2012-03-16 01:19:24 +0000431 std::vector<unsigned> &EndBits,
Craig Topper48c112b2012-03-16 05:58:09 +0000432 std::vector<uint64_t> &FieldVals,
433 const insn_t &Insn) const;
Owen Anderson4e818902011-02-18 21:51:29 +0000434
James Molloy8067df92011-09-07 19:42:28 +0000435 // Emits code to check the Predicates member of an instruction are true.
436 // Returns true if predicate matches were emitted, false otherwise.
Craig Topper48c112b2012-03-16 05:58:09 +0000437 bool emitPredicateMatch(raw_ostream &o, unsigned &Indentation,
438 unsigned Opc) const;
James Molloy8067df92011-09-07 19:42:28 +0000439
Jim Grosbachecaef492012-08-14 19:06:05 +0000440 bool doesOpcodeNeedPredicate(unsigned Opc) const;
441 unsigned getPredicateIndex(DecoderTableInfo &TableInfo, StringRef P) const;
442 void emitPredicateTableEntry(DecoderTableInfo &TableInfo,
443 unsigned Opc) const;
James Molloyd9ba4fd2012-02-09 10:56:31 +0000444
Jim Grosbachecaef492012-08-14 19:06:05 +0000445 void emitSoftFailTableEntry(DecoderTableInfo &TableInfo,
446 unsigned Opc) const;
447
448 // Emits table entries to decode the singleton.
449 void emitSingletonTableEntry(DecoderTableInfo &TableInfo,
450 unsigned Opc) const;
Owen Anderson4e818902011-02-18 21:51:29 +0000451
452 // Emits code to decode the singleton, and then to decode the rest.
Jim Grosbachecaef492012-08-14 19:06:05 +0000453 void emitSingletonTableEntry(DecoderTableInfo &TableInfo,
454 const Filter &Best) const;
Owen Anderson4e818902011-02-18 21:51:29 +0000455
Jim Grosbachecaef492012-08-14 19:06:05 +0000456 void emitBinaryParser(raw_ostream &o, unsigned &Indentation,
Craig Topper48c112b2012-03-16 05:58:09 +0000457 const OperandInfo &OpInfo) const;
Owen Andersone3591652011-07-28 21:54:31 +0000458
Jim Grosbachecaef492012-08-14 19:06:05 +0000459 void emitDecoder(raw_ostream &OS, unsigned Indentation, unsigned Opc) const;
460 unsigned getDecoderIndex(DecoderSet &Decoders, unsigned Opc) const;
461
Owen Anderson4e818902011-02-18 21:51:29 +0000462 // Assign a single filter and run with it.
Craig Topper48c112b2012-03-16 05:58:09 +0000463 void runSingleFilter(unsigned startBit, unsigned numBit, bool mixed);
Owen Anderson4e818902011-02-18 21:51:29 +0000464
465 // reportRegion is a helper function for filterProcessor to mark a region as
466 // eligible for use as a filter region.
467 void reportRegion(bitAttr_t RA, unsigned StartBit, unsigned BitIndex,
Craig Topper82d0d5f2012-03-16 01:19:24 +0000468 bool AllowMixed);
Owen Anderson4e818902011-02-18 21:51:29 +0000469
470 // FilterProcessor scans the well-known encoding bits of the instructions and
471 // builds up a list of candidate filters. It chooses the best filter and
472 // recursively descends down the decoding tree.
473 bool filterProcessor(bool AllowMixed, bool Greedy = true);
474
475 // Decides on the best configuration of filter(s) to use in order to decode
476 // the instructions. A conflict of instructions may occur, in which case we
477 // dump the conflict set to the standard error.
478 void doFilter();
479
Jim Grosbachecaef492012-08-14 19:06:05 +0000480public:
481 // emitTableEntries - Emit state machine entries to decode our share of
482 // instructions.
483 void emitTableEntries(DecoderTableInfo &TableInfo) const;
Owen Anderson4e818902011-02-18 21:51:29 +0000484};
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +0000485} // End anonymous namespace
Owen Anderson4e818902011-02-18 21:51:29 +0000486
487///////////////////////////
488// //
Craig Topper93e64342012-03-16 00:56:01 +0000489// Filter Implementation //
Owen Anderson4e818902011-02-18 21:51:29 +0000490// //
491///////////////////////////
492
Craig Topper82d0d5f2012-03-16 01:19:24 +0000493Filter::Filter(const Filter &f)
494 : Owner(f.Owner), StartBit(f.StartBit), NumBits(f.NumBits), Mixed(f.Mixed),
495 FilteredInstructions(f.FilteredInstructions),
496 VariableInstructions(f.VariableInstructions),
497 FilterChooserMap(f.FilterChooserMap), NumFiltered(f.NumFiltered),
498 LastOpcFiltered(f.LastOpcFiltered) {
Owen Anderson4e818902011-02-18 21:51:29 +0000499}
500
501Filter::Filter(FilterChooser &owner, unsigned startBit, unsigned numBits,
Craig Topper82d0d5f2012-03-16 01:19:24 +0000502 bool mixed)
503 : Owner(&owner), StartBit(startBit), NumBits(numBits), Mixed(mixed) {
Owen Andersonc78e03c2011-07-19 21:06:00 +0000504 assert(StartBit + NumBits - 1 < Owner->BitWidth);
Owen Anderson4e818902011-02-18 21:51:29 +0000505
506 NumFiltered = 0;
507 LastOpcFiltered = 0;
Owen Anderson4e818902011-02-18 21:51:29 +0000508
509 for (unsigned i = 0, e = Owner->Opcodes.size(); i != e; ++i) {
510 insn_t Insn;
511
512 // Populates the insn given the uid.
513 Owner->insnWithID(Insn, Owner->Opcodes[i]);
514
515 uint64_t Field;
516 // Scans the segment for possibly well-specified encoding bits.
517 bool ok = Owner->fieldFromInsn(Field, Insn, StartBit, NumBits);
518
519 if (ok) {
520 // The encoding bits are well-known. Lets add the uid of the
521 // instruction into the bucket keyed off the constant field value.
522 LastOpcFiltered = Owner->Opcodes[i];
523 FilteredInstructions[Field].push_back(LastOpcFiltered);
524 ++NumFiltered;
525 } else {
Craig Topper93e64342012-03-16 00:56:01 +0000526 // Some of the encoding bit(s) are unspecified. This contributes to
Owen Anderson4e818902011-02-18 21:51:29 +0000527 // one additional member of "Variable" instructions.
528 VariableInstructions.push_back(Owner->Opcodes[i]);
Owen Anderson4e818902011-02-18 21:51:29 +0000529 }
530 }
531
532 assert((FilteredInstructions.size() + VariableInstructions.size() > 0)
533 && "Filter returns no instruction categories");
534}
535
536Filter::~Filter() {
Craig Topper48c112b2012-03-16 05:58:09 +0000537 std::map<unsigned, const FilterChooser*>::iterator filterIterator;
Owen Anderson4e818902011-02-18 21:51:29 +0000538 for (filterIterator = FilterChooserMap.begin();
539 filterIterator != FilterChooserMap.end();
540 filterIterator++) {
541 delete filterIterator->second;
542 }
543}
544
545// Divides the decoding task into sub tasks and delegates them to the
546// inferior FilterChooser's.
547//
548// A special case arises when there's only one entry in the filtered
549// instructions. In order to unambiguously decode the singleton, we need to
550// match the remaining undecoded encoding bits against the singleton.
551void Filter::recurse() {
552 std::map<uint64_t, std::vector<unsigned> >::const_iterator mapIterator;
553
Owen Anderson4e818902011-02-18 21:51:29 +0000554 // Starts by inheriting our parent filter chooser's filter bit values.
Owen Andersonc78e03c2011-07-19 21:06:00 +0000555 std::vector<bit_value_t> BitValueArray(Owner->FilterBitValues);
Owen Anderson4e818902011-02-18 21:51:29 +0000556
Owen Anderson4e818902011-02-18 21:51:29 +0000557 if (VariableInstructions.size()) {
558 // Conservatively marks each segment position as BIT_UNSET.
Craig Topper29688ab2012-08-17 05:42:16 +0000559 for (unsigned bitIndex = 0; bitIndex < NumBits; ++bitIndex)
Owen Anderson4e818902011-02-18 21:51:29 +0000560 BitValueArray[StartBit + bitIndex] = BIT_UNSET;
561
Chris Lattner0ab5e2c2011-04-15 05:18:47 +0000562 // Delegates to an inferior filter chooser for further processing on this
Owen Anderson4e818902011-02-18 21:51:29 +0000563 // group of instructions whose segment values are variable.
Craig Topper48c112b2012-03-16 05:58:09 +0000564 FilterChooserMap.insert(std::pair<unsigned, const FilterChooser*>(
Owen Anderson4e818902011-02-18 21:51:29 +0000565 (unsigned)-1,
566 new FilterChooser(Owner->AllInstructions,
567 VariableInstructions,
568 Owner->Operands,
569 BitValueArray,
570 *Owner)
571 ));
572 }
573
574 // No need to recurse for a singleton filtered instruction.
Jim Grosbachecaef492012-08-14 19:06:05 +0000575 // See also Filter::emit*().
Owen Anderson4e818902011-02-18 21:51:29 +0000576 if (getNumFiltered() == 1) {
577 //Owner->SingletonExists(LastOpcFiltered);
578 assert(FilterChooserMap.size() == 1);
579 return;
580 }
581
582 // Otherwise, create sub choosers.
583 for (mapIterator = FilteredInstructions.begin();
584 mapIterator != FilteredInstructions.end();
585 mapIterator++) {
586
587 // Marks all the segment positions with either BIT_TRUE or BIT_FALSE.
Craig Topper29688ab2012-08-17 05:42:16 +0000588 for (unsigned bitIndex = 0; bitIndex < NumBits; ++bitIndex) {
Owen Anderson4e818902011-02-18 21:51:29 +0000589 if (mapIterator->first & (1ULL << bitIndex))
590 BitValueArray[StartBit + bitIndex] = BIT_TRUE;
591 else
592 BitValueArray[StartBit + bitIndex] = BIT_FALSE;
593 }
594
Chris Lattner0ab5e2c2011-04-15 05:18:47 +0000595 // Delegates to an inferior filter chooser for further processing on this
Owen Anderson4e818902011-02-18 21:51:29 +0000596 // category of instructions.
Craig Topper48c112b2012-03-16 05:58:09 +0000597 FilterChooserMap.insert(std::pair<unsigned, const FilterChooser*>(
Owen Anderson4e818902011-02-18 21:51:29 +0000598 mapIterator->first,
599 new FilterChooser(Owner->AllInstructions,
600 mapIterator->second,
601 Owner->Operands,
602 BitValueArray,
603 *Owner)
604 ));
605 }
606}
607
Jim Grosbachecaef492012-08-14 19:06:05 +0000608static void resolveTableFixups(DecoderTable &Table, const FixupList &Fixups,
609 uint32_t DestIdx) {
610 // Any NumToSkip fixups in the current scope can resolve to the
611 // current location.
612 for (FixupList::const_reverse_iterator I = Fixups.rbegin(),
613 E = Fixups.rend();
614 I != E; ++I) {
615 // Calculate the distance from the byte following the fixup entry byte
616 // to the destination. The Target is calculated from after the 16-bit
617 // NumToSkip entry itself, so subtract two from the displacement here
618 // to account for that.
619 uint32_t FixupIdx = *I;
620 uint32_t Delta = DestIdx - FixupIdx - 2;
621 // Our NumToSkip entries are 16-bits. Make sure our table isn't too
622 // big.
623 assert(Delta < 65536U && "disassembler decoding table too large!");
624 Table[FixupIdx] = (uint8_t)Delta;
625 Table[FixupIdx + 1] = (uint8_t)(Delta >> 8);
626 }
627}
Owen Anderson4e818902011-02-18 21:51:29 +0000628
Jim Grosbachecaef492012-08-14 19:06:05 +0000629// Emit table entries to decode instructions given a segment or segments
630// of bits.
631void Filter::emitTableEntry(DecoderTableInfo &TableInfo) const {
632 TableInfo.Table.push_back(MCD::OPC_ExtractField);
633 TableInfo.Table.push_back(StartBit);
634 TableInfo.Table.push_back(NumBits);
Owen Anderson4e818902011-02-18 21:51:29 +0000635
Jim Grosbachecaef492012-08-14 19:06:05 +0000636 // A new filter entry begins a new scope for fixup resolution.
637 TableInfo.FixupStack.push_back(FixupList());
Owen Anderson4e818902011-02-18 21:51:29 +0000638
Craig Topper48c112b2012-03-16 05:58:09 +0000639 std::map<unsigned, const FilterChooser*>::const_iterator filterIterator;
Owen Anderson4e818902011-02-18 21:51:29 +0000640
Jim Grosbachecaef492012-08-14 19:06:05 +0000641 DecoderTable &Table = TableInfo.Table;
642
643 size_t PrevFilter = 0;
644 bool HasFallthrough = false;
Owen Anderson4e818902011-02-18 21:51:29 +0000645 for (filterIterator = FilterChooserMap.begin();
646 filterIterator != FilterChooserMap.end();
647 filterIterator++) {
Owen Anderson4e818902011-02-18 21:51:29 +0000648 // Field value -1 implies a non-empty set of variable instructions.
649 // See also recurse().
650 if (filterIterator->first == (unsigned)-1) {
Jim Grosbachecaef492012-08-14 19:06:05 +0000651 HasFallthrough = true;
Owen Anderson4e818902011-02-18 21:51:29 +0000652
Jim Grosbachecaef492012-08-14 19:06:05 +0000653 // Each scope should always have at least one filter value to check
654 // for.
655 assert(PrevFilter != 0 && "empty filter set!");
656 FixupList &CurScope = TableInfo.FixupStack.back();
657 // Resolve any NumToSkip fixups in the current scope.
658 resolveTableFixups(Table, CurScope, Table.size());
659 CurScope.clear();
660 PrevFilter = 0; // Don't re-process the filter's fallthrough.
661 } else {
662 Table.push_back(MCD::OPC_FilterValue);
663 // Encode and emit the value to filter against.
664 uint8_t Buffer[8];
665 unsigned Len = encodeULEB128(filterIterator->first, Buffer);
666 Table.insert(Table.end(), Buffer, Buffer + Len);
667 // Reserve space for the NumToSkip entry. We'll backpatch the value
668 // later.
669 PrevFilter = Table.size();
670 Table.push_back(0);
671 Table.push_back(0);
672 }
Owen Anderson4e818902011-02-18 21:51:29 +0000673
674 // We arrive at a category of instructions with the same segment value.
675 // Now delegate to the sub filter chooser for further decodings.
676 // The case may fallthrough, which happens if the remaining well-known
677 // encoding bits do not match exactly.
Jim Grosbachecaef492012-08-14 19:06:05 +0000678 filterIterator->second->emitTableEntries(TableInfo);
Owen Anderson4e818902011-02-18 21:51:29 +0000679
Jim Grosbachecaef492012-08-14 19:06:05 +0000680 // Now that we've emitted the body of the handler, update the NumToSkip
681 // of the filter itself to be able to skip forward when false. Subtract
682 // two as to account for the width of the NumToSkip field itself.
683 if (PrevFilter) {
684 uint32_t NumToSkip = Table.size() - PrevFilter - 2;
685 assert(NumToSkip < 65536U && "disassembler decoding table too large!");
686 Table[PrevFilter] = (uint8_t)NumToSkip;
687 Table[PrevFilter + 1] = (uint8_t)(NumToSkip >> 8);
688 }
Owen Anderson4e818902011-02-18 21:51:29 +0000689 }
690
Jim Grosbachecaef492012-08-14 19:06:05 +0000691 // Any remaining unresolved fixups bubble up to the parent fixup scope.
692 assert(TableInfo.FixupStack.size() > 1 && "fixup stack underflow!");
693 FixupScopeList::iterator Source = TableInfo.FixupStack.end() - 1;
694 FixupScopeList::iterator Dest = Source - 1;
695 Dest->insert(Dest->end(), Source->begin(), Source->end());
696 TableInfo.FixupStack.pop_back();
697
698 // If there is no fallthrough, then the final filter should get fixed
699 // up according to the enclosing scope rather than the current position.
700 if (!HasFallthrough)
701 TableInfo.FixupStack.back().push_back(PrevFilter);
Owen Anderson4e818902011-02-18 21:51:29 +0000702}
703
704// Returns the number of fanout produced by the filter. More fanout implies
705// the filter distinguishes more categories of instructions.
706unsigned Filter::usefulness() const {
707 if (VariableInstructions.size())
708 return FilteredInstructions.size();
709 else
710 return FilteredInstructions.size() + 1;
711}
712
713//////////////////////////////////
714// //
715// Filterchooser Implementation //
716// //
717//////////////////////////////////
718
Jim Grosbachecaef492012-08-14 19:06:05 +0000719// Emit the decoder state machine table.
720void FixedLenDecoderEmitter::emitTable(formatted_raw_ostream &OS,
721 DecoderTable &Table,
722 unsigned Indentation,
723 unsigned BitWidth,
724 StringRef Namespace) const {
725 OS.indent(Indentation) << "static const uint8_t DecoderTable" << Namespace
726 << BitWidth << "[] = {\n";
Owen Anderson4e818902011-02-18 21:51:29 +0000727
Jim Grosbachecaef492012-08-14 19:06:05 +0000728 Indentation += 2;
Owen Anderson4e818902011-02-18 21:51:29 +0000729
Jim Grosbachecaef492012-08-14 19:06:05 +0000730 // FIXME: We may be able to use the NumToSkip values to recover
731 // appropriate indentation levels.
732 DecoderTable::const_iterator I = Table.begin();
733 DecoderTable::const_iterator E = Table.end();
734 while (I != E) {
735 assert (I < E && "incomplete decode table entry!");
Owen Anderson4e818902011-02-18 21:51:29 +0000736
Jim Grosbachecaef492012-08-14 19:06:05 +0000737 uint64_t Pos = I - Table.begin();
738 OS << "/* " << Pos << " */";
739 OS.PadToColumn(12);
Owen Anderson4e818902011-02-18 21:51:29 +0000740
Jim Grosbachecaef492012-08-14 19:06:05 +0000741 switch (*I) {
742 default:
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000743 PrintFatalError("invalid decode table opcode");
Jim Grosbachecaef492012-08-14 19:06:05 +0000744 case MCD::OPC_ExtractField: {
745 ++I;
746 unsigned Start = *I++;
747 unsigned Len = *I++;
748 OS.indent(Indentation) << "MCD::OPC_ExtractField, " << Start << ", "
749 << Len << ", // Inst{";
750 if (Len > 1)
751 OS << (Start + Len - 1) << "-";
752 OS << Start << "} ...\n";
753 break;
754 }
755 case MCD::OPC_FilterValue: {
756 ++I;
757 OS.indent(Indentation) << "MCD::OPC_FilterValue, ";
758 // The filter value is ULEB128 encoded.
759 while (*I >= 128)
760 OS << utostr(*I++) << ", ";
761 OS << utostr(*I++) << ", ";
762
763 // 16-bit numtoskip value.
764 uint8_t Byte = *I++;
765 uint32_t NumToSkip = Byte;
766 OS << utostr(Byte) << ", ";
767 Byte = *I++;
768 OS << utostr(Byte) << ", ";
769 NumToSkip |= Byte << 8;
770 OS << "// Skip to: " << ((I - Table.begin()) + NumToSkip) << "\n";
771 break;
772 }
773 case MCD::OPC_CheckField: {
774 ++I;
775 unsigned Start = *I++;
776 unsigned Len = *I++;
777 OS.indent(Indentation) << "MCD::OPC_CheckField, " << Start << ", "
778 << Len << ", ";// << Val << ", " << NumToSkip << ",\n";
779 // ULEB128 encoded field value.
780 for (; *I >= 128; ++I)
781 OS << utostr(*I) << ", ";
782 OS << utostr(*I++) << ", ";
783 // 16-bit numtoskip value.
784 uint8_t Byte = *I++;
785 uint32_t NumToSkip = Byte;
786 OS << utostr(Byte) << ", ";
787 Byte = *I++;
788 OS << utostr(Byte) << ", ";
789 NumToSkip |= Byte << 8;
790 OS << "// Skip to: " << ((I - Table.begin()) + NumToSkip) << "\n";
791 break;
792 }
793 case MCD::OPC_CheckPredicate: {
794 ++I;
795 OS.indent(Indentation) << "MCD::OPC_CheckPredicate, ";
796 for (; *I >= 128; ++I)
797 OS << utostr(*I) << ", ";
798 OS << utostr(*I++) << ", ";
799
800 // 16-bit numtoskip value.
801 uint8_t Byte = *I++;
802 uint32_t NumToSkip = Byte;
803 OS << utostr(Byte) << ", ";
804 Byte = *I++;
805 OS << utostr(Byte) << ", ";
806 NumToSkip |= Byte << 8;
807 OS << "// Skip to: " << ((I - Table.begin()) + NumToSkip) << "\n";
808 break;
809 }
810 case MCD::OPC_Decode: {
811 ++I;
812 // Extract the ULEB128 encoded Opcode to a buffer.
813 uint8_t Buffer[8], *p = Buffer;
814 while ((*p++ = *I++) >= 128)
815 assert((p - Buffer) <= (ptrdiff_t)sizeof(Buffer)
816 && "ULEB128 value too large!");
817 // Decode the Opcode value.
818 unsigned Opc = decodeULEB128(Buffer);
819 OS.indent(Indentation) << "MCD::OPC_Decode, ";
820 for (p = Buffer; *p >= 128; ++p)
821 OS << utostr(*p) << ", ";
822 OS << utostr(*p) << ", ";
823
824 // Decoder index.
825 for (; *I >= 128; ++I)
826 OS << utostr(*I) << ", ";
827 OS << utostr(*I++) << ", ";
828
829 OS << "// Opcode: "
830 << NumberedInstructions->at(Opc)->TheDef->getName() << "\n";
831 break;
832 }
833 case MCD::OPC_SoftFail: {
834 ++I;
835 OS.indent(Indentation) << "MCD::OPC_SoftFail";
836 // Positive mask
837 uint64_t Value = 0;
838 unsigned Shift = 0;
839 do {
840 OS << ", " << utostr(*I);
841 Value += (*I & 0x7f) << Shift;
842 Shift += 7;
843 } while (*I++ >= 128);
844 if (Value > 127)
845 OS << " /* 0x" << utohexstr(Value) << " */";
846 // Negative mask
847 Value = 0;
848 Shift = 0;
849 do {
850 OS << ", " << utostr(*I);
851 Value += (*I & 0x7f) << Shift;
852 Shift += 7;
853 } while (*I++ >= 128);
854 if (Value > 127)
855 OS << " /* 0x" << utohexstr(Value) << " */";
856 OS << ",\n";
857 break;
858 }
859 case MCD::OPC_Fail: {
860 ++I;
861 OS.indent(Indentation) << "MCD::OPC_Fail,\n";
862 break;
863 }
864 }
865 }
866 OS.indent(Indentation) << "0\n";
867
868 Indentation -= 2;
869
870 OS.indent(Indentation) << "};\n\n";
871}
872
873void FixedLenDecoderEmitter::
874emitPredicateFunction(formatted_raw_ostream &OS, PredicateSet &Predicates,
875 unsigned Indentation) const {
876 // The predicate function is just a big switch statement based on the
877 // input predicate index.
878 OS.indent(Indentation) << "static bool checkDecoderPredicate(unsigned Idx, "
879 << "uint64_t Bits) {\n";
880 Indentation += 2;
Aaron Ballmane59e3582013-07-15 16:53:32 +0000881 if (!Predicates.empty()) {
882 OS.indent(Indentation) << "switch (Idx) {\n";
883 OS.indent(Indentation) << "default: llvm_unreachable(\"Invalid index!\");\n";
884 unsigned Index = 0;
885 for (PredicateSet::const_iterator I = Predicates.begin(), E = Predicates.end();
886 I != E; ++I, ++Index) {
887 OS.indent(Indentation) << "case " << Index << ":\n";
888 OS.indent(Indentation+2) << "return (" << *I << ");\n";
889 }
890 OS.indent(Indentation) << "}\n";
891 } else {
892 // No case statement to emit
893 OS.indent(Indentation) << "llvm_unreachable(\"Invalid index!\");\n";
Jim Grosbachecaef492012-08-14 19:06:05 +0000894 }
Jim Grosbachecaef492012-08-14 19:06:05 +0000895 Indentation -= 2;
896 OS.indent(Indentation) << "}\n\n";
897}
898
899void FixedLenDecoderEmitter::
900emitDecoderFunction(formatted_raw_ostream &OS, DecoderSet &Decoders,
901 unsigned Indentation) const {
902 // The decoder function is just a big switch statement based on the
903 // input decoder index.
904 OS.indent(Indentation) << "template<typename InsnType>\n";
905 OS.indent(Indentation) << "static DecodeStatus decodeToMCInst(DecodeStatus S,"
906 << " unsigned Idx, InsnType insn, MCInst &MI,\n";
907 OS.indent(Indentation) << " uint64_t "
Benjamin Kramer26b568d2012-08-15 10:26:44 +0000908 << "Address, const void *Decoder) {\n";
Jim Grosbachecaef492012-08-14 19:06:05 +0000909 Indentation += 2;
910 OS.indent(Indentation) << "InsnType tmp;\n";
911 OS.indent(Indentation) << "switch (Idx) {\n";
912 OS.indent(Indentation) << "default: llvm_unreachable(\"Invalid index!\");\n";
913 unsigned Index = 0;
914 for (DecoderSet::const_iterator I = Decoders.begin(), E = Decoders.end();
915 I != E; ++I, ++Index) {
916 OS.indent(Indentation) << "case " << Index << ":\n";
Craig Topperebc3aa22012-08-17 05:16:15 +0000917 OS << *I;
Jim Grosbachecaef492012-08-14 19:06:05 +0000918 OS.indent(Indentation+2) << "return S;\n";
919 }
920 OS.indent(Indentation) << "}\n";
921 Indentation -= 2;
922 OS.indent(Indentation) << "}\n\n";
Owen Anderson4e818902011-02-18 21:51:29 +0000923}
924
925// Populates the field of the insn given the start position and the number of
926// consecutive bits to scan for.
927//
928// Returns false if and on the first uninitialized bit value encountered.
929// Returns true, otherwise.
930bool FilterChooser::fieldFromInsn(uint64_t &Field, insn_t &Insn,
Craig Topper48c112b2012-03-16 05:58:09 +0000931 unsigned StartBit, unsigned NumBits) const {
Owen Anderson4e818902011-02-18 21:51:29 +0000932 Field = 0;
933
934 for (unsigned i = 0; i < NumBits; ++i) {
935 if (Insn[StartBit + i] == BIT_UNSET)
936 return false;
937
938 if (Insn[StartBit + i] == BIT_TRUE)
939 Field = Field | (1ULL << i);
940 }
941
942 return true;
943}
944
945/// dumpFilterArray - dumpFilterArray prints out debugging info for the given
946/// filter array as a series of chars.
947void FilterChooser::dumpFilterArray(raw_ostream &o,
Craig Topper48c112b2012-03-16 05:58:09 +0000948 const std::vector<bit_value_t> &filter) const {
Craig Topper29688ab2012-08-17 05:42:16 +0000949 for (unsigned bitIndex = BitWidth; bitIndex > 0; bitIndex--) {
Owen Anderson4e818902011-02-18 21:51:29 +0000950 switch (filter[bitIndex - 1]) {
951 case BIT_UNFILTERED:
952 o << ".";
953 break;
954 case BIT_UNSET:
955 o << "_";
956 break;
957 case BIT_TRUE:
958 o << "1";
959 break;
960 case BIT_FALSE:
961 o << "0";
962 break;
963 }
964 }
965}
966
967/// dumpStack - dumpStack traverses the filter chooser chain and calls
968/// dumpFilterArray on each filter chooser up to the top level one.
Craig Topper48c112b2012-03-16 05:58:09 +0000969void FilterChooser::dumpStack(raw_ostream &o, const char *prefix) const {
970 const FilterChooser *current = this;
Owen Anderson4e818902011-02-18 21:51:29 +0000971
972 while (current) {
973 o << prefix;
974 dumpFilterArray(o, current->FilterBitValues);
975 o << '\n';
976 current = current->Parent;
977 }
978}
979
980// Called from Filter::recurse() when singleton exists. For debug purpose.
Craig Topper48c112b2012-03-16 05:58:09 +0000981void FilterChooser::SingletonExists(unsigned Opc) const {
Owen Anderson4e818902011-02-18 21:51:29 +0000982 insn_t Insn0;
983 insnWithID(Insn0, Opc);
984
985 errs() << "Singleton exists: " << nameWithID(Opc)
986 << " with its decoding dominating ";
987 for (unsigned i = 0; i < Opcodes.size(); ++i) {
988 if (Opcodes[i] == Opc) continue;
989 errs() << nameWithID(Opcodes[i]) << ' ';
990 }
991 errs() << '\n';
992
993 dumpStack(errs(), "\t\t");
Craig Topper82d0d5f2012-03-16 01:19:24 +0000994 for (unsigned i = 0; i < Opcodes.size(); ++i) {
Owen Anderson4e818902011-02-18 21:51:29 +0000995 const std::string &Name = nameWithID(Opcodes[i]);
996
997 errs() << '\t' << Name << " ";
998 dumpBits(errs(),
999 getBitsField(*AllInstructions[Opcodes[i]]->TheDef, "Inst"));
1000 errs() << '\n';
1001 }
1002}
1003
1004// Calculates the island(s) needed to decode the instruction.
1005// This returns a list of undecoded bits of an instructions, for example,
1006// Inst{20} = 1 && Inst{3-0} == 0b1111 represents two islands of yet-to-be
1007// decoded bits in order to verify that the instruction matches the Opcode.
1008unsigned FilterChooser::getIslands(std::vector<unsigned> &StartBits,
Craig Topper82d0d5f2012-03-16 01:19:24 +00001009 std::vector<unsigned> &EndBits,
1010 std::vector<uint64_t> &FieldVals,
Craig Topper48c112b2012-03-16 05:58:09 +00001011 const insn_t &Insn) const {
Owen Anderson4e818902011-02-18 21:51:29 +00001012 unsigned Num, BitNo;
1013 Num = BitNo = 0;
1014
1015 uint64_t FieldVal = 0;
1016
1017 // 0: Init
1018 // 1: Water (the bit value does not affect decoding)
1019 // 2: Island (well-known bit value needed for decoding)
1020 int State = 0;
1021 int Val = -1;
1022
Owen Andersonc78e03c2011-07-19 21:06:00 +00001023 for (unsigned i = 0; i < BitWidth; ++i) {
Owen Anderson4e818902011-02-18 21:51:29 +00001024 Val = Value(Insn[i]);
1025 bool Filtered = PositionFiltered(i);
1026 switch (State) {
Craig Topperc4965bc2012-02-05 07:21:30 +00001027 default: llvm_unreachable("Unreachable code!");
Owen Anderson4e818902011-02-18 21:51:29 +00001028 case 0:
1029 case 1:
1030 if (Filtered || Val == -1)
1031 State = 1; // Still in Water
1032 else {
1033 State = 2; // Into the Island
1034 BitNo = 0;
1035 StartBits.push_back(i);
1036 FieldVal = Val;
1037 }
1038 break;
1039 case 2:
1040 if (Filtered || Val == -1) {
1041 State = 1; // Into the Water
1042 EndBits.push_back(i - 1);
1043 FieldVals.push_back(FieldVal);
1044 ++Num;
1045 } else {
1046 State = 2; // Still in Island
1047 ++BitNo;
1048 FieldVal = FieldVal | Val << BitNo;
1049 }
1050 break;
1051 }
1052 }
1053 // If we are still in Island after the loop, do some housekeeping.
1054 if (State == 2) {
Owen Andersonc78e03c2011-07-19 21:06:00 +00001055 EndBits.push_back(BitWidth - 1);
Owen Anderson4e818902011-02-18 21:51:29 +00001056 FieldVals.push_back(FieldVal);
1057 ++Num;
1058 }
1059
1060 assert(StartBits.size() == Num && EndBits.size() == Num &&
1061 FieldVals.size() == Num);
1062 return Num;
1063}
1064
Owen Andersone3591652011-07-28 21:54:31 +00001065void FilterChooser::emitBinaryParser(raw_ostream &o, unsigned &Indentation,
Craig Topper48c112b2012-03-16 05:58:09 +00001066 const OperandInfo &OpInfo) const {
1067 const std::string &Decoder = OpInfo.Decoder;
Owen Andersone3591652011-07-28 21:54:31 +00001068
1069 if (OpInfo.numFields() == 1) {
Craig Topper48c112b2012-03-16 05:58:09 +00001070 OperandInfo::const_iterator OI = OpInfo.begin();
Craig Topperebc3aa22012-08-17 05:16:15 +00001071 o.indent(Indentation) << "tmp = fieldFromInstruction"
Jim Grosbachecaef492012-08-14 19:06:05 +00001072 << "(insn, " << OI->Base << ", " << OI->Width
1073 << ");\n";
Owen Andersone3591652011-07-28 21:54:31 +00001074 } else {
Craig Topperebc3aa22012-08-17 05:16:15 +00001075 o.indent(Indentation) << "tmp = 0;\n";
Craig Topper48c112b2012-03-16 05:58:09 +00001076 for (OperandInfo::const_iterator OI = OpInfo.begin(), OE = OpInfo.end();
Owen Andersone3591652011-07-28 21:54:31 +00001077 OI != OE; ++OI) {
Craig Topperebc3aa22012-08-17 05:16:15 +00001078 o.indent(Indentation) << "tmp |= (fieldFromInstruction"
Andrew Trick61abca62011-09-08 05:23:14 +00001079 << "(insn, " << OI->Base << ", " << OI->Width
Owen Andersone3591652011-07-28 21:54:31 +00001080 << ") << " << OI->Offset << ");\n";
1081 }
1082 }
1083
1084 if (Decoder != "")
Craig Topperebc3aa22012-08-17 05:16:15 +00001085 o.indent(Indentation) << Emitter->GuardPrefix << Decoder
Jim Grosbach3f4b2392012-02-29 22:07:56 +00001086 << "(MI, tmp, Address, Decoder)"
1087 << Emitter->GuardPostfix << "\n";
Owen Andersone3591652011-07-28 21:54:31 +00001088 else
Craig Topperebc3aa22012-08-17 05:16:15 +00001089 o.indent(Indentation) << "MI.addOperand(MCOperand::CreateImm(tmp));\n";
Owen Andersone3591652011-07-28 21:54:31 +00001090
1091}
1092
Jim Grosbachecaef492012-08-14 19:06:05 +00001093void FilterChooser::emitDecoder(raw_ostream &OS, unsigned Indentation,
1094 unsigned Opc) const {
1095 std::map<unsigned, std::vector<OperandInfo> >::const_iterator OpIter =
1096 Operands.find(Opc);
1097 const std::vector<OperandInfo>& InsnOperands = OpIter->second;
1098 for (std::vector<OperandInfo>::const_iterator
1099 I = InsnOperands.begin(), E = InsnOperands.end(); I != E; ++I) {
1100 // If a custom instruction decoder was specified, use that.
1101 if (I->numFields() == 0 && I->Decoder.size()) {
Craig Topperebc3aa22012-08-17 05:16:15 +00001102 OS.indent(Indentation) << Emitter->GuardPrefix << I->Decoder
Jim Grosbachecaef492012-08-14 19:06:05 +00001103 << "(MI, insn, Address, Decoder)"
1104 << Emitter->GuardPostfix << "\n";
1105 break;
1106 }
1107
1108 emitBinaryParser(OS, Indentation, *I);
1109 }
1110}
1111
1112unsigned FilterChooser::getDecoderIndex(DecoderSet &Decoders,
1113 unsigned Opc) const {
1114 // Build up the predicate string.
1115 SmallString<256> Decoder;
1116 // FIXME: emitDecoder() function can take a buffer directly rather than
1117 // a stream.
1118 raw_svector_ostream S(Decoder);
Craig Topperebc3aa22012-08-17 05:16:15 +00001119 unsigned I = 4;
Jim Grosbachecaef492012-08-14 19:06:05 +00001120 emitDecoder(S, I, Opc);
1121 S.flush();
1122
1123 // Using the full decoder string as the key value here is a bit
1124 // heavyweight, but is effective. If the string comparisons become a
1125 // performance concern, we can implement a mangling of the predicate
1126 // data easilly enough with a map back to the actual string. That's
1127 // overkill for now, though.
1128
1129 // Make sure the predicate is in the table.
1130 Decoders.insert(Decoder.str());
1131 // Now figure out the index for when we write out the table.
1132 DecoderSet::const_iterator P = std::find(Decoders.begin(),
1133 Decoders.end(),
1134 Decoder.str());
1135 return (unsigned)(P - Decoders.begin());
1136}
1137
James Molloy8067df92011-09-07 19:42:28 +00001138static void emitSinglePredicateMatch(raw_ostream &o, StringRef str,
Craig Topper48c112b2012-03-16 05:58:09 +00001139 const std::string &PredicateNamespace) {
Andrew Trick43674ad2011-09-08 05:25:49 +00001140 if (str[0] == '!')
1141 o << "!(Bits & " << PredicateNamespace << "::"
1142 << str.slice(1,str.size()) << ")";
James Molloy8067df92011-09-07 19:42:28 +00001143 else
Andrew Trick43674ad2011-09-08 05:25:49 +00001144 o << "(Bits & " << PredicateNamespace << "::" << str << ")";
James Molloy8067df92011-09-07 19:42:28 +00001145}
1146
1147bool FilterChooser::emitPredicateMatch(raw_ostream &o, unsigned &Indentation,
Craig Topper48c112b2012-03-16 05:58:09 +00001148 unsigned Opc) const {
Jim Grosbach3f4b2392012-02-29 22:07:56 +00001149 ListInit *Predicates =
1150 AllInstructions[Opc]->TheDef->getValueAsListInit("Predicates");
James Molloy8067df92011-09-07 19:42:28 +00001151 for (unsigned i = 0; i < Predicates->getSize(); ++i) {
1152 Record *Pred = Predicates->getElementAsRecord(i);
1153 if (!Pred->getValue("AssemblerMatcherPredicate"))
1154 continue;
1155
1156 std::string P = Pred->getValueAsString("AssemblerCondString");
1157
1158 if (!P.length())
1159 continue;
1160
1161 if (i != 0)
1162 o << " && ";
1163
1164 StringRef SR(P);
1165 std::pair<StringRef, StringRef> pairs = SR.split(',');
1166 while (pairs.second.size()) {
1167 emitSinglePredicateMatch(o, pairs.first, Emitter->PredicateNamespace);
1168 o << " && ";
1169 pairs = pairs.second.split(',');
1170 }
1171 emitSinglePredicateMatch(o, pairs.first, Emitter->PredicateNamespace);
1172 }
1173 return Predicates->getSize() > 0;
Andrew Trick61abca62011-09-08 05:23:14 +00001174}
James Molloy8067df92011-09-07 19:42:28 +00001175
Jim Grosbachecaef492012-08-14 19:06:05 +00001176bool FilterChooser::doesOpcodeNeedPredicate(unsigned Opc) const {
1177 ListInit *Predicates =
1178 AllInstructions[Opc]->TheDef->getValueAsListInit("Predicates");
1179 for (unsigned i = 0; i < Predicates->getSize(); ++i) {
1180 Record *Pred = Predicates->getElementAsRecord(i);
1181 if (!Pred->getValue("AssemblerMatcherPredicate"))
1182 continue;
1183
1184 std::string P = Pred->getValueAsString("AssemblerCondString");
1185
1186 if (!P.length())
1187 continue;
1188
1189 return true;
1190 }
1191 return false;
1192}
1193
1194unsigned FilterChooser::getPredicateIndex(DecoderTableInfo &TableInfo,
1195 StringRef Predicate) const {
1196 // Using the full predicate string as the key value here is a bit
1197 // heavyweight, but is effective. If the string comparisons become a
1198 // performance concern, we can implement a mangling of the predicate
1199 // data easilly enough with a map back to the actual string. That's
1200 // overkill for now, though.
1201
1202 // Make sure the predicate is in the table.
1203 TableInfo.Predicates.insert(Predicate.str());
1204 // Now figure out the index for when we write out the table.
1205 PredicateSet::const_iterator P = std::find(TableInfo.Predicates.begin(),
1206 TableInfo.Predicates.end(),
1207 Predicate.str());
1208 return (unsigned)(P - TableInfo.Predicates.begin());
1209}
1210
1211void FilterChooser::emitPredicateTableEntry(DecoderTableInfo &TableInfo,
1212 unsigned Opc) const {
1213 if (!doesOpcodeNeedPredicate(Opc))
1214 return;
1215
1216 // Build up the predicate string.
1217 SmallString<256> Predicate;
1218 // FIXME: emitPredicateMatch() functions can take a buffer directly rather
1219 // than a stream.
1220 raw_svector_ostream PS(Predicate);
1221 unsigned I = 0;
1222 emitPredicateMatch(PS, I, Opc);
1223
1224 // Figure out the index into the predicate table for the predicate just
1225 // computed.
1226 unsigned PIdx = getPredicateIndex(TableInfo, PS.str());
1227 SmallString<16> PBytes;
1228 raw_svector_ostream S(PBytes);
1229 encodeULEB128(PIdx, S);
1230 S.flush();
1231
1232 TableInfo.Table.push_back(MCD::OPC_CheckPredicate);
1233 // Predicate index
Craig Topper29688ab2012-08-17 05:42:16 +00001234 for (unsigned i = 0, e = PBytes.size(); i != e; ++i)
Jim Grosbachecaef492012-08-14 19:06:05 +00001235 TableInfo.Table.push_back(PBytes[i]);
1236 // Push location for NumToSkip backpatching.
1237 TableInfo.FixupStack.back().push_back(TableInfo.Table.size());
1238 TableInfo.Table.push_back(0);
1239 TableInfo.Table.push_back(0);
1240}
1241
1242void FilterChooser::emitSoftFailTableEntry(DecoderTableInfo &TableInfo,
1243 unsigned Opc) const {
Jim Grosbach3f4b2392012-02-29 22:07:56 +00001244 BitsInit *SFBits =
1245 AllInstructions[Opc]->TheDef->getValueAsBitsInit("SoftFail");
James Molloyd9ba4fd2012-02-09 10:56:31 +00001246 if (!SFBits) return;
1247 BitsInit *InstBits = AllInstructions[Opc]->TheDef->getValueAsBitsInit("Inst");
1248
1249 APInt PositiveMask(BitWidth, 0ULL);
1250 APInt NegativeMask(BitWidth, 0ULL);
1251 for (unsigned i = 0; i < BitWidth; ++i) {
1252 bit_value_t B = bitFromBits(*SFBits, i);
1253 bit_value_t IB = bitFromBits(*InstBits, i);
1254
1255 if (B != BIT_TRUE) continue;
1256
1257 switch (IB) {
1258 case BIT_FALSE:
1259 // The bit is meant to be false, so emit a check to see if it is true.
1260 PositiveMask.setBit(i);
1261 break;
1262 case BIT_TRUE:
1263 // The bit is meant to be true, so emit a check to see if it is false.
1264 NegativeMask.setBit(i);
1265 break;
1266 default:
1267 // The bit is not set; this must be an error!
1268 StringRef Name = AllInstructions[Opc]->TheDef->getName();
Jim Grosbachecaef492012-08-14 19:06:05 +00001269 errs() << "SoftFail Conflict: bit SoftFail{" << i << "} in " << Name
1270 << " is set but Inst{" << i << "} is unset!\n"
James Molloyd9ba4fd2012-02-09 10:56:31 +00001271 << " - You can only mark a bit as SoftFail if it is fully defined"
1272 << " (1/0 - not '?') in Inst\n";
Jim Grosbachecaef492012-08-14 19:06:05 +00001273 return;
James Molloyd9ba4fd2012-02-09 10:56:31 +00001274 }
1275 }
1276
1277 bool NeedPositiveMask = PositiveMask.getBoolValue();
1278 bool NeedNegativeMask = NegativeMask.getBoolValue();
1279
1280 if (!NeedPositiveMask && !NeedNegativeMask)
1281 return;
1282
Jim Grosbachecaef492012-08-14 19:06:05 +00001283 TableInfo.Table.push_back(MCD::OPC_SoftFail);
James Molloyd9ba4fd2012-02-09 10:56:31 +00001284
Jim Grosbachecaef492012-08-14 19:06:05 +00001285 SmallString<16> MaskBytes;
1286 raw_svector_ostream S(MaskBytes);
1287 if (NeedPositiveMask) {
1288 encodeULEB128(PositiveMask.getZExtValue(), S);
1289 S.flush();
Craig Topper29688ab2012-08-17 05:42:16 +00001290 for (unsigned i = 0, e = MaskBytes.size(); i != e; ++i)
Jim Grosbachecaef492012-08-14 19:06:05 +00001291 TableInfo.Table.push_back(MaskBytes[i]);
1292 } else
1293 TableInfo.Table.push_back(0);
1294 if (NeedNegativeMask) {
1295 MaskBytes.clear();
1296 S.resync();
1297 encodeULEB128(NegativeMask.getZExtValue(), S);
1298 S.flush();
Craig Topper29688ab2012-08-17 05:42:16 +00001299 for (unsigned i = 0, e = MaskBytes.size(); i != e; ++i)
Jim Grosbachecaef492012-08-14 19:06:05 +00001300 TableInfo.Table.push_back(MaskBytes[i]);
1301 } else
1302 TableInfo.Table.push_back(0);
James Molloyd9ba4fd2012-02-09 10:56:31 +00001303}
1304
Jim Grosbachecaef492012-08-14 19:06:05 +00001305// Emits table entries to decode the singleton.
1306void FilterChooser::emitSingletonTableEntry(DecoderTableInfo &TableInfo,
1307 unsigned Opc) const {
Owen Anderson4e818902011-02-18 21:51:29 +00001308 std::vector<unsigned> StartBits;
1309 std::vector<unsigned> EndBits;
1310 std::vector<uint64_t> FieldVals;
1311 insn_t Insn;
1312 insnWithID(Insn, Opc);
1313
1314 // Look for islands of undecoded bits of the singleton.
1315 getIslands(StartBits, EndBits, FieldVals, Insn);
1316
1317 unsigned Size = StartBits.size();
Owen Anderson4e818902011-02-18 21:51:29 +00001318
Jim Grosbachecaef492012-08-14 19:06:05 +00001319 // Emit the predicate table entry if one is needed.
1320 emitPredicateTableEntry(TableInfo, Opc);
Owen Anderson4e818902011-02-18 21:51:29 +00001321
Jim Grosbachecaef492012-08-14 19:06:05 +00001322 // Check any additional encoding fields needed.
Craig Topper29688ab2012-08-17 05:42:16 +00001323 for (unsigned I = Size; I != 0; --I) {
1324 unsigned NumBits = EndBits[I-1] - StartBits[I-1] + 1;
Jim Grosbachecaef492012-08-14 19:06:05 +00001325 TableInfo.Table.push_back(MCD::OPC_CheckField);
1326 TableInfo.Table.push_back(StartBits[I-1]);
1327 TableInfo.Table.push_back(NumBits);
1328 uint8_t Buffer[8], *p;
1329 encodeULEB128(FieldVals[I-1], Buffer);
1330 for (p = Buffer; *p >= 128 ; ++p)
1331 TableInfo.Table.push_back(*p);
1332 TableInfo.Table.push_back(*p);
1333 // Push location for NumToSkip backpatching.
1334 TableInfo.FixupStack.back().push_back(TableInfo.Table.size());
1335 // The fixup is always 16-bits, so go ahead and allocate the space
1336 // in the table so all our relative position calculations work OK even
1337 // before we fully resolve the real value here.
1338 TableInfo.Table.push_back(0);
1339 TableInfo.Table.push_back(0);
Owen Anderson4e818902011-02-18 21:51:29 +00001340 }
Owen Anderson4e818902011-02-18 21:51:29 +00001341
Jim Grosbachecaef492012-08-14 19:06:05 +00001342 // Check for soft failure of the match.
1343 emitSoftFailTableEntry(TableInfo, Opc);
Owen Anderson4e818902011-02-18 21:51:29 +00001344
Jim Grosbachecaef492012-08-14 19:06:05 +00001345 TableInfo.Table.push_back(MCD::OPC_Decode);
1346 uint8_t Buffer[8], *p;
1347 encodeULEB128(Opc, Buffer);
1348 for (p = Buffer; *p >= 128 ; ++p)
1349 TableInfo.Table.push_back(*p);
1350 TableInfo.Table.push_back(*p);
1351
1352 unsigned DIdx = getDecoderIndex(TableInfo.Decoders, Opc);
1353 SmallString<16> Bytes;
1354 raw_svector_ostream S(Bytes);
1355 encodeULEB128(DIdx, S);
1356 S.flush();
1357
1358 // Decoder index
Craig Topper29688ab2012-08-17 05:42:16 +00001359 for (unsigned i = 0, e = Bytes.size(); i != e; ++i)
Jim Grosbachecaef492012-08-14 19:06:05 +00001360 TableInfo.Table.push_back(Bytes[i]);
Owen Anderson4e818902011-02-18 21:51:29 +00001361}
1362
Jim Grosbachecaef492012-08-14 19:06:05 +00001363// Emits table entries to decode the singleton, and then to decode the rest.
1364void FilterChooser::emitSingletonTableEntry(DecoderTableInfo &TableInfo,
1365 const Filter &Best) const {
Owen Anderson4e818902011-02-18 21:51:29 +00001366 unsigned Opc = Best.getSingletonOpc();
1367
Jim Grosbachecaef492012-08-14 19:06:05 +00001368 // complex singletons need predicate checks from the first singleton
1369 // to refer forward to the variable filterchooser that follows.
1370 TableInfo.FixupStack.push_back(FixupList());
Owen Anderson4e818902011-02-18 21:51:29 +00001371
Jim Grosbachecaef492012-08-14 19:06:05 +00001372 emitSingletonTableEntry(TableInfo, Opc);
Owen Anderson4e818902011-02-18 21:51:29 +00001373
Jim Grosbachecaef492012-08-14 19:06:05 +00001374 resolveTableFixups(TableInfo.Table, TableInfo.FixupStack.back(),
1375 TableInfo.Table.size());
1376 TableInfo.FixupStack.pop_back();
1377
1378 Best.getVariableFC().emitTableEntries(TableInfo);
Owen Anderson4e818902011-02-18 21:51:29 +00001379}
1380
Jim Grosbachecaef492012-08-14 19:06:05 +00001381
Owen Anderson4e818902011-02-18 21:51:29 +00001382// Assign a single filter and run with it. Top level API client can initialize
1383// with a single filter to start the filtering process.
Craig Topper48c112b2012-03-16 05:58:09 +00001384void FilterChooser::runSingleFilter(unsigned startBit, unsigned numBit,
1385 bool mixed) {
Owen Anderson4e818902011-02-18 21:51:29 +00001386 Filters.clear();
1387 Filter F(*this, startBit, numBit, true);
1388 Filters.push_back(F);
1389 BestIndex = 0; // Sole Filter instance to choose from.
1390 bestFilter().recurse();
1391}
1392
1393// reportRegion is a helper function for filterProcessor to mark a region as
1394// eligible for use as a filter region.
1395void FilterChooser::reportRegion(bitAttr_t RA, unsigned StartBit,
Craig Topper82d0d5f2012-03-16 01:19:24 +00001396 unsigned BitIndex, bool AllowMixed) {
Owen Anderson4e818902011-02-18 21:51:29 +00001397 if (RA == ATTR_MIXED && AllowMixed)
1398 Filters.push_back(Filter(*this, StartBit, BitIndex - StartBit, true));
1399 else if (RA == ATTR_ALL_SET && !AllowMixed)
1400 Filters.push_back(Filter(*this, StartBit, BitIndex - StartBit, false));
1401}
1402
1403// FilterProcessor scans the well-known encoding bits of the instructions and
1404// builds up a list of candidate filters. It chooses the best filter and
1405// recursively descends down the decoding tree.
1406bool FilterChooser::filterProcessor(bool AllowMixed, bool Greedy) {
1407 Filters.clear();
1408 BestIndex = -1;
1409 unsigned numInstructions = Opcodes.size();
1410
1411 assert(numInstructions && "Filter created with no instructions");
1412
1413 // No further filtering is necessary.
1414 if (numInstructions == 1)
1415 return true;
1416
1417 // Heuristics. See also doFilter()'s "Heuristics" comment when num of
1418 // instructions is 3.
1419 if (AllowMixed && !Greedy) {
1420 assert(numInstructions == 3);
1421
1422 for (unsigned i = 0; i < Opcodes.size(); ++i) {
1423 std::vector<unsigned> StartBits;
1424 std::vector<unsigned> EndBits;
1425 std::vector<uint64_t> FieldVals;
1426 insn_t Insn;
1427
1428 insnWithID(Insn, Opcodes[i]);
1429
1430 // Look for islands of undecoded bits of any instruction.
1431 if (getIslands(StartBits, EndBits, FieldVals, Insn) > 0) {
1432 // Found an instruction with island(s). Now just assign a filter.
Craig Topper48c112b2012-03-16 05:58:09 +00001433 runSingleFilter(StartBits[0], EndBits[0] - StartBits[0] + 1, true);
Owen Anderson4e818902011-02-18 21:51:29 +00001434 return true;
1435 }
1436 }
1437 }
1438
Craig Topper29688ab2012-08-17 05:42:16 +00001439 unsigned BitIndex;
Owen Anderson4e818902011-02-18 21:51:29 +00001440
1441 // We maintain BIT_WIDTH copies of the bitAttrs automaton.
1442 // The automaton consumes the corresponding bit from each
1443 // instruction.
1444 //
1445 // Input symbols: 0, 1, and _ (unset).
1446 // States: NONE, FILTERED, ALL_SET, ALL_UNSET, and MIXED.
1447 // Initial state: NONE.
1448 //
1449 // (NONE) ------- [01] -> (ALL_SET)
1450 // (NONE) ------- _ ----> (ALL_UNSET)
1451 // (ALL_SET) ---- [01] -> (ALL_SET)
1452 // (ALL_SET) ---- _ ----> (MIXED)
1453 // (ALL_UNSET) -- [01] -> (MIXED)
1454 // (ALL_UNSET) -- _ ----> (ALL_UNSET)
1455 // (MIXED) ------ . ----> (MIXED)
1456 // (FILTERED)---- . ----> (FILTERED)
1457
Owen Andersonc78e03c2011-07-19 21:06:00 +00001458 std::vector<bitAttr_t> bitAttrs;
Owen Anderson4e818902011-02-18 21:51:29 +00001459
1460 // FILTERED bit positions provide no entropy and are not worthy of pursuing.
1461 // Filter::recurse() set either BIT_TRUE or BIT_FALSE for each position.
Owen Andersonc78e03c2011-07-19 21:06:00 +00001462 for (BitIndex = 0; BitIndex < BitWidth; ++BitIndex)
Owen Anderson4e818902011-02-18 21:51:29 +00001463 if (FilterBitValues[BitIndex] == BIT_TRUE ||
1464 FilterBitValues[BitIndex] == BIT_FALSE)
Owen Andersonc78e03c2011-07-19 21:06:00 +00001465 bitAttrs.push_back(ATTR_FILTERED);
Owen Anderson4e818902011-02-18 21:51:29 +00001466 else
Owen Andersonc78e03c2011-07-19 21:06:00 +00001467 bitAttrs.push_back(ATTR_NONE);
Owen Anderson4e818902011-02-18 21:51:29 +00001468
Craig Topper29688ab2012-08-17 05:42:16 +00001469 for (unsigned InsnIndex = 0; InsnIndex < numInstructions; ++InsnIndex) {
Owen Anderson4e818902011-02-18 21:51:29 +00001470 insn_t insn;
1471
1472 insnWithID(insn, Opcodes[InsnIndex]);
1473
Owen Andersonc78e03c2011-07-19 21:06:00 +00001474 for (BitIndex = 0; BitIndex < BitWidth; ++BitIndex) {
Owen Anderson4e818902011-02-18 21:51:29 +00001475 switch (bitAttrs[BitIndex]) {
1476 case ATTR_NONE:
1477 if (insn[BitIndex] == BIT_UNSET)
1478 bitAttrs[BitIndex] = ATTR_ALL_UNSET;
1479 else
1480 bitAttrs[BitIndex] = ATTR_ALL_SET;
1481 break;
1482 case ATTR_ALL_SET:
1483 if (insn[BitIndex] == BIT_UNSET)
1484 bitAttrs[BitIndex] = ATTR_MIXED;
1485 break;
1486 case ATTR_ALL_UNSET:
1487 if (insn[BitIndex] != BIT_UNSET)
1488 bitAttrs[BitIndex] = ATTR_MIXED;
1489 break;
1490 case ATTR_MIXED:
1491 case ATTR_FILTERED:
1492 break;
1493 }
1494 }
1495 }
1496
1497 // The regionAttr automaton consumes the bitAttrs automatons' state,
1498 // lowest-to-highest.
1499 //
1500 // Input symbols: F(iltered), (all_)S(et), (all_)U(nset), M(ixed)
1501 // States: NONE, ALL_SET, MIXED
1502 // Initial state: NONE
1503 //
1504 // (NONE) ----- F --> (NONE)
1505 // (NONE) ----- S --> (ALL_SET) ; and set region start
1506 // (NONE) ----- U --> (NONE)
1507 // (NONE) ----- M --> (MIXED) ; and set region start
1508 // (ALL_SET) -- F --> (NONE) ; and report an ALL_SET region
1509 // (ALL_SET) -- S --> (ALL_SET)
1510 // (ALL_SET) -- U --> (NONE) ; and report an ALL_SET region
1511 // (ALL_SET) -- M --> (MIXED) ; and report an ALL_SET region
1512 // (MIXED) ---- F --> (NONE) ; and report a MIXED region
1513 // (MIXED) ---- S --> (ALL_SET) ; and report a MIXED region
1514 // (MIXED) ---- U --> (NONE) ; and report a MIXED region
1515 // (MIXED) ---- M --> (MIXED)
1516
1517 bitAttr_t RA = ATTR_NONE;
1518 unsigned StartBit = 0;
1519
Craig Topper29688ab2012-08-17 05:42:16 +00001520 for (BitIndex = 0; BitIndex < BitWidth; ++BitIndex) {
Owen Anderson4e818902011-02-18 21:51:29 +00001521 bitAttr_t bitAttr = bitAttrs[BitIndex];
1522
1523 assert(bitAttr != ATTR_NONE && "Bit without attributes");
1524
1525 switch (RA) {
1526 case ATTR_NONE:
1527 switch (bitAttr) {
1528 case ATTR_FILTERED:
1529 break;
1530 case ATTR_ALL_SET:
1531 StartBit = BitIndex;
1532 RA = ATTR_ALL_SET;
1533 break;
1534 case ATTR_ALL_UNSET:
1535 break;
1536 case ATTR_MIXED:
1537 StartBit = BitIndex;
1538 RA = ATTR_MIXED;
1539 break;
1540 default:
Craig Topperc4965bc2012-02-05 07:21:30 +00001541 llvm_unreachable("Unexpected bitAttr!");
Owen Anderson4e818902011-02-18 21:51:29 +00001542 }
1543 break;
1544 case ATTR_ALL_SET:
1545 switch (bitAttr) {
1546 case ATTR_FILTERED:
1547 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1548 RA = ATTR_NONE;
1549 break;
1550 case ATTR_ALL_SET:
1551 break;
1552 case ATTR_ALL_UNSET:
1553 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1554 RA = ATTR_NONE;
1555 break;
1556 case ATTR_MIXED:
1557 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1558 StartBit = BitIndex;
1559 RA = ATTR_MIXED;
1560 break;
1561 default:
Craig Topperc4965bc2012-02-05 07:21:30 +00001562 llvm_unreachable("Unexpected bitAttr!");
Owen Anderson4e818902011-02-18 21:51:29 +00001563 }
1564 break;
1565 case ATTR_MIXED:
1566 switch (bitAttr) {
1567 case ATTR_FILTERED:
1568 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1569 StartBit = BitIndex;
1570 RA = ATTR_NONE;
1571 break;
1572 case ATTR_ALL_SET:
1573 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1574 StartBit = BitIndex;
1575 RA = ATTR_ALL_SET;
1576 break;
1577 case ATTR_ALL_UNSET:
1578 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1579 RA = ATTR_NONE;
1580 break;
1581 case ATTR_MIXED:
1582 break;
1583 default:
Craig Topperc4965bc2012-02-05 07:21:30 +00001584 llvm_unreachable("Unexpected bitAttr!");
Owen Anderson4e818902011-02-18 21:51:29 +00001585 }
1586 break;
1587 case ATTR_ALL_UNSET:
Craig Topperc4965bc2012-02-05 07:21:30 +00001588 llvm_unreachable("regionAttr state machine has no ATTR_UNSET state");
Owen Anderson4e818902011-02-18 21:51:29 +00001589 case ATTR_FILTERED:
Craig Topperc4965bc2012-02-05 07:21:30 +00001590 llvm_unreachable("regionAttr state machine has no ATTR_FILTERED state");
Owen Anderson4e818902011-02-18 21:51:29 +00001591 }
1592 }
1593
1594 // At the end, if we're still in ALL_SET or MIXED states, report a region
1595 switch (RA) {
1596 case ATTR_NONE:
1597 break;
1598 case ATTR_FILTERED:
1599 break;
1600 case ATTR_ALL_SET:
1601 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1602 break;
1603 case ATTR_ALL_UNSET:
1604 break;
1605 case ATTR_MIXED:
1606 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1607 break;
1608 }
1609
1610 // We have finished with the filter processings. Now it's time to choose
1611 // the best performing filter.
1612 BestIndex = 0;
1613 bool AllUseless = true;
1614 unsigned BestScore = 0;
1615
1616 for (unsigned i = 0, e = Filters.size(); i != e; ++i) {
1617 unsigned Usefulness = Filters[i].usefulness();
1618
1619 if (Usefulness)
1620 AllUseless = false;
1621
1622 if (Usefulness > BestScore) {
1623 BestIndex = i;
1624 BestScore = Usefulness;
1625 }
1626 }
1627
1628 if (!AllUseless)
1629 bestFilter().recurse();
1630
1631 return !AllUseless;
1632} // end of FilterChooser::filterProcessor(bool)
1633
1634// Decides on the best configuration of filter(s) to use in order to decode
1635// the instructions. A conflict of instructions may occur, in which case we
1636// dump the conflict set to the standard error.
1637void FilterChooser::doFilter() {
1638 unsigned Num = Opcodes.size();
1639 assert(Num && "FilterChooser created with no instructions");
1640
1641 // Try regions of consecutive known bit values first.
1642 if (filterProcessor(false))
1643 return;
1644
1645 // Then regions of mixed bits (both known and unitialized bit values allowed).
1646 if (filterProcessor(true))
1647 return;
1648
1649 // Heuristics to cope with conflict set {t2CMPrs, t2SUBSrr, t2SUBSrs} where
1650 // no single instruction for the maximum ATTR_MIXED region Inst{14-4} has a
1651 // well-known encoding pattern. In such case, we backtrack and scan for the
1652 // the very first consecutive ATTR_ALL_SET region and assign a filter to it.
1653 if (Num == 3 && filterProcessor(true, false))
1654 return;
1655
1656 // If we come to here, the instruction decoding has failed.
1657 // Set the BestIndex to -1 to indicate so.
1658 BestIndex = -1;
1659}
1660
Jim Grosbachecaef492012-08-14 19:06:05 +00001661// emitTableEntries - Emit state machine entries to decode our share of
1662// instructions.
1663void FilterChooser::emitTableEntries(DecoderTableInfo &TableInfo) const {
1664 if (Opcodes.size() == 1) {
Owen Anderson4e818902011-02-18 21:51:29 +00001665 // There is only one instruction in the set, which is great!
1666 // Call emitSingletonDecoder() to see whether there are any remaining
1667 // encodings bits.
Jim Grosbachecaef492012-08-14 19:06:05 +00001668 emitSingletonTableEntry(TableInfo, Opcodes[0]);
1669 return;
1670 }
Owen Anderson4e818902011-02-18 21:51:29 +00001671
1672 // Choose the best filter to do the decodings!
1673 if (BestIndex != -1) {
Craig Topper48c112b2012-03-16 05:58:09 +00001674 const Filter &Best = Filters[BestIndex];
Owen Anderson4e818902011-02-18 21:51:29 +00001675 if (Best.getNumFiltered() == 1)
Jim Grosbachecaef492012-08-14 19:06:05 +00001676 emitSingletonTableEntry(TableInfo, Best);
Owen Anderson4e818902011-02-18 21:51:29 +00001677 else
Jim Grosbachecaef492012-08-14 19:06:05 +00001678 Best.emitTableEntry(TableInfo);
1679 return;
Owen Anderson4e818902011-02-18 21:51:29 +00001680 }
1681
Jim Grosbachecaef492012-08-14 19:06:05 +00001682 // We don't know how to decode these instructions! Dump the
1683 // conflict set and bail.
Owen Anderson4e818902011-02-18 21:51:29 +00001684
1685 // Print out useful conflict information for postmortem analysis.
1686 errs() << "Decoding Conflict:\n";
1687
1688 dumpStack(errs(), "\t\t");
1689
Craig Topper82d0d5f2012-03-16 01:19:24 +00001690 for (unsigned i = 0; i < Opcodes.size(); ++i) {
Owen Anderson4e818902011-02-18 21:51:29 +00001691 const std::string &Name = nameWithID(Opcodes[i]);
1692
1693 errs() << '\t' << Name << " ";
1694 dumpBits(errs(),
1695 getBitsField(*AllInstructions[Opcodes[i]]->TheDef, "Inst"));
1696 errs() << '\n';
1697 }
Owen Anderson4e818902011-02-18 21:51:29 +00001698}
1699
Hal Finkel71b2e202013-12-19 16:12:53 +00001700static bool populateInstruction(CodeGenTarget &Target,
1701 const CodeGenInstruction &CGI, unsigned Opc,
Craig Topper82d0d5f2012-03-16 01:19:24 +00001702 std::map<unsigned, std::vector<OperandInfo> > &Operands){
Owen Anderson4e818902011-02-18 21:51:29 +00001703 const Record &Def = *CGI.TheDef;
1704 // If all the bit positions are not specified; do not decode this instruction.
1705 // We are bound to fail! For proper disassembly, the well-known encoding bits
1706 // of the instruction must be fully specified.
Owen Anderson4e818902011-02-18 21:51:29 +00001707
David Greeneaf8ee2c2011-07-29 22:43:06 +00001708 BitsInit &Bits = getBitsField(Def, "Inst");
Jim Grosbachf3fd36e2011-07-06 21:33:38 +00001709 if (Bits.allInComplete()) return false;
1710
Owen Anderson4e818902011-02-18 21:51:29 +00001711 std::vector<OperandInfo> InsnOperands;
1712
1713 // If the instruction has specified a custom decoding hook, use that instead
1714 // of trying to auto-generate the decoder.
1715 std::string InstDecoder = Def.getValueAsString("DecoderMethod");
1716 if (InstDecoder != "") {
Owen Andersone3591652011-07-28 21:54:31 +00001717 InsnOperands.push_back(OperandInfo(InstDecoder));
Owen Anderson4e818902011-02-18 21:51:29 +00001718 Operands[Opc] = InsnOperands;
1719 return true;
1720 }
1721
1722 // Generate a description of the operand of the instruction that we know
1723 // how to decode automatically.
1724 // FIXME: We'll need to have a way to manually override this as needed.
1725
1726 // Gather the outputs/inputs of the instruction, so we can find their
1727 // positions in the encoding. This assumes for now that they appear in the
1728 // MCInst in the order that they're listed.
David Greeneaf8ee2c2011-07-29 22:43:06 +00001729 std::vector<std::pair<Init*, std::string> > InOutOperands;
1730 DagInit *Out = Def.getValueAsDag("OutOperandList");
1731 DagInit *In = Def.getValueAsDag("InOperandList");
Owen Anderson4e818902011-02-18 21:51:29 +00001732 for (unsigned i = 0; i < Out->getNumArgs(); ++i)
1733 InOutOperands.push_back(std::make_pair(Out->getArg(i), Out->getArgName(i)));
1734 for (unsigned i = 0; i < In->getNumArgs(); ++i)
1735 InOutOperands.push_back(std::make_pair(In->getArg(i), In->getArgName(i)));
1736
Owen Anderson53562d02011-07-28 23:56:20 +00001737 // Search for tied operands, so that we can correctly instantiate
1738 // operands that are not explicitly represented in the encoding.
Owen Andersoncb32ce22011-07-29 18:28:52 +00001739 std::map<std::string, std::string> TiedNames;
Owen Anderson53562d02011-07-28 23:56:20 +00001740 for (unsigned i = 0; i < CGI.Operands.size(); ++i) {
1741 int tiedTo = CGI.Operands[i].getTiedRegister();
Owen Andersoncb32ce22011-07-29 18:28:52 +00001742 if (tiedTo != -1) {
Hal Finkel71b2e202013-12-19 16:12:53 +00001743 std::pair<unsigned, unsigned> SO =
1744 CGI.Operands.getSubOperandNumber(tiedTo);
1745 TiedNames[InOutOperands[i].second] = InOutOperands[SO.first].second;
1746 TiedNames[InOutOperands[SO.first].second] = InOutOperands[i].second;
1747 }
1748 }
1749
1750 std::map<std::string, std::vector<OperandInfo> > NumberedInsnOperands;
1751 std::set<std::string> NumberedInsnOperandsNoTie;
1752 if (Target.getInstructionSet()->
1753 getValueAsBit("decodePositionallyEncodedOperands")) {
1754 const std::vector<RecordVal> &Vals = Def.getValues();
1755 unsigned NumberedOp = 0;
1756
Hal Finkel5457bd02014-03-13 07:57:54 +00001757 std::set<unsigned> NamedOpIndices;
1758 if (Target.getInstructionSet()->
1759 getValueAsBit("noNamedPositionallyEncodedOperands"))
1760 // Collect the set of operand indices that might correspond to named
1761 // operand, and skip these when assigning operands based on position.
1762 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
1763 unsigned OpIdx;
1764 if (!CGI.Operands.hasOperandNamed(Vals[i].getName(), OpIdx))
1765 continue;
1766
1767 NamedOpIndices.insert(OpIdx);
1768 }
1769
Hal Finkel71b2e202013-12-19 16:12:53 +00001770 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
1771 // Ignore fixed fields in the record, we're looking for values like:
1772 // bits<5> RST = { ?, ?, ?, ?, ? };
1773 if (Vals[i].getPrefix() || Vals[i].getValue()->isComplete())
1774 continue;
1775
1776 // Determine if Vals[i] actually contributes to the Inst encoding.
1777 unsigned bi = 0;
1778 for (; bi < Bits.getNumBits(); ++bi) {
Craig Topper24064772014-04-15 07:20:03 +00001779 VarInit *Var = nullptr;
Hal Finkel71b2e202013-12-19 16:12:53 +00001780 VarBitInit *BI = dyn_cast<VarBitInit>(Bits.getBit(bi));
1781 if (BI)
1782 Var = dyn_cast<VarInit>(BI->getBitVar());
1783 else
1784 Var = dyn_cast<VarInit>(Bits.getBit(bi));
1785
1786 if (Var && Var->getName() == Vals[i].getName())
1787 break;
1788 }
1789
1790 if (bi == Bits.getNumBits())
1791 continue;
1792
1793 // Skip variables that correspond to explicitly-named operands.
1794 unsigned OpIdx;
1795 if (CGI.Operands.hasOperandNamed(Vals[i].getName(), OpIdx))
1796 continue;
1797
1798 // Get the bit range for this operand:
1799 unsigned bitStart = bi++, bitWidth = 1;
1800 for (; bi < Bits.getNumBits(); ++bi) {
Craig Topper24064772014-04-15 07:20:03 +00001801 VarInit *Var = nullptr;
Hal Finkel71b2e202013-12-19 16:12:53 +00001802 VarBitInit *BI = dyn_cast<VarBitInit>(Bits.getBit(bi));
1803 if (BI)
1804 Var = dyn_cast<VarInit>(BI->getBitVar());
1805 else
1806 Var = dyn_cast<VarInit>(Bits.getBit(bi));
1807
1808 if (!Var)
1809 break;
1810
1811 if (Var->getName() != Vals[i].getName())
1812 break;
1813
1814 ++bitWidth;
1815 }
1816
1817 unsigned NumberOps = CGI.Operands.size();
1818 while (NumberedOp < NumberOps &&
Hal Finkel5457bd02014-03-13 07:57:54 +00001819 (CGI.Operands.isFlatOperandNotEmitted(NumberedOp) ||
1820 (NamedOpIndices.size() && NamedOpIndices.count(
1821 CGI.Operands.getSubOperandNumber(NumberedOp).first))))
Hal Finkel71b2e202013-12-19 16:12:53 +00001822 ++NumberedOp;
1823
1824 OpIdx = NumberedOp++;
1825
1826 // OpIdx now holds the ordered operand number of Vals[i].
1827 std::pair<unsigned, unsigned> SO =
1828 CGI.Operands.getSubOperandNumber(OpIdx);
1829 const std::string &Name = CGI.Operands[SO.first].Name;
1830
1831 DEBUG(dbgs() << "Numbered operand mapping for " << Def.getName() << ": " <<
1832 Name << "(" << SO.first << ", " << SO.second << ") => " <<
1833 Vals[i].getName() << "\n");
1834
1835 std::string Decoder = "";
1836 Record *TypeRecord = CGI.Operands[SO.first].Rec;
1837
1838 RecordVal *DecoderString = TypeRecord->getValue("DecoderMethod");
1839 StringInit *String = DecoderString ?
Craig Topper24064772014-04-15 07:20:03 +00001840 dyn_cast<StringInit>(DecoderString->getValue()) : nullptr;
Hal Finkel71b2e202013-12-19 16:12:53 +00001841 if (String && String->getValue() != "")
1842 Decoder = String->getValue();
1843
1844 if (Decoder == "" &&
1845 CGI.Operands[SO.first].MIOperandInfo &&
1846 CGI.Operands[SO.first].MIOperandInfo->getNumArgs()) {
1847 Init *Arg = CGI.Operands[SO.first].MIOperandInfo->
1848 getArg(SO.second);
1849 if (TypedInit *TI = cast<TypedInit>(Arg)) {
1850 RecordRecTy *Type = cast<RecordRecTy>(TI->getType());
1851 TypeRecord = Type->getRecord();
1852 }
1853 }
1854
1855 bool isReg = false;
1856 if (TypeRecord->isSubClassOf("RegisterOperand"))
1857 TypeRecord = TypeRecord->getValueAsDef("RegClass");
1858 if (TypeRecord->isSubClassOf("RegisterClass")) {
1859 Decoder = "Decode" + TypeRecord->getName() + "RegisterClass";
1860 isReg = true;
1861 } else if (TypeRecord->isSubClassOf("PointerLikeRegClass")) {
1862 Decoder = "DecodePointerLikeRegClass" +
1863 utostr(TypeRecord->getValueAsInt("RegClassKind"));
1864 isReg = true;
1865 }
1866
1867 DecoderString = TypeRecord->getValue("DecoderMethod");
1868 String = DecoderString ?
Craig Topper24064772014-04-15 07:20:03 +00001869 dyn_cast<StringInit>(DecoderString->getValue()) : nullptr;
Hal Finkel71b2e202013-12-19 16:12:53 +00001870 if (!isReg && String && String->getValue() != "")
1871 Decoder = String->getValue();
1872
1873 OperandInfo OpInfo(Decoder);
1874 OpInfo.addField(bitStart, bitWidth, 0);
1875
1876 NumberedInsnOperands[Name].push_back(OpInfo);
1877
1878 // FIXME: For complex operands with custom decoders we can't handle tied
1879 // sub-operands automatically. Skip those here and assume that this is
1880 // fixed up elsewhere.
1881 if (CGI.Operands[SO.first].MIOperandInfo &&
1882 CGI.Operands[SO.first].MIOperandInfo->getNumArgs() > 1 &&
1883 String && String->getValue() != "")
1884 NumberedInsnOperandsNoTie.insert(Name);
Owen Andersoncb32ce22011-07-29 18:28:52 +00001885 }
Owen Anderson53562d02011-07-28 23:56:20 +00001886 }
1887
Owen Anderson4e818902011-02-18 21:51:29 +00001888 // For each operand, see if we can figure out where it is encoded.
Craig Topper501d95c2012-03-16 06:52:56 +00001889 for (std::vector<std::pair<Init*, std::string> >::const_iterator
Owen Anderson4e818902011-02-18 21:51:29 +00001890 NI = InOutOperands.begin(), NE = InOutOperands.end(); NI != NE; ++NI) {
Hal Finkel71b2e202013-12-19 16:12:53 +00001891 if (!NumberedInsnOperands[NI->second].empty()) {
1892 InsnOperands.insert(InsnOperands.end(),
1893 NumberedInsnOperands[NI->second].begin(),
1894 NumberedInsnOperands[NI->second].end());
1895 continue;
1896 } else if (!NumberedInsnOperands[TiedNames[NI->second]].empty()) {
1897 if (!NumberedInsnOperandsNoTie.count(TiedNames[NI->second])) {
1898 // Figure out to which (sub)operand we're tied.
1899 unsigned i = CGI.Operands.getOperandNamed(TiedNames[NI->second]);
1900 int tiedTo = CGI.Operands[i].getTiedRegister();
1901 if (tiedTo == -1) {
1902 i = CGI.Operands.getOperandNamed(NI->second);
1903 tiedTo = CGI.Operands[i].getTiedRegister();
1904 }
1905
1906 if (tiedTo != -1) {
1907 std::pair<unsigned, unsigned> SO =
1908 CGI.Operands.getSubOperandNumber(tiedTo);
1909
1910 InsnOperands.push_back(NumberedInsnOperands[TiedNames[NI->second]]
1911 [SO.second]);
1912 }
1913 }
1914 continue;
1915 }
1916
Owen Anderson4e818902011-02-18 21:51:29 +00001917 std::string Decoder = "";
1918
Owen Andersone3591652011-07-28 21:54:31 +00001919 // At this point, we can locate the field, but we need to know how to
1920 // interpret it. As a first step, require the target to provide callbacks
1921 // for decoding register classes.
1922 // FIXME: This need to be extended to handle instructions with custom
1923 // decoder methods, and operands with (simple) MIOperandInfo's.
Sean Silva88eb8dd2012-10-10 20:24:47 +00001924 TypedInit *TI = cast<TypedInit>(NI->first);
1925 RecordRecTy *Type = cast<RecordRecTy>(TI->getType());
Owen Andersone3591652011-07-28 21:54:31 +00001926 Record *TypeRecord = Type->getRecord();
1927 bool isReg = false;
1928 if (TypeRecord->isSubClassOf("RegisterOperand"))
1929 TypeRecord = TypeRecord->getValueAsDef("RegClass");
1930 if (TypeRecord->isSubClassOf("RegisterClass")) {
1931 Decoder = "Decode" + TypeRecord->getName() + "RegisterClass";
1932 isReg = true;
Hal Finkel9d95e8d2013-12-19 14:58:22 +00001933 } else if (TypeRecord->isSubClassOf("PointerLikeRegClass")) {
1934 Decoder = "DecodePointerLikeRegClass" +
1935 utostr(TypeRecord->getValueAsInt("RegClassKind"));
1936 isReg = true;
Owen Andersone3591652011-07-28 21:54:31 +00001937 }
1938
1939 RecordVal *DecoderString = TypeRecord->getValue("DecoderMethod");
David Greeneaf8ee2c2011-07-29 22:43:06 +00001940 StringInit *String = DecoderString ?
Craig Topper24064772014-04-15 07:20:03 +00001941 dyn_cast<StringInit>(DecoderString->getValue()) : nullptr;
Owen Andersone3591652011-07-28 21:54:31 +00001942 if (!isReg && String && String->getValue() != "")
1943 Decoder = String->getValue();
1944
1945 OperandInfo OpInfo(Decoder);
1946 unsigned Base = ~0U;
1947 unsigned Width = 0;
1948 unsigned Offset = 0;
1949
Owen Anderson4e818902011-02-18 21:51:29 +00001950 for (unsigned bi = 0; bi < Bits.getNumBits(); ++bi) {
Craig Topper24064772014-04-15 07:20:03 +00001951 VarInit *Var = nullptr;
Sean Silvafb509ed2012-10-10 20:24:43 +00001952 VarBitInit *BI = dyn_cast<VarBitInit>(Bits.getBit(bi));
Owen Anderson3022d672011-08-01 22:45:43 +00001953 if (BI)
Sean Silvafb509ed2012-10-10 20:24:43 +00001954 Var = dyn_cast<VarInit>(BI->getBitVar());
Owen Anderson3022d672011-08-01 22:45:43 +00001955 else
Sean Silvafb509ed2012-10-10 20:24:43 +00001956 Var = dyn_cast<VarInit>(Bits.getBit(bi));
Owen Anderson3022d672011-08-01 22:45:43 +00001957
1958 if (!Var) {
Owen Andersone3591652011-07-28 21:54:31 +00001959 if (Base != ~0U) {
1960 OpInfo.addField(Base, Width, Offset);
1961 Base = ~0U;
1962 Width = 0;
1963 Offset = 0;
1964 }
1965 continue;
1966 }
Owen Anderson4e818902011-02-18 21:51:29 +00001967
Owen Anderson53562d02011-07-28 23:56:20 +00001968 if (Var->getName() != NI->second &&
Owen Andersoncb32ce22011-07-29 18:28:52 +00001969 Var->getName() != TiedNames[NI->second]) {
Owen Andersone3591652011-07-28 21:54:31 +00001970 if (Base != ~0U) {
1971 OpInfo.addField(Base, Width, Offset);
1972 Base = ~0U;
1973 Width = 0;
1974 Offset = 0;
1975 }
1976 continue;
Owen Anderson4e818902011-02-18 21:51:29 +00001977 }
1978
Owen Andersone3591652011-07-28 21:54:31 +00001979 if (Base == ~0U) {
1980 Base = bi;
1981 Width = 1;
Owen Anderson3022d672011-08-01 22:45:43 +00001982 Offset = BI ? BI->getBitNum() : 0;
1983 } else if (BI && BI->getBitNum() != Offset + Width) {
Owen Andersone08f5b52011-07-29 23:01:18 +00001984 OpInfo.addField(Base, Width, Offset);
1985 Base = bi;
1986 Width = 1;
1987 Offset = BI->getBitNum();
Owen Andersone3591652011-07-28 21:54:31 +00001988 } else {
1989 ++Width;
Owen Anderson4e818902011-02-18 21:51:29 +00001990 }
Owen Anderson4e818902011-02-18 21:51:29 +00001991 }
1992
Owen Andersone3591652011-07-28 21:54:31 +00001993 if (Base != ~0U)
1994 OpInfo.addField(Base, Width, Offset);
1995
1996 if (OpInfo.numFields() > 0)
1997 InsnOperands.push_back(OpInfo);
Owen Anderson4e818902011-02-18 21:51:29 +00001998 }
1999
2000 Operands[Opc] = InsnOperands;
2001
2002
2003#if 0
2004 DEBUG({
2005 // Dumps the instruction encoding bits.
2006 dumpBits(errs(), Bits);
2007
2008 errs() << '\n';
2009
2010 // Dumps the list of operand info.
2011 for (unsigned i = 0, e = CGI.Operands.size(); i != e; ++i) {
2012 const CGIOperandList::OperandInfo &Info = CGI.Operands[i];
2013 const std::string &OperandName = Info.Name;
2014 const Record &OperandDef = *Info.Rec;
2015
2016 errs() << "\t" << OperandName << " (" << OperandDef.getName() << ")\n";
2017 }
2018 });
2019#endif
2020
2021 return true;
2022}
2023
Jim Grosbachecaef492012-08-14 19:06:05 +00002024// emitFieldFromInstruction - Emit the templated helper function
2025// fieldFromInstruction().
2026static void emitFieldFromInstruction(formatted_raw_ostream &OS) {
2027 OS << "// Helper function for extracting fields from encoded instructions.\n"
2028 << "template<typename InsnType>\n"
2029 << "static InsnType fieldFromInstruction(InsnType insn, unsigned startBit,\n"
2030 << " unsigned numBits) {\n"
2031 << " assert(startBit + numBits <= (sizeof(InsnType)*8) &&\n"
2032 << " \"Instruction field out of bounds!\");\n"
2033 << " InsnType fieldMask;\n"
2034 << " if (numBits == sizeof(InsnType)*8)\n"
2035 << " fieldMask = (InsnType)(-1LL);\n"
2036 << " else\n"
NAKAMURA Takumibf99a422012-12-26 06:43:14 +00002037 << " fieldMask = (((InsnType)1 << numBits) - 1) << startBit;\n"
Jim Grosbachecaef492012-08-14 19:06:05 +00002038 << " return (insn & fieldMask) >> startBit;\n"
2039 << "}\n\n";
2040}
Owen Anderson4e818902011-02-18 21:51:29 +00002041
Jim Grosbachecaef492012-08-14 19:06:05 +00002042// emitDecodeInstruction - Emit the templated helper function
2043// decodeInstruction().
2044static void emitDecodeInstruction(formatted_raw_ostream &OS) {
2045 OS << "template<typename InsnType>\n"
2046 << "static DecodeStatus decodeInstruction(const uint8_t DecodeTable[], MCInst &MI,\n"
2047 << " InsnType insn, uint64_t Address,\n"
2048 << " const void *DisAsm,\n"
2049 << " const MCSubtargetInfo &STI) {\n"
2050 << " uint64_t Bits = STI.getFeatureBits();\n"
2051 << "\n"
2052 << " const uint8_t *Ptr = DecodeTable;\n"
Jim Grosbach4c363492012-09-17 18:00:53 +00002053 << " uint32_t CurFieldValue = 0;\n"
Jim Grosbachecaef492012-08-14 19:06:05 +00002054 << " DecodeStatus S = MCDisassembler::Success;\n"
2055 << " for (;;) {\n"
2056 << " ptrdiff_t Loc = Ptr - DecodeTable;\n"
2057 << " switch (*Ptr) {\n"
2058 << " default:\n"
2059 << " errs() << Loc << \": Unexpected decode table opcode!\\n\";\n"
2060 << " return MCDisassembler::Fail;\n"
2061 << " case MCD::OPC_ExtractField: {\n"
2062 << " unsigned Start = *++Ptr;\n"
2063 << " unsigned Len = *++Ptr;\n"
2064 << " ++Ptr;\n"
2065 << " CurFieldValue = fieldFromInstruction(insn, Start, Len);\n"
2066 << " DEBUG(dbgs() << Loc << \": OPC_ExtractField(\" << Start << \", \"\n"
2067 << " << Len << \"): \" << CurFieldValue << \"\\n\");\n"
2068 << " break;\n"
2069 << " }\n"
2070 << " case MCD::OPC_FilterValue: {\n"
2071 << " // Decode the field value.\n"
2072 << " unsigned Len;\n"
2073 << " InsnType Val = decodeULEB128(++Ptr, &Len);\n"
2074 << " Ptr += Len;\n"
2075 << " // NumToSkip is a plain 16-bit integer.\n"
2076 << " unsigned NumToSkip = *Ptr++;\n"
2077 << " NumToSkip |= (*Ptr++) << 8;\n"
2078 << "\n"
2079 << " // Perform the filter operation.\n"
2080 << " if (Val != CurFieldValue)\n"
2081 << " Ptr += NumToSkip;\n"
2082 << " DEBUG(dbgs() << Loc << \": OPC_FilterValue(\" << Val << \", \" << NumToSkip\n"
2083 << " << \"): \" << ((Val != CurFieldValue) ? \"FAIL:\" : \"PASS:\")\n"
2084 << " << \" continuing at \" << (Ptr - DecodeTable) << \"\\n\");\n"
2085 << "\n"
2086 << " break;\n"
2087 << " }\n"
2088 << " case MCD::OPC_CheckField: {\n"
2089 << " unsigned Start = *++Ptr;\n"
2090 << " unsigned Len = *++Ptr;\n"
2091 << " InsnType FieldValue = fieldFromInstruction(insn, Start, Len);\n"
2092 << " // Decode the field value.\n"
2093 << " uint32_t ExpectedValue = decodeULEB128(++Ptr, &Len);\n"
2094 << " Ptr += Len;\n"
2095 << " // NumToSkip is a plain 16-bit integer.\n"
2096 << " unsigned NumToSkip = *Ptr++;\n"
2097 << " NumToSkip |= (*Ptr++) << 8;\n"
2098 << "\n"
2099 << " // If the actual and expected values don't match, skip.\n"
2100 << " if (ExpectedValue != FieldValue)\n"
2101 << " Ptr += NumToSkip;\n"
2102 << " DEBUG(dbgs() << Loc << \": OPC_CheckField(\" << Start << \", \"\n"
2103 << " << Len << \", \" << ExpectedValue << \", \" << NumToSkip\n"
2104 << " << \"): FieldValue = \" << FieldValue << \", ExpectedValue = \"\n"
2105 << " << ExpectedValue << \": \"\n"
2106 << " << ((ExpectedValue == FieldValue) ? \"PASS\\n\" : \"FAIL\\n\"));\n"
2107 << " break;\n"
2108 << " }\n"
2109 << " case MCD::OPC_CheckPredicate: {\n"
2110 << " unsigned Len;\n"
2111 << " // Decode the Predicate Index value.\n"
2112 << " unsigned PIdx = decodeULEB128(++Ptr, &Len);\n"
2113 << " Ptr += Len;\n"
2114 << " // NumToSkip is a plain 16-bit integer.\n"
2115 << " unsigned NumToSkip = *Ptr++;\n"
2116 << " NumToSkip |= (*Ptr++) << 8;\n"
2117 << " // Check the predicate.\n"
2118 << " bool Pred;\n"
2119 << " if (!(Pred = checkDecoderPredicate(PIdx, Bits)))\n"
2120 << " Ptr += NumToSkip;\n"
2121 << " (void)Pred;\n"
2122 << " DEBUG(dbgs() << Loc << \": OPC_CheckPredicate(\" << PIdx << \"): \"\n"
2123 << " << (Pred ? \"PASS\\n\" : \"FAIL\\n\"));\n"
2124 << "\n"
2125 << " break;\n"
2126 << " }\n"
2127 << " case MCD::OPC_Decode: {\n"
2128 << " unsigned Len;\n"
2129 << " // Decode the Opcode value.\n"
2130 << " unsigned Opc = decodeULEB128(++Ptr, &Len);\n"
2131 << " Ptr += Len;\n"
2132 << " unsigned DecodeIdx = decodeULEB128(Ptr, &Len);\n"
2133 << " Ptr += Len;\n"
2134 << " DEBUG(dbgs() << Loc << \": OPC_Decode: opcode \" << Opc\n"
2135 << " << \", using decoder \" << DecodeIdx << \"\\n\" );\n"
2136 << " DEBUG(dbgs() << \"----- DECODE SUCCESSFUL -----\\n\");\n"
2137 << "\n"
2138 << " MI.setOpcode(Opc);\n"
Benjamin Kramer26b568d2012-08-15 10:26:44 +00002139 << " return decodeToMCInst(S, DecodeIdx, insn, MI, Address, DisAsm);\n"
Jim Grosbachecaef492012-08-14 19:06:05 +00002140 << " }\n"
2141 << " case MCD::OPC_SoftFail: {\n"
2142 << " // Decode the mask values.\n"
2143 << " unsigned Len;\n"
2144 << " InsnType PositiveMask = decodeULEB128(++Ptr, &Len);\n"
2145 << " Ptr += Len;\n"
2146 << " InsnType NegativeMask = decodeULEB128(Ptr, &Len);\n"
2147 << " Ptr += Len;\n"
2148 << " bool Fail = (insn & PositiveMask) || (~insn & NegativeMask);\n"
2149 << " if (Fail)\n"
2150 << " S = MCDisassembler::SoftFail;\n"
2151 << " DEBUG(dbgs() << Loc << \": OPC_SoftFail: \" << (Fail ? \"FAIL\\n\":\"PASS\\n\"));\n"
2152 << " break;\n"
2153 << " }\n"
2154 << " case MCD::OPC_Fail: {\n"
2155 << " DEBUG(dbgs() << Loc << \": OPC_Fail\\n\");\n"
2156 << " return MCDisassembler::Fail;\n"
2157 << " }\n"
2158 << " }\n"
2159 << " }\n"
2160 << " llvm_unreachable(\"bogosity detected in disassembler state machine!\");\n"
2161 << "}\n\n";
Owen Anderson4e818902011-02-18 21:51:29 +00002162}
2163
2164// Emits disassembler code for instruction decoding.
Craig Topper82d0d5f2012-03-16 01:19:24 +00002165void FixedLenDecoderEmitter::run(raw_ostream &o) {
Jim Grosbachecaef492012-08-14 19:06:05 +00002166 formatted_raw_ostream OS(o);
2167 OS << "#include \"llvm/MC/MCInst.h\"\n";
2168 OS << "#include \"llvm/Support/Debug.h\"\n";
2169 OS << "#include \"llvm/Support/DataTypes.h\"\n";
2170 OS << "#include \"llvm/Support/LEB128.h\"\n";
2171 OS << "#include \"llvm/Support/raw_ostream.h\"\n";
2172 OS << "#include <assert.h>\n";
2173 OS << '\n';
2174 OS << "namespace llvm {\n\n";
2175
2176 emitFieldFromInstruction(OS);
Owen Anderson4e818902011-02-18 21:51:29 +00002177
Hal Finkel81e6fcc2013-12-17 22:37:50 +00002178 Target.reverseBitsForLittleEndianEncoding();
2179
Owen Andersonc78e03c2011-07-19 21:06:00 +00002180 // Parameterize the decoders based on namespace and instruction width.
Jim Grosbachecaef492012-08-14 19:06:05 +00002181 NumberedInstructions = &Target.getInstructionsByEnumValue();
Owen Andersonc78e03c2011-07-19 21:06:00 +00002182 std::map<std::pair<std::string, unsigned>,
2183 std::vector<unsigned> > OpcMap;
2184 std::map<unsigned, std::vector<OperandInfo> > Operands;
2185
Jim Grosbachecaef492012-08-14 19:06:05 +00002186 for (unsigned i = 0; i < NumberedInstructions->size(); ++i) {
2187 const CodeGenInstruction *Inst = NumberedInstructions->at(i);
Craig Topper48c112b2012-03-16 05:58:09 +00002188 const Record *Def = Inst->TheDef;
Owen Andersonc78e03c2011-07-19 21:06:00 +00002189 unsigned Size = Def->getValueAsInt("Size");
2190 if (Def->getValueAsString("Namespace") == "TargetOpcode" ||
2191 Def->getValueAsBit("isPseudo") ||
2192 Def->getValueAsBit("isAsmParserOnly") ||
2193 Def->getValueAsBit("isCodeGenOnly"))
2194 continue;
2195
2196 std::string DecoderNamespace = Def->getValueAsString("DecoderNamespace");
2197
2198 if (Size) {
Hal Finkel71b2e202013-12-19 16:12:53 +00002199 if (populateInstruction(Target, *Inst, i, Operands)) {
Owen Andersonc78e03c2011-07-19 21:06:00 +00002200 OpcMap[std::make_pair(DecoderNamespace, Size)].push_back(i);
2201 }
2202 }
2203 }
2204
Jim Grosbachecaef492012-08-14 19:06:05 +00002205 DecoderTableInfo TableInfo;
Owen Andersonc78e03c2011-07-19 21:06:00 +00002206 for (std::map<std::pair<std::string, unsigned>,
Craig Topper48c112b2012-03-16 05:58:09 +00002207 std::vector<unsigned> >::const_iterator
Owen Andersonc78e03c2011-07-19 21:06:00 +00002208 I = OpcMap.begin(), E = OpcMap.end(); I != E; ++I) {
Owen Andersonc78e03c2011-07-19 21:06:00 +00002209 // Emit the decoder for this namespace+width combination.
Jim Grosbachecaef492012-08-14 19:06:05 +00002210 FilterChooser FC(*NumberedInstructions, I->second, Operands,
Owen Andersona4043c42011-08-17 17:44:15 +00002211 8*I->first.second, this);
Jim Grosbachecaef492012-08-14 19:06:05 +00002212
2213 // The decode table is cleared for each top level decoder function. The
2214 // predicates and decoders themselves, however, are shared across all
2215 // decoders to give more opportunities for uniqueing.
2216 TableInfo.Table.clear();
2217 TableInfo.FixupStack.clear();
2218 TableInfo.Table.reserve(16384);
2219 TableInfo.FixupStack.push_back(FixupList());
2220 FC.emitTableEntries(TableInfo);
2221 // Any NumToSkip fixups in the top level scope can resolve to the
2222 // OPC_Fail at the end of the table.
2223 assert(TableInfo.FixupStack.size() == 1 && "fixup stack phasing error!");
2224 // Resolve any NumToSkip fixups in the current scope.
2225 resolveTableFixups(TableInfo.Table, TableInfo.FixupStack.back(),
2226 TableInfo.Table.size());
2227 TableInfo.FixupStack.clear();
2228
2229 TableInfo.Table.push_back(MCD::OPC_Fail);
2230
2231 // Print the table to the output stream.
2232 emitTable(OS, TableInfo.Table, 0, FC.getBitWidth(), I->first.first);
2233 OS.flush();
Owen Andersonc78e03c2011-07-19 21:06:00 +00002234 }
Owen Anderson4e818902011-02-18 21:51:29 +00002235
Jim Grosbachecaef492012-08-14 19:06:05 +00002236 // Emit the predicate function.
2237 emitPredicateFunction(OS, TableInfo.Predicates, 0);
2238
2239 // Emit the decoder function.
2240 emitDecoderFunction(OS, TableInfo.Decoders, 0);
2241
2242 // Emit the main entry point for the decoder, decodeInstruction().
2243 emitDecodeInstruction(OS);
2244
2245 OS << "\n} // End llvm namespace\n";
Owen Anderson4e818902011-02-18 21:51:29 +00002246}
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +00002247
2248namespace llvm {
2249
2250void EmitFixedLenDecoder(RecordKeeper &RK, raw_ostream &OS,
2251 std::string PredicateNamespace,
2252 std::string GPrefix,
2253 std::string GPostfix,
2254 std::string ROK,
2255 std::string RFail,
2256 std::string L) {
2257 FixedLenDecoderEmitter(RK, PredicateNamespace, GPrefix, GPostfix,
2258 ROK, RFail, L).run(OS);
2259}
2260
2261} // End llvm namespace