blob: ca6fe501f7337c7a31bcfd7d350db821e23d396c [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
Owen Anderson4e818902011-02-18 21:51:29 +000015#include "CodeGenTarget.h"
James Molloyd9ba4fd2012-02-09 10:56:31 +000016#include "llvm/ADT/APInt.h"
Jim Grosbachecaef492012-08-14 19:06:05 +000017#include "llvm/ADT/SmallString.h"
Owen Anderson4e818902011-02-18 21:51:29 +000018#include "llvm/ADT/StringExtras.h"
Jim Grosbachecaef492012-08-14 19:06:05 +000019#include "llvm/ADT/StringRef.h"
20#include "llvm/ADT/Twine.h"
21#include "llvm/MC/MCFixedLenDisassembler.h"
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +000022#include "llvm/Support/DataTypes.h"
Owen Anderson4e818902011-02-18 21:51:29 +000023#include "llvm/Support/Debug.h"
Jim Grosbachecaef492012-08-14 19:06:05 +000024#include "llvm/Support/FormattedStream.h"
25#include "llvm/Support/LEB128.h"
Owen Anderson4e818902011-02-18 21:51:29 +000026#include "llvm/Support/raw_ostream.h"
Chandler Carruth91d19d82012-12-04 10:37:14 +000027#include "llvm/TableGen/Error.h"
28#include "llvm/TableGen/Record.h"
Owen Anderson4e818902011-02-18 21:51:29 +000029#include <map>
30#include <string>
Benjamin Kramer82de7d32016-05-27 14:27:24 +000031#include <utility>
Chandler Carruth91d19d82012-12-04 10:37:14 +000032#include <vector>
Owen Anderson4e818902011-02-18 21:51:29 +000033
34using namespace llvm;
35
Chandler Carruth97acce22014-04-22 03:06:00 +000036#define DEBUG_TYPE "decoder-emitter"
37
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +000038namespace {
39struct EncodingField {
40 unsigned Base, Width, Offset;
41 EncodingField(unsigned B, unsigned W, unsigned O)
42 : Base(B), Width(W), Offset(O) { }
43};
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +000044
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +000045struct OperandInfo {
46 std::vector<EncodingField> Fields;
47 std::string Decoder;
Petr Pavlu182b0572015-07-15 08:04:27 +000048 bool HasCompleteDecoder;
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +000049
Petr Pavlu182b0572015-07-15 08:04:27 +000050 OperandInfo(std::string D, bool HCD)
Benjamin Kramer82de7d32016-05-27 14:27:24 +000051 : Decoder(std::move(D)), HasCompleteDecoder(HCD) {}
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +000052
53 void addField(unsigned Base, unsigned Width, unsigned Offset) {
54 Fields.push_back(EncodingField(Base, Width, Offset));
55 }
56
57 unsigned numFields() const { return Fields.size(); }
58
59 typedef std::vector<EncodingField>::const_iterator const_iterator;
60
61 const_iterator begin() const { return Fields.begin(); }
62 const_iterator end() const { return Fields.end(); }
63};
Jim Grosbachecaef492012-08-14 19:06:05 +000064
65typedef std::vector<uint8_t> DecoderTable;
66typedef uint32_t DecoderFixup;
67typedef std::vector<DecoderFixup> FixupList;
68typedef std::vector<FixupList> FixupScopeList;
Rafael Espindola55512f92015-11-18 06:52:18 +000069typedef SmallSetVector<std::string, 16> PredicateSet;
70typedef SmallSetVector<std::string, 16> DecoderSet;
Jim Grosbachecaef492012-08-14 19:06:05 +000071struct DecoderTableInfo {
72 DecoderTable Table;
73 FixupScopeList FixupStack;
74 PredicateSet Predicates;
75 DecoderSet Decoders;
76};
77
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +000078} // End anonymous namespace
79
80namespace {
81class FixedLenDecoderEmitter {
Craig Topperf9265322016-01-17 20:38:14 +000082 ArrayRef<const CodeGenInstruction *> NumberedInstructions;
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +000083public:
84
85 // Defaults preserved here for documentation, even though they aren't
86 // strictly necessary given the way that this is currently being called.
Benjamin Kramer82de7d32016-05-27 14:27:24 +000087 FixedLenDecoderEmitter(RecordKeeper &R, std::string PredicateNamespace,
88 std::string GPrefix = "if (",
Petr Pavlu182b0572015-07-15 08:04:27 +000089 std::string GPostfix = " == MCDisassembler::Fail)",
Benjamin Kramer82de7d32016-05-27 14:27:24 +000090 std::string ROK = "MCDisassembler::Success",
91 std::string RFail = "MCDisassembler::Fail",
92 std::string L = "")
93 : Target(R), PredicateNamespace(std::move(PredicateNamespace)),
94 GuardPrefix(std::move(GPrefix)), GuardPostfix(std::move(GPostfix)),
95 ReturnOK(std::move(ROK)), ReturnFail(std::move(RFail)),
96 Locals(std::move(L)) {}
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +000097
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
Petr Pavlu21894652015-07-14 08:00:34 +0000211/// even registers, while VST4q8b is a vst4 to double-spaced odd registers.
Owen Anderson4e818902011-02-18 21:51:29 +0000212///
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 Toppercf05f912014-09-03 06:07:54 +0000233 std::map<unsigned, std::unique_ptr<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
Craig Topper5c2b4ac2014-09-03 05:49:07 +0000255 Filter(Filter &&f);
Owen Anderson4e818902011-02-18 21:51:29 +0000256 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.
Craig Topperf9265322016-01-17 20:38:14 +0000309 ArrayRef<const CodeGenInstruction *> AllInstructions;
Owen Anderson4e818902011-02-18 21:51:29 +0000310
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
Aaron Ballmanf9a18972015-02-15 22:54:22 +0000336 FilterChooser(const FilterChooser &) = delete;
337 void operator=(const FilterChooser &) = delete;
Owen Anderson4e818902011-02-18 21:51:29 +0000338public:
Owen Anderson4e818902011-02-18 21:51:29 +0000339
Craig Topperf9265322016-01-17 20:38:14 +0000340 FilterChooser(ArrayRef<const CodeGenInstruction *> Insts,
Owen Anderson4e818902011-02-18 21:51:29 +0000341 const std::vector<unsigned> &IDs,
Craig Topper501d95c2012-03-16 06:52:56 +0000342 const std::map<unsigned, std::vector<OperandInfo> > &Ops,
Owen Andersona4043c42011-08-17 17:44:15 +0000343 unsigned BW,
Craig Topper82d0d5f2012-03-16 01:19:24 +0000344 const FixedLenDecoderEmitter *E)
345 : AllInstructions(Insts), Opcodes(IDs), Operands(Ops), Filters(),
Craig Topper1ddc2882014-09-04 04:49:03 +0000346 FilterBitValues(BW, BIT_UNFILTERED), Parent(nullptr), BestIndex(-1),
347 BitWidth(BW), Emitter(E) {
Owen Anderson4e818902011-02-18 21:51:29 +0000348 doFilter();
349 }
350
Craig Topperf9265322016-01-17 20:38:14 +0000351 FilterChooser(ArrayRef<const CodeGenInstruction *> Insts,
Owen Anderson4e818902011-02-18 21:51:29 +0000352 const std::vector<unsigned> &IDs,
Craig Topper501d95c2012-03-16 06:52:56 +0000353 const std::map<unsigned, std::vector<OperandInfo> > &Ops,
354 const std::vector<bit_value_t> &ParentFilterBitValues,
355 const FilterChooser &parent)
Craig Topper82d0d5f2012-03-16 01:19:24 +0000356 : AllInstructions(Insts), Opcodes(IDs), Operands(Ops),
Owen Andersonc78e03c2011-07-19 21:06:00 +0000357 Filters(), FilterBitValues(ParentFilterBitValues),
Owen Andersona4043c42011-08-17 17:44:15 +0000358 Parent(&parent), BestIndex(-1), BitWidth(parent.BitWidth),
359 Emitter(parent.Emitter) {
Owen Anderson4e818902011-02-18 21:51:29 +0000360 doFilter();
361 }
362
Jim Grosbachecaef492012-08-14 19:06:05 +0000363 unsigned getBitWidth() const { return BitWidth; }
Owen Anderson4e818902011-02-18 21:51:29 +0000364
365protected:
366 // Populates the insn given the uid.
367 void insnWithID(insn_t &Insn, unsigned Opcode) const {
David Greeneaf8ee2c2011-07-29 22:43:06 +0000368 BitsInit &Bits = getBitsField(*AllInstructions[Opcode]->TheDef, "Inst");
Owen Anderson4e818902011-02-18 21:51:29 +0000369
James Molloyd9ba4fd2012-02-09 10:56:31 +0000370 // We may have a SoftFail bitmask, which specifies a mask where an encoding
371 // may differ from the value in "Inst" and yet still be valid, but the
372 // disassembler should return SoftFail instead of Success.
373 //
374 // This is used for marking UNPREDICTABLE instructions in the ARM world.
Jim Grosbach3f4b2392012-02-29 22:07:56 +0000375 BitsInit *SFBits =
376 AllInstructions[Opcode]->TheDef->getValueAsBitsInit("SoftFail");
James Molloyd9ba4fd2012-02-09 10:56:31 +0000377
378 for (unsigned i = 0; i < BitWidth; ++i) {
379 if (SFBits && bitFromBits(*SFBits, i) == BIT_TRUE)
380 Insn.push_back(BIT_UNSET);
381 else
382 Insn.push_back(bitFromBits(Bits, i));
383 }
Owen Anderson4e818902011-02-18 21:51:29 +0000384 }
385
386 // Returns the record name.
387 const std::string &nameWithID(unsigned Opcode) const {
388 return AllInstructions[Opcode]->TheDef->getName();
389 }
390
391 // Populates the field of the insn given the start position and the number of
392 // consecutive bits to scan for.
393 //
394 // Returns false if there exists any uninitialized bit value in the range.
395 // Returns true, otherwise.
396 bool fieldFromInsn(uint64_t &Field, insn_t &Insn, unsigned StartBit,
Craig Topper82d0d5f2012-03-16 01:19:24 +0000397 unsigned NumBits) const;
Owen Anderson4e818902011-02-18 21:51:29 +0000398
399 /// dumpFilterArray - dumpFilterArray prints out debugging info for the given
400 /// filter array as a series of chars.
Craig Topper48c112b2012-03-16 05:58:09 +0000401 void dumpFilterArray(raw_ostream &o,
402 const std::vector<bit_value_t> & filter) const;
Owen Anderson4e818902011-02-18 21:51:29 +0000403
404 /// dumpStack - dumpStack traverses the filter chooser chain and calls
405 /// dumpFilterArray on each filter chooser up to the top level one.
Craig Topper48c112b2012-03-16 05:58:09 +0000406 void dumpStack(raw_ostream &o, const char *prefix) const;
Owen Anderson4e818902011-02-18 21:51:29 +0000407
408 Filter &bestFilter() {
409 assert(BestIndex != -1 && "BestIndex not set");
410 return Filters[BestIndex];
411 }
412
413 // Called from Filter::recurse() when singleton exists. For debug purpose.
Craig Topper48c112b2012-03-16 05:58:09 +0000414 void SingletonExists(unsigned Opc) const;
Owen Anderson4e818902011-02-18 21:51:29 +0000415
Craig Topper48c112b2012-03-16 05:58:09 +0000416 bool PositionFiltered(unsigned i) const {
Owen Anderson4e818902011-02-18 21:51:29 +0000417 return ValueSet(FilterBitValues[i]);
418 }
419
420 // Calculates the island(s) needed to decode the instruction.
421 // This returns a lit of undecoded bits of an instructions, for example,
422 // Inst{20} = 1 && Inst{3-0} == 0b1111 represents two islands of yet-to-be
423 // decoded bits in order to verify that the instruction matches the Opcode.
424 unsigned getIslands(std::vector<unsigned> &StartBits,
Craig Topper82d0d5f2012-03-16 01:19:24 +0000425 std::vector<unsigned> &EndBits,
Craig Topper48c112b2012-03-16 05:58:09 +0000426 std::vector<uint64_t> &FieldVals,
427 const insn_t &Insn) const;
Owen Anderson4e818902011-02-18 21:51:29 +0000428
James Molloy8067df92011-09-07 19:42:28 +0000429 // Emits code to check the Predicates member of an instruction are true.
430 // Returns true if predicate matches were emitted, false otherwise.
Craig Topper48c112b2012-03-16 05:58:09 +0000431 bool emitPredicateMatch(raw_ostream &o, unsigned &Indentation,
432 unsigned Opc) const;
James Molloy8067df92011-09-07 19:42:28 +0000433
Jim Grosbachecaef492012-08-14 19:06:05 +0000434 bool doesOpcodeNeedPredicate(unsigned Opc) const;
435 unsigned getPredicateIndex(DecoderTableInfo &TableInfo, StringRef P) const;
436 void emitPredicateTableEntry(DecoderTableInfo &TableInfo,
437 unsigned Opc) const;
James Molloyd9ba4fd2012-02-09 10:56:31 +0000438
Jim Grosbachecaef492012-08-14 19:06:05 +0000439 void emitSoftFailTableEntry(DecoderTableInfo &TableInfo,
440 unsigned Opc) const;
441
442 // Emits table entries to decode the singleton.
443 void emitSingletonTableEntry(DecoderTableInfo &TableInfo,
444 unsigned Opc) const;
Owen Anderson4e818902011-02-18 21:51:29 +0000445
446 // Emits code to decode the singleton, and then to decode the rest.
Jim Grosbachecaef492012-08-14 19:06:05 +0000447 void emitSingletonTableEntry(DecoderTableInfo &TableInfo,
448 const Filter &Best) const;
Owen Anderson4e818902011-02-18 21:51:29 +0000449
Jim Grosbachecaef492012-08-14 19:06:05 +0000450 void emitBinaryParser(raw_ostream &o, unsigned &Indentation,
Petr Pavlu182b0572015-07-15 08:04:27 +0000451 const OperandInfo &OpInfo,
452 bool &OpHasCompleteDecoder) const;
Owen Andersone3591652011-07-28 21:54:31 +0000453
Petr Pavlu182b0572015-07-15 08:04:27 +0000454 void emitDecoder(raw_ostream &OS, unsigned Indentation, unsigned Opc,
455 bool &HasCompleteDecoder) const;
456 unsigned getDecoderIndex(DecoderSet &Decoders, unsigned Opc,
457 bool &HasCompleteDecoder) const;
Jim Grosbachecaef492012-08-14 19:06:05 +0000458
Owen Anderson4e818902011-02-18 21:51:29 +0000459 // Assign a single filter and run with it.
Craig Topper48c112b2012-03-16 05:58:09 +0000460 void runSingleFilter(unsigned startBit, unsigned numBit, bool mixed);
Owen Anderson4e818902011-02-18 21:51:29 +0000461
462 // reportRegion is a helper function for filterProcessor to mark a region as
463 // eligible for use as a filter region.
464 void reportRegion(bitAttr_t RA, unsigned StartBit, unsigned BitIndex,
Craig Topper82d0d5f2012-03-16 01:19:24 +0000465 bool AllowMixed);
Owen Anderson4e818902011-02-18 21:51:29 +0000466
467 // FilterProcessor scans the well-known encoding bits of the instructions and
468 // builds up a list of candidate filters. It chooses the best filter and
469 // recursively descends down the decoding tree.
470 bool filterProcessor(bool AllowMixed, bool Greedy = true);
471
472 // Decides on the best configuration of filter(s) to use in order to decode
473 // the instructions. A conflict of instructions may occur, in which case we
474 // dump the conflict set to the standard error.
475 void doFilter();
476
Jim Grosbachecaef492012-08-14 19:06:05 +0000477public:
478 // emitTableEntries - Emit state machine entries to decode our share of
479 // instructions.
480 void emitTableEntries(DecoderTableInfo &TableInfo) const;
Owen Anderson4e818902011-02-18 21:51:29 +0000481};
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +0000482} // End anonymous namespace
Owen Anderson4e818902011-02-18 21:51:29 +0000483
484///////////////////////////
485// //
Craig Topper93e64342012-03-16 00:56:01 +0000486// Filter Implementation //
Owen Anderson4e818902011-02-18 21:51:29 +0000487// //
488///////////////////////////
489
Craig Topper5c2b4ac2014-09-03 05:49:07 +0000490Filter::Filter(Filter &&f)
Craig Topper82d0d5f2012-03-16 01:19:24 +0000491 : Owner(f.Owner), StartBit(f.StartBit), NumBits(f.NumBits), Mixed(f.Mixed),
Craig Topper5c2b4ac2014-09-03 05:49:07 +0000492 FilteredInstructions(std::move(f.FilteredInstructions)),
493 VariableInstructions(std::move(f.VariableInstructions)),
494 FilterChooserMap(std::move(f.FilterChooserMap)), NumFiltered(f.NumFiltered),
Craig Topper82d0d5f2012-03-16 01:19:24 +0000495 LastOpcFiltered(f.LastOpcFiltered) {
Owen Anderson4e818902011-02-18 21:51:29 +0000496}
497
498Filter::Filter(FilterChooser &owner, unsigned startBit, unsigned numBits,
Craig Topper82d0d5f2012-03-16 01:19:24 +0000499 bool mixed)
500 : Owner(&owner), StartBit(startBit), NumBits(numBits), Mixed(mixed) {
Owen Andersonc78e03c2011-07-19 21:06:00 +0000501 assert(StartBit + NumBits - 1 < Owner->BitWidth);
Owen Anderson4e818902011-02-18 21:51:29 +0000502
503 NumFiltered = 0;
504 LastOpcFiltered = 0;
Owen Anderson4e818902011-02-18 21:51:29 +0000505
506 for (unsigned i = 0, e = Owner->Opcodes.size(); i != e; ++i) {
507 insn_t Insn;
508
509 // Populates the insn given the uid.
510 Owner->insnWithID(Insn, Owner->Opcodes[i]);
511
512 uint64_t Field;
513 // Scans the segment for possibly well-specified encoding bits.
514 bool ok = Owner->fieldFromInsn(Field, Insn, StartBit, NumBits);
515
516 if (ok) {
517 // The encoding bits are well-known. Lets add the uid of the
518 // instruction into the bucket keyed off the constant field value.
519 LastOpcFiltered = Owner->Opcodes[i];
520 FilteredInstructions[Field].push_back(LastOpcFiltered);
521 ++NumFiltered;
522 } else {
Craig Topper93e64342012-03-16 00:56:01 +0000523 // Some of the encoding bit(s) are unspecified. This contributes to
Owen Anderson4e818902011-02-18 21:51:29 +0000524 // one additional member of "Variable" instructions.
525 VariableInstructions.push_back(Owner->Opcodes[i]);
Owen Anderson4e818902011-02-18 21:51:29 +0000526 }
527 }
528
529 assert((FilteredInstructions.size() + VariableInstructions.size() > 0)
530 && "Filter returns no instruction categories");
531}
532
533Filter::~Filter() {
Owen Anderson4e818902011-02-18 21:51:29 +0000534}
535
536// Divides the decoding task into sub tasks and delegates them to the
537// inferior FilterChooser's.
538//
539// A special case arises when there's only one entry in the filtered
540// instructions. In order to unambiguously decode the singleton, we need to
541// match the remaining undecoded encoding bits against the singleton.
542void Filter::recurse() {
Owen Anderson4e818902011-02-18 21:51:29 +0000543 // Starts by inheriting our parent filter chooser's filter bit values.
Owen Andersonc78e03c2011-07-19 21:06:00 +0000544 std::vector<bit_value_t> BitValueArray(Owner->FilterBitValues);
Owen Anderson4e818902011-02-18 21:51:29 +0000545
Alexander Kornienko8c0809c2015-01-15 11:41:30 +0000546 if (!VariableInstructions.empty()) {
Owen Anderson4e818902011-02-18 21:51:29 +0000547 // Conservatively marks each segment position as BIT_UNSET.
Craig Topper29688ab2012-08-17 05:42:16 +0000548 for (unsigned bitIndex = 0; bitIndex < NumBits; ++bitIndex)
Owen Anderson4e818902011-02-18 21:51:29 +0000549 BitValueArray[StartBit + bitIndex] = BIT_UNSET;
550
Chris Lattner0ab5e2c2011-04-15 05:18:47 +0000551 // Delegates to an inferior filter chooser for further processing on this
Owen Anderson4e818902011-02-18 21:51:29 +0000552 // group of instructions whose segment values are variable.
Yaron Kerene499db02014-09-03 08:22:30 +0000553 FilterChooserMap.insert(
554 std::make_pair(-1U, llvm::make_unique<FilterChooser>(
555 Owner->AllInstructions, VariableInstructions,
556 Owner->Operands, BitValueArray, *Owner)));
Owen Anderson4e818902011-02-18 21:51:29 +0000557 }
558
559 // No need to recurse for a singleton filtered instruction.
Jim Grosbachecaef492012-08-14 19:06:05 +0000560 // See also Filter::emit*().
Owen Anderson4e818902011-02-18 21:51:29 +0000561 if (getNumFiltered() == 1) {
562 //Owner->SingletonExists(LastOpcFiltered);
563 assert(FilterChooserMap.size() == 1);
564 return;
565 }
566
567 // Otherwise, create sub choosers.
Craig Topper1f7604d2014-12-13 05:12:19 +0000568 for (const auto &Inst : FilteredInstructions) {
Owen Anderson4e818902011-02-18 21:51:29 +0000569
570 // Marks all the segment positions with either BIT_TRUE or BIT_FALSE.
Craig Topper29688ab2012-08-17 05:42:16 +0000571 for (unsigned bitIndex = 0; bitIndex < NumBits; ++bitIndex) {
Craig Topper1f7604d2014-12-13 05:12:19 +0000572 if (Inst.first & (1ULL << bitIndex))
Owen Anderson4e818902011-02-18 21:51:29 +0000573 BitValueArray[StartBit + bitIndex] = BIT_TRUE;
574 else
575 BitValueArray[StartBit + bitIndex] = BIT_FALSE;
576 }
577
Chris Lattner0ab5e2c2011-04-15 05:18:47 +0000578 // Delegates to an inferior filter chooser for further processing on this
Owen Anderson4e818902011-02-18 21:51:29 +0000579 // category of instructions.
Craig Toppercf05f912014-09-03 06:07:54 +0000580 FilterChooserMap.insert(std::make_pair(
Craig Topper1f7604d2014-12-13 05:12:19 +0000581 Inst.first, llvm::make_unique<FilterChooser>(
582 Owner->AllInstructions, Inst.second,
Yaron Kerene499db02014-09-03 08:22:30 +0000583 Owner->Operands, BitValueArray, *Owner)));
Owen Anderson4e818902011-02-18 21:51:29 +0000584 }
585}
586
Jim Grosbachecaef492012-08-14 19:06:05 +0000587static void resolveTableFixups(DecoderTable &Table, const FixupList &Fixups,
588 uint32_t DestIdx) {
589 // Any NumToSkip fixups in the current scope can resolve to the
590 // current location.
591 for (FixupList::const_reverse_iterator I = Fixups.rbegin(),
592 E = Fixups.rend();
593 I != E; ++I) {
594 // Calculate the distance from the byte following the fixup entry byte
595 // to the destination. The Target is calculated from after the 16-bit
596 // NumToSkip entry itself, so subtract two from the displacement here
597 // to account for that.
598 uint32_t FixupIdx = *I;
599 uint32_t Delta = DestIdx - FixupIdx - 2;
600 // Our NumToSkip entries are 16-bits. Make sure our table isn't too
601 // big.
602 assert(Delta < 65536U && "disassembler decoding table too large!");
603 Table[FixupIdx] = (uint8_t)Delta;
604 Table[FixupIdx + 1] = (uint8_t)(Delta >> 8);
605 }
606}
Owen Anderson4e818902011-02-18 21:51:29 +0000607
Jim Grosbachecaef492012-08-14 19:06:05 +0000608// Emit table entries to decode instructions given a segment or segments
609// of bits.
610void Filter::emitTableEntry(DecoderTableInfo &TableInfo) const {
611 TableInfo.Table.push_back(MCD::OPC_ExtractField);
612 TableInfo.Table.push_back(StartBit);
613 TableInfo.Table.push_back(NumBits);
Owen Anderson4e818902011-02-18 21:51:29 +0000614
Jim Grosbachecaef492012-08-14 19:06:05 +0000615 // A new filter entry begins a new scope for fixup resolution.
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +0000616 TableInfo.FixupStack.emplace_back();
Owen Anderson4e818902011-02-18 21:51:29 +0000617
Jim Grosbachecaef492012-08-14 19:06:05 +0000618 DecoderTable &Table = TableInfo.Table;
619
620 size_t PrevFilter = 0;
621 bool HasFallthrough = false;
Craig Topper1f7604d2014-12-13 05:12:19 +0000622 for (auto &Filter : FilterChooserMap) {
Owen Anderson4e818902011-02-18 21:51:29 +0000623 // Field value -1 implies a non-empty set of variable instructions.
624 // See also recurse().
Craig Topper1f7604d2014-12-13 05:12:19 +0000625 if (Filter.first == (unsigned)-1) {
Jim Grosbachecaef492012-08-14 19:06:05 +0000626 HasFallthrough = true;
Owen Anderson4e818902011-02-18 21:51:29 +0000627
Jim Grosbachecaef492012-08-14 19:06:05 +0000628 // Each scope should always have at least one filter value to check
629 // for.
630 assert(PrevFilter != 0 && "empty filter set!");
631 FixupList &CurScope = TableInfo.FixupStack.back();
632 // Resolve any NumToSkip fixups in the current scope.
633 resolveTableFixups(Table, CurScope, Table.size());
634 CurScope.clear();
635 PrevFilter = 0; // Don't re-process the filter's fallthrough.
636 } else {
637 Table.push_back(MCD::OPC_FilterValue);
638 // Encode and emit the value to filter against.
639 uint8_t Buffer[8];
Craig Topper1f7604d2014-12-13 05:12:19 +0000640 unsigned Len = encodeULEB128(Filter.first, Buffer);
Jim Grosbachecaef492012-08-14 19:06:05 +0000641 Table.insert(Table.end(), Buffer, Buffer + Len);
642 // Reserve space for the NumToSkip entry. We'll backpatch the value
643 // later.
644 PrevFilter = Table.size();
645 Table.push_back(0);
646 Table.push_back(0);
647 }
Owen Anderson4e818902011-02-18 21:51:29 +0000648
649 // We arrive at a category of instructions with the same segment value.
650 // Now delegate to the sub filter chooser for further decodings.
651 // The case may fallthrough, which happens if the remaining well-known
652 // encoding bits do not match exactly.
Craig Topper1f7604d2014-12-13 05:12:19 +0000653 Filter.second->emitTableEntries(TableInfo);
Owen Anderson4e818902011-02-18 21:51:29 +0000654
Jim Grosbachecaef492012-08-14 19:06:05 +0000655 // Now that we've emitted the body of the handler, update the NumToSkip
656 // of the filter itself to be able to skip forward when false. Subtract
657 // two as to account for the width of the NumToSkip field itself.
658 if (PrevFilter) {
659 uint32_t NumToSkip = Table.size() - PrevFilter - 2;
660 assert(NumToSkip < 65536U && "disassembler decoding table too large!");
661 Table[PrevFilter] = (uint8_t)NumToSkip;
662 Table[PrevFilter + 1] = (uint8_t)(NumToSkip >> 8);
663 }
Owen Anderson4e818902011-02-18 21:51:29 +0000664 }
665
Jim Grosbachecaef492012-08-14 19:06:05 +0000666 // Any remaining unresolved fixups bubble up to the parent fixup scope.
667 assert(TableInfo.FixupStack.size() > 1 && "fixup stack underflow!");
668 FixupScopeList::iterator Source = TableInfo.FixupStack.end() - 1;
669 FixupScopeList::iterator Dest = Source - 1;
670 Dest->insert(Dest->end(), Source->begin(), Source->end());
671 TableInfo.FixupStack.pop_back();
672
673 // If there is no fallthrough, then the final filter should get fixed
674 // up according to the enclosing scope rather than the current position.
675 if (!HasFallthrough)
676 TableInfo.FixupStack.back().push_back(PrevFilter);
Owen Anderson4e818902011-02-18 21:51:29 +0000677}
678
679// Returns the number of fanout produced by the filter. More fanout implies
680// the filter distinguishes more categories of instructions.
681unsigned Filter::usefulness() const {
Alexander Kornienko8c0809c2015-01-15 11:41:30 +0000682 if (!VariableInstructions.empty())
Owen Anderson4e818902011-02-18 21:51:29 +0000683 return FilteredInstructions.size();
684 else
685 return FilteredInstructions.size() + 1;
686}
687
688//////////////////////////////////
689// //
690// Filterchooser Implementation //
691// //
692//////////////////////////////////
693
Jim Grosbachecaef492012-08-14 19:06:05 +0000694// Emit the decoder state machine table.
695void FixedLenDecoderEmitter::emitTable(formatted_raw_ostream &OS,
696 DecoderTable &Table,
697 unsigned Indentation,
698 unsigned BitWidth,
699 StringRef Namespace) const {
700 OS.indent(Indentation) << "static const uint8_t DecoderTable" << Namespace
701 << BitWidth << "[] = {\n";
Owen Anderson4e818902011-02-18 21:51:29 +0000702
Jim Grosbachecaef492012-08-14 19:06:05 +0000703 Indentation += 2;
Owen Anderson4e818902011-02-18 21:51:29 +0000704
Jim Grosbachecaef492012-08-14 19:06:05 +0000705 // FIXME: We may be able to use the NumToSkip values to recover
706 // appropriate indentation levels.
707 DecoderTable::const_iterator I = Table.begin();
708 DecoderTable::const_iterator E = Table.end();
709 while (I != E) {
710 assert (I < E && "incomplete decode table entry!");
Owen Anderson4e818902011-02-18 21:51:29 +0000711
Jim Grosbachecaef492012-08-14 19:06:05 +0000712 uint64_t Pos = I - Table.begin();
713 OS << "/* " << Pos << " */";
714 OS.PadToColumn(12);
Owen Anderson4e818902011-02-18 21:51:29 +0000715
Jim Grosbachecaef492012-08-14 19:06:05 +0000716 switch (*I) {
717 default:
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000718 PrintFatalError("invalid decode table opcode");
Jim Grosbachecaef492012-08-14 19:06:05 +0000719 case MCD::OPC_ExtractField: {
720 ++I;
721 unsigned Start = *I++;
722 unsigned Len = *I++;
723 OS.indent(Indentation) << "MCD::OPC_ExtractField, " << Start << ", "
724 << Len << ", // Inst{";
725 if (Len > 1)
726 OS << (Start + Len - 1) << "-";
727 OS << Start << "} ...\n";
728 break;
729 }
730 case MCD::OPC_FilterValue: {
731 ++I;
732 OS.indent(Indentation) << "MCD::OPC_FilterValue, ";
733 // The filter value is ULEB128 encoded.
734 while (*I >= 128)
Craig Topper429093a2016-01-31 01:55:15 +0000735 OS << (unsigned)*I++ << ", ";
736 OS << (unsigned)*I++ << ", ";
Jim Grosbachecaef492012-08-14 19:06:05 +0000737
738 // 16-bit numtoskip value.
739 uint8_t Byte = *I++;
740 uint32_t NumToSkip = Byte;
Craig Topper429093a2016-01-31 01:55:15 +0000741 OS << (unsigned)Byte << ", ";
Jim Grosbachecaef492012-08-14 19:06:05 +0000742 Byte = *I++;
Craig Topper429093a2016-01-31 01:55:15 +0000743 OS << (unsigned)Byte << ", ";
Jim Grosbachecaef492012-08-14 19:06:05 +0000744 NumToSkip |= Byte << 8;
745 OS << "// Skip to: " << ((I - Table.begin()) + NumToSkip) << "\n";
746 break;
747 }
748 case MCD::OPC_CheckField: {
749 ++I;
750 unsigned Start = *I++;
751 unsigned Len = *I++;
752 OS.indent(Indentation) << "MCD::OPC_CheckField, " << Start << ", "
753 << Len << ", ";// << Val << ", " << NumToSkip << ",\n";
754 // ULEB128 encoded field value.
755 for (; *I >= 128; ++I)
Craig Topper429093a2016-01-31 01:55:15 +0000756 OS << (unsigned)*I << ", ";
757 OS << (unsigned)*I++ << ", ";
Jim Grosbachecaef492012-08-14 19:06:05 +0000758 // 16-bit numtoskip value.
759 uint8_t Byte = *I++;
760 uint32_t NumToSkip = Byte;
Craig Topper429093a2016-01-31 01:55:15 +0000761 OS << (unsigned)Byte << ", ";
Jim Grosbachecaef492012-08-14 19:06:05 +0000762 Byte = *I++;
Craig Topper429093a2016-01-31 01:55:15 +0000763 OS << (unsigned)Byte << ", ";
Jim Grosbachecaef492012-08-14 19:06:05 +0000764 NumToSkip |= Byte << 8;
765 OS << "// Skip to: " << ((I - Table.begin()) + NumToSkip) << "\n";
766 break;
767 }
768 case MCD::OPC_CheckPredicate: {
769 ++I;
770 OS.indent(Indentation) << "MCD::OPC_CheckPredicate, ";
771 for (; *I >= 128; ++I)
Craig Topper429093a2016-01-31 01:55:15 +0000772 OS << (unsigned)*I << ", ";
773 OS << (unsigned)*I++ << ", ";
Jim Grosbachecaef492012-08-14 19:06:05 +0000774
775 // 16-bit numtoskip value.
776 uint8_t Byte = *I++;
777 uint32_t NumToSkip = Byte;
Craig Topper429093a2016-01-31 01:55:15 +0000778 OS << (unsigned)Byte << ", ";
Jim Grosbachecaef492012-08-14 19:06:05 +0000779 Byte = *I++;
Craig Topper429093a2016-01-31 01:55:15 +0000780 OS << (unsigned)Byte << ", ";
Jim Grosbachecaef492012-08-14 19:06:05 +0000781 NumToSkip |= Byte << 8;
782 OS << "// Skip to: " << ((I - Table.begin()) + NumToSkip) << "\n";
783 break;
784 }
Petr Pavlu182b0572015-07-15 08:04:27 +0000785 case MCD::OPC_Decode:
786 case MCD::OPC_TryDecode: {
787 bool IsTry = *I == MCD::OPC_TryDecode;
Jim Grosbachecaef492012-08-14 19:06:05 +0000788 ++I;
789 // Extract the ULEB128 encoded Opcode to a buffer.
790 uint8_t Buffer[8], *p = Buffer;
791 while ((*p++ = *I++) >= 128)
792 assert((p - Buffer) <= (ptrdiff_t)sizeof(Buffer)
793 && "ULEB128 value too large!");
794 // Decode the Opcode value.
795 unsigned Opc = decodeULEB128(Buffer);
Petr Pavlu182b0572015-07-15 08:04:27 +0000796 OS.indent(Indentation) << "MCD::OPC_" << (IsTry ? "Try" : "")
797 << "Decode, ";
Jim Grosbachecaef492012-08-14 19:06:05 +0000798 for (p = Buffer; *p >= 128; ++p)
Craig Topper429093a2016-01-31 01:55:15 +0000799 OS << (unsigned)*p << ", ";
800 OS << (unsigned)*p << ", ";
Jim Grosbachecaef492012-08-14 19:06:05 +0000801
802 // Decoder index.
803 for (; *I >= 128; ++I)
Craig Topper429093a2016-01-31 01:55:15 +0000804 OS << (unsigned)*I << ", ";
805 OS << (unsigned)*I++ << ", ";
Jim Grosbachecaef492012-08-14 19:06:05 +0000806
Petr Pavlu182b0572015-07-15 08:04:27 +0000807 if (!IsTry) {
808 OS << "// Opcode: "
Craig Topperf9265322016-01-17 20:38:14 +0000809 << NumberedInstructions[Opc]->TheDef->getName() << "\n";
Petr Pavlu182b0572015-07-15 08:04:27 +0000810 break;
811 }
812
813 // Fallthrough for OPC_TryDecode.
814
815 // 16-bit numtoskip value.
816 uint8_t Byte = *I++;
817 uint32_t NumToSkip = Byte;
Craig Topper429093a2016-01-31 01:55:15 +0000818 OS << (unsigned)Byte << ", ";
Petr Pavlu182b0572015-07-15 08:04:27 +0000819 Byte = *I++;
Craig Topper429093a2016-01-31 01:55:15 +0000820 OS << (unsigned)Byte << ", ";
Petr Pavlu182b0572015-07-15 08:04:27 +0000821 NumToSkip |= Byte << 8;
822
Jim Grosbachecaef492012-08-14 19:06:05 +0000823 OS << "// Opcode: "
Craig Topperf9265322016-01-17 20:38:14 +0000824 << NumberedInstructions[Opc]->TheDef->getName()
Petr Pavlu182b0572015-07-15 08:04:27 +0000825 << ", skip to: " << ((I - Table.begin()) + NumToSkip) << "\n";
Jim Grosbachecaef492012-08-14 19:06:05 +0000826 break;
827 }
828 case MCD::OPC_SoftFail: {
829 ++I;
830 OS.indent(Indentation) << "MCD::OPC_SoftFail";
831 // Positive mask
832 uint64_t Value = 0;
833 unsigned Shift = 0;
834 do {
Craig Topper429093a2016-01-31 01:55:15 +0000835 OS << ", " << (unsigned)*I;
Jim Grosbachecaef492012-08-14 19:06:05 +0000836 Value += (*I & 0x7f) << Shift;
837 Shift += 7;
838 } while (*I++ >= 128);
Craig Topper429093a2016-01-31 01:55:15 +0000839 if (Value > 127) {
840 OS << " /* 0x";
841 OS.write_hex(Value);
842 OS << " */";
843 }
Jim Grosbachecaef492012-08-14 19:06:05 +0000844 // Negative mask
845 Value = 0;
846 Shift = 0;
847 do {
Craig Topper429093a2016-01-31 01:55:15 +0000848 OS << ", " << (unsigned)*I;
Jim Grosbachecaef492012-08-14 19:06:05 +0000849 Value += (*I & 0x7f) << Shift;
850 Shift += 7;
851 } while (*I++ >= 128);
Craig Topper429093a2016-01-31 01:55:15 +0000852 if (Value > 127) {
853 OS << " /* 0x";
854 OS.write_hex(Value);
855 OS << " */";
856 }
Jim Grosbachecaef492012-08-14 19:06:05 +0000857 OS << ",\n";
858 break;
859 }
860 case MCD::OPC_Fail: {
861 ++I;
862 OS.indent(Indentation) << "MCD::OPC_Fail,\n";
863 break;
864 }
865 }
866 }
867 OS.indent(Indentation) << "0\n";
868
869 Indentation -= 2;
870
871 OS.indent(Indentation) << "};\n\n";
872}
873
874void FixedLenDecoderEmitter::
875emitPredicateFunction(formatted_raw_ostream &OS, PredicateSet &Predicates,
876 unsigned Indentation) const {
877 // The predicate function is just a big switch statement based on the
878 // input predicate index.
879 OS.indent(Indentation) << "static bool checkDecoderPredicate(unsigned Idx, "
Michael Kupersteindb0712f2015-05-26 10:47:10 +0000880 << "const FeatureBitset& Bits) {\n";
Jim Grosbachecaef492012-08-14 19:06:05 +0000881 Indentation += 2;
Aaron Ballmane59e3582013-07-15 16:53:32 +0000882 if (!Predicates.empty()) {
883 OS.indent(Indentation) << "switch (Idx) {\n";
884 OS.indent(Indentation) << "default: llvm_unreachable(\"Invalid index!\");\n";
885 unsigned Index = 0;
Craig Topper1f7604d2014-12-13 05:12:19 +0000886 for (const auto &Predicate : Predicates) {
887 OS.indent(Indentation) << "case " << Index++ << ":\n";
888 OS.indent(Indentation+2) << "return (" << Predicate << ");\n";
Aaron Ballmane59e3582013-07-15 16:53:32 +0000889 }
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 "
Petr Pavlu182b0572015-07-15 08:04:27 +0000908 << "Address, const void *Decoder, bool &DecodeComplete) {\n";
Jim Grosbachecaef492012-08-14 19:06:05 +0000909 Indentation += 2;
Petr Pavlu182b0572015-07-15 08:04:27 +0000910 OS.indent(Indentation) << "DecodeComplete = true;\n";
Jim Grosbachecaef492012-08-14 19:06:05 +0000911 OS.indent(Indentation) << "InsnType tmp;\n";
912 OS.indent(Indentation) << "switch (Idx) {\n";
913 OS.indent(Indentation) << "default: llvm_unreachable(\"Invalid index!\");\n";
914 unsigned Index = 0;
Craig Topper1f7604d2014-12-13 05:12:19 +0000915 for (const auto &Decoder : Decoders) {
916 OS.indent(Indentation) << "case " << Index++ << ":\n";
917 OS << Decoder;
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,
Petr Pavlu182b0572015-07-15 08:04:27 +00001066 const OperandInfo &OpInfo,
1067 bool &OpHasCompleteDecoder) const {
Craig Topper48c112b2012-03-16 05:58:09 +00001068 const std::string &Decoder = OpInfo.Decoder;
Owen Andersone3591652011-07-28 21:54:31 +00001069
Craig Topper5546f8c2014-09-27 05:26:42 +00001070 if (OpInfo.numFields() != 1)
Craig Topperebc3aa22012-08-17 05:16:15 +00001071 o.indent(Indentation) << "tmp = 0;\n";
Craig Topper5546f8c2014-09-27 05:26:42 +00001072
1073 for (const EncodingField &EF : OpInfo) {
1074 o.indent(Indentation) << "tmp ";
1075 if (OpInfo.numFields() != 1) o << '|';
1076 o << "= fieldFromInstruction"
1077 << "(insn, " << EF.Base << ", " << EF.Width << ')';
1078 if (OpInfo.numFields() != 1 || EF.Offset != 0)
1079 o << " << " << EF.Offset;
1080 o << ";\n";
Owen Andersone3591652011-07-28 21:54:31 +00001081 }
1082
Petr Pavlu182b0572015-07-15 08:04:27 +00001083 if (Decoder != "") {
1084 OpHasCompleteDecoder = OpInfo.HasCompleteDecoder;
Craig Topperebc3aa22012-08-17 05:16:15 +00001085 o.indent(Indentation) << Emitter->GuardPrefix << Decoder
Petr Pavlu182b0572015-07-15 08:04:27 +00001086 << "(MI, tmp, Address, Decoder)"
1087 << Emitter->GuardPostfix
1088 << " { " << (OpHasCompleteDecoder ? "" : "DecodeComplete = false; ")
1089 << "return MCDisassembler::Fail; }\n";
1090 } else {
1091 OpHasCompleteDecoder = true;
Jim Grosbache9119e42015-05-13 18:37:00 +00001092 o.indent(Indentation) << "MI.addOperand(MCOperand::createImm(tmp));\n";
Petr Pavlu182b0572015-07-15 08:04:27 +00001093 }
Owen Andersone3591652011-07-28 21:54:31 +00001094}
1095
Jim Grosbachecaef492012-08-14 19:06:05 +00001096void FilterChooser::emitDecoder(raw_ostream &OS, unsigned Indentation,
Petr Pavlu182b0572015-07-15 08:04:27 +00001097 unsigned Opc, bool &HasCompleteDecoder) const {
1098 HasCompleteDecoder = true;
1099
Craig Topper1f7604d2014-12-13 05:12:19 +00001100 for (const auto &Op : Operands.find(Opc)->second) {
Jim Grosbachecaef492012-08-14 19:06:05 +00001101 // If a custom instruction decoder was specified, use that.
Craig Topper1f7604d2014-12-13 05:12:19 +00001102 if (Op.numFields() == 0 && Op.Decoder.size()) {
Petr Pavlu182b0572015-07-15 08:04:27 +00001103 HasCompleteDecoder = Op.HasCompleteDecoder;
Craig Topper1f7604d2014-12-13 05:12:19 +00001104 OS.indent(Indentation) << Emitter->GuardPrefix << Op.Decoder
Jim Grosbachecaef492012-08-14 19:06:05 +00001105 << "(MI, insn, Address, Decoder)"
Petr Pavlu182b0572015-07-15 08:04:27 +00001106 << Emitter->GuardPostfix
1107 << " { " << (HasCompleteDecoder ? "" : "DecodeComplete = false; ")
1108 << "return MCDisassembler::Fail; }\n";
Jim Grosbachecaef492012-08-14 19:06:05 +00001109 break;
1110 }
1111
Petr Pavlu182b0572015-07-15 08:04:27 +00001112 bool OpHasCompleteDecoder;
1113 emitBinaryParser(OS, Indentation, Op, OpHasCompleteDecoder);
1114 if (!OpHasCompleteDecoder)
1115 HasCompleteDecoder = false;
Jim Grosbachecaef492012-08-14 19:06:05 +00001116 }
1117}
1118
1119unsigned FilterChooser::getDecoderIndex(DecoderSet &Decoders,
Petr Pavlu182b0572015-07-15 08:04:27 +00001120 unsigned Opc,
1121 bool &HasCompleteDecoder) const {
Jim Grosbachecaef492012-08-14 19:06:05 +00001122 // Build up the predicate string.
1123 SmallString<256> Decoder;
1124 // FIXME: emitDecoder() function can take a buffer directly rather than
1125 // a stream.
1126 raw_svector_ostream S(Decoder);
Craig Topperebc3aa22012-08-17 05:16:15 +00001127 unsigned I = 4;
Petr Pavlu182b0572015-07-15 08:04:27 +00001128 emitDecoder(S, I, Opc, HasCompleteDecoder);
Jim Grosbachecaef492012-08-14 19:06:05 +00001129
1130 // Using the full decoder string as the key value here is a bit
1131 // heavyweight, but is effective. If the string comparisons become a
1132 // performance concern, we can implement a mangling of the predicate
Nick Lewycky06b0ea22015-08-18 22:41:58 +00001133 // data easily enough with a map back to the actual string. That's
Jim Grosbachecaef492012-08-14 19:06:05 +00001134 // overkill for now, though.
1135
1136 // Make sure the predicate is in the table.
Yaron Keren92e1b622015-03-18 10:17:07 +00001137 Decoders.insert(StringRef(Decoder));
Jim Grosbachecaef492012-08-14 19:06:05 +00001138 // Now figure out the index for when we write out the table.
1139 DecoderSet::const_iterator P = std::find(Decoders.begin(),
1140 Decoders.end(),
1141 Decoder.str());
1142 return (unsigned)(P - Decoders.begin());
1143}
1144
James Molloy8067df92011-09-07 19:42:28 +00001145static void emitSinglePredicateMatch(raw_ostream &o, StringRef str,
Craig Topper48c112b2012-03-16 05:58:09 +00001146 const std::string &PredicateNamespace) {
Andrew Trick43674ad2011-09-08 05:25:49 +00001147 if (str[0] == '!')
Michael Kupersteindb0712f2015-05-26 10:47:10 +00001148 o << "!Bits[" << PredicateNamespace << "::"
1149 << str.slice(1,str.size()) << "]";
James Molloy8067df92011-09-07 19:42:28 +00001150 else
Michael Kupersteindb0712f2015-05-26 10:47:10 +00001151 o << "Bits[" << PredicateNamespace << "::" << str << "]";
James Molloy8067df92011-09-07 19:42:28 +00001152}
1153
1154bool FilterChooser::emitPredicateMatch(raw_ostream &o, unsigned &Indentation,
Craig Topper48c112b2012-03-16 05:58:09 +00001155 unsigned Opc) const {
Jim Grosbach3f4b2392012-02-29 22:07:56 +00001156 ListInit *Predicates =
1157 AllInstructions[Opc]->TheDef->getValueAsListInit("Predicates");
Toma Tabacu3d5ce492015-04-07 12:10:11 +00001158 bool IsFirstEmission = true;
Craig Topper664f6a02015-06-02 04:15:57 +00001159 for (unsigned i = 0; i < Predicates->size(); ++i) {
James Molloy8067df92011-09-07 19:42:28 +00001160 Record *Pred = Predicates->getElementAsRecord(i);
1161 if (!Pred->getValue("AssemblerMatcherPredicate"))
1162 continue;
1163
1164 std::string P = Pred->getValueAsString("AssemblerCondString");
1165
1166 if (!P.length())
1167 continue;
1168
Toma Tabacu3d5ce492015-04-07 12:10:11 +00001169 if (!IsFirstEmission)
James Molloy8067df92011-09-07 19:42:28 +00001170 o << " && ";
1171
1172 StringRef SR(P);
1173 std::pair<StringRef, StringRef> pairs = SR.split(',');
1174 while (pairs.second.size()) {
1175 emitSinglePredicateMatch(o, pairs.first, Emitter->PredicateNamespace);
1176 o << " && ";
1177 pairs = pairs.second.split(',');
1178 }
1179 emitSinglePredicateMatch(o, pairs.first, Emitter->PredicateNamespace);
Toma Tabacu3d5ce492015-04-07 12:10:11 +00001180 IsFirstEmission = false;
James Molloy8067df92011-09-07 19:42:28 +00001181 }
Craig Topper664f6a02015-06-02 04:15:57 +00001182 return !Predicates->empty();
Andrew Trick61abca62011-09-08 05:23:14 +00001183}
James Molloy8067df92011-09-07 19:42:28 +00001184
Jim Grosbachecaef492012-08-14 19:06:05 +00001185bool FilterChooser::doesOpcodeNeedPredicate(unsigned Opc) const {
1186 ListInit *Predicates =
1187 AllInstructions[Opc]->TheDef->getValueAsListInit("Predicates");
Craig Topper664f6a02015-06-02 04:15:57 +00001188 for (unsigned i = 0; i < Predicates->size(); ++i) {
Jim Grosbachecaef492012-08-14 19:06:05 +00001189 Record *Pred = Predicates->getElementAsRecord(i);
1190 if (!Pred->getValue("AssemblerMatcherPredicate"))
1191 continue;
1192
1193 std::string P = Pred->getValueAsString("AssemblerCondString");
1194
1195 if (!P.length())
1196 continue;
1197
1198 return true;
1199 }
1200 return false;
1201}
1202
1203unsigned FilterChooser::getPredicateIndex(DecoderTableInfo &TableInfo,
1204 StringRef Predicate) const {
1205 // Using the full predicate string as the key value here is a bit
1206 // heavyweight, but is effective. If the string comparisons become a
1207 // performance concern, we can implement a mangling of the predicate
Nick Lewycky06b0ea22015-08-18 22:41:58 +00001208 // data easily enough with a map back to the actual string. That's
Jim Grosbachecaef492012-08-14 19:06:05 +00001209 // overkill for now, though.
1210
1211 // Make sure the predicate is in the table.
1212 TableInfo.Predicates.insert(Predicate.str());
1213 // Now figure out the index for when we write out the table.
1214 PredicateSet::const_iterator P = std::find(TableInfo.Predicates.begin(),
1215 TableInfo.Predicates.end(),
1216 Predicate.str());
1217 return (unsigned)(P - TableInfo.Predicates.begin());
1218}
1219
1220void FilterChooser::emitPredicateTableEntry(DecoderTableInfo &TableInfo,
1221 unsigned Opc) const {
1222 if (!doesOpcodeNeedPredicate(Opc))
1223 return;
1224
1225 // Build up the predicate string.
1226 SmallString<256> Predicate;
1227 // FIXME: emitPredicateMatch() functions can take a buffer directly rather
1228 // than a stream.
1229 raw_svector_ostream PS(Predicate);
1230 unsigned I = 0;
1231 emitPredicateMatch(PS, I, Opc);
1232
1233 // Figure out the index into the predicate table for the predicate just
1234 // computed.
1235 unsigned PIdx = getPredicateIndex(TableInfo, PS.str());
1236 SmallString<16> PBytes;
1237 raw_svector_ostream S(PBytes);
1238 encodeULEB128(PIdx, S);
Jim Grosbachecaef492012-08-14 19:06:05 +00001239
1240 TableInfo.Table.push_back(MCD::OPC_CheckPredicate);
1241 // Predicate index
Craig Topper29688ab2012-08-17 05:42:16 +00001242 for (unsigned i = 0, e = PBytes.size(); i != e; ++i)
Jim Grosbachecaef492012-08-14 19:06:05 +00001243 TableInfo.Table.push_back(PBytes[i]);
1244 // Push location for NumToSkip backpatching.
1245 TableInfo.FixupStack.back().push_back(TableInfo.Table.size());
1246 TableInfo.Table.push_back(0);
1247 TableInfo.Table.push_back(0);
1248}
1249
1250void FilterChooser::emitSoftFailTableEntry(DecoderTableInfo &TableInfo,
1251 unsigned Opc) const {
Jim Grosbach3f4b2392012-02-29 22:07:56 +00001252 BitsInit *SFBits =
1253 AllInstructions[Opc]->TheDef->getValueAsBitsInit("SoftFail");
James Molloyd9ba4fd2012-02-09 10:56:31 +00001254 if (!SFBits) return;
1255 BitsInit *InstBits = AllInstructions[Opc]->TheDef->getValueAsBitsInit("Inst");
1256
1257 APInt PositiveMask(BitWidth, 0ULL);
1258 APInt NegativeMask(BitWidth, 0ULL);
1259 for (unsigned i = 0; i < BitWidth; ++i) {
1260 bit_value_t B = bitFromBits(*SFBits, i);
1261 bit_value_t IB = bitFromBits(*InstBits, i);
1262
1263 if (B != BIT_TRUE) continue;
1264
1265 switch (IB) {
1266 case BIT_FALSE:
1267 // The bit is meant to be false, so emit a check to see if it is true.
1268 PositiveMask.setBit(i);
1269 break;
1270 case BIT_TRUE:
1271 // The bit is meant to be true, so emit a check to see if it is false.
1272 NegativeMask.setBit(i);
1273 break;
1274 default:
1275 // The bit is not set; this must be an error!
1276 StringRef Name = AllInstructions[Opc]->TheDef->getName();
Jim Grosbachecaef492012-08-14 19:06:05 +00001277 errs() << "SoftFail Conflict: bit SoftFail{" << i << "} in " << Name
1278 << " is set but Inst{" << i << "} is unset!\n"
James Molloyd9ba4fd2012-02-09 10:56:31 +00001279 << " - You can only mark a bit as SoftFail if it is fully defined"
1280 << " (1/0 - not '?') in Inst\n";
Jim Grosbachecaef492012-08-14 19:06:05 +00001281 return;
James Molloyd9ba4fd2012-02-09 10:56:31 +00001282 }
1283 }
1284
1285 bool NeedPositiveMask = PositiveMask.getBoolValue();
1286 bool NeedNegativeMask = NegativeMask.getBoolValue();
1287
1288 if (!NeedPositiveMask && !NeedNegativeMask)
1289 return;
1290
Jim Grosbachecaef492012-08-14 19:06:05 +00001291 TableInfo.Table.push_back(MCD::OPC_SoftFail);
James Molloyd9ba4fd2012-02-09 10:56:31 +00001292
Jim Grosbachecaef492012-08-14 19:06:05 +00001293 SmallString<16> MaskBytes;
1294 raw_svector_ostream S(MaskBytes);
1295 if (NeedPositiveMask) {
1296 encodeULEB128(PositiveMask.getZExtValue(), S);
Craig Topper29688ab2012-08-17 05:42:16 +00001297 for (unsigned i = 0, e = MaskBytes.size(); i != e; ++i)
Jim Grosbachecaef492012-08-14 19:06:05 +00001298 TableInfo.Table.push_back(MaskBytes[i]);
1299 } else
1300 TableInfo.Table.push_back(0);
1301 if (NeedNegativeMask) {
1302 MaskBytes.clear();
Jim Grosbachecaef492012-08-14 19:06:05 +00001303 encodeULEB128(NegativeMask.getZExtValue(), S);
Craig Topper29688ab2012-08-17 05:42:16 +00001304 for (unsigned i = 0, e = MaskBytes.size(); i != e; ++i)
Jim Grosbachecaef492012-08-14 19:06:05 +00001305 TableInfo.Table.push_back(MaskBytes[i]);
1306 } else
1307 TableInfo.Table.push_back(0);
James Molloyd9ba4fd2012-02-09 10:56:31 +00001308}
1309
Jim Grosbachecaef492012-08-14 19:06:05 +00001310// Emits table entries to decode the singleton.
1311void FilterChooser::emitSingletonTableEntry(DecoderTableInfo &TableInfo,
1312 unsigned Opc) const {
Owen Anderson4e818902011-02-18 21:51:29 +00001313 std::vector<unsigned> StartBits;
1314 std::vector<unsigned> EndBits;
1315 std::vector<uint64_t> FieldVals;
1316 insn_t Insn;
1317 insnWithID(Insn, Opc);
1318
1319 // Look for islands of undecoded bits of the singleton.
1320 getIslands(StartBits, EndBits, FieldVals, Insn);
1321
1322 unsigned Size = StartBits.size();
Owen Anderson4e818902011-02-18 21:51:29 +00001323
Jim Grosbachecaef492012-08-14 19:06:05 +00001324 // Emit the predicate table entry if one is needed.
1325 emitPredicateTableEntry(TableInfo, Opc);
Owen Anderson4e818902011-02-18 21:51:29 +00001326
Jim Grosbachecaef492012-08-14 19:06:05 +00001327 // Check any additional encoding fields needed.
Craig Topper29688ab2012-08-17 05:42:16 +00001328 for (unsigned I = Size; I != 0; --I) {
1329 unsigned NumBits = EndBits[I-1] - StartBits[I-1] + 1;
Jim Grosbachecaef492012-08-14 19:06:05 +00001330 TableInfo.Table.push_back(MCD::OPC_CheckField);
1331 TableInfo.Table.push_back(StartBits[I-1]);
1332 TableInfo.Table.push_back(NumBits);
1333 uint8_t Buffer[8], *p;
1334 encodeULEB128(FieldVals[I-1], Buffer);
1335 for (p = Buffer; *p >= 128 ; ++p)
1336 TableInfo.Table.push_back(*p);
1337 TableInfo.Table.push_back(*p);
1338 // Push location for NumToSkip backpatching.
1339 TableInfo.FixupStack.back().push_back(TableInfo.Table.size());
1340 // The fixup is always 16-bits, so go ahead and allocate the space
1341 // in the table so all our relative position calculations work OK even
1342 // before we fully resolve the real value here.
1343 TableInfo.Table.push_back(0);
1344 TableInfo.Table.push_back(0);
Owen Anderson4e818902011-02-18 21:51:29 +00001345 }
Owen Anderson4e818902011-02-18 21:51:29 +00001346
Jim Grosbachecaef492012-08-14 19:06:05 +00001347 // Check for soft failure of the match.
1348 emitSoftFailTableEntry(TableInfo, Opc);
Owen Anderson4e818902011-02-18 21:51:29 +00001349
Petr Pavlu182b0572015-07-15 08:04:27 +00001350 bool HasCompleteDecoder;
1351 unsigned DIdx = getDecoderIndex(TableInfo.Decoders, Opc, HasCompleteDecoder);
1352
1353 // Produce OPC_Decode or OPC_TryDecode opcode based on the information
1354 // whether the instruction decoder is complete or not. If it is complete
1355 // then it handles all possible values of remaining variable/unfiltered bits
1356 // and for any value can determine if the bitpattern is a valid instruction
1357 // or not. This means OPC_Decode will be the final step in the decoding
1358 // process. If it is not complete, then the Fail return code from the
1359 // decoder method indicates that additional processing should be done to see
1360 // if there is any other instruction that also matches the bitpattern and
1361 // can decode it.
1362 TableInfo.Table.push_back(HasCompleteDecoder ? MCD::OPC_Decode :
1363 MCD::OPC_TryDecode);
Jim Grosbachecaef492012-08-14 19:06:05 +00001364 uint8_t Buffer[8], *p;
1365 encodeULEB128(Opc, Buffer);
1366 for (p = Buffer; *p >= 128 ; ++p)
1367 TableInfo.Table.push_back(*p);
1368 TableInfo.Table.push_back(*p);
1369
Jim Grosbachecaef492012-08-14 19:06:05 +00001370 SmallString<16> Bytes;
1371 raw_svector_ostream S(Bytes);
1372 encodeULEB128(DIdx, S);
Jim Grosbachecaef492012-08-14 19:06:05 +00001373
1374 // Decoder index
Craig Topper29688ab2012-08-17 05:42:16 +00001375 for (unsigned i = 0, e = Bytes.size(); i != e; ++i)
Jim Grosbachecaef492012-08-14 19:06:05 +00001376 TableInfo.Table.push_back(Bytes[i]);
Petr Pavlu182b0572015-07-15 08:04:27 +00001377
1378 if (!HasCompleteDecoder) {
1379 // Push location for NumToSkip backpatching.
1380 TableInfo.FixupStack.back().push_back(TableInfo.Table.size());
1381 // Allocate the space for the fixup.
1382 TableInfo.Table.push_back(0);
1383 TableInfo.Table.push_back(0);
1384 }
Owen Anderson4e818902011-02-18 21:51:29 +00001385}
1386
Jim Grosbachecaef492012-08-14 19:06:05 +00001387// Emits table entries to decode the singleton, and then to decode the rest.
1388void FilterChooser::emitSingletonTableEntry(DecoderTableInfo &TableInfo,
1389 const Filter &Best) const {
Owen Anderson4e818902011-02-18 21:51:29 +00001390 unsigned Opc = Best.getSingletonOpc();
1391
Jim Grosbachecaef492012-08-14 19:06:05 +00001392 // complex singletons need predicate checks from the first singleton
1393 // to refer forward to the variable filterchooser that follows.
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00001394 TableInfo.FixupStack.emplace_back();
Owen Anderson4e818902011-02-18 21:51:29 +00001395
Jim Grosbachecaef492012-08-14 19:06:05 +00001396 emitSingletonTableEntry(TableInfo, Opc);
Owen Anderson4e818902011-02-18 21:51:29 +00001397
Jim Grosbachecaef492012-08-14 19:06:05 +00001398 resolveTableFixups(TableInfo.Table, TableInfo.FixupStack.back(),
1399 TableInfo.Table.size());
1400 TableInfo.FixupStack.pop_back();
1401
1402 Best.getVariableFC().emitTableEntries(TableInfo);
Owen Anderson4e818902011-02-18 21:51:29 +00001403}
1404
Jim Grosbachecaef492012-08-14 19:06:05 +00001405
Owen Anderson4e818902011-02-18 21:51:29 +00001406// Assign a single filter and run with it. Top level API client can initialize
1407// with a single filter to start the filtering process.
Craig Topper48c112b2012-03-16 05:58:09 +00001408void FilterChooser::runSingleFilter(unsigned startBit, unsigned numBit,
1409 bool mixed) {
Owen Anderson4e818902011-02-18 21:51:29 +00001410 Filters.clear();
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00001411 Filters.emplace_back(*this, startBit, numBit, true);
Owen Anderson4e818902011-02-18 21:51:29 +00001412 BestIndex = 0; // Sole Filter instance to choose from.
1413 bestFilter().recurse();
1414}
1415
1416// reportRegion is a helper function for filterProcessor to mark a region as
1417// eligible for use as a filter region.
1418void FilterChooser::reportRegion(bitAttr_t RA, unsigned StartBit,
Craig Topper82d0d5f2012-03-16 01:19:24 +00001419 unsigned BitIndex, bool AllowMixed) {
Owen Anderson4e818902011-02-18 21:51:29 +00001420 if (RA == ATTR_MIXED && AllowMixed)
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00001421 Filters.emplace_back(*this, StartBit, BitIndex - StartBit, true);
Owen Anderson4e818902011-02-18 21:51:29 +00001422 else if (RA == ATTR_ALL_SET && !AllowMixed)
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00001423 Filters.emplace_back(*this, StartBit, BitIndex - StartBit, false);
Owen Anderson4e818902011-02-18 21:51:29 +00001424}
1425
1426// FilterProcessor scans the well-known encoding bits of the instructions and
1427// builds up a list of candidate filters. It chooses the best filter and
1428// recursively descends down the decoding tree.
1429bool FilterChooser::filterProcessor(bool AllowMixed, bool Greedy) {
1430 Filters.clear();
1431 BestIndex = -1;
1432 unsigned numInstructions = Opcodes.size();
1433
1434 assert(numInstructions && "Filter created with no instructions");
1435
1436 // No further filtering is necessary.
1437 if (numInstructions == 1)
1438 return true;
1439
1440 // Heuristics. See also doFilter()'s "Heuristics" comment when num of
1441 // instructions is 3.
1442 if (AllowMixed && !Greedy) {
1443 assert(numInstructions == 3);
1444
1445 for (unsigned i = 0; i < Opcodes.size(); ++i) {
1446 std::vector<unsigned> StartBits;
1447 std::vector<unsigned> EndBits;
1448 std::vector<uint64_t> FieldVals;
1449 insn_t Insn;
1450
1451 insnWithID(Insn, Opcodes[i]);
1452
1453 // Look for islands of undecoded bits of any instruction.
1454 if (getIslands(StartBits, EndBits, FieldVals, Insn) > 0) {
1455 // Found an instruction with island(s). Now just assign a filter.
Craig Topper48c112b2012-03-16 05:58:09 +00001456 runSingleFilter(StartBits[0], EndBits[0] - StartBits[0] + 1, true);
Owen Anderson4e818902011-02-18 21:51:29 +00001457 return true;
1458 }
1459 }
1460 }
1461
Craig Topper29688ab2012-08-17 05:42:16 +00001462 unsigned BitIndex;
Owen Anderson4e818902011-02-18 21:51:29 +00001463
1464 // We maintain BIT_WIDTH copies of the bitAttrs automaton.
1465 // The automaton consumes the corresponding bit from each
1466 // instruction.
1467 //
1468 // Input symbols: 0, 1, and _ (unset).
1469 // States: NONE, FILTERED, ALL_SET, ALL_UNSET, and MIXED.
1470 // Initial state: NONE.
1471 //
1472 // (NONE) ------- [01] -> (ALL_SET)
1473 // (NONE) ------- _ ----> (ALL_UNSET)
1474 // (ALL_SET) ---- [01] -> (ALL_SET)
1475 // (ALL_SET) ---- _ ----> (MIXED)
1476 // (ALL_UNSET) -- [01] -> (MIXED)
1477 // (ALL_UNSET) -- _ ----> (ALL_UNSET)
1478 // (MIXED) ------ . ----> (MIXED)
1479 // (FILTERED)---- . ----> (FILTERED)
1480
Owen Andersonc78e03c2011-07-19 21:06:00 +00001481 std::vector<bitAttr_t> bitAttrs;
Owen Anderson4e818902011-02-18 21:51:29 +00001482
1483 // FILTERED bit positions provide no entropy and are not worthy of pursuing.
1484 // Filter::recurse() set either BIT_TRUE or BIT_FALSE for each position.
Owen Andersonc78e03c2011-07-19 21:06:00 +00001485 for (BitIndex = 0; BitIndex < BitWidth; ++BitIndex)
Owen Anderson4e818902011-02-18 21:51:29 +00001486 if (FilterBitValues[BitIndex] == BIT_TRUE ||
1487 FilterBitValues[BitIndex] == BIT_FALSE)
Owen Andersonc78e03c2011-07-19 21:06:00 +00001488 bitAttrs.push_back(ATTR_FILTERED);
Owen Anderson4e818902011-02-18 21:51:29 +00001489 else
Owen Andersonc78e03c2011-07-19 21:06:00 +00001490 bitAttrs.push_back(ATTR_NONE);
Owen Anderson4e818902011-02-18 21:51:29 +00001491
Craig Topper29688ab2012-08-17 05:42:16 +00001492 for (unsigned InsnIndex = 0; InsnIndex < numInstructions; ++InsnIndex) {
Owen Anderson4e818902011-02-18 21:51:29 +00001493 insn_t insn;
1494
1495 insnWithID(insn, Opcodes[InsnIndex]);
1496
Owen Andersonc78e03c2011-07-19 21:06:00 +00001497 for (BitIndex = 0; BitIndex < BitWidth; ++BitIndex) {
Owen Anderson4e818902011-02-18 21:51:29 +00001498 switch (bitAttrs[BitIndex]) {
1499 case ATTR_NONE:
1500 if (insn[BitIndex] == BIT_UNSET)
1501 bitAttrs[BitIndex] = ATTR_ALL_UNSET;
1502 else
1503 bitAttrs[BitIndex] = ATTR_ALL_SET;
1504 break;
1505 case ATTR_ALL_SET:
1506 if (insn[BitIndex] == BIT_UNSET)
1507 bitAttrs[BitIndex] = ATTR_MIXED;
1508 break;
1509 case ATTR_ALL_UNSET:
1510 if (insn[BitIndex] != BIT_UNSET)
1511 bitAttrs[BitIndex] = ATTR_MIXED;
1512 break;
1513 case ATTR_MIXED:
1514 case ATTR_FILTERED:
1515 break;
1516 }
1517 }
1518 }
1519
1520 // The regionAttr automaton consumes the bitAttrs automatons' state,
1521 // lowest-to-highest.
1522 //
1523 // Input symbols: F(iltered), (all_)S(et), (all_)U(nset), M(ixed)
1524 // States: NONE, ALL_SET, MIXED
1525 // Initial state: NONE
1526 //
1527 // (NONE) ----- F --> (NONE)
1528 // (NONE) ----- S --> (ALL_SET) ; and set region start
1529 // (NONE) ----- U --> (NONE)
1530 // (NONE) ----- M --> (MIXED) ; and set region start
1531 // (ALL_SET) -- F --> (NONE) ; and report an ALL_SET region
1532 // (ALL_SET) -- S --> (ALL_SET)
1533 // (ALL_SET) -- U --> (NONE) ; and report an ALL_SET region
1534 // (ALL_SET) -- M --> (MIXED) ; and report an ALL_SET region
1535 // (MIXED) ---- F --> (NONE) ; and report a MIXED region
1536 // (MIXED) ---- S --> (ALL_SET) ; and report a MIXED region
1537 // (MIXED) ---- U --> (NONE) ; and report a MIXED region
1538 // (MIXED) ---- M --> (MIXED)
1539
1540 bitAttr_t RA = ATTR_NONE;
1541 unsigned StartBit = 0;
1542
Craig Topper29688ab2012-08-17 05:42:16 +00001543 for (BitIndex = 0; BitIndex < BitWidth; ++BitIndex) {
Owen Anderson4e818902011-02-18 21:51:29 +00001544 bitAttr_t bitAttr = bitAttrs[BitIndex];
1545
1546 assert(bitAttr != ATTR_NONE && "Bit without attributes");
1547
1548 switch (RA) {
1549 case ATTR_NONE:
1550 switch (bitAttr) {
1551 case ATTR_FILTERED:
1552 break;
1553 case ATTR_ALL_SET:
1554 StartBit = BitIndex;
1555 RA = ATTR_ALL_SET;
1556 break;
1557 case ATTR_ALL_UNSET:
1558 break;
1559 case ATTR_MIXED:
1560 StartBit = BitIndex;
1561 RA = ATTR_MIXED;
1562 break;
1563 default:
Craig Topperc4965bc2012-02-05 07:21:30 +00001564 llvm_unreachable("Unexpected bitAttr!");
Owen Anderson4e818902011-02-18 21:51:29 +00001565 }
1566 break;
1567 case ATTR_ALL_SET:
1568 switch (bitAttr) {
1569 case ATTR_FILTERED:
1570 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1571 RA = ATTR_NONE;
1572 break;
1573 case ATTR_ALL_SET:
1574 break;
1575 case ATTR_ALL_UNSET:
1576 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1577 RA = ATTR_NONE;
1578 break;
1579 case ATTR_MIXED:
1580 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1581 StartBit = BitIndex;
1582 RA = ATTR_MIXED;
1583 break;
1584 default:
Craig Topperc4965bc2012-02-05 07:21:30 +00001585 llvm_unreachable("Unexpected bitAttr!");
Owen Anderson4e818902011-02-18 21:51:29 +00001586 }
1587 break;
1588 case ATTR_MIXED:
1589 switch (bitAttr) {
1590 case ATTR_FILTERED:
1591 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1592 StartBit = BitIndex;
1593 RA = ATTR_NONE;
1594 break;
1595 case ATTR_ALL_SET:
1596 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1597 StartBit = BitIndex;
1598 RA = ATTR_ALL_SET;
1599 break;
1600 case ATTR_ALL_UNSET:
1601 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1602 RA = ATTR_NONE;
1603 break;
1604 case ATTR_MIXED:
1605 break;
1606 default:
Craig Topperc4965bc2012-02-05 07:21:30 +00001607 llvm_unreachable("Unexpected bitAttr!");
Owen Anderson4e818902011-02-18 21:51:29 +00001608 }
1609 break;
1610 case ATTR_ALL_UNSET:
Craig Topperc4965bc2012-02-05 07:21:30 +00001611 llvm_unreachable("regionAttr state machine has no ATTR_UNSET state");
Owen Anderson4e818902011-02-18 21:51:29 +00001612 case ATTR_FILTERED:
Craig Topperc4965bc2012-02-05 07:21:30 +00001613 llvm_unreachable("regionAttr state machine has no ATTR_FILTERED state");
Owen Anderson4e818902011-02-18 21:51:29 +00001614 }
1615 }
1616
1617 // At the end, if we're still in ALL_SET or MIXED states, report a region
1618 switch (RA) {
1619 case ATTR_NONE:
1620 break;
1621 case ATTR_FILTERED:
1622 break;
1623 case ATTR_ALL_SET:
1624 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1625 break;
1626 case ATTR_ALL_UNSET:
1627 break;
1628 case ATTR_MIXED:
1629 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1630 break;
1631 }
1632
1633 // We have finished with the filter processings. Now it's time to choose
1634 // the best performing filter.
1635 BestIndex = 0;
1636 bool AllUseless = true;
1637 unsigned BestScore = 0;
1638
1639 for (unsigned i = 0, e = Filters.size(); i != e; ++i) {
1640 unsigned Usefulness = Filters[i].usefulness();
1641
1642 if (Usefulness)
1643 AllUseless = false;
1644
1645 if (Usefulness > BestScore) {
1646 BestIndex = i;
1647 BestScore = Usefulness;
1648 }
1649 }
1650
1651 if (!AllUseless)
1652 bestFilter().recurse();
1653
1654 return !AllUseless;
1655} // end of FilterChooser::filterProcessor(bool)
1656
1657// Decides on the best configuration of filter(s) to use in order to decode
1658// the instructions. A conflict of instructions may occur, in which case we
1659// dump the conflict set to the standard error.
1660void FilterChooser::doFilter() {
1661 unsigned Num = Opcodes.size();
1662 assert(Num && "FilterChooser created with no instructions");
1663
1664 // Try regions of consecutive known bit values first.
1665 if (filterProcessor(false))
1666 return;
1667
1668 // Then regions of mixed bits (both known and unitialized bit values allowed).
1669 if (filterProcessor(true))
1670 return;
1671
1672 // Heuristics to cope with conflict set {t2CMPrs, t2SUBSrr, t2SUBSrs} where
1673 // no single instruction for the maximum ATTR_MIXED region Inst{14-4} has a
1674 // well-known encoding pattern. In such case, we backtrack and scan for the
1675 // the very first consecutive ATTR_ALL_SET region and assign a filter to it.
1676 if (Num == 3 && filterProcessor(true, false))
1677 return;
1678
1679 // If we come to here, the instruction decoding has failed.
1680 // Set the BestIndex to -1 to indicate so.
1681 BestIndex = -1;
1682}
1683
Jim Grosbachecaef492012-08-14 19:06:05 +00001684// emitTableEntries - Emit state machine entries to decode our share of
1685// instructions.
1686void FilterChooser::emitTableEntries(DecoderTableInfo &TableInfo) const {
1687 if (Opcodes.size() == 1) {
Owen Anderson4e818902011-02-18 21:51:29 +00001688 // There is only one instruction in the set, which is great!
1689 // Call emitSingletonDecoder() to see whether there are any remaining
1690 // encodings bits.
Jim Grosbachecaef492012-08-14 19:06:05 +00001691 emitSingletonTableEntry(TableInfo, Opcodes[0]);
1692 return;
1693 }
Owen Anderson4e818902011-02-18 21:51:29 +00001694
1695 // Choose the best filter to do the decodings!
1696 if (BestIndex != -1) {
Craig Topper48c112b2012-03-16 05:58:09 +00001697 const Filter &Best = Filters[BestIndex];
Owen Anderson4e818902011-02-18 21:51:29 +00001698 if (Best.getNumFiltered() == 1)
Jim Grosbachecaef492012-08-14 19:06:05 +00001699 emitSingletonTableEntry(TableInfo, Best);
Owen Anderson4e818902011-02-18 21:51:29 +00001700 else
Jim Grosbachecaef492012-08-14 19:06:05 +00001701 Best.emitTableEntry(TableInfo);
1702 return;
Owen Anderson4e818902011-02-18 21:51:29 +00001703 }
1704
Jim Grosbachecaef492012-08-14 19:06:05 +00001705 // We don't know how to decode these instructions! Dump the
1706 // conflict set and bail.
Owen Anderson4e818902011-02-18 21:51:29 +00001707
1708 // Print out useful conflict information for postmortem analysis.
1709 errs() << "Decoding Conflict:\n";
1710
1711 dumpStack(errs(), "\t\t");
1712
Craig Topper82d0d5f2012-03-16 01:19:24 +00001713 for (unsigned i = 0; i < Opcodes.size(); ++i) {
Owen Anderson4e818902011-02-18 21:51:29 +00001714 const std::string &Name = nameWithID(Opcodes[i]);
1715
1716 errs() << '\t' << Name << " ";
1717 dumpBits(errs(),
1718 getBitsField(*AllInstructions[Opcodes[i]]->TheDef, "Inst"));
1719 errs() << '\n';
1720 }
Owen Anderson4e818902011-02-18 21:51:29 +00001721}
1722
Hal Finkel71b2e202013-12-19 16:12:53 +00001723static bool populateInstruction(CodeGenTarget &Target,
1724 const CodeGenInstruction &CGI, unsigned Opc,
Craig Topper82d0d5f2012-03-16 01:19:24 +00001725 std::map<unsigned, std::vector<OperandInfo> > &Operands){
Owen Anderson4e818902011-02-18 21:51:29 +00001726 const Record &Def = *CGI.TheDef;
1727 // If all the bit positions are not specified; do not decode this instruction.
1728 // We are bound to fail! For proper disassembly, the well-known encoding bits
1729 // of the instruction must be fully specified.
Owen Anderson4e818902011-02-18 21:51:29 +00001730
David Greeneaf8ee2c2011-07-29 22:43:06 +00001731 BitsInit &Bits = getBitsField(Def, "Inst");
Jim Grosbachf3fd36e2011-07-06 21:33:38 +00001732 if (Bits.allInComplete()) return false;
1733
Owen Anderson4e818902011-02-18 21:51:29 +00001734 std::vector<OperandInfo> InsnOperands;
1735
1736 // If the instruction has specified a custom decoding hook, use that instead
1737 // of trying to auto-generate the decoder.
1738 std::string InstDecoder = Def.getValueAsString("DecoderMethod");
1739 if (InstDecoder != "") {
Petr Pavlu182b0572015-07-15 08:04:27 +00001740 bool HasCompleteInstDecoder = Def.getValueAsBit("hasCompleteDecoder");
1741 InsnOperands.push_back(OperandInfo(InstDecoder, HasCompleteInstDecoder));
Owen Anderson4e818902011-02-18 21:51:29 +00001742 Operands[Opc] = InsnOperands;
1743 return true;
1744 }
1745
1746 // Generate a description of the operand of the instruction that we know
1747 // how to decode automatically.
1748 // FIXME: We'll need to have a way to manually override this as needed.
1749
1750 // Gather the outputs/inputs of the instruction, so we can find their
1751 // positions in the encoding. This assumes for now that they appear in the
1752 // MCInst in the order that they're listed.
David Greeneaf8ee2c2011-07-29 22:43:06 +00001753 std::vector<std::pair<Init*, std::string> > InOutOperands;
1754 DagInit *Out = Def.getValueAsDag("OutOperandList");
1755 DagInit *In = Def.getValueAsDag("InOperandList");
Owen Anderson4e818902011-02-18 21:51:29 +00001756 for (unsigned i = 0; i < Out->getNumArgs(); ++i)
1757 InOutOperands.push_back(std::make_pair(Out->getArg(i), Out->getArgName(i)));
1758 for (unsigned i = 0; i < In->getNumArgs(); ++i)
1759 InOutOperands.push_back(std::make_pair(In->getArg(i), In->getArgName(i)));
1760
Owen Anderson53562d02011-07-28 23:56:20 +00001761 // Search for tied operands, so that we can correctly instantiate
1762 // operands that are not explicitly represented in the encoding.
Owen Andersoncb32ce22011-07-29 18:28:52 +00001763 std::map<std::string, std::string> TiedNames;
Owen Anderson53562d02011-07-28 23:56:20 +00001764 for (unsigned i = 0; i < CGI.Operands.size(); ++i) {
1765 int tiedTo = CGI.Operands[i].getTiedRegister();
Owen Andersoncb32ce22011-07-29 18:28:52 +00001766 if (tiedTo != -1) {
Hal Finkel71b2e202013-12-19 16:12:53 +00001767 std::pair<unsigned, unsigned> SO =
1768 CGI.Operands.getSubOperandNumber(tiedTo);
1769 TiedNames[InOutOperands[i].second] = InOutOperands[SO.first].second;
1770 TiedNames[InOutOperands[SO.first].second] = InOutOperands[i].second;
1771 }
1772 }
1773
1774 std::map<std::string, std::vector<OperandInfo> > NumberedInsnOperands;
1775 std::set<std::string> NumberedInsnOperandsNoTie;
1776 if (Target.getInstructionSet()->
1777 getValueAsBit("decodePositionallyEncodedOperands")) {
1778 const std::vector<RecordVal> &Vals = Def.getValues();
1779 unsigned NumberedOp = 0;
1780
Hal Finkel5457bd02014-03-13 07:57:54 +00001781 std::set<unsigned> NamedOpIndices;
1782 if (Target.getInstructionSet()->
1783 getValueAsBit("noNamedPositionallyEncodedOperands"))
1784 // Collect the set of operand indices that might correspond to named
1785 // operand, and skip these when assigning operands based on position.
1786 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
1787 unsigned OpIdx;
1788 if (!CGI.Operands.hasOperandNamed(Vals[i].getName(), OpIdx))
1789 continue;
1790
1791 NamedOpIndices.insert(OpIdx);
1792 }
1793
Hal Finkel71b2e202013-12-19 16:12:53 +00001794 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
1795 // Ignore fixed fields in the record, we're looking for values like:
1796 // bits<5> RST = { ?, ?, ?, ?, ? };
1797 if (Vals[i].getPrefix() || Vals[i].getValue()->isComplete())
1798 continue;
1799
1800 // Determine if Vals[i] actually contributes to the Inst encoding.
1801 unsigned bi = 0;
1802 for (; bi < Bits.getNumBits(); ++bi) {
Craig Topper24064772014-04-15 07:20:03 +00001803 VarInit *Var = nullptr;
Hal Finkel71b2e202013-12-19 16:12:53 +00001804 VarBitInit *BI = dyn_cast<VarBitInit>(Bits.getBit(bi));
1805 if (BI)
1806 Var = dyn_cast<VarInit>(BI->getBitVar());
1807 else
1808 Var = dyn_cast<VarInit>(Bits.getBit(bi));
1809
1810 if (Var && Var->getName() == Vals[i].getName())
1811 break;
1812 }
1813
1814 if (bi == Bits.getNumBits())
1815 continue;
1816
1817 // Skip variables that correspond to explicitly-named operands.
1818 unsigned OpIdx;
1819 if (CGI.Operands.hasOperandNamed(Vals[i].getName(), OpIdx))
1820 continue;
1821
1822 // Get the bit range for this operand:
1823 unsigned bitStart = bi++, bitWidth = 1;
1824 for (; bi < Bits.getNumBits(); ++bi) {
Craig Topper24064772014-04-15 07:20:03 +00001825 VarInit *Var = nullptr;
Hal Finkel71b2e202013-12-19 16:12:53 +00001826 VarBitInit *BI = dyn_cast<VarBitInit>(Bits.getBit(bi));
1827 if (BI)
1828 Var = dyn_cast<VarInit>(BI->getBitVar());
1829 else
1830 Var = dyn_cast<VarInit>(Bits.getBit(bi));
1831
1832 if (!Var)
1833 break;
1834
1835 if (Var->getName() != Vals[i].getName())
1836 break;
1837
1838 ++bitWidth;
1839 }
1840
1841 unsigned NumberOps = CGI.Operands.size();
1842 while (NumberedOp < NumberOps &&
Hal Finkel5457bd02014-03-13 07:57:54 +00001843 (CGI.Operands.isFlatOperandNotEmitted(NumberedOp) ||
Alexander Kornienko8c0809c2015-01-15 11:41:30 +00001844 (!NamedOpIndices.empty() && NamedOpIndices.count(
Hal Finkel5457bd02014-03-13 07:57:54 +00001845 CGI.Operands.getSubOperandNumber(NumberedOp).first))))
Hal Finkel71b2e202013-12-19 16:12:53 +00001846 ++NumberedOp;
1847
1848 OpIdx = NumberedOp++;
1849
1850 // OpIdx now holds the ordered operand number of Vals[i].
1851 std::pair<unsigned, unsigned> SO =
1852 CGI.Operands.getSubOperandNumber(OpIdx);
1853 const std::string &Name = CGI.Operands[SO.first].Name;
1854
1855 DEBUG(dbgs() << "Numbered operand mapping for " << Def.getName() << ": " <<
1856 Name << "(" << SO.first << ", " << SO.second << ") => " <<
1857 Vals[i].getName() << "\n");
1858
1859 std::string Decoder = "";
1860 Record *TypeRecord = CGI.Operands[SO.first].Rec;
1861
1862 RecordVal *DecoderString = TypeRecord->getValue("DecoderMethod");
1863 StringInit *String = DecoderString ?
Craig Topper24064772014-04-15 07:20:03 +00001864 dyn_cast<StringInit>(DecoderString->getValue()) : nullptr;
Hal Finkel71b2e202013-12-19 16:12:53 +00001865 if (String && String->getValue() != "")
1866 Decoder = String->getValue();
1867
1868 if (Decoder == "" &&
1869 CGI.Operands[SO.first].MIOperandInfo &&
1870 CGI.Operands[SO.first].MIOperandInfo->getNumArgs()) {
1871 Init *Arg = CGI.Operands[SO.first].MIOperandInfo->
1872 getArg(SO.second);
1873 if (TypedInit *TI = cast<TypedInit>(Arg)) {
1874 RecordRecTy *Type = cast<RecordRecTy>(TI->getType());
1875 TypeRecord = Type->getRecord();
1876 }
1877 }
1878
1879 bool isReg = false;
1880 if (TypeRecord->isSubClassOf("RegisterOperand"))
1881 TypeRecord = TypeRecord->getValueAsDef("RegClass");
1882 if (TypeRecord->isSubClassOf("RegisterClass")) {
1883 Decoder = "Decode" + TypeRecord->getName() + "RegisterClass";
1884 isReg = true;
1885 } else if (TypeRecord->isSubClassOf("PointerLikeRegClass")) {
1886 Decoder = "DecodePointerLikeRegClass" +
1887 utostr(TypeRecord->getValueAsInt("RegClassKind"));
1888 isReg = true;
1889 }
1890
1891 DecoderString = TypeRecord->getValue("DecoderMethod");
1892 String = DecoderString ?
Craig Topper24064772014-04-15 07:20:03 +00001893 dyn_cast<StringInit>(DecoderString->getValue()) : nullptr;
Hal Finkel71b2e202013-12-19 16:12:53 +00001894 if (!isReg && String && String->getValue() != "")
1895 Decoder = String->getValue();
1896
Petr Pavlu182b0572015-07-15 08:04:27 +00001897 RecordVal *HasCompleteDecoderVal =
1898 TypeRecord->getValue("hasCompleteDecoder");
1899 BitInit *HasCompleteDecoderBit = HasCompleteDecoderVal ?
1900 dyn_cast<BitInit>(HasCompleteDecoderVal->getValue()) : nullptr;
1901 bool HasCompleteDecoder = HasCompleteDecoderBit ?
1902 HasCompleteDecoderBit->getValue() : true;
1903
1904 OperandInfo OpInfo(Decoder, HasCompleteDecoder);
Hal Finkel71b2e202013-12-19 16:12:53 +00001905 OpInfo.addField(bitStart, bitWidth, 0);
1906
1907 NumberedInsnOperands[Name].push_back(OpInfo);
1908
1909 // FIXME: For complex operands with custom decoders we can't handle tied
1910 // sub-operands automatically. Skip those here and assume that this is
1911 // fixed up elsewhere.
1912 if (CGI.Operands[SO.first].MIOperandInfo &&
1913 CGI.Operands[SO.first].MIOperandInfo->getNumArgs() > 1 &&
1914 String && String->getValue() != "")
1915 NumberedInsnOperandsNoTie.insert(Name);
Owen Andersoncb32ce22011-07-29 18:28:52 +00001916 }
Owen Anderson53562d02011-07-28 23:56:20 +00001917 }
1918
Owen Anderson4e818902011-02-18 21:51:29 +00001919 // For each operand, see if we can figure out where it is encoded.
Craig Topper1f7604d2014-12-13 05:12:19 +00001920 for (const auto &Op : InOutOperands) {
1921 if (!NumberedInsnOperands[Op.second].empty()) {
Hal Finkel71b2e202013-12-19 16:12:53 +00001922 InsnOperands.insert(InsnOperands.end(),
Craig Topper1f7604d2014-12-13 05:12:19 +00001923 NumberedInsnOperands[Op.second].begin(),
1924 NumberedInsnOperands[Op.second].end());
Hal Finkel71b2e202013-12-19 16:12:53 +00001925 continue;
Craig Topper1f7604d2014-12-13 05:12:19 +00001926 }
1927 if (!NumberedInsnOperands[TiedNames[Op.second]].empty()) {
1928 if (!NumberedInsnOperandsNoTie.count(TiedNames[Op.second])) {
Hal Finkel71b2e202013-12-19 16:12:53 +00001929 // Figure out to which (sub)operand we're tied.
Craig Topper1f7604d2014-12-13 05:12:19 +00001930 unsigned i = CGI.Operands.getOperandNamed(TiedNames[Op.second]);
Hal Finkel71b2e202013-12-19 16:12:53 +00001931 int tiedTo = CGI.Operands[i].getTiedRegister();
1932 if (tiedTo == -1) {
Craig Topper1f7604d2014-12-13 05:12:19 +00001933 i = CGI.Operands.getOperandNamed(Op.second);
Hal Finkel71b2e202013-12-19 16:12:53 +00001934 tiedTo = CGI.Operands[i].getTiedRegister();
1935 }
1936
1937 if (tiedTo != -1) {
1938 std::pair<unsigned, unsigned> SO =
1939 CGI.Operands.getSubOperandNumber(tiedTo);
1940
Craig Topper1f7604d2014-12-13 05:12:19 +00001941 InsnOperands.push_back(NumberedInsnOperands[TiedNames[Op.second]]
Hal Finkel71b2e202013-12-19 16:12:53 +00001942 [SO.second]);
1943 }
1944 }
1945 continue;
1946 }
1947
Owen Anderson4e818902011-02-18 21:51:29 +00001948 std::string Decoder = "";
1949
Owen Andersone3591652011-07-28 21:54:31 +00001950 // At this point, we can locate the field, but we need to know how to
1951 // interpret it. As a first step, require the target to provide callbacks
1952 // for decoding register classes.
1953 // FIXME: This need to be extended to handle instructions with custom
1954 // decoder methods, and operands with (simple) MIOperandInfo's.
Craig Topper1f7604d2014-12-13 05:12:19 +00001955 TypedInit *TI = cast<TypedInit>(Op.first);
Sean Silva88eb8dd2012-10-10 20:24:47 +00001956 RecordRecTy *Type = cast<RecordRecTy>(TI->getType());
Owen Andersone3591652011-07-28 21:54:31 +00001957 Record *TypeRecord = Type->getRecord();
1958 bool isReg = false;
1959 if (TypeRecord->isSubClassOf("RegisterOperand"))
1960 TypeRecord = TypeRecord->getValueAsDef("RegClass");
1961 if (TypeRecord->isSubClassOf("RegisterClass")) {
1962 Decoder = "Decode" + TypeRecord->getName() + "RegisterClass";
1963 isReg = true;
Hal Finkel9d95e8d2013-12-19 14:58:22 +00001964 } else if (TypeRecord->isSubClassOf("PointerLikeRegClass")) {
1965 Decoder = "DecodePointerLikeRegClass" +
1966 utostr(TypeRecord->getValueAsInt("RegClassKind"));
1967 isReg = true;
Owen Andersone3591652011-07-28 21:54:31 +00001968 }
1969
1970 RecordVal *DecoderString = TypeRecord->getValue("DecoderMethod");
David Greeneaf8ee2c2011-07-29 22:43:06 +00001971 StringInit *String = DecoderString ?
Craig Topper24064772014-04-15 07:20:03 +00001972 dyn_cast<StringInit>(DecoderString->getValue()) : nullptr;
Owen Andersone3591652011-07-28 21:54:31 +00001973 if (!isReg && String && String->getValue() != "")
1974 Decoder = String->getValue();
1975
Petr Pavlu182b0572015-07-15 08:04:27 +00001976 RecordVal *HasCompleteDecoderVal =
1977 TypeRecord->getValue("hasCompleteDecoder");
1978 BitInit *HasCompleteDecoderBit = HasCompleteDecoderVal ?
1979 dyn_cast<BitInit>(HasCompleteDecoderVal->getValue()) : nullptr;
1980 bool HasCompleteDecoder = HasCompleteDecoderBit ?
1981 HasCompleteDecoderBit->getValue() : true;
1982
1983 OperandInfo OpInfo(Decoder, HasCompleteDecoder);
Owen Andersone3591652011-07-28 21:54:31 +00001984 unsigned Base = ~0U;
1985 unsigned Width = 0;
1986 unsigned Offset = 0;
1987
Owen Anderson4e818902011-02-18 21:51:29 +00001988 for (unsigned bi = 0; bi < Bits.getNumBits(); ++bi) {
Craig Topper24064772014-04-15 07:20:03 +00001989 VarInit *Var = nullptr;
Sean Silvafb509ed2012-10-10 20:24:43 +00001990 VarBitInit *BI = dyn_cast<VarBitInit>(Bits.getBit(bi));
Owen Anderson3022d672011-08-01 22:45:43 +00001991 if (BI)
Sean Silvafb509ed2012-10-10 20:24:43 +00001992 Var = dyn_cast<VarInit>(BI->getBitVar());
Owen Anderson3022d672011-08-01 22:45:43 +00001993 else
Sean Silvafb509ed2012-10-10 20:24:43 +00001994 Var = dyn_cast<VarInit>(Bits.getBit(bi));
Owen Anderson3022d672011-08-01 22:45:43 +00001995
1996 if (!Var) {
Owen Andersone3591652011-07-28 21:54:31 +00001997 if (Base != ~0U) {
1998 OpInfo.addField(Base, Width, Offset);
1999 Base = ~0U;
2000 Width = 0;
2001 Offset = 0;
2002 }
2003 continue;
2004 }
Owen Anderson4e818902011-02-18 21:51:29 +00002005
Craig Topper1f7604d2014-12-13 05:12:19 +00002006 if (Var->getName() != Op.second &&
2007 Var->getName() != TiedNames[Op.second]) {
Owen Andersone3591652011-07-28 21:54:31 +00002008 if (Base != ~0U) {
2009 OpInfo.addField(Base, Width, Offset);
2010 Base = ~0U;
2011 Width = 0;
2012 Offset = 0;
2013 }
2014 continue;
Owen Anderson4e818902011-02-18 21:51:29 +00002015 }
2016
Owen Andersone3591652011-07-28 21:54:31 +00002017 if (Base == ~0U) {
2018 Base = bi;
2019 Width = 1;
Owen Anderson3022d672011-08-01 22:45:43 +00002020 Offset = BI ? BI->getBitNum() : 0;
2021 } else if (BI && BI->getBitNum() != Offset + Width) {
Owen Andersone08f5b52011-07-29 23:01:18 +00002022 OpInfo.addField(Base, Width, Offset);
2023 Base = bi;
2024 Width = 1;
2025 Offset = BI->getBitNum();
Owen Andersone3591652011-07-28 21:54:31 +00002026 } else {
2027 ++Width;
Owen Anderson4e818902011-02-18 21:51:29 +00002028 }
Owen Anderson4e818902011-02-18 21:51:29 +00002029 }
2030
Owen Andersone3591652011-07-28 21:54:31 +00002031 if (Base != ~0U)
2032 OpInfo.addField(Base, Width, Offset);
2033
2034 if (OpInfo.numFields() > 0)
2035 InsnOperands.push_back(OpInfo);
Owen Anderson4e818902011-02-18 21:51:29 +00002036 }
2037
2038 Operands[Opc] = InsnOperands;
2039
2040
2041#if 0
2042 DEBUG({
2043 // Dumps the instruction encoding bits.
2044 dumpBits(errs(), Bits);
2045
2046 errs() << '\n';
2047
2048 // Dumps the list of operand info.
2049 for (unsigned i = 0, e = CGI.Operands.size(); i != e; ++i) {
2050 const CGIOperandList::OperandInfo &Info = CGI.Operands[i];
2051 const std::string &OperandName = Info.Name;
2052 const Record &OperandDef = *Info.Rec;
2053
2054 errs() << "\t" << OperandName << " (" << OperandDef.getName() << ")\n";
2055 }
2056 });
2057#endif
2058
2059 return true;
2060}
2061
Jim Grosbachecaef492012-08-14 19:06:05 +00002062// emitFieldFromInstruction - Emit the templated helper function
2063// fieldFromInstruction().
2064static void emitFieldFromInstruction(formatted_raw_ostream &OS) {
2065 OS << "// Helper function for extracting fields from encoded instructions.\n"
2066 << "template<typename InsnType>\n"
2067 << "static InsnType fieldFromInstruction(InsnType insn, unsigned startBit,\n"
2068 << " unsigned numBits) {\n"
2069 << " assert(startBit + numBits <= (sizeof(InsnType)*8) &&\n"
2070 << " \"Instruction field out of bounds!\");\n"
2071 << " InsnType fieldMask;\n"
2072 << " if (numBits == sizeof(InsnType)*8)\n"
2073 << " fieldMask = (InsnType)(-1LL);\n"
2074 << " else\n"
NAKAMURA Takumibf99a422012-12-26 06:43:14 +00002075 << " fieldMask = (((InsnType)1 << numBits) - 1) << startBit;\n"
Jim Grosbachecaef492012-08-14 19:06:05 +00002076 << " return (insn & fieldMask) >> startBit;\n"
2077 << "}\n\n";
2078}
Owen Anderson4e818902011-02-18 21:51:29 +00002079
Jim Grosbachecaef492012-08-14 19:06:05 +00002080// emitDecodeInstruction - Emit the templated helper function
2081// decodeInstruction().
2082static void emitDecodeInstruction(formatted_raw_ostream &OS) {
2083 OS << "template<typename InsnType>\n"
2084 << "static DecodeStatus decodeInstruction(const uint8_t DecodeTable[], MCInst &MI,\n"
2085 << " InsnType insn, uint64_t Address,\n"
2086 << " const void *DisAsm,\n"
2087 << " const MCSubtargetInfo &STI) {\n"
Michael Kupersteindb0712f2015-05-26 10:47:10 +00002088 << " const FeatureBitset& Bits = STI.getFeatureBits();\n"
Jim Grosbachecaef492012-08-14 19:06:05 +00002089 << "\n"
2090 << " const uint8_t *Ptr = DecodeTable;\n"
Jim Grosbach4c363492012-09-17 18:00:53 +00002091 << " uint32_t CurFieldValue = 0;\n"
Jim Grosbachecaef492012-08-14 19:06:05 +00002092 << " DecodeStatus S = MCDisassembler::Success;\n"
2093 << " for (;;) {\n"
2094 << " ptrdiff_t Loc = Ptr - DecodeTable;\n"
2095 << " switch (*Ptr) {\n"
2096 << " default:\n"
2097 << " errs() << Loc << \": Unexpected decode table opcode!\\n\";\n"
2098 << " return MCDisassembler::Fail;\n"
2099 << " case MCD::OPC_ExtractField: {\n"
2100 << " unsigned Start = *++Ptr;\n"
2101 << " unsigned Len = *++Ptr;\n"
2102 << " ++Ptr;\n"
2103 << " CurFieldValue = fieldFromInstruction(insn, Start, Len);\n"
2104 << " DEBUG(dbgs() << Loc << \": OPC_ExtractField(\" << Start << \", \"\n"
2105 << " << Len << \"): \" << CurFieldValue << \"\\n\");\n"
2106 << " break;\n"
2107 << " }\n"
2108 << " case MCD::OPC_FilterValue: {\n"
2109 << " // Decode the field value.\n"
2110 << " unsigned Len;\n"
2111 << " InsnType Val = decodeULEB128(++Ptr, &Len);\n"
2112 << " Ptr += Len;\n"
2113 << " // NumToSkip is a plain 16-bit integer.\n"
2114 << " unsigned NumToSkip = *Ptr++;\n"
2115 << " NumToSkip |= (*Ptr++) << 8;\n"
2116 << "\n"
2117 << " // Perform the filter operation.\n"
2118 << " if (Val != CurFieldValue)\n"
2119 << " Ptr += NumToSkip;\n"
2120 << " DEBUG(dbgs() << Loc << \": OPC_FilterValue(\" << Val << \", \" << NumToSkip\n"
2121 << " << \"): \" << ((Val != CurFieldValue) ? \"FAIL:\" : \"PASS:\")\n"
2122 << " << \" continuing at \" << (Ptr - DecodeTable) << \"\\n\");\n"
2123 << "\n"
2124 << " break;\n"
2125 << " }\n"
2126 << " case MCD::OPC_CheckField: {\n"
2127 << " unsigned Start = *++Ptr;\n"
2128 << " unsigned Len = *++Ptr;\n"
2129 << " InsnType FieldValue = fieldFromInstruction(insn, Start, Len);\n"
2130 << " // Decode the field value.\n"
2131 << " uint32_t ExpectedValue = decodeULEB128(++Ptr, &Len);\n"
2132 << " Ptr += Len;\n"
2133 << " // NumToSkip is a plain 16-bit integer.\n"
2134 << " unsigned NumToSkip = *Ptr++;\n"
2135 << " NumToSkip |= (*Ptr++) << 8;\n"
2136 << "\n"
2137 << " // If the actual and expected values don't match, skip.\n"
2138 << " if (ExpectedValue != FieldValue)\n"
2139 << " Ptr += NumToSkip;\n"
2140 << " DEBUG(dbgs() << Loc << \": OPC_CheckField(\" << Start << \", \"\n"
2141 << " << Len << \", \" << ExpectedValue << \", \" << NumToSkip\n"
2142 << " << \"): FieldValue = \" << FieldValue << \", ExpectedValue = \"\n"
2143 << " << ExpectedValue << \": \"\n"
2144 << " << ((ExpectedValue == FieldValue) ? \"PASS\\n\" : \"FAIL\\n\"));\n"
2145 << " break;\n"
2146 << " }\n"
2147 << " case MCD::OPC_CheckPredicate: {\n"
2148 << " unsigned Len;\n"
2149 << " // Decode the Predicate Index value.\n"
2150 << " unsigned PIdx = decodeULEB128(++Ptr, &Len);\n"
2151 << " Ptr += Len;\n"
2152 << " // NumToSkip is a plain 16-bit integer.\n"
2153 << " unsigned NumToSkip = *Ptr++;\n"
2154 << " NumToSkip |= (*Ptr++) << 8;\n"
2155 << " // Check the predicate.\n"
2156 << " bool Pred;\n"
2157 << " if (!(Pred = checkDecoderPredicate(PIdx, Bits)))\n"
2158 << " Ptr += NumToSkip;\n"
2159 << " (void)Pred;\n"
2160 << " DEBUG(dbgs() << Loc << \": OPC_CheckPredicate(\" << PIdx << \"): \"\n"
2161 << " << (Pred ? \"PASS\\n\" : \"FAIL\\n\"));\n"
2162 << "\n"
2163 << " break;\n"
2164 << " }\n"
2165 << " case MCD::OPC_Decode: {\n"
2166 << " unsigned Len;\n"
2167 << " // Decode the Opcode value.\n"
2168 << " unsigned Opc = decodeULEB128(++Ptr, &Len);\n"
2169 << " Ptr += Len;\n"
2170 << " unsigned DecodeIdx = decodeULEB128(Ptr, &Len);\n"
2171 << " Ptr += Len;\n"
Jim Grosbachecaef492012-08-14 19:06:05 +00002172 << "\n"
Cameron Esfahanif97999d2015-08-11 01:15:07 +00002173 << " MI.clear();\n"
Jim Grosbachecaef492012-08-14 19:06:05 +00002174 << " MI.setOpcode(Opc);\n"
Petr Pavlu182b0572015-07-15 08:04:27 +00002175 << " bool DecodeComplete;\n"
2176 << " S = decodeToMCInst(S, DecodeIdx, insn, MI, Address, DisAsm, DecodeComplete);\n"
2177 << " assert(DecodeComplete);\n"
2178 << "\n"
2179 << " DEBUG(dbgs() << Loc << \": OPC_Decode: opcode \" << Opc\n"
2180 << " << \", using decoder \" << DecodeIdx << \": \"\n"
2181 << " << (S != MCDisassembler::Fail ? \"PASS\" : \"FAIL\") << \"\\n\");\n"
2182 << " return S;\n"
2183 << " }\n"
2184 << " case MCD::OPC_TryDecode: {\n"
2185 << " unsigned Len;\n"
2186 << " // Decode the Opcode value.\n"
2187 << " unsigned Opc = decodeULEB128(++Ptr, &Len);\n"
2188 << " Ptr += Len;\n"
2189 << " unsigned DecodeIdx = decodeULEB128(Ptr, &Len);\n"
2190 << " Ptr += Len;\n"
2191 << " // NumToSkip is a plain 16-bit integer.\n"
2192 << " unsigned NumToSkip = *Ptr++;\n"
2193 << " NumToSkip |= (*Ptr++) << 8;\n"
2194 << "\n"
2195 << " // Perform the decode operation.\n"
2196 << " MCInst TmpMI;\n"
2197 << " TmpMI.setOpcode(Opc);\n"
2198 << " bool DecodeComplete;\n"
2199 << " S = decodeToMCInst(S, DecodeIdx, insn, TmpMI, Address, DisAsm, DecodeComplete);\n"
2200 << " DEBUG(dbgs() << Loc << \": OPC_TryDecode: opcode \" << Opc\n"
2201 << " << \", using decoder \" << DecodeIdx << \": \");\n"
2202 << "\n"
2203 << " if (DecodeComplete) {\n"
2204 << " // Decoding complete.\n"
2205 << " DEBUG(dbgs() << (S != MCDisassembler::Fail ? \"PASS\" : \"FAIL\") << \"\\n\");\n"
2206 << " MI = TmpMI;\n"
2207 << " return S;\n"
2208 << " } else {\n"
2209 << " assert(S == MCDisassembler::Fail);\n"
2210 << " // If the decoding was incomplete, skip.\n"
2211 << " Ptr += NumToSkip;\n"
2212 << " DEBUG(dbgs() << \"FAIL: continuing at \" << (Ptr - DecodeTable) << \"\\n\");\n"
2213 << " // Reset decode status. This also drops a SoftFail status that could be\n"
2214 << " // set before the decode attempt.\n"
2215 << " S = MCDisassembler::Success;\n"
2216 << " }\n"
2217 << " break;\n"
Jim Grosbachecaef492012-08-14 19:06:05 +00002218 << " }\n"
2219 << " case MCD::OPC_SoftFail: {\n"
2220 << " // Decode the mask values.\n"
2221 << " unsigned Len;\n"
2222 << " InsnType PositiveMask = decodeULEB128(++Ptr, &Len);\n"
2223 << " Ptr += Len;\n"
2224 << " InsnType NegativeMask = decodeULEB128(Ptr, &Len);\n"
2225 << " Ptr += Len;\n"
2226 << " bool Fail = (insn & PositiveMask) || (~insn & NegativeMask);\n"
2227 << " if (Fail)\n"
2228 << " S = MCDisassembler::SoftFail;\n"
2229 << " DEBUG(dbgs() << Loc << \": OPC_SoftFail: \" << (Fail ? \"FAIL\\n\":\"PASS\\n\"));\n"
2230 << " break;\n"
2231 << " }\n"
2232 << " case MCD::OPC_Fail: {\n"
2233 << " DEBUG(dbgs() << Loc << \": OPC_Fail\\n\");\n"
2234 << " return MCDisassembler::Fail;\n"
2235 << " }\n"
2236 << " }\n"
2237 << " }\n"
2238 << " llvm_unreachable(\"bogosity detected in disassembler state machine!\");\n"
2239 << "}\n\n";
Owen Anderson4e818902011-02-18 21:51:29 +00002240}
2241
2242// Emits disassembler code for instruction decoding.
Craig Topper82d0d5f2012-03-16 01:19:24 +00002243void FixedLenDecoderEmitter::run(raw_ostream &o) {
Jim Grosbachecaef492012-08-14 19:06:05 +00002244 formatted_raw_ostream OS(o);
2245 OS << "#include \"llvm/MC/MCInst.h\"\n";
2246 OS << "#include \"llvm/Support/Debug.h\"\n";
2247 OS << "#include \"llvm/Support/DataTypes.h\"\n";
2248 OS << "#include \"llvm/Support/LEB128.h\"\n";
2249 OS << "#include \"llvm/Support/raw_ostream.h\"\n";
2250 OS << "#include <assert.h>\n";
2251 OS << '\n';
2252 OS << "namespace llvm {\n\n";
2253
2254 emitFieldFromInstruction(OS);
Owen Anderson4e818902011-02-18 21:51:29 +00002255
Hal Finkel81e6fcc2013-12-17 22:37:50 +00002256 Target.reverseBitsForLittleEndianEncoding();
2257
Owen Andersonc78e03c2011-07-19 21:06:00 +00002258 // Parameterize the decoders based on namespace and instruction width.
Craig Topperf9265322016-01-17 20:38:14 +00002259 NumberedInstructions = Target.getInstructionsByEnumValue();
Owen Andersonc78e03c2011-07-19 21:06:00 +00002260 std::map<std::pair<std::string, unsigned>,
2261 std::vector<unsigned> > OpcMap;
2262 std::map<unsigned, std::vector<OperandInfo> > Operands;
2263
Craig Topperf9265322016-01-17 20:38:14 +00002264 for (unsigned i = 0; i < NumberedInstructions.size(); ++i) {
2265 const CodeGenInstruction *Inst = NumberedInstructions[i];
Craig Topper48c112b2012-03-16 05:58:09 +00002266 const Record *Def = Inst->TheDef;
Owen Andersonc78e03c2011-07-19 21:06:00 +00002267 unsigned Size = Def->getValueAsInt("Size");
2268 if (Def->getValueAsString("Namespace") == "TargetOpcode" ||
2269 Def->getValueAsBit("isPseudo") ||
2270 Def->getValueAsBit("isAsmParserOnly") ||
2271 Def->getValueAsBit("isCodeGenOnly"))
2272 continue;
2273
2274 std::string DecoderNamespace = Def->getValueAsString("DecoderNamespace");
2275
2276 if (Size) {
Hal Finkel71b2e202013-12-19 16:12:53 +00002277 if (populateInstruction(Target, *Inst, i, Operands)) {
Owen Andersonc78e03c2011-07-19 21:06:00 +00002278 OpcMap[std::make_pair(DecoderNamespace, Size)].push_back(i);
2279 }
2280 }
2281 }
2282
Jim Grosbachecaef492012-08-14 19:06:05 +00002283 DecoderTableInfo TableInfo;
Craig Topper1f7604d2014-12-13 05:12:19 +00002284 for (const auto &Opc : OpcMap) {
Owen Andersonc78e03c2011-07-19 21:06:00 +00002285 // Emit the decoder for this namespace+width combination.
Craig Topperf9265322016-01-17 20:38:14 +00002286 FilterChooser FC(NumberedInstructions, Opc.second, Operands,
Craig Topper1f7604d2014-12-13 05:12:19 +00002287 8*Opc.first.second, this);
Jim Grosbachecaef492012-08-14 19:06:05 +00002288
2289 // The decode table is cleared for each top level decoder function. The
2290 // predicates and decoders themselves, however, are shared across all
2291 // decoders to give more opportunities for uniqueing.
2292 TableInfo.Table.clear();
2293 TableInfo.FixupStack.clear();
2294 TableInfo.Table.reserve(16384);
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00002295 TableInfo.FixupStack.emplace_back();
Jim Grosbachecaef492012-08-14 19:06:05 +00002296 FC.emitTableEntries(TableInfo);
2297 // Any NumToSkip fixups in the top level scope can resolve to the
2298 // OPC_Fail at the end of the table.
2299 assert(TableInfo.FixupStack.size() == 1 && "fixup stack phasing error!");
2300 // Resolve any NumToSkip fixups in the current scope.
2301 resolveTableFixups(TableInfo.Table, TableInfo.FixupStack.back(),
2302 TableInfo.Table.size());
2303 TableInfo.FixupStack.clear();
2304
2305 TableInfo.Table.push_back(MCD::OPC_Fail);
2306
2307 // Print the table to the output stream.
Craig Topper1f7604d2014-12-13 05:12:19 +00002308 emitTable(OS, TableInfo.Table, 0, FC.getBitWidth(), Opc.first.first);
Jim Grosbachecaef492012-08-14 19:06:05 +00002309 OS.flush();
Owen Andersonc78e03c2011-07-19 21:06:00 +00002310 }
Owen Anderson4e818902011-02-18 21:51:29 +00002311
Jim Grosbachecaef492012-08-14 19:06:05 +00002312 // Emit the predicate function.
2313 emitPredicateFunction(OS, TableInfo.Predicates, 0);
2314
2315 // Emit the decoder function.
2316 emitDecoderFunction(OS, TableInfo.Decoders, 0);
2317
2318 // Emit the main entry point for the decoder, decodeInstruction().
2319 emitDecodeInstruction(OS);
2320
2321 OS << "\n} // End llvm namespace\n";
Owen Anderson4e818902011-02-18 21:51:29 +00002322}
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +00002323
2324namespace llvm {
2325
2326void EmitFixedLenDecoder(RecordKeeper &RK, raw_ostream &OS,
Benjamin Kramerc321e532016-06-08 19:09:22 +00002327 const std::string &PredicateNamespace,
2328 const std::string &GPrefix,
2329 const std::string &GPostfix, const std::string &ROK,
2330 const std::string &RFail, const std::string &L) {
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +00002331 FixedLenDecoderEmitter(RK, PredicateNamespace, GPrefix, GPostfix,
2332 ROK, RFail, L).run(OS);
2333}
2334
2335} // End llvm namespace