blob: a20b469cd84280479311728de895e8c482884480 [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
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +000015#include "CodeGenInstruction.h"
Owen Anderson4e818902011-02-18 21:51:29 +000016#include "CodeGenTarget.h"
James Molloyd9ba4fd2012-02-09 10:56:31 +000017#include "llvm/ADT/APInt.h"
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +000018#include "llvm/ADT/ArrayRef.h"
Justin Lebar5e83dfe2016-10-21 21:45:01 +000019#include "llvm/ADT/CachedHashString.h"
Jim Grosbachecaef492012-08-14 19:06:05 +000020#include "llvm/ADT/SmallString.h"
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +000021#include "llvm/ADT/SetVector.h"
22#include "llvm/ADT/STLExtras.h"
Owen Anderson4e818902011-02-18 21:51:29 +000023#include "llvm/ADT/StringExtras.h"
Jim Grosbachecaef492012-08-14 19:06:05 +000024#include "llvm/ADT/StringRef.h"
Jim Grosbachecaef492012-08-14 19:06:05 +000025#include "llvm/MC/MCFixedLenDisassembler.h"
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +000026#include "llvm/Support/Casting.h"
Owen Anderson4e818902011-02-18 21:51:29 +000027#include "llvm/Support/Debug.h"
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +000028#include "llvm/Support/ErrorHandling.h"
Jim Grosbachecaef492012-08-14 19:06:05 +000029#include "llvm/Support/FormattedStream.h"
30#include "llvm/Support/LEB128.h"
Owen Anderson4e818902011-02-18 21:51:29 +000031#include "llvm/Support/raw_ostream.h"
Chandler Carruth91d19d82012-12-04 10:37:14 +000032#include "llvm/TableGen/Error.h"
33#include "llvm/TableGen/Record.h"
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +000034#include <algorithm>
35#include <cassert>
36#include <cstddef>
37#include <cstdint>
Owen Anderson4e818902011-02-18 21:51:29 +000038#include <map>
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +000039#include <memory>
40#include <set>
Owen Anderson4e818902011-02-18 21:51:29 +000041#include <string>
Benjamin Kramer82de7d32016-05-27 14:27:24 +000042#include <utility>
Chandler Carruth91d19d82012-12-04 10:37:14 +000043#include <vector>
Owen Anderson4e818902011-02-18 21:51:29 +000044
45using namespace llvm;
46
Chandler Carruth97acce22014-04-22 03:06:00 +000047#define DEBUG_TYPE "decoder-emitter"
48
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +000049namespace {
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +000050
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +000051struct EncodingField {
52 unsigned Base, Width, Offset;
53 EncodingField(unsigned B, unsigned W, unsigned O)
54 : Base(B), Width(W), Offset(O) { }
55};
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +000056
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +000057struct OperandInfo {
58 std::vector<EncodingField> Fields;
59 std::string Decoder;
Petr Pavlu182b0572015-07-15 08:04:27 +000060 bool HasCompleteDecoder;
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +000061
Petr Pavlu182b0572015-07-15 08:04:27 +000062 OperandInfo(std::string D, bool HCD)
Benjamin Kramer82de7d32016-05-27 14:27:24 +000063 : Decoder(std::move(D)), HasCompleteDecoder(HCD) {}
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +000064
65 void addField(unsigned Base, unsigned Width, unsigned Offset) {
66 Fields.push_back(EncodingField(Base, Width, Offset));
67 }
68
69 unsigned numFields() const { return Fields.size(); }
70
71 typedef std::vector<EncodingField>::const_iterator const_iterator;
72
73 const_iterator begin() const { return Fields.begin(); }
74 const_iterator end() const { return Fields.end(); }
75};
Jim Grosbachecaef492012-08-14 19:06:05 +000076
77typedef std::vector<uint8_t> DecoderTable;
78typedef uint32_t DecoderFixup;
79typedef std::vector<DecoderFixup> FixupList;
80typedef std::vector<FixupList> FixupScopeList;
Justin Lebar5e83dfe2016-10-21 21:45:01 +000081typedef SmallSetVector<CachedHashString, 16> PredicateSet;
82typedef SmallSetVector<CachedHashString, 16> DecoderSet;
Jim Grosbachecaef492012-08-14 19:06:05 +000083struct DecoderTableInfo {
84 DecoderTable Table;
85 FixupScopeList FixupStack;
86 PredicateSet Predicates;
87 DecoderSet Decoders;
88};
89
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +000090class FixedLenDecoderEmitter {
Craig Topperf9265322016-01-17 20:38:14 +000091 ArrayRef<const CodeGenInstruction *> NumberedInstructions;
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +000092
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +000093public:
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +000094 // Defaults preserved here for documentation, even though they aren't
95 // strictly necessary given the way that this is currently being called.
Benjamin Kramer82de7d32016-05-27 14:27:24 +000096 FixedLenDecoderEmitter(RecordKeeper &R, std::string PredicateNamespace,
97 std::string GPrefix = "if (",
Petr Pavlu182b0572015-07-15 08:04:27 +000098 std::string GPostfix = " == MCDisassembler::Fail)",
Benjamin Kramer82de7d32016-05-27 14:27:24 +000099 std::string ROK = "MCDisassembler::Success",
100 std::string RFail = "MCDisassembler::Fail",
101 std::string L = "")
102 : Target(R), PredicateNamespace(std::move(PredicateNamespace)),
103 GuardPrefix(std::move(GPrefix)), GuardPostfix(std::move(GPostfix)),
104 ReturnOK(std::move(ROK)), ReturnFail(std::move(RFail)),
105 Locals(std::move(L)) {}
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +0000106
Jim Grosbachecaef492012-08-14 19:06:05 +0000107 // Emit the decoder state machine table.
108 void emitTable(formatted_raw_ostream &o, DecoderTable &Table,
109 unsigned Indentation, unsigned BitWidth,
110 StringRef Namespace) const;
111 void emitPredicateFunction(formatted_raw_ostream &OS,
112 PredicateSet &Predicates,
113 unsigned Indentation) const;
114 void emitDecoderFunction(formatted_raw_ostream &OS,
115 DecoderSet &Decoders,
116 unsigned Indentation) const;
117
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +0000118 // run - Output the code emitter
119 void run(raw_ostream &o);
120
121private:
122 CodeGenTarget Target;
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +0000123
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +0000124public:
125 std::string PredicateNamespace;
126 std::string GuardPrefix, GuardPostfix;
127 std::string ReturnOK, ReturnFail;
128 std::string Locals;
129};
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +0000130
131} // end anonymous namespace
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +0000132
Owen Anderson4e818902011-02-18 21:51:29 +0000133// The set (BIT_TRUE, BIT_FALSE, BIT_UNSET) represents a ternary logic system
134// for a bit value.
135//
136// BIT_UNFILTERED is used as the init value for a filter position. It is used
137// only for filter processings.
138typedef enum {
139 BIT_TRUE, // '1'
140 BIT_FALSE, // '0'
141 BIT_UNSET, // '?'
142 BIT_UNFILTERED // unfiltered
143} bit_value_t;
144
145static bool ValueSet(bit_value_t V) {
146 return (V == BIT_TRUE || V == BIT_FALSE);
147}
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +0000148
Owen Anderson4e818902011-02-18 21:51:29 +0000149static bool ValueNotSet(bit_value_t V) {
150 return (V == BIT_UNSET);
151}
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +0000152
Owen Anderson4e818902011-02-18 21:51:29 +0000153static int Value(bit_value_t V) {
154 return ValueNotSet(V) ? -1 : (V == BIT_FALSE ? 0 : 1);
155}
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +0000156
Craig Topper48c112b2012-03-16 05:58:09 +0000157static bit_value_t bitFromBits(const BitsInit &bits, unsigned index) {
Sean Silvafb509ed2012-10-10 20:24:43 +0000158 if (BitInit *bit = dyn_cast<BitInit>(bits.getBit(index)))
Owen Anderson4e818902011-02-18 21:51:29 +0000159 return bit->getValue() ? BIT_TRUE : BIT_FALSE;
160
161 // The bit is uninitialized.
162 return BIT_UNSET;
163}
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +0000164
Owen Anderson4e818902011-02-18 21:51:29 +0000165// Prints the bit value for each position.
Craig Topper48c112b2012-03-16 05:58:09 +0000166static void dumpBits(raw_ostream &o, const BitsInit &bits) {
Craig Topper29688ab2012-08-17 05:42:16 +0000167 for (unsigned index = bits.getNumBits(); index > 0; --index) {
Owen Anderson4e818902011-02-18 21:51:29 +0000168 switch (bitFromBits(bits, index - 1)) {
169 case BIT_TRUE:
170 o << "1";
171 break;
172 case BIT_FALSE:
173 o << "0";
174 break;
175 case BIT_UNSET:
176 o << "_";
177 break;
178 default:
Craig Topperc4965bc2012-02-05 07:21:30 +0000179 llvm_unreachable("unexpected return value from bitFromBits");
Owen Anderson4e818902011-02-18 21:51:29 +0000180 }
181 }
182}
183
Mehdi Amini32986ed2016-10-04 23:47:33 +0000184static BitsInit &getBitsField(const Record &def, StringRef str) {
David Greeneaf8ee2c2011-07-29 22:43:06 +0000185 BitsInit *bits = def.getValueAsBitsInit(str);
Owen Anderson4e818902011-02-18 21:51:29 +0000186 return *bits;
187}
188
Owen Anderson4e818902011-02-18 21:51:29 +0000189// Representation of the instruction to work on.
Owen Andersonc78e03c2011-07-19 21:06:00 +0000190typedef std::vector<bit_value_t> insn_t;
Owen Anderson4e818902011-02-18 21:51:29 +0000191
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +0000192namespace {
193
194class FilterChooser;
195
Owen Anderson4e818902011-02-18 21:51:29 +0000196/// Filter - Filter works with FilterChooser to produce the decoding tree for
197/// the ISA.
198///
199/// It is useful to think of a Filter as governing the switch stmts of the
200/// decoding tree in a certain level. Each case stmt delegates to an inferior
201/// FilterChooser to decide what further decoding logic to employ, or in another
202/// words, what other remaining bits to look at. The FilterChooser eventually
203/// chooses a best Filter to do its job.
204///
205/// This recursive scheme ends when the number of Opcodes assigned to the
206/// FilterChooser becomes 1 or if there is a conflict. A conflict happens when
207/// the Filter/FilterChooser combo does not know how to distinguish among the
208/// Opcodes assigned.
209///
210/// An example of a conflict is
211///
212/// Conflict:
213/// 111101000.00........00010000....
214/// 111101000.00........0001........
215/// 1111010...00........0001........
216/// 1111010...00....................
217/// 1111010.........................
218/// 1111............................
219/// ................................
220/// VST4q8a 111101000_00________00010000____
221/// VST4q8b 111101000_00________00010000____
222///
223/// The Debug output shows the path that the decoding tree follows to reach the
224/// the conclusion that there is a conflict. VST4q8a is a vst4 to double-spaced
Petr Pavlu21894652015-07-14 08:00:34 +0000225/// even registers, while VST4q8b is a vst4 to double-spaced odd registers.
Owen Anderson4e818902011-02-18 21:51:29 +0000226///
227/// The encoding info in the .td files does not specify this meta information,
228/// which could have been used by the decoder to resolve the conflict. The
229/// decoder could try to decode the even/odd register numbering and assign to
230/// VST4q8a or VST4q8b, but for the time being, the decoder chooses the "a"
231/// version and return the Opcode since the two have the same Asm format string.
232class Filter {
233protected:
Craig Topper501d95c2012-03-16 06:52:56 +0000234 const FilterChooser *Owner;// points to the FilterChooser who owns this filter
Owen Anderson4e818902011-02-18 21:51:29 +0000235 unsigned StartBit; // the starting bit position
236 unsigned NumBits; // number of bits to filter
237 bool Mixed; // a mixed region contains both set and unset bits
238
239 // Map of well-known segment value to the set of uid's with that value.
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +0000240 std::map<uint64_t, std::vector<unsigned>> FilteredInstructions;
Owen Anderson4e818902011-02-18 21:51:29 +0000241
242 // Set of uid's with non-constant segment values.
243 std::vector<unsigned> VariableInstructions;
244
245 // Map of well-known segment value to its delegate.
Craig Toppercf05f912014-09-03 06:07:54 +0000246 std::map<unsigned, std::unique_ptr<const FilterChooser>> FilterChooserMap;
Owen Anderson4e818902011-02-18 21:51:29 +0000247
248 // Number of instructions which fall under FilteredInstructions category.
249 unsigned NumFiltered;
250
251 // Keeps track of the last opcode in the filtered bucket.
252 unsigned LastOpcFiltered;
253
Owen Anderson4e818902011-02-18 21:51:29 +0000254public:
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +0000255 Filter(Filter &&f);
256 Filter(FilterChooser &owner, unsigned startBit, unsigned numBits, bool mixed);
257
258 ~Filter() = default;
259
Craig Topper48c112b2012-03-16 05:58:09 +0000260 unsigned getNumFiltered() const { return NumFiltered; }
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +0000261
Craig Topper48c112b2012-03-16 05:58:09 +0000262 unsigned getSingletonOpc() const {
Owen Anderson4e818902011-02-18 21:51:29 +0000263 assert(NumFiltered == 1);
264 return LastOpcFiltered;
265 }
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +0000266
Owen Anderson4e818902011-02-18 21:51:29 +0000267 // Return the filter chooser for the group of instructions without constant
268 // segment values.
Craig Topper48c112b2012-03-16 05:58:09 +0000269 const FilterChooser &getVariableFC() const {
Owen Anderson4e818902011-02-18 21:51:29 +0000270 assert(NumFiltered == 1);
271 assert(FilterChooserMap.size() == 1);
272 return *(FilterChooserMap.find((unsigned)-1)->second);
273 }
274
Owen Anderson4e818902011-02-18 21:51:29 +0000275 // Divides the decoding task into sub tasks and delegates them to the
276 // inferior FilterChooser's.
277 //
278 // A special case arises when there's only one entry in the filtered
279 // instructions. In order to unambiguously decode the singleton, we need to
280 // match the remaining undecoded encoding bits against the singleton.
281 void recurse();
282
Jim Grosbachecaef492012-08-14 19:06:05 +0000283 // Emit table entries to decode instructions given a segment or segments of
284 // bits.
285 void emitTableEntry(DecoderTableInfo &TableInfo) const;
Owen Anderson4e818902011-02-18 21:51:29 +0000286
287 // Returns the number of fanout produced by the filter. More fanout implies
288 // the filter distinguishes more categories of instructions.
289 unsigned usefulness() const;
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +0000290}; // end class Filter
291
292} // end anonymous namespace
Owen Anderson4e818902011-02-18 21:51:29 +0000293
294// These are states of our finite state machines used in FilterChooser's
295// filterProcessor() which produces the filter candidates to use.
296typedef enum {
297 ATTR_NONE,
298 ATTR_FILTERED,
299 ATTR_ALL_SET,
300 ATTR_ALL_UNSET,
301 ATTR_MIXED
302} bitAttr_t;
303
304/// FilterChooser - FilterChooser chooses the best filter among a set of Filters
305/// in order to perform the decoding of instructions at the current level.
306///
307/// Decoding proceeds from the top down. Based on the well-known encoding bits
308/// of instructions available, FilterChooser builds up the possible Filters that
309/// can further the task of decoding by distinguishing among the remaining
310/// candidate instructions.
311///
312/// Once a filter has been chosen, it is called upon to divide the decoding task
313/// into sub-tasks and delegates them to its inferior FilterChoosers for further
314/// processings.
315///
316/// It is useful to think of a Filter as governing the switch stmts of the
317/// decoding tree. And each case is delegated to an inferior FilterChooser to
318/// decide what further remaining bits to look at.
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +0000319namespace {
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +0000320
Owen Anderson4e818902011-02-18 21:51:29 +0000321class FilterChooser {
322protected:
323 friend class Filter;
324
325 // Vector of codegen instructions to choose our filter.
Craig Topperf9265322016-01-17 20:38:14 +0000326 ArrayRef<const CodeGenInstruction *> AllInstructions;
Owen Anderson4e818902011-02-18 21:51:29 +0000327
328 // Vector of uid's for this filter chooser to work on.
Craig Topper501d95c2012-03-16 06:52:56 +0000329 const std::vector<unsigned> &Opcodes;
Owen Anderson4e818902011-02-18 21:51:29 +0000330
331 // Lookup table for the operand decoding of instructions.
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +0000332 const std::map<unsigned, std::vector<OperandInfo>> &Operands;
Owen Anderson4e818902011-02-18 21:51:29 +0000333
334 // Vector of candidate filters.
335 std::vector<Filter> Filters;
336
337 // Array of bit values passed down from our parent.
338 // Set to all BIT_UNFILTERED's for Parent == NULL.
Owen Andersonc78e03c2011-07-19 21:06:00 +0000339 std::vector<bit_value_t> FilterBitValues;
Owen Anderson4e818902011-02-18 21:51:29 +0000340
341 // Links to the FilterChooser above us in the decoding tree.
Craig Topper501d95c2012-03-16 06:52:56 +0000342 const FilterChooser *Parent;
Owen Anderson4e818902011-02-18 21:51:29 +0000343
344 // Index of the best filter from Filters.
345 int BestIndex;
346
Owen Andersonc78e03c2011-07-19 21:06:00 +0000347 // Width of instructions
348 unsigned BitWidth;
349
Owen Andersona4043c42011-08-17 17:44:15 +0000350 // Parent emitter
351 const FixedLenDecoderEmitter *Emitter;
352
Owen Anderson4e818902011-02-18 21:51:29 +0000353public:
Craig Topperf9265322016-01-17 20:38:14 +0000354 FilterChooser(ArrayRef<const CodeGenInstruction *> Insts,
Owen Anderson4e818902011-02-18 21:51:29 +0000355 const std::vector<unsigned> &IDs,
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +0000356 const std::map<unsigned, std::vector<OperandInfo>> &Ops,
Owen Andersona4043c42011-08-17 17:44:15 +0000357 unsigned BW,
Craig Topper82d0d5f2012-03-16 01:19:24 +0000358 const FixedLenDecoderEmitter *E)
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +0000359 : AllInstructions(Insts), Opcodes(IDs), Operands(Ops),
Craig Topper1ddc2882014-09-04 04:49:03 +0000360 FilterBitValues(BW, BIT_UNFILTERED), Parent(nullptr), BestIndex(-1),
361 BitWidth(BW), Emitter(E) {
Owen Anderson4e818902011-02-18 21:51:29 +0000362 doFilter();
363 }
364
Craig Topperf9265322016-01-17 20:38:14 +0000365 FilterChooser(ArrayRef<const CodeGenInstruction *> Insts,
Owen Anderson4e818902011-02-18 21:51:29 +0000366 const std::vector<unsigned> &IDs,
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +0000367 const std::map<unsigned, std::vector<OperandInfo>> &Ops,
Craig Topper501d95c2012-03-16 06:52:56 +0000368 const std::vector<bit_value_t> &ParentFilterBitValues,
369 const FilterChooser &parent)
Craig Topper82d0d5f2012-03-16 01:19:24 +0000370 : AllInstructions(Insts), Opcodes(IDs), Operands(Ops),
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +0000371 FilterBitValues(ParentFilterBitValues), Parent(&parent), BestIndex(-1),
372 BitWidth(parent.BitWidth), Emitter(parent.Emitter) {
Owen Anderson4e818902011-02-18 21:51:29 +0000373 doFilter();
374 }
375
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +0000376 FilterChooser(const FilterChooser &) = delete;
377 void operator=(const FilterChooser &) = delete;
378
Jim Grosbachecaef492012-08-14 19:06:05 +0000379 unsigned getBitWidth() const { return BitWidth; }
Owen Anderson4e818902011-02-18 21:51:29 +0000380
381protected:
382 // Populates the insn given the uid.
383 void insnWithID(insn_t &Insn, unsigned Opcode) const {
David Greeneaf8ee2c2011-07-29 22:43:06 +0000384 BitsInit &Bits = getBitsField(*AllInstructions[Opcode]->TheDef, "Inst");
Owen Anderson4e818902011-02-18 21:51:29 +0000385
James Molloyd9ba4fd2012-02-09 10:56:31 +0000386 // We may have a SoftFail bitmask, which specifies a mask where an encoding
387 // may differ from the value in "Inst" and yet still be valid, but the
388 // disassembler should return SoftFail instead of Success.
389 //
390 // This is used for marking UNPREDICTABLE instructions in the ARM world.
Jim Grosbach3f4b2392012-02-29 22:07:56 +0000391 BitsInit *SFBits =
392 AllInstructions[Opcode]->TheDef->getValueAsBitsInit("SoftFail");
James Molloyd9ba4fd2012-02-09 10:56:31 +0000393
394 for (unsigned i = 0; i < BitWidth; ++i) {
395 if (SFBits && bitFromBits(*SFBits, i) == BIT_TRUE)
396 Insn.push_back(BIT_UNSET);
397 else
398 Insn.push_back(bitFromBits(Bits, i));
399 }
Owen Anderson4e818902011-02-18 21:51:29 +0000400 }
401
402 // Returns the record name.
403 const std::string &nameWithID(unsigned Opcode) const {
404 return AllInstructions[Opcode]->TheDef->getName();
405 }
406
407 // Populates the field of the insn given the start position and the number of
408 // consecutive bits to scan for.
409 //
410 // Returns false if there exists any uninitialized bit value in the range.
411 // Returns true, otherwise.
412 bool fieldFromInsn(uint64_t &Field, insn_t &Insn, unsigned StartBit,
Craig Topper82d0d5f2012-03-16 01:19:24 +0000413 unsigned NumBits) const;
Owen Anderson4e818902011-02-18 21:51:29 +0000414
415 /// dumpFilterArray - dumpFilterArray prints out debugging info for the given
416 /// filter array as a series of chars.
Craig Topper48c112b2012-03-16 05:58:09 +0000417 void dumpFilterArray(raw_ostream &o,
418 const std::vector<bit_value_t> & filter) const;
Owen Anderson4e818902011-02-18 21:51:29 +0000419
420 /// dumpStack - dumpStack traverses the filter chooser chain and calls
421 /// dumpFilterArray on each filter chooser up to the top level one.
Craig Topper48c112b2012-03-16 05:58:09 +0000422 void dumpStack(raw_ostream &o, const char *prefix) const;
Owen Anderson4e818902011-02-18 21:51:29 +0000423
424 Filter &bestFilter() {
425 assert(BestIndex != -1 && "BestIndex not set");
426 return Filters[BestIndex];
427 }
428
Craig Topper48c112b2012-03-16 05:58:09 +0000429 bool PositionFiltered(unsigned i) const {
Owen Anderson4e818902011-02-18 21:51:29 +0000430 return ValueSet(FilterBitValues[i]);
431 }
432
433 // Calculates the island(s) needed to decode the instruction.
434 // This returns a lit of undecoded bits of an instructions, for example,
435 // Inst{20} = 1 && Inst{3-0} == 0b1111 represents two islands of yet-to-be
436 // decoded bits in order to verify that the instruction matches the Opcode.
437 unsigned getIslands(std::vector<unsigned> &StartBits,
Craig Topper82d0d5f2012-03-16 01:19:24 +0000438 std::vector<unsigned> &EndBits,
Craig Topper48c112b2012-03-16 05:58:09 +0000439 std::vector<uint64_t> &FieldVals,
440 const insn_t &Insn) const;
Owen Anderson4e818902011-02-18 21:51:29 +0000441
James Molloy8067df92011-09-07 19:42:28 +0000442 // Emits code to check the Predicates member of an instruction are true.
443 // Returns true if predicate matches were emitted, false otherwise.
Craig Topper48c112b2012-03-16 05:58:09 +0000444 bool emitPredicateMatch(raw_ostream &o, unsigned &Indentation,
445 unsigned Opc) const;
James Molloy8067df92011-09-07 19:42:28 +0000446
Jim Grosbachecaef492012-08-14 19:06:05 +0000447 bool doesOpcodeNeedPredicate(unsigned Opc) const;
448 unsigned getPredicateIndex(DecoderTableInfo &TableInfo, StringRef P) const;
449 void emitPredicateTableEntry(DecoderTableInfo &TableInfo,
450 unsigned Opc) const;
James Molloyd9ba4fd2012-02-09 10:56:31 +0000451
Jim Grosbachecaef492012-08-14 19:06:05 +0000452 void emitSoftFailTableEntry(DecoderTableInfo &TableInfo,
453 unsigned Opc) const;
454
455 // Emits table entries to decode the singleton.
456 void emitSingletonTableEntry(DecoderTableInfo &TableInfo,
457 unsigned Opc) const;
Owen Anderson4e818902011-02-18 21:51:29 +0000458
459 // Emits code to decode the singleton, and then to decode the rest.
Jim Grosbachecaef492012-08-14 19:06:05 +0000460 void emitSingletonTableEntry(DecoderTableInfo &TableInfo,
461 const Filter &Best) const;
Owen Anderson4e818902011-02-18 21:51:29 +0000462
Jim Grosbachecaef492012-08-14 19:06:05 +0000463 void emitBinaryParser(raw_ostream &o, unsigned &Indentation,
Petr Pavlu182b0572015-07-15 08:04:27 +0000464 const OperandInfo &OpInfo,
465 bool &OpHasCompleteDecoder) const;
Owen Andersone3591652011-07-28 21:54:31 +0000466
Petr Pavlu182b0572015-07-15 08:04:27 +0000467 void emitDecoder(raw_ostream &OS, unsigned Indentation, unsigned Opc,
468 bool &HasCompleteDecoder) const;
469 unsigned getDecoderIndex(DecoderSet &Decoders, unsigned Opc,
470 bool &HasCompleteDecoder) const;
Jim Grosbachecaef492012-08-14 19:06:05 +0000471
Owen Anderson4e818902011-02-18 21:51:29 +0000472 // Assign a single filter and run with it.
Craig Topper48c112b2012-03-16 05:58:09 +0000473 void runSingleFilter(unsigned startBit, unsigned numBit, bool mixed);
Owen Anderson4e818902011-02-18 21:51:29 +0000474
475 // reportRegion is a helper function for filterProcessor to mark a region as
476 // eligible for use as a filter region.
477 void reportRegion(bitAttr_t RA, unsigned StartBit, unsigned BitIndex,
Craig Topper82d0d5f2012-03-16 01:19:24 +0000478 bool AllowMixed);
Owen Anderson4e818902011-02-18 21:51:29 +0000479
480 // FilterProcessor scans the well-known encoding bits of the instructions and
481 // builds up a list of candidate filters. It chooses the best filter and
482 // recursively descends down the decoding tree.
483 bool filterProcessor(bool AllowMixed, bool Greedy = true);
484
485 // Decides on the best configuration of filter(s) to use in order to decode
486 // the instructions. A conflict of instructions may occur, in which case we
487 // dump the conflict set to the standard error.
488 void doFilter();
489
Jim Grosbachecaef492012-08-14 19:06:05 +0000490public:
491 // emitTableEntries - Emit state machine entries to decode our share of
492 // instructions.
493 void emitTableEntries(DecoderTableInfo &TableInfo) const;
Owen Anderson4e818902011-02-18 21:51:29 +0000494};
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +0000495
496} // end anonymous namespace
Owen Anderson4e818902011-02-18 21:51:29 +0000497
498///////////////////////////
499// //
Craig Topper93e64342012-03-16 00:56:01 +0000500// Filter Implementation //
Owen Anderson4e818902011-02-18 21:51:29 +0000501// //
502///////////////////////////
503
Craig Topper5c2b4ac2014-09-03 05:49:07 +0000504Filter::Filter(Filter &&f)
Craig Topper82d0d5f2012-03-16 01:19:24 +0000505 : Owner(f.Owner), StartBit(f.StartBit), NumBits(f.NumBits), Mixed(f.Mixed),
Craig Topper5c2b4ac2014-09-03 05:49:07 +0000506 FilteredInstructions(std::move(f.FilteredInstructions)),
507 VariableInstructions(std::move(f.VariableInstructions)),
508 FilterChooserMap(std::move(f.FilterChooserMap)), NumFiltered(f.NumFiltered),
Craig Topper82d0d5f2012-03-16 01:19:24 +0000509 LastOpcFiltered(f.LastOpcFiltered) {
Owen Anderson4e818902011-02-18 21:51:29 +0000510}
511
512Filter::Filter(FilterChooser &owner, unsigned startBit, unsigned numBits,
Craig Topper82d0d5f2012-03-16 01:19:24 +0000513 bool mixed)
514 : Owner(&owner), StartBit(startBit), NumBits(numBits), Mixed(mixed) {
Owen Andersonc78e03c2011-07-19 21:06:00 +0000515 assert(StartBit + NumBits - 1 < Owner->BitWidth);
Owen Anderson4e818902011-02-18 21:51:29 +0000516
517 NumFiltered = 0;
518 LastOpcFiltered = 0;
Owen Anderson4e818902011-02-18 21:51:29 +0000519
520 for (unsigned i = 0, e = Owner->Opcodes.size(); i != e; ++i) {
521 insn_t Insn;
522
523 // Populates the insn given the uid.
524 Owner->insnWithID(Insn, Owner->Opcodes[i]);
525
526 uint64_t Field;
527 // Scans the segment for possibly well-specified encoding bits.
528 bool ok = Owner->fieldFromInsn(Field, Insn, StartBit, NumBits);
529
530 if (ok) {
531 // The encoding bits are well-known. Lets add the uid of the
532 // instruction into the bucket keyed off the constant field value.
533 LastOpcFiltered = Owner->Opcodes[i];
534 FilteredInstructions[Field].push_back(LastOpcFiltered);
535 ++NumFiltered;
536 } else {
Craig Topper93e64342012-03-16 00:56:01 +0000537 // Some of the encoding bit(s) are unspecified. This contributes to
Owen Anderson4e818902011-02-18 21:51:29 +0000538 // one additional member of "Variable" instructions.
539 VariableInstructions.push_back(Owner->Opcodes[i]);
Owen Anderson4e818902011-02-18 21:51:29 +0000540 }
541 }
542
543 assert((FilteredInstructions.size() + VariableInstructions.size() > 0)
544 && "Filter returns no instruction categories");
545}
546
Owen Anderson4e818902011-02-18 21:51:29 +0000547// Divides the decoding task into sub tasks and delegates them to the
548// inferior FilterChooser's.
549//
550// A special case arises when there's only one entry in the filtered
551// instructions. In order to unambiguously decode the singleton, we need to
552// match the remaining undecoded encoding bits against the singleton.
553void Filter::recurse() {
Owen Anderson4e818902011-02-18 21:51:29 +0000554 // Starts by inheriting our parent filter chooser's filter bit values.
Owen Andersonc78e03c2011-07-19 21:06:00 +0000555 std::vector<bit_value_t> BitValueArray(Owner->FilterBitValues);
Owen Anderson4e818902011-02-18 21:51:29 +0000556
Alexander Kornienko8c0809c2015-01-15 11:41:30 +0000557 if (!VariableInstructions.empty()) {
Owen Anderson4e818902011-02-18 21:51:29 +0000558 // Conservatively marks each segment position as BIT_UNSET.
Craig Topper29688ab2012-08-17 05:42:16 +0000559 for (unsigned bitIndex = 0; bitIndex < NumBits; ++bitIndex)
Owen Anderson4e818902011-02-18 21:51:29 +0000560 BitValueArray[StartBit + bitIndex] = BIT_UNSET;
561
Chris Lattner0ab5e2c2011-04-15 05:18:47 +0000562 // Delegates to an inferior filter chooser for further processing on this
Owen Anderson4e818902011-02-18 21:51:29 +0000563 // group of instructions whose segment values are variable.
Yaron Kerene499db02014-09-03 08:22:30 +0000564 FilterChooserMap.insert(
565 std::make_pair(-1U, llvm::make_unique<FilterChooser>(
566 Owner->AllInstructions, VariableInstructions,
567 Owner->Operands, BitValueArray, *Owner)));
Owen Anderson4e818902011-02-18 21:51:29 +0000568 }
569
570 // No need to recurse for a singleton filtered instruction.
Jim Grosbachecaef492012-08-14 19:06:05 +0000571 // See also Filter::emit*().
Owen Anderson4e818902011-02-18 21:51:29 +0000572 if (getNumFiltered() == 1) {
Owen Anderson4e818902011-02-18 21:51:29 +0000573 assert(FilterChooserMap.size() == 1);
574 return;
575 }
576
577 // Otherwise, create sub choosers.
Craig Topper1f7604d2014-12-13 05:12:19 +0000578 for (const auto &Inst : FilteredInstructions) {
Owen Anderson4e818902011-02-18 21:51:29 +0000579
580 // Marks all the segment positions with either BIT_TRUE or BIT_FALSE.
Craig Topper29688ab2012-08-17 05:42:16 +0000581 for (unsigned bitIndex = 0; bitIndex < NumBits; ++bitIndex) {
Craig Topper1f7604d2014-12-13 05:12:19 +0000582 if (Inst.first & (1ULL << bitIndex))
Owen Anderson4e818902011-02-18 21:51:29 +0000583 BitValueArray[StartBit + bitIndex] = BIT_TRUE;
584 else
585 BitValueArray[StartBit + bitIndex] = BIT_FALSE;
586 }
587
Chris Lattner0ab5e2c2011-04-15 05:18:47 +0000588 // Delegates to an inferior filter chooser for further processing on this
Owen Anderson4e818902011-02-18 21:51:29 +0000589 // category of instructions.
Craig Toppercf05f912014-09-03 06:07:54 +0000590 FilterChooserMap.insert(std::make_pair(
Craig Topper1f7604d2014-12-13 05:12:19 +0000591 Inst.first, llvm::make_unique<FilterChooser>(
592 Owner->AllInstructions, Inst.second,
Yaron Kerene499db02014-09-03 08:22:30 +0000593 Owner->Operands, BitValueArray, *Owner)));
Owen Anderson4e818902011-02-18 21:51:29 +0000594 }
595}
596
Jim Grosbachecaef492012-08-14 19:06:05 +0000597static void resolveTableFixups(DecoderTable &Table, const FixupList &Fixups,
598 uint32_t DestIdx) {
599 // Any NumToSkip fixups in the current scope can resolve to the
600 // current location.
601 for (FixupList::const_reverse_iterator I = Fixups.rbegin(),
602 E = Fixups.rend();
603 I != E; ++I) {
604 // Calculate the distance from the byte following the fixup entry byte
605 // to the destination. The Target is calculated from after the 16-bit
606 // NumToSkip entry itself, so subtract two from the displacement here
607 // to account for that.
608 uint32_t FixupIdx = *I;
609 uint32_t Delta = DestIdx - FixupIdx - 2;
610 // Our NumToSkip entries are 16-bits. Make sure our table isn't too
611 // big.
612 assert(Delta < 65536U && "disassembler decoding table too large!");
613 Table[FixupIdx] = (uint8_t)Delta;
614 Table[FixupIdx + 1] = (uint8_t)(Delta >> 8);
615 }
616}
Owen Anderson4e818902011-02-18 21:51:29 +0000617
Jim Grosbachecaef492012-08-14 19:06:05 +0000618// Emit table entries to decode instructions given a segment or segments
619// of bits.
620void Filter::emitTableEntry(DecoderTableInfo &TableInfo) const {
621 TableInfo.Table.push_back(MCD::OPC_ExtractField);
622 TableInfo.Table.push_back(StartBit);
623 TableInfo.Table.push_back(NumBits);
Owen Anderson4e818902011-02-18 21:51:29 +0000624
Jim Grosbachecaef492012-08-14 19:06:05 +0000625 // A new filter entry begins a new scope for fixup resolution.
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +0000626 TableInfo.FixupStack.emplace_back();
Owen Anderson4e818902011-02-18 21:51:29 +0000627
Jim Grosbachecaef492012-08-14 19:06:05 +0000628 DecoderTable &Table = TableInfo.Table;
629
630 size_t PrevFilter = 0;
631 bool HasFallthrough = false;
Craig Topper1f7604d2014-12-13 05:12:19 +0000632 for (auto &Filter : FilterChooserMap) {
Owen Anderson4e818902011-02-18 21:51:29 +0000633 // Field value -1 implies a non-empty set of variable instructions.
634 // See also recurse().
Craig Topper1f7604d2014-12-13 05:12:19 +0000635 if (Filter.first == (unsigned)-1) {
Jim Grosbachecaef492012-08-14 19:06:05 +0000636 HasFallthrough = true;
Owen Anderson4e818902011-02-18 21:51:29 +0000637
Jim Grosbachecaef492012-08-14 19:06:05 +0000638 // Each scope should always have at least one filter value to check
639 // for.
640 assert(PrevFilter != 0 && "empty filter set!");
641 FixupList &CurScope = TableInfo.FixupStack.back();
642 // Resolve any NumToSkip fixups in the current scope.
643 resolveTableFixups(Table, CurScope, Table.size());
644 CurScope.clear();
645 PrevFilter = 0; // Don't re-process the filter's fallthrough.
646 } else {
647 Table.push_back(MCD::OPC_FilterValue);
648 // Encode and emit the value to filter against.
649 uint8_t Buffer[8];
Craig Topper1f7604d2014-12-13 05:12:19 +0000650 unsigned Len = encodeULEB128(Filter.first, Buffer);
Jim Grosbachecaef492012-08-14 19:06:05 +0000651 Table.insert(Table.end(), Buffer, Buffer + Len);
652 // Reserve space for the NumToSkip entry. We'll backpatch the value
653 // later.
654 PrevFilter = Table.size();
655 Table.push_back(0);
656 Table.push_back(0);
657 }
Owen Anderson4e818902011-02-18 21:51:29 +0000658
659 // We arrive at a category of instructions with the same segment value.
660 // Now delegate to the sub filter chooser for further decodings.
661 // The case may fallthrough, which happens if the remaining well-known
662 // encoding bits do not match exactly.
Craig Topper1f7604d2014-12-13 05:12:19 +0000663 Filter.second->emitTableEntries(TableInfo);
Owen Anderson4e818902011-02-18 21:51:29 +0000664
Jim Grosbachecaef492012-08-14 19:06:05 +0000665 // Now that we've emitted the body of the handler, update the NumToSkip
666 // of the filter itself to be able to skip forward when false. Subtract
667 // two as to account for the width of the NumToSkip field itself.
668 if (PrevFilter) {
669 uint32_t NumToSkip = Table.size() - PrevFilter - 2;
670 assert(NumToSkip < 65536U && "disassembler decoding table too large!");
671 Table[PrevFilter] = (uint8_t)NumToSkip;
672 Table[PrevFilter + 1] = (uint8_t)(NumToSkip >> 8);
673 }
Owen Anderson4e818902011-02-18 21:51:29 +0000674 }
675
Jim Grosbachecaef492012-08-14 19:06:05 +0000676 // Any remaining unresolved fixups bubble up to the parent fixup scope.
677 assert(TableInfo.FixupStack.size() > 1 && "fixup stack underflow!");
678 FixupScopeList::iterator Source = TableInfo.FixupStack.end() - 1;
679 FixupScopeList::iterator Dest = Source - 1;
680 Dest->insert(Dest->end(), Source->begin(), Source->end());
681 TableInfo.FixupStack.pop_back();
682
683 // If there is no fallthrough, then the final filter should get fixed
684 // up according to the enclosing scope rather than the current position.
685 if (!HasFallthrough)
686 TableInfo.FixupStack.back().push_back(PrevFilter);
Owen Anderson4e818902011-02-18 21:51:29 +0000687}
688
689// Returns the number of fanout produced by the filter. More fanout implies
690// the filter distinguishes more categories of instructions.
691unsigned Filter::usefulness() const {
Alexander Kornienko8c0809c2015-01-15 11:41:30 +0000692 if (!VariableInstructions.empty())
Owen Anderson4e818902011-02-18 21:51:29 +0000693 return FilteredInstructions.size();
694 else
695 return FilteredInstructions.size() + 1;
696}
697
698//////////////////////////////////
699// //
700// Filterchooser Implementation //
701// //
702//////////////////////////////////
703
Jim Grosbachecaef492012-08-14 19:06:05 +0000704// Emit the decoder state machine table.
705void FixedLenDecoderEmitter::emitTable(formatted_raw_ostream &OS,
706 DecoderTable &Table,
707 unsigned Indentation,
708 unsigned BitWidth,
709 StringRef Namespace) const {
710 OS.indent(Indentation) << "static const uint8_t DecoderTable" << Namespace
711 << BitWidth << "[] = {\n";
Owen Anderson4e818902011-02-18 21:51:29 +0000712
Jim Grosbachecaef492012-08-14 19:06:05 +0000713 Indentation += 2;
Owen Anderson4e818902011-02-18 21:51:29 +0000714
Jim Grosbachecaef492012-08-14 19:06:05 +0000715 // FIXME: We may be able to use the NumToSkip values to recover
716 // appropriate indentation levels.
717 DecoderTable::const_iterator I = Table.begin();
718 DecoderTable::const_iterator E = Table.end();
719 while (I != E) {
720 assert (I < E && "incomplete decode table entry!");
Owen Anderson4e818902011-02-18 21:51:29 +0000721
Jim Grosbachecaef492012-08-14 19:06:05 +0000722 uint64_t Pos = I - Table.begin();
723 OS << "/* " << Pos << " */";
724 OS.PadToColumn(12);
Owen Anderson4e818902011-02-18 21:51:29 +0000725
Jim Grosbachecaef492012-08-14 19:06:05 +0000726 switch (*I) {
727 default:
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000728 PrintFatalError("invalid decode table opcode");
Jim Grosbachecaef492012-08-14 19:06:05 +0000729 case MCD::OPC_ExtractField: {
730 ++I;
731 unsigned Start = *I++;
732 unsigned Len = *I++;
733 OS.indent(Indentation) << "MCD::OPC_ExtractField, " << Start << ", "
734 << Len << ", // Inst{";
735 if (Len > 1)
736 OS << (Start + Len - 1) << "-";
737 OS << Start << "} ...\n";
738 break;
739 }
740 case MCD::OPC_FilterValue: {
741 ++I;
742 OS.indent(Indentation) << "MCD::OPC_FilterValue, ";
743 // The filter value is ULEB128 encoded.
744 while (*I >= 128)
Craig Topper429093a2016-01-31 01:55:15 +0000745 OS << (unsigned)*I++ << ", ";
746 OS << (unsigned)*I++ << ", ";
Jim Grosbachecaef492012-08-14 19:06:05 +0000747
748 // 16-bit numtoskip value.
749 uint8_t Byte = *I++;
750 uint32_t NumToSkip = Byte;
Craig Topper429093a2016-01-31 01:55:15 +0000751 OS << (unsigned)Byte << ", ";
Jim Grosbachecaef492012-08-14 19:06:05 +0000752 Byte = *I++;
Craig Topper429093a2016-01-31 01:55:15 +0000753 OS << (unsigned)Byte << ", ";
Jim Grosbachecaef492012-08-14 19:06:05 +0000754 NumToSkip |= Byte << 8;
755 OS << "// Skip to: " << ((I - Table.begin()) + NumToSkip) << "\n";
756 break;
757 }
758 case MCD::OPC_CheckField: {
759 ++I;
760 unsigned Start = *I++;
761 unsigned Len = *I++;
762 OS.indent(Indentation) << "MCD::OPC_CheckField, " << Start << ", "
763 << Len << ", ";// << Val << ", " << NumToSkip << ",\n";
764 // ULEB128 encoded field value.
765 for (; *I >= 128; ++I)
Craig Topper429093a2016-01-31 01:55:15 +0000766 OS << (unsigned)*I << ", ";
767 OS << (unsigned)*I++ << ", ";
Jim Grosbachecaef492012-08-14 19:06:05 +0000768 // 16-bit numtoskip value.
769 uint8_t Byte = *I++;
770 uint32_t NumToSkip = Byte;
Craig Topper429093a2016-01-31 01:55:15 +0000771 OS << (unsigned)Byte << ", ";
Jim Grosbachecaef492012-08-14 19:06:05 +0000772 Byte = *I++;
Craig Topper429093a2016-01-31 01:55:15 +0000773 OS << (unsigned)Byte << ", ";
Jim Grosbachecaef492012-08-14 19:06:05 +0000774 NumToSkip |= Byte << 8;
775 OS << "// Skip to: " << ((I - Table.begin()) + NumToSkip) << "\n";
776 break;
777 }
778 case MCD::OPC_CheckPredicate: {
779 ++I;
780 OS.indent(Indentation) << "MCD::OPC_CheckPredicate, ";
781 for (; *I >= 128; ++I)
Craig Topper429093a2016-01-31 01:55:15 +0000782 OS << (unsigned)*I << ", ";
783 OS << (unsigned)*I++ << ", ";
Jim Grosbachecaef492012-08-14 19:06:05 +0000784
785 // 16-bit numtoskip value.
786 uint8_t Byte = *I++;
787 uint32_t NumToSkip = Byte;
Craig Topper429093a2016-01-31 01:55:15 +0000788 OS << (unsigned)Byte << ", ";
Jim Grosbachecaef492012-08-14 19:06:05 +0000789 Byte = *I++;
Craig Topper429093a2016-01-31 01:55:15 +0000790 OS << (unsigned)Byte << ", ";
Jim Grosbachecaef492012-08-14 19:06:05 +0000791 NumToSkip |= Byte << 8;
792 OS << "// Skip to: " << ((I - Table.begin()) + NumToSkip) << "\n";
793 break;
794 }
Petr Pavlu182b0572015-07-15 08:04:27 +0000795 case MCD::OPC_Decode:
796 case MCD::OPC_TryDecode: {
797 bool IsTry = *I == MCD::OPC_TryDecode;
Jim Grosbachecaef492012-08-14 19:06:05 +0000798 ++I;
799 // Extract the ULEB128 encoded Opcode to a buffer.
800 uint8_t Buffer[8], *p = Buffer;
801 while ((*p++ = *I++) >= 128)
802 assert((p - Buffer) <= (ptrdiff_t)sizeof(Buffer)
803 && "ULEB128 value too large!");
804 // Decode the Opcode value.
805 unsigned Opc = decodeULEB128(Buffer);
Petr Pavlu182b0572015-07-15 08:04:27 +0000806 OS.indent(Indentation) << "MCD::OPC_" << (IsTry ? "Try" : "")
807 << "Decode, ";
Jim Grosbachecaef492012-08-14 19:06:05 +0000808 for (p = Buffer; *p >= 128; ++p)
Craig Topper429093a2016-01-31 01:55:15 +0000809 OS << (unsigned)*p << ", ";
810 OS << (unsigned)*p << ", ";
Jim Grosbachecaef492012-08-14 19:06:05 +0000811
812 // Decoder index.
813 for (; *I >= 128; ++I)
Craig Topper429093a2016-01-31 01:55:15 +0000814 OS << (unsigned)*I << ", ";
815 OS << (unsigned)*I++ << ", ";
Jim Grosbachecaef492012-08-14 19:06:05 +0000816
Petr Pavlu182b0572015-07-15 08:04:27 +0000817 if (!IsTry) {
818 OS << "// Opcode: "
Craig Topperf9265322016-01-17 20:38:14 +0000819 << NumberedInstructions[Opc]->TheDef->getName() << "\n";
Petr Pavlu182b0572015-07-15 08:04:27 +0000820 break;
821 }
822
823 // Fallthrough for OPC_TryDecode.
824
825 // 16-bit numtoskip value.
826 uint8_t Byte = *I++;
827 uint32_t NumToSkip = Byte;
Craig Topper429093a2016-01-31 01:55:15 +0000828 OS << (unsigned)Byte << ", ";
Petr Pavlu182b0572015-07-15 08:04:27 +0000829 Byte = *I++;
Craig Topper429093a2016-01-31 01:55:15 +0000830 OS << (unsigned)Byte << ", ";
Petr Pavlu182b0572015-07-15 08:04:27 +0000831 NumToSkip |= Byte << 8;
832
Jim Grosbachecaef492012-08-14 19:06:05 +0000833 OS << "// Opcode: "
Craig Topperf9265322016-01-17 20:38:14 +0000834 << NumberedInstructions[Opc]->TheDef->getName()
Petr Pavlu182b0572015-07-15 08:04:27 +0000835 << ", skip to: " << ((I - Table.begin()) + NumToSkip) << "\n";
Jim Grosbachecaef492012-08-14 19:06:05 +0000836 break;
837 }
838 case MCD::OPC_SoftFail: {
839 ++I;
840 OS.indent(Indentation) << "MCD::OPC_SoftFail";
841 // Positive mask
842 uint64_t Value = 0;
843 unsigned Shift = 0;
844 do {
Craig Topper429093a2016-01-31 01:55:15 +0000845 OS << ", " << (unsigned)*I;
Jim Grosbachecaef492012-08-14 19:06:05 +0000846 Value += (*I & 0x7f) << Shift;
847 Shift += 7;
848 } while (*I++ >= 128);
Craig Topper429093a2016-01-31 01:55:15 +0000849 if (Value > 127) {
850 OS << " /* 0x";
851 OS.write_hex(Value);
852 OS << " */";
853 }
Jim Grosbachecaef492012-08-14 19:06:05 +0000854 // Negative mask
855 Value = 0;
856 Shift = 0;
857 do {
Craig Topper429093a2016-01-31 01:55:15 +0000858 OS << ", " << (unsigned)*I;
Jim Grosbachecaef492012-08-14 19:06:05 +0000859 Value += (*I & 0x7f) << Shift;
860 Shift += 7;
861 } while (*I++ >= 128);
Craig Topper429093a2016-01-31 01:55:15 +0000862 if (Value > 127) {
863 OS << " /* 0x";
864 OS.write_hex(Value);
865 OS << " */";
866 }
Jim Grosbachecaef492012-08-14 19:06:05 +0000867 OS << ",\n";
868 break;
869 }
870 case MCD::OPC_Fail: {
871 ++I;
872 OS.indent(Indentation) << "MCD::OPC_Fail,\n";
873 break;
874 }
875 }
876 }
877 OS.indent(Indentation) << "0\n";
878
879 Indentation -= 2;
880
881 OS.indent(Indentation) << "};\n\n";
882}
883
884void FixedLenDecoderEmitter::
885emitPredicateFunction(formatted_raw_ostream &OS, PredicateSet &Predicates,
886 unsigned Indentation) const {
887 // The predicate function is just a big switch statement based on the
888 // input predicate index.
889 OS.indent(Indentation) << "static bool checkDecoderPredicate(unsigned Idx, "
Michael Kupersteindb0712f2015-05-26 10:47:10 +0000890 << "const FeatureBitset& Bits) {\n";
Jim Grosbachecaef492012-08-14 19:06:05 +0000891 Indentation += 2;
Aaron Ballmane59e3582013-07-15 16:53:32 +0000892 if (!Predicates.empty()) {
893 OS.indent(Indentation) << "switch (Idx) {\n";
894 OS.indent(Indentation) << "default: llvm_unreachable(\"Invalid index!\");\n";
895 unsigned Index = 0;
Craig Topper1f7604d2014-12-13 05:12:19 +0000896 for (const auto &Predicate : Predicates) {
897 OS.indent(Indentation) << "case " << Index++ << ":\n";
898 OS.indent(Indentation+2) << "return (" << Predicate << ");\n";
Aaron Ballmane59e3582013-07-15 16:53:32 +0000899 }
900 OS.indent(Indentation) << "}\n";
901 } else {
902 // No case statement to emit
903 OS.indent(Indentation) << "llvm_unreachable(\"Invalid index!\");\n";
Jim Grosbachecaef492012-08-14 19:06:05 +0000904 }
Jim Grosbachecaef492012-08-14 19:06:05 +0000905 Indentation -= 2;
906 OS.indent(Indentation) << "}\n\n";
907}
908
909void FixedLenDecoderEmitter::
910emitDecoderFunction(formatted_raw_ostream &OS, DecoderSet &Decoders,
911 unsigned Indentation) const {
912 // The decoder function is just a big switch statement based on the
913 // input decoder index.
914 OS.indent(Indentation) << "template<typename InsnType>\n";
915 OS.indent(Indentation) << "static DecodeStatus decodeToMCInst(DecodeStatus S,"
916 << " unsigned Idx, InsnType insn, MCInst &MI,\n";
917 OS.indent(Indentation) << " uint64_t "
Petr Pavlu182b0572015-07-15 08:04:27 +0000918 << "Address, const void *Decoder, bool &DecodeComplete) {\n";
Jim Grosbachecaef492012-08-14 19:06:05 +0000919 Indentation += 2;
Petr Pavlu182b0572015-07-15 08:04:27 +0000920 OS.indent(Indentation) << "DecodeComplete = true;\n";
Jim Grosbachecaef492012-08-14 19:06:05 +0000921 OS.indent(Indentation) << "InsnType tmp;\n";
922 OS.indent(Indentation) << "switch (Idx) {\n";
923 OS.indent(Indentation) << "default: llvm_unreachable(\"Invalid index!\");\n";
924 unsigned Index = 0;
Craig Topper1f7604d2014-12-13 05:12:19 +0000925 for (const auto &Decoder : Decoders) {
926 OS.indent(Indentation) << "case " << Index++ << ":\n";
927 OS << Decoder;
Jim Grosbachecaef492012-08-14 19:06:05 +0000928 OS.indent(Indentation+2) << "return S;\n";
929 }
930 OS.indent(Indentation) << "}\n";
931 Indentation -= 2;
932 OS.indent(Indentation) << "}\n\n";
Owen Anderson4e818902011-02-18 21:51:29 +0000933}
934
935// Populates the field of the insn given the start position and the number of
936// consecutive bits to scan for.
937//
938// Returns false if and on the first uninitialized bit value encountered.
939// Returns true, otherwise.
940bool FilterChooser::fieldFromInsn(uint64_t &Field, insn_t &Insn,
Craig Topper48c112b2012-03-16 05:58:09 +0000941 unsigned StartBit, unsigned NumBits) const {
Owen Anderson4e818902011-02-18 21:51:29 +0000942 Field = 0;
943
944 for (unsigned i = 0; i < NumBits; ++i) {
945 if (Insn[StartBit + i] == BIT_UNSET)
946 return false;
947
948 if (Insn[StartBit + i] == BIT_TRUE)
949 Field = Field | (1ULL << i);
950 }
951
952 return true;
953}
954
955/// dumpFilterArray - dumpFilterArray prints out debugging info for the given
956/// filter array as a series of chars.
957void FilterChooser::dumpFilterArray(raw_ostream &o,
Craig Topper48c112b2012-03-16 05:58:09 +0000958 const std::vector<bit_value_t> &filter) const {
Craig Topper29688ab2012-08-17 05:42:16 +0000959 for (unsigned bitIndex = BitWidth; bitIndex > 0; bitIndex--) {
Owen Anderson4e818902011-02-18 21:51:29 +0000960 switch (filter[bitIndex - 1]) {
961 case BIT_UNFILTERED:
962 o << ".";
963 break;
964 case BIT_UNSET:
965 o << "_";
966 break;
967 case BIT_TRUE:
968 o << "1";
969 break;
970 case BIT_FALSE:
971 o << "0";
972 break;
973 }
974 }
975}
976
977/// dumpStack - dumpStack traverses the filter chooser chain and calls
978/// dumpFilterArray on each filter chooser up to the top level one.
Craig Topper48c112b2012-03-16 05:58:09 +0000979void FilterChooser::dumpStack(raw_ostream &o, const char *prefix) const {
980 const FilterChooser *current = this;
Owen Anderson4e818902011-02-18 21:51:29 +0000981
982 while (current) {
983 o << prefix;
984 dumpFilterArray(o, current->FilterBitValues);
985 o << '\n';
986 current = current->Parent;
987 }
988}
989
Owen Anderson4e818902011-02-18 21:51:29 +0000990// Calculates the island(s) needed to decode the instruction.
991// This returns a list of undecoded bits of an instructions, for example,
992// Inst{20} = 1 && Inst{3-0} == 0b1111 represents two islands of yet-to-be
993// decoded bits in order to verify that the instruction matches the Opcode.
994unsigned FilterChooser::getIslands(std::vector<unsigned> &StartBits,
Craig Topper82d0d5f2012-03-16 01:19:24 +0000995 std::vector<unsigned> &EndBits,
996 std::vector<uint64_t> &FieldVals,
Craig Topper48c112b2012-03-16 05:58:09 +0000997 const insn_t &Insn) const {
Owen Anderson4e818902011-02-18 21:51:29 +0000998 unsigned Num, BitNo;
999 Num = BitNo = 0;
1000
1001 uint64_t FieldVal = 0;
1002
1003 // 0: Init
1004 // 1: Water (the bit value does not affect decoding)
1005 // 2: Island (well-known bit value needed for decoding)
1006 int State = 0;
1007 int Val = -1;
1008
Owen Andersonc78e03c2011-07-19 21:06:00 +00001009 for (unsigned i = 0; i < BitWidth; ++i) {
Owen Anderson4e818902011-02-18 21:51:29 +00001010 Val = Value(Insn[i]);
1011 bool Filtered = PositionFiltered(i);
1012 switch (State) {
Craig Topperc4965bc2012-02-05 07:21:30 +00001013 default: llvm_unreachable("Unreachable code!");
Owen Anderson4e818902011-02-18 21:51:29 +00001014 case 0:
1015 case 1:
1016 if (Filtered || Val == -1)
1017 State = 1; // Still in Water
1018 else {
1019 State = 2; // Into the Island
1020 BitNo = 0;
1021 StartBits.push_back(i);
1022 FieldVal = Val;
1023 }
1024 break;
1025 case 2:
1026 if (Filtered || Val == -1) {
1027 State = 1; // Into the Water
1028 EndBits.push_back(i - 1);
1029 FieldVals.push_back(FieldVal);
1030 ++Num;
1031 } else {
1032 State = 2; // Still in Island
1033 ++BitNo;
1034 FieldVal = FieldVal | Val << BitNo;
1035 }
1036 break;
1037 }
1038 }
1039 // If we are still in Island after the loop, do some housekeeping.
1040 if (State == 2) {
Owen Andersonc78e03c2011-07-19 21:06:00 +00001041 EndBits.push_back(BitWidth - 1);
Owen Anderson4e818902011-02-18 21:51:29 +00001042 FieldVals.push_back(FieldVal);
1043 ++Num;
1044 }
1045
1046 assert(StartBits.size() == Num && EndBits.size() == Num &&
1047 FieldVals.size() == Num);
1048 return Num;
1049}
1050
Owen Andersone3591652011-07-28 21:54:31 +00001051void FilterChooser::emitBinaryParser(raw_ostream &o, unsigned &Indentation,
Petr Pavlu182b0572015-07-15 08:04:27 +00001052 const OperandInfo &OpInfo,
1053 bool &OpHasCompleteDecoder) const {
Craig Topper48c112b2012-03-16 05:58:09 +00001054 const std::string &Decoder = OpInfo.Decoder;
Owen Andersone3591652011-07-28 21:54:31 +00001055
Craig Topper5546f8c2014-09-27 05:26:42 +00001056 if (OpInfo.numFields() != 1)
Craig Topperebc3aa22012-08-17 05:16:15 +00001057 o.indent(Indentation) << "tmp = 0;\n";
Craig Topper5546f8c2014-09-27 05:26:42 +00001058
1059 for (const EncodingField &EF : OpInfo) {
1060 o.indent(Indentation) << "tmp ";
1061 if (OpInfo.numFields() != 1) o << '|';
1062 o << "= fieldFromInstruction"
1063 << "(insn, " << EF.Base << ", " << EF.Width << ')';
1064 if (OpInfo.numFields() != 1 || EF.Offset != 0)
1065 o << " << " << EF.Offset;
1066 o << ";\n";
Owen Andersone3591652011-07-28 21:54:31 +00001067 }
1068
Petr Pavlu182b0572015-07-15 08:04:27 +00001069 if (Decoder != "") {
1070 OpHasCompleteDecoder = OpInfo.HasCompleteDecoder;
Craig Topperebc3aa22012-08-17 05:16:15 +00001071 o.indent(Indentation) << Emitter->GuardPrefix << Decoder
Petr Pavlu182b0572015-07-15 08:04:27 +00001072 << "(MI, tmp, Address, Decoder)"
1073 << Emitter->GuardPostfix
1074 << " { " << (OpHasCompleteDecoder ? "" : "DecodeComplete = false; ")
1075 << "return MCDisassembler::Fail; }\n";
1076 } else {
1077 OpHasCompleteDecoder = true;
Jim Grosbache9119e42015-05-13 18:37:00 +00001078 o.indent(Indentation) << "MI.addOperand(MCOperand::createImm(tmp));\n";
Petr Pavlu182b0572015-07-15 08:04:27 +00001079 }
Owen Andersone3591652011-07-28 21:54:31 +00001080}
1081
Jim Grosbachecaef492012-08-14 19:06:05 +00001082void FilterChooser::emitDecoder(raw_ostream &OS, unsigned Indentation,
Petr Pavlu182b0572015-07-15 08:04:27 +00001083 unsigned Opc, bool &HasCompleteDecoder) const {
1084 HasCompleteDecoder = true;
1085
Craig Topper1f7604d2014-12-13 05:12:19 +00001086 for (const auto &Op : Operands.find(Opc)->second) {
Jim Grosbachecaef492012-08-14 19:06:05 +00001087 // If a custom instruction decoder was specified, use that.
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +00001088 if (Op.numFields() == 0 && !Op.Decoder.empty()) {
Petr Pavlu182b0572015-07-15 08:04:27 +00001089 HasCompleteDecoder = Op.HasCompleteDecoder;
Craig Topper1f7604d2014-12-13 05:12:19 +00001090 OS.indent(Indentation) << Emitter->GuardPrefix << Op.Decoder
Jim Grosbachecaef492012-08-14 19:06:05 +00001091 << "(MI, insn, Address, Decoder)"
Petr Pavlu182b0572015-07-15 08:04:27 +00001092 << Emitter->GuardPostfix
1093 << " { " << (HasCompleteDecoder ? "" : "DecodeComplete = false; ")
1094 << "return MCDisassembler::Fail; }\n";
Jim Grosbachecaef492012-08-14 19:06:05 +00001095 break;
1096 }
1097
Petr Pavlu182b0572015-07-15 08:04:27 +00001098 bool OpHasCompleteDecoder;
1099 emitBinaryParser(OS, Indentation, Op, OpHasCompleteDecoder);
1100 if (!OpHasCompleteDecoder)
1101 HasCompleteDecoder = false;
Jim Grosbachecaef492012-08-14 19:06:05 +00001102 }
1103}
1104
1105unsigned FilterChooser::getDecoderIndex(DecoderSet &Decoders,
Petr Pavlu182b0572015-07-15 08:04:27 +00001106 unsigned Opc,
1107 bool &HasCompleteDecoder) const {
Jim Grosbachecaef492012-08-14 19:06:05 +00001108 // Build up the predicate string.
1109 SmallString<256> Decoder;
1110 // FIXME: emitDecoder() function can take a buffer directly rather than
1111 // a stream.
1112 raw_svector_ostream S(Decoder);
Craig Topperebc3aa22012-08-17 05:16:15 +00001113 unsigned I = 4;
Petr Pavlu182b0572015-07-15 08:04:27 +00001114 emitDecoder(S, I, Opc, HasCompleteDecoder);
Jim Grosbachecaef492012-08-14 19:06:05 +00001115
1116 // Using the full decoder string as the key value here is a bit
1117 // heavyweight, but is effective. If the string comparisons become a
1118 // performance concern, we can implement a mangling of the predicate
Nick Lewycky06b0ea22015-08-18 22:41:58 +00001119 // data easily enough with a map back to the actual string. That's
Jim Grosbachecaef492012-08-14 19:06:05 +00001120 // overkill for now, though.
1121
1122 // Make sure the predicate is in the table.
Justin Lebar5e83dfe2016-10-21 21:45:01 +00001123 Decoders.insert(CachedHashString(Decoder));
Jim Grosbachecaef492012-08-14 19:06:05 +00001124 // Now figure out the index for when we write out the table.
David Majnemer42531262016-08-12 03:55:06 +00001125 DecoderSet::const_iterator P = find(Decoders, Decoder.str());
Jim Grosbachecaef492012-08-14 19:06:05 +00001126 return (unsigned)(P - Decoders.begin());
1127}
1128
James Molloy8067df92011-09-07 19:42:28 +00001129static void emitSinglePredicateMatch(raw_ostream &o, StringRef str,
Craig Topper48c112b2012-03-16 05:58:09 +00001130 const std::string &PredicateNamespace) {
Andrew Trick43674ad2011-09-08 05:25:49 +00001131 if (str[0] == '!')
Michael Kupersteindb0712f2015-05-26 10:47:10 +00001132 o << "!Bits[" << PredicateNamespace << "::"
1133 << str.slice(1,str.size()) << "]";
James Molloy8067df92011-09-07 19:42:28 +00001134 else
Michael Kupersteindb0712f2015-05-26 10:47:10 +00001135 o << "Bits[" << PredicateNamespace << "::" << str << "]";
James Molloy8067df92011-09-07 19:42:28 +00001136}
1137
1138bool FilterChooser::emitPredicateMatch(raw_ostream &o, unsigned &Indentation,
Craig Topper48c112b2012-03-16 05:58:09 +00001139 unsigned Opc) const {
Jim Grosbach3f4b2392012-02-29 22:07:56 +00001140 ListInit *Predicates =
1141 AllInstructions[Opc]->TheDef->getValueAsListInit("Predicates");
Toma Tabacu3d5ce492015-04-07 12:10:11 +00001142 bool IsFirstEmission = true;
Craig Topper664f6a02015-06-02 04:15:57 +00001143 for (unsigned i = 0; i < Predicates->size(); ++i) {
James Molloy8067df92011-09-07 19:42:28 +00001144 Record *Pred = Predicates->getElementAsRecord(i);
1145 if (!Pred->getValue("AssemblerMatcherPredicate"))
1146 continue;
1147
1148 std::string P = Pred->getValueAsString("AssemblerCondString");
1149
1150 if (!P.length())
1151 continue;
1152
Toma Tabacu3d5ce492015-04-07 12:10:11 +00001153 if (!IsFirstEmission)
James Molloy8067df92011-09-07 19:42:28 +00001154 o << " && ";
1155
1156 StringRef SR(P);
1157 std::pair<StringRef, StringRef> pairs = SR.split(',');
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +00001158 while (!pairs.second.empty()) {
James Molloy8067df92011-09-07 19:42:28 +00001159 emitSinglePredicateMatch(o, pairs.first, Emitter->PredicateNamespace);
1160 o << " && ";
1161 pairs = pairs.second.split(',');
1162 }
1163 emitSinglePredicateMatch(o, pairs.first, Emitter->PredicateNamespace);
Toma Tabacu3d5ce492015-04-07 12:10:11 +00001164 IsFirstEmission = false;
James Molloy8067df92011-09-07 19:42:28 +00001165 }
Craig Topper664f6a02015-06-02 04:15:57 +00001166 return !Predicates->empty();
Andrew Trick61abca62011-09-08 05:23:14 +00001167}
James Molloy8067df92011-09-07 19:42:28 +00001168
Jim Grosbachecaef492012-08-14 19:06:05 +00001169bool FilterChooser::doesOpcodeNeedPredicate(unsigned Opc) const {
1170 ListInit *Predicates =
1171 AllInstructions[Opc]->TheDef->getValueAsListInit("Predicates");
Craig Topper664f6a02015-06-02 04:15:57 +00001172 for (unsigned i = 0; i < Predicates->size(); ++i) {
Jim Grosbachecaef492012-08-14 19:06:05 +00001173 Record *Pred = Predicates->getElementAsRecord(i);
1174 if (!Pred->getValue("AssemblerMatcherPredicate"))
1175 continue;
1176
1177 std::string P = Pred->getValueAsString("AssemblerCondString");
1178
1179 if (!P.length())
1180 continue;
1181
1182 return true;
1183 }
1184 return false;
1185}
1186
1187unsigned FilterChooser::getPredicateIndex(DecoderTableInfo &TableInfo,
1188 StringRef Predicate) const {
1189 // Using the full predicate string as the key value here is a bit
1190 // heavyweight, but is effective. If the string comparisons become a
1191 // performance concern, we can implement a mangling of the predicate
Nick Lewycky06b0ea22015-08-18 22:41:58 +00001192 // data easily enough with a map back to the actual string. That's
Jim Grosbachecaef492012-08-14 19:06:05 +00001193 // overkill for now, though.
1194
1195 // Make sure the predicate is in the table.
Justin Lebar5e83dfe2016-10-21 21:45:01 +00001196 TableInfo.Predicates.insert(CachedHashString(Predicate));
Jim Grosbachecaef492012-08-14 19:06:05 +00001197 // Now figure out the index for when we write out the table.
Justin Lebar5e83dfe2016-10-21 21:45:01 +00001198 PredicateSet::const_iterator P = find(TableInfo.Predicates, Predicate);
Jim Grosbachecaef492012-08-14 19:06:05 +00001199 return (unsigned)(P - TableInfo.Predicates.begin());
1200}
1201
1202void FilterChooser::emitPredicateTableEntry(DecoderTableInfo &TableInfo,
1203 unsigned Opc) const {
1204 if (!doesOpcodeNeedPredicate(Opc))
1205 return;
1206
1207 // Build up the predicate string.
1208 SmallString<256> Predicate;
1209 // FIXME: emitPredicateMatch() functions can take a buffer directly rather
1210 // than a stream.
1211 raw_svector_ostream PS(Predicate);
1212 unsigned I = 0;
1213 emitPredicateMatch(PS, I, Opc);
1214
1215 // Figure out the index into the predicate table for the predicate just
1216 // computed.
1217 unsigned PIdx = getPredicateIndex(TableInfo, PS.str());
1218 SmallString<16> PBytes;
1219 raw_svector_ostream S(PBytes);
1220 encodeULEB128(PIdx, S);
Jim Grosbachecaef492012-08-14 19:06:05 +00001221
1222 TableInfo.Table.push_back(MCD::OPC_CheckPredicate);
1223 // Predicate index
Craig Topper29688ab2012-08-17 05:42:16 +00001224 for (unsigned i = 0, e = PBytes.size(); i != e; ++i)
Jim Grosbachecaef492012-08-14 19:06:05 +00001225 TableInfo.Table.push_back(PBytes[i]);
1226 // Push location for NumToSkip backpatching.
1227 TableInfo.FixupStack.back().push_back(TableInfo.Table.size());
1228 TableInfo.Table.push_back(0);
1229 TableInfo.Table.push_back(0);
1230}
1231
1232void FilterChooser::emitSoftFailTableEntry(DecoderTableInfo &TableInfo,
1233 unsigned Opc) const {
Jim Grosbach3f4b2392012-02-29 22:07:56 +00001234 BitsInit *SFBits =
1235 AllInstructions[Opc]->TheDef->getValueAsBitsInit("SoftFail");
James Molloyd9ba4fd2012-02-09 10:56:31 +00001236 if (!SFBits) return;
1237 BitsInit *InstBits = AllInstructions[Opc]->TheDef->getValueAsBitsInit("Inst");
1238
1239 APInt PositiveMask(BitWidth, 0ULL);
1240 APInt NegativeMask(BitWidth, 0ULL);
1241 for (unsigned i = 0; i < BitWidth; ++i) {
1242 bit_value_t B = bitFromBits(*SFBits, i);
1243 bit_value_t IB = bitFromBits(*InstBits, i);
1244
1245 if (B != BIT_TRUE) continue;
1246
1247 switch (IB) {
1248 case BIT_FALSE:
1249 // The bit is meant to be false, so emit a check to see if it is true.
1250 PositiveMask.setBit(i);
1251 break;
1252 case BIT_TRUE:
1253 // The bit is meant to be true, so emit a check to see if it is false.
1254 NegativeMask.setBit(i);
1255 break;
1256 default:
1257 // The bit is not set; this must be an error!
1258 StringRef Name = AllInstructions[Opc]->TheDef->getName();
Jim Grosbachecaef492012-08-14 19:06:05 +00001259 errs() << "SoftFail Conflict: bit SoftFail{" << i << "} in " << Name
1260 << " is set but Inst{" << i << "} is unset!\n"
James Molloyd9ba4fd2012-02-09 10:56:31 +00001261 << " - You can only mark a bit as SoftFail if it is fully defined"
1262 << " (1/0 - not '?') in Inst\n";
Jim Grosbachecaef492012-08-14 19:06:05 +00001263 return;
James Molloyd9ba4fd2012-02-09 10:56:31 +00001264 }
1265 }
1266
1267 bool NeedPositiveMask = PositiveMask.getBoolValue();
1268 bool NeedNegativeMask = NegativeMask.getBoolValue();
1269
1270 if (!NeedPositiveMask && !NeedNegativeMask)
1271 return;
1272
Jim Grosbachecaef492012-08-14 19:06:05 +00001273 TableInfo.Table.push_back(MCD::OPC_SoftFail);
James Molloyd9ba4fd2012-02-09 10:56:31 +00001274
Jim Grosbachecaef492012-08-14 19:06:05 +00001275 SmallString<16> MaskBytes;
1276 raw_svector_ostream S(MaskBytes);
1277 if (NeedPositiveMask) {
1278 encodeULEB128(PositiveMask.getZExtValue(), S);
Craig Topper29688ab2012-08-17 05:42:16 +00001279 for (unsigned i = 0, e = MaskBytes.size(); i != e; ++i)
Jim Grosbachecaef492012-08-14 19:06:05 +00001280 TableInfo.Table.push_back(MaskBytes[i]);
1281 } else
1282 TableInfo.Table.push_back(0);
1283 if (NeedNegativeMask) {
1284 MaskBytes.clear();
Jim Grosbachecaef492012-08-14 19:06:05 +00001285 encodeULEB128(NegativeMask.getZExtValue(), S);
Craig Topper29688ab2012-08-17 05:42:16 +00001286 for (unsigned i = 0, e = MaskBytes.size(); i != e; ++i)
Jim Grosbachecaef492012-08-14 19:06:05 +00001287 TableInfo.Table.push_back(MaskBytes[i]);
1288 } else
1289 TableInfo.Table.push_back(0);
James Molloyd9ba4fd2012-02-09 10:56:31 +00001290}
1291
Jim Grosbachecaef492012-08-14 19:06:05 +00001292// Emits table entries to decode the singleton.
1293void FilterChooser::emitSingletonTableEntry(DecoderTableInfo &TableInfo,
1294 unsigned Opc) const {
Owen Anderson4e818902011-02-18 21:51:29 +00001295 std::vector<unsigned> StartBits;
1296 std::vector<unsigned> EndBits;
1297 std::vector<uint64_t> FieldVals;
1298 insn_t Insn;
1299 insnWithID(Insn, Opc);
1300
1301 // Look for islands of undecoded bits of the singleton.
1302 getIslands(StartBits, EndBits, FieldVals, Insn);
1303
1304 unsigned Size = StartBits.size();
Owen Anderson4e818902011-02-18 21:51:29 +00001305
Jim Grosbachecaef492012-08-14 19:06:05 +00001306 // Emit the predicate table entry if one is needed.
1307 emitPredicateTableEntry(TableInfo, Opc);
Owen Anderson4e818902011-02-18 21:51:29 +00001308
Jim Grosbachecaef492012-08-14 19:06:05 +00001309 // Check any additional encoding fields needed.
Craig Topper29688ab2012-08-17 05:42:16 +00001310 for (unsigned I = Size; I != 0; --I) {
1311 unsigned NumBits = EndBits[I-1] - StartBits[I-1] + 1;
Jim Grosbachecaef492012-08-14 19:06:05 +00001312 TableInfo.Table.push_back(MCD::OPC_CheckField);
1313 TableInfo.Table.push_back(StartBits[I-1]);
1314 TableInfo.Table.push_back(NumBits);
1315 uint8_t Buffer[8], *p;
1316 encodeULEB128(FieldVals[I-1], Buffer);
1317 for (p = Buffer; *p >= 128 ; ++p)
1318 TableInfo.Table.push_back(*p);
1319 TableInfo.Table.push_back(*p);
1320 // Push location for NumToSkip backpatching.
1321 TableInfo.FixupStack.back().push_back(TableInfo.Table.size());
1322 // The fixup is always 16-bits, so go ahead and allocate the space
1323 // in the table so all our relative position calculations work OK even
1324 // before we fully resolve the real value here.
1325 TableInfo.Table.push_back(0);
1326 TableInfo.Table.push_back(0);
Owen Anderson4e818902011-02-18 21:51:29 +00001327 }
Owen Anderson4e818902011-02-18 21:51:29 +00001328
Jim Grosbachecaef492012-08-14 19:06:05 +00001329 // Check for soft failure of the match.
1330 emitSoftFailTableEntry(TableInfo, Opc);
Owen Anderson4e818902011-02-18 21:51:29 +00001331
Petr Pavlu182b0572015-07-15 08:04:27 +00001332 bool HasCompleteDecoder;
1333 unsigned DIdx = getDecoderIndex(TableInfo.Decoders, Opc, HasCompleteDecoder);
1334
1335 // Produce OPC_Decode or OPC_TryDecode opcode based on the information
1336 // whether the instruction decoder is complete or not. If it is complete
1337 // then it handles all possible values of remaining variable/unfiltered bits
1338 // and for any value can determine if the bitpattern is a valid instruction
1339 // or not. This means OPC_Decode will be the final step in the decoding
1340 // process. If it is not complete, then the Fail return code from the
1341 // decoder method indicates that additional processing should be done to see
1342 // if there is any other instruction that also matches the bitpattern and
1343 // can decode it.
1344 TableInfo.Table.push_back(HasCompleteDecoder ? MCD::OPC_Decode :
1345 MCD::OPC_TryDecode);
Jim Grosbachecaef492012-08-14 19:06:05 +00001346 uint8_t Buffer[8], *p;
1347 encodeULEB128(Opc, Buffer);
1348 for (p = Buffer; *p >= 128 ; ++p)
1349 TableInfo.Table.push_back(*p);
1350 TableInfo.Table.push_back(*p);
1351
Jim Grosbachecaef492012-08-14 19:06:05 +00001352 SmallString<16> Bytes;
1353 raw_svector_ostream S(Bytes);
1354 encodeULEB128(DIdx, S);
Jim Grosbachecaef492012-08-14 19:06:05 +00001355
1356 // Decoder index
Craig Topper29688ab2012-08-17 05:42:16 +00001357 for (unsigned i = 0, e = Bytes.size(); i != e; ++i)
Jim Grosbachecaef492012-08-14 19:06:05 +00001358 TableInfo.Table.push_back(Bytes[i]);
Petr Pavlu182b0572015-07-15 08:04:27 +00001359
1360 if (!HasCompleteDecoder) {
1361 // Push location for NumToSkip backpatching.
1362 TableInfo.FixupStack.back().push_back(TableInfo.Table.size());
1363 // Allocate the space for the fixup.
1364 TableInfo.Table.push_back(0);
1365 TableInfo.Table.push_back(0);
1366 }
Owen Anderson4e818902011-02-18 21:51:29 +00001367}
1368
Jim Grosbachecaef492012-08-14 19:06:05 +00001369// Emits table entries to decode the singleton, and then to decode the rest.
1370void FilterChooser::emitSingletonTableEntry(DecoderTableInfo &TableInfo,
1371 const Filter &Best) const {
Owen Anderson4e818902011-02-18 21:51:29 +00001372 unsigned Opc = Best.getSingletonOpc();
1373
Jim Grosbachecaef492012-08-14 19:06:05 +00001374 // complex singletons need predicate checks from the first singleton
1375 // to refer forward to the variable filterchooser that follows.
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00001376 TableInfo.FixupStack.emplace_back();
Owen Anderson4e818902011-02-18 21:51:29 +00001377
Jim Grosbachecaef492012-08-14 19:06:05 +00001378 emitSingletonTableEntry(TableInfo, Opc);
Owen Anderson4e818902011-02-18 21:51:29 +00001379
Jim Grosbachecaef492012-08-14 19:06:05 +00001380 resolveTableFixups(TableInfo.Table, TableInfo.FixupStack.back(),
1381 TableInfo.Table.size());
1382 TableInfo.FixupStack.pop_back();
1383
1384 Best.getVariableFC().emitTableEntries(TableInfo);
Owen Anderson4e818902011-02-18 21:51:29 +00001385}
1386
1387// Assign a single filter and run with it. Top level API client can initialize
1388// with a single filter to start the filtering process.
Craig Topper48c112b2012-03-16 05:58:09 +00001389void FilterChooser::runSingleFilter(unsigned startBit, unsigned numBit,
1390 bool mixed) {
Owen Anderson4e818902011-02-18 21:51:29 +00001391 Filters.clear();
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00001392 Filters.emplace_back(*this, startBit, numBit, true);
Owen Anderson4e818902011-02-18 21:51:29 +00001393 BestIndex = 0; // Sole Filter instance to choose from.
1394 bestFilter().recurse();
1395}
1396
1397// reportRegion is a helper function for filterProcessor to mark a region as
1398// eligible for use as a filter region.
1399void FilterChooser::reportRegion(bitAttr_t RA, unsigned StartBit,
Craig Topper82d0d5f2012-03-16 01:19:24 +00001400 unsigned BitIndex, bool AllowMixed) {
Owen Anderson4e818902011-02-18 21:51:29 +00001401 if (RA == ATTR_MIXED && AllowMixed)
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00001402 Filters.emplace_back(*this, StartBit, BitIndex - StartBit, true);
Owen Anderson4e818902011-02-18 21:51:29 +00001403 else if (RA == ATTR_ALL_SET && !AllowMixed)
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00001404 Filters.emplace_back(*this, StartBit, BitIndex - StartBit, false);
Owen Anderson4e818902011-02-18 21:51:29 +00001405}
1406
1407// FilterProcessor scans the well-known encoding bits of the instructions and
1408// builds up a list of candidate filters. It chooses the best filter and
1409// recursively descends down the decoding tree.
1410bool FilterChooser::filterProcessor(bool AllowMixed, bool Greedy) {
1411 Filters.clear();
1412 BestIndex = -1;
1413 unsigned numInstructions = Opcodes.size();
1414
1415 assert(numInstructions && "Filter created with no instructions");
1416
1417 // No further filtering is necessary.
1418 if (numInstructions == 1)
1419 return true;
1420
1421 // Heuristics. See also doFilter()'s "Heuristics" comment when num of
1422 // instructions is 3.
1423 if (AllowMixed && !Greedy) {
1424 assert(numInstructions == 3);
1425
1426 for (unsigned i = 0; i < Opcodes.size(); ++i) {
1427 std::vector<unsigned> StartBits;
1428 std::vector<unsigned> EndBits;
1429 std::vector<uint64_t> FieldVals;
1430 insn_t Insn;
1431
1432 insnWithID(Insn, Opcodes[i]);
1433
1434 // Look for islands of undecoded bits of any instruction.
1435 if (getIslands(StartBits, EndBits, FieldVals, Insn) > 0) {
1436 // Found an instruction with island(s). Now just assign a filter.
Craig Topper48c112b2012-03-16 05:58:09 +00001437 runSingleFilter(StartBits[0], EndBits[0] - StartBits[0] + 1, true);
Owen Anderson4e818902011-02-18 21:51:29 +00001438 return true;
1439 }
1440 }
1441 }
1442
Craig Topper29688ab2012-08-17 05:42:16 +00001443 unsigned BitIndex;
Owen Anderson4e818902011-02-18 21:51:29 +00001444
1445 // We maintain BIT_WIDTH copies of the bitAttrs automaton.
1446 // The automaton consumes the corresponding bit from each
1447 // instruction.
1448 //
1449 // Input symbols: 0, 1, and _ (unset).
1450 // States: NONE, FILTERED, ALL_SET, ALL_UNSET, and MIXED.
1451 // Initial state: NONE.
1452 //
1453 // (NONE) ------- [01] -> (ALL_SET)
1454 // (NONE) ------- _ ----> (ALL_UNSET)
1455 // (ALL_SET) ---- [01] -> (ALL_SET)
1456 // (ALL_SET) ---- _ ----> (MIXED)
1457 // (ALL_UNSET) -- [01] -> (MIXED)
1458 // (ALL_UNSET) -- _ ----> (ALL_UNSET)
1459 // (MIXED) ------ . ----> (MIXED)
1460 // (FILTERED)---- . ----> (FILTERED)
1461
Owen Andersonc78e03c2011-07-19 21:06:00 +00001462 std::vector<bitAttr_t> bitAttrs;
Owen Anderson4e818902011-02-18 21:51:29 +00001463
1464 // FILTERED bit positions provide no entropy and are not worthy of pursuing.
1465 // Filter::recurse() set either BIT_TRUE or BIT_FALSE for each position.
Owen Andersonc78e03c2011-07-19 21:06:00 +00001466 for (BitIndex = 0; BitIndex < BitWidth; ++BitIndex)
Owen Anderson4e818902011-02-18 21:51:29 +00001467 if (FilterBitValues[BitIndex] == BIT_TRUE ||
1468 FilterBitValues[BitIndex] == BIT_FALSE)
Owen Andersonc78e03c2011-07-19 21:06:00 +00001469 bitAttrs.push_back(ATTR_FILTERED);
Owen Anderson4e818902011-02-18 21:51:29 +00001470 else
Owen Andersonc78e03c2011-07-19 21:06:00 +00001471 bitAttrs.push_back(ATTR_NONE);
Owen Anderson4e818902011-02-18 21:51:29 +00001472
Craig Topper29688ab2012-08-17 05:42:16 +00001473 for (unsigned InsnIndex = 0; InsnIndex < numInstructions; ++InsnIndex) {
Owen Anderson4e818902011-02-18 21:51:29 +00001474 insn_t insn;
1475
1476 insnWithID(insn, Opcodes[InsnIndex]);
1477
Owen Andersonc78e03c2011-07-19 21:06:00 +00001478 for (BitIndex = 0; BitIndex < BitWidth; ++BitIndex) {
Owen Anderson4e818902011-02-18 21:51:29 +00001479 switch (bitAttrs[BitIndex]) {
1480 case ATTR_NONE:
1481 if (insn[BitIndex] == BIT_UNSET)
1482 bitAttrs[BitIndex] = ATTR_ALL_UNSET;
1483 else
1484 bitAttrs[BitIndex] = ATTR_ALL_SET;
1485 break;
1486 case ATTR_ALL_SET:
1487 if (insn[BitIndex] == BIT_UNSET)
1488 bitAttrs[BitIndex] = ATTR_MIXED;
1489 break;
1490 case ATTR_ALL_UNSET:
1491 if (insn[BitIndex] != BIT_UNSET)
1492 bitAttrs[BitIndex] = ATTR_MIXED;
1493 break;
1494 case ATTR_MIXED:
1495 case ATTR_FILTERED:
1496 break;
1497 }
1498 }
1499 }
1500
1501 // The regionAttr automaton consumes the bitAttrs automatons' state,
1502 // lowest-to-highest.
1503 //
1504 // Input symbols: F(iltered), (all_)S(et), (all_)U(nset), M(ixed)
1505 // States: NONE, ALL_SET, MIXED
1506 // Initial state: NONE
1507 //
1508 // (NONE) ----- F --> (NONE)
1509 // (NONE) ----- S --> (ALL_SET) ; and set region start
1510 // (NONE) ----- U --> (NONE)
1511 // (NONE) ----- M --> (MIXED) ; and set region start
1512 // (ALL_SET) -- F --> (NONE) ; and report an ALL_SET region
1513 // (ALL_SET) -- S --> (ALL_SET)
1514 // (ALL_SET) -- U --> (NONE) ; and report an ALL_SET region
1515 // (ALL_SET) -- M --> (MIXED) ; and report an ALL_SET region
1516 // (MIXED) ---- F --> (NONE) ; and report a MIXED region
1517 // (MIXED) ---- S --> (ALL_SET) ; and report a MIXED region
1518 // (MIXED) ---- U --> (NONE) ; and report a MIXED region
1519 // (MIXED) ---- M --> (MIXED)
1520
1521 bitAttr_t RA = ATTR_NONE;
1522 unsigned StartBit = 0;
1523
Craig Topper29688ab2012-08-17 05:42:16 +00001524 for (BitIndex = 0; BitIndex < BitWidth; ++BitIndex) {
Owen Anderson4e818902011-02-18 21:51:29 +00001525 bitAttr_t bitAttr = bitAttrs[BitIndex];
1526
1527 assert(bitAttr != ATTR_NONE && "Bit without attributes");
1528
1529 switch (RA) {
1530 case ATTR_NONE:
1531 switch (bitAttr) {
1532 case ATTR_FILTERED:
1533 break;
1534 case ATTR_ALL_SET:
1535 StartBit = BitIndex;
1536 RA = ATTR_ALL_SET;
1537 break;
1538 case ATTR_ALL_UNSET:
1539 break;
1540 case ATTR_MIXED:
1541 StartBit = BitIndex;
1542 RA = ATTR_MIXED;
1543 break;
1544 default:
Craig Topperc4965bc2012-02-05 07:21:30 +00001545 llvm_unreachable("Unexpected bitAttr!");
Owen Anderson4e818902011-02-18 21:51:29 +00001546 }
1547 break;
1548 case ATTR_ALL_SET:
1549 switch (bitAttr) {
1550 case ATTR_FILTERED:
1551 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1552 RA = ATTR_NONE;
1553 break;
1554 case ATTR_ALL_SET:
1555 break;
1556 case ATTR_ALL_UNSET:
1557 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1558 RA = ATTR_NONE;
1559 break;
1560 case ATTR_MIXED:
1561 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1562 StartBit = BitIndex;
1563 RA = ATTR_MIXED;
1564 break;
1565 default:
Craig Topperc4965bc2012-02-05 07:21:30 +00001566 llvm_unreachable("Unexpected bitAttr!");
Owen Anderson4e818902011-02-18 21:51:29 +00001567 }
1568 break;
1569 case ATTR_MIXED:
1570 switch (bitAttr) {
1571 case ATTR_FILTERED:
1572 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1573 StartBit = BitIndex;
1574 RA = ATTR_NONE;
1575 break;
1576 case ATTR_ALL_SET:
1577 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1578 StartBit = BitIndex;
1579 RA = ATTR_ALL_SET;
1580 break;
1581 case ATTR_ALL_UNSET:
1582 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1583 RA = ATTR_NONE;
1584 break;
1585 case ATTR_MIXED:
1586 break;
1587 default:
Craig Topperc4965bc2012-02-05 07:21:30 +00001588 llvm_unreachable("Unexpected bitAttr!");
Owen Anderson4e818902011-02-18 21:51:29 +00001589 }
1590 break;
1591 case ATTR_ALL_UNSET:
Craig Topperc4965bc2012-02-05 07:21:30 +00001592 llvm_unreachable("regionAttr state machine has no ATTR_UNSET state");
Owen Anderson4e818902011-02-18 21:51:29 +00001593 case ATTR_FILTERED:
Craig Topperc4965bc2012-02-05 07:21:30 +00001594 llvm_unreachable("regionAttr state machine has no ATTR_FILTERED state");
Owen Anderson4e818902011-02-18 21:51:29 +00001595 }
1596 }
1597
1598 // At the end, if we're still in ALL_SET or MIXED states, report a region
1599 switch (RA) {
1600 case ATTR_NONE:
1601 break;
1602 case ATTR_FILTERED:
1603 break;
1604 case ATTR_ALL_SET:
1605 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1606 break;
1607 case ATTR_ALL_UNSET:
1608 break;
1609 case ATTR_MIXED:
1610 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1611 break;
1612 }
1613
1614 // We have finished with the filter processings. Now it's time to choose
1615 // the best performing filter.
1616 BestIndex = 0;
1617 bool AllUseless = true;
1618 unsigned BestScore = 0;
1619
1620 for (unsigned i = 0, e = Filters.size(); i != e; ++i) {
1621 unsigned Usefulness = Filters[i].usefulness();
1622
1623 if (Usefulness)
1624 AllUseless = false;
1625
1626 if (Usefulness > BestScore) {
1627 BestIndex = i;
1628 BestScore = Usefulness;
1629 }
1630 }
1631
1632 if (!AllUseless)
1633 bestFilter().recurse();
1634
1635 return !AllUseless;
1636} // end of FilterChooser::filterProcessor(bool)
1637
1638// Decides on the best configuration of filter(s) to use in order to decode
1639// the instructions. A conflict of instructions may occur, in which case we
1640// dump the conflict set to the standard error.
1641void FilterChooser::doFilter() {
1642 unsigned Num = Opcodes.size();
1643 assert(Num && "FilterChooser created with no instructions");
1644
1645 // Try regions of consecutive known bit values first.
1646 if (filterProcessor(false))
1647 return;
1648
1649 // Then regions of mixed bits (both known and unitialized bit values allowed).
1650 if (filterProcessor(true))
1651 return;
1652
1653 // Heuristics to cope with conflict set {t2CMPrs, t2SUBSrr, t2SUBSrs} where
1654 // no single instruction for the maximum ATTR_MIXED region Inst{14-4} has a
1655 // well-known encoding pattern. In such case, we backtrack and scan for the
1656 // the very first consecutive ATTR_ALL_SET region and assign a filter to it.
1657 if (Num == 3 && filterProcessor(true, false))
1658 return;
1659
1660 // If we come to here, the instruction decoding has failed.
1661 // Set the BestIndex to -1 to indicate so.
1662 BestIndex = -1;
1663}
1664
Jim Grosbachecaef492012-08-14 19:06:05 +00001665// emitTableEntries - Emit state machine entries to decode our share of
1666// instructions.
1667void FilterChooser::emitTableEntries(DecoderTableInfo &TableInfo) const {
1668 if (Opcodes.size() == 1) {
Owen Anderson4e818902011-02-18 21:51:29 +00001669 // There is only one instruction in the set, which is great!
1670 // Call emitSingletonDecoder() to see whether there are any remaining
1671 // encodings bits.
Jim Grosbachecaef492012-08-14 19:06:05 +00001672 emitSingletonTableEntry(TableInfo, Opcodes[0]);
1673 return;
1674 }
Owen Anderson4e818902011-02-18 21:51:29 +00001675
1676 // Choose the best filter to do the decodings!
1677 if (BestIndex != -1) {
Craig Topper48c112b2012-03-16 05:58:09 +00001678 const Filter &Best = Filters[BestIndex];
Owen Anderson4e818902011-02-18 21:51:29 +00001679 if (Best.getNumFiltered() == 1)
Jim Grosbachecaef492012-08-14 19:06:05 +00001680 emitSingletonTableEntry(TableInfo, Best);
Owen Anderson4e818902011-02-18 21:51:29 +00001681 else
Jim Grosbachecaef492012-08-14 19:06:05 +00001682 Best.emitTableEntry(TableInfo);
1683 return;
Owen Anderson4e818902011-02-18 21:51:29 +00001684 }
1685
Jim Grosbachecaef492012-08-14 19:06:05 +00001686 // We don't know how to decode these instructions! Dump the
1687 // conflict set and bail.
Owen Anderson4e818902011-02-18 21:51:29 +00001688
1689 // Print out useful conflict information for postmortem analysis.
1690 errs() << "Decoding Conflict:\n";
1691
1692 dumpStack(errs(), "\t\t");
1693
Craig Topper82d0d5f2012-03-16 01:19:24 +00001694 for (unsigned i = 0; i < Opcodes.size(); ++i) {
Owen Anderson4e818902011-02-18 21:51:29 +00001695 const std::string &Name = nameWithID(Opcodes[i]);
1696
1697 errs() << '\t' << Name << " ";
1698 dumpBits(errs(),
1699 getBitsField(*AllInstructions[Opcodes[i]]->TheDef, "Inst"));
1700 errs() << '\n';
1701 }
Owen Anderson4e818902011-02-18 21:51:29 +00001702}
1703
Matt Arsenault4cb438b2016-07-18 23:20:46 +00001704static std::string findOperandDecoderMethod(TypedInit *TI) {
1705 std::string Decoder;
1706
1707 RecordRecTy *Type = cast<RecordRecTy>(TI->getType());
1708 Record *TypeRecord = Type->getRecord();
1709
1710 RecordVal *DecoderString = TypeRecord->getValue("DecoderMethod");
1711 StringInit *String = DecoderString ?
1712 dyn_cast<StringInit>(DecoderString->getValue()) : nullptr;
1713 if (String) {
1714 Decoder = String->getValue();
1715 if (!Decoder.empty())
1716 return Decoder;
1717 }
1718
1719 if (TypeRecord->isSubClassOf("RegisterOperand"))
1720 TypeRecord = TypeRecord->getValueAsDef("RegClass");
1721
1722 if (TypeRecord->isSubClassOf("RegisterClass")) {
1723 Decoder = "Decode" + TypeRecord->getName() + "RegisterClass";
1724 } else if (TypeRecord->isSubClassOf("PointerLikeRegClass")) {
1725 Decoder = "DecodePointerLikeRegClass" +
1726 utostr(TypeRecord->getValueAsInt("RegClassKind"));
1727 }
1728
1729 return Decoder;
1730}
1731
Hal Finkel71b2e202013-12-19 16:12:53 +00001732static bool populateInstruction(CodeGenTarget &Target,
1733 const CodeGenInstruction &CGI, unsigned Opc,
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +00001734 std::map<unsigned, std::vector<OperandInfo>> &Operands){
Owen Anderson4e818902011-02-18 21:51:29 +00001735 const Record &Def = *CGI.TheDef;
1736 // If all the bit positions are not specified; do not decode this instruction.
1737 // We are bound to fail! For proper disassembly, the well-known encoding bits
1738 // of the instruction must be fully specified.
Owen Anderson4e818902011-02-18 21:51:29 +00001739
David Greeneaf8ee2c2011-07-29 22:43:06 +00001740 BitsInit &Bits = getBitsField(Def, "Inst");
Jim Grosbachf3fd36e2011-07-06 21:33:38 +00001741 if (Bits.allInComplete()) return false;
1742
Owen Anderson4e818902011-02-18 21:51:29 +00001743 std::vector<OperandInfo> InsnOperands;
1744
1745 // If the instruction has specified a custom decoding hook, use that instead
1746 // of trying to auto-generate the decoder.
1747 std::string InstDecoder = Def.getValueAsString("DecoderMethod");
1748 if (InstDecoder != "") {
Petr Pavlu182b0572015-07-15 08:04:27 +00001749 bool HasCompleteInstDecoder = Def.getValueAsBit("hasCompleteDecoder");
1750 InsnOperands.push_back(OperandInfo(InstDecoder, HasCompleteInstDecoder));
Owen Anderson4e818902011-02-18 21:51:29 +00001751 Operands[Opc] = InsnOperands;
1752 return true;
1753 }
1754
1755 // Generate a description of the operand of the instruction that we know
1756 // how to decode automatically.
1757 // FIXME: We'll need to have a way to manually override this as needed.
1758
1759 // Gather the outputs/inputs of the instruction, so we can find their
1760 // positions in the encoding. This assumes for now that they appear in the
1761 // MCInst in the order that they're listed.
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +00001762 std::vector<std::pair<Init*, std::string>> InOutOperands;
David Greeneaf8ee2c2011-07-29 22:43:06 +00001763 DagInit *Out = Def.getValueAsDag("OutOperandList");
1764 DagInit *In = Def.getValueAsDag("InOperandList");
Owen Anderson4e818902011-02-18 21:51:29 +00001765 for (unsigned i = 0; i < Out->getNumArgs(); ++i)
1766 InOutOperands.push_back(std::make_pair(Out->getArg(i), Out->getArgName(i)));
1767 for (unsigned i = 0; i < In->getNumArgs(); ++i)
1768 InOutOperands.push_back(std::make_pair(In->getArg(i), In->getArgName(i)));
1769
Owen Anderson53562d02011-07-28 23:56:20 +00001770 // Search for tied operands, so that we can correctly instantiate
1771 // operands that are not explicitly represented in the encoding.
Owen Andersoncb32ce22011-07-29 18:28:52 +00001772 std::map<std::string, std::string> TiedNames;
Owen Anderson53562d02011-07-28 23:56:20 +00001773 for (unsigned i = 0; i < CGI.Operands.size(); ++i) {
1774 int tiedTo = CGI.Operands[i].getTiedRegister();
Owen Andersoncb32ce22011-07-29 18:28:52 +00001775 if (tiedTo != -1) {
Hal Finkel71b2e202013-12-19 16:12:53 +00001776 std::pair<unsigned, unsigned> SO =
1777 CGI.Operands.getSubOperandNumber(tiedTo);
1778 TiedNames[InOutOperands[i].second] = InOutOperands[SO.first].second;
1779 TiedNames[InOutOperands[SO.first].second] = InOutOperands[i].second;
1780 }
1781 }
1782
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +00001783 std::map<std::string, std::vector<OperandInfo>> NumberedInsnOperands;
Hal Finkel71b2e202013-12-19 16:12:53 +00001784 std::set<std::string> NumberedInsnOperandsNoTie;
1785 if (Target.getInstructionSet()->
1786 getValueAsBit("decodePositionallyEncodedOperands")) {
1787 const std::vector<RecordVal> &Vals = Def.getValues();
1788 unsigned NumberedOp = 0;
1789
Hal Finkel5457bd02014-03-13 07:57:54 +00001790 std::set<unsigned> NamedOpIndices;
1791 if (Target.getInstructionSet()->
1792 getValueAsBit("noNamedPositionallyEncodedOperands"))
1793 // Collect the set of operand indices that might correspond to named
1794 // operand, and skip these when assigning operands based on position.
1795 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
1796 unsigned OpIdx;
1797 if (!CGI.Operands.hasOperandNamed(Vals[i].getName(), OpIdx))
1798 continue;
1799
1800 NamedOpIndices.insert(OpIdx);
1801 }
1802
Hal Finkel71b2e202013-12-19 16:12:53 +00001803 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
1804 // Ignore fixed fields in the record, we're looking for values like:
1805 // bits<5> RST = { ?, ?, ?, ?, ? };
1806 if (Vals[i].getPrefix() || Vals[i].getValue()->isComplete())
1807 continue;
1808
1809 // Determine if Vals[i] actually contributes to the Inst encoding.
1810 unsigned bi = 0;
1811 for (; bi < Bits.getNumBits(); ++bi) {
Craig Topper24064772014-04-15 07:20:03 +00001812 VarInit *Var = nullptr;
Hal Finkel71b2e202013-12-19 16:12:53 +00001813 VarBitInit *BI = dyn_cast<VarBitInit>(Bits.getBit(bi));
1814 if (BI)
1815 Var = dyn_cast<VarInit>(BI->getBitVar());
1816 else
1817 Var = dyn_cast<VarInit>(Bits.getBit(bi));
1818
1819 if (Var && Var->getName() == Vals[i].getName())
1820 break;
1821 }
1822
1823 if (bi == Bits.getNumBits())
1824 continue;
1825
1826 // Skip variables that correspond to explicitly-named operands.
1827 unsigned OpIdx;
1828 if (CGI.Operands.hasOperandNamed(Vals[i].getName(), OpIdx))
1829 continue;
1830
1831 // Get the bit range for this operand:
1832 unsigned bitStart = bi++, bitWidth = 1;
1833 for (; bi < Bits.getNumBits(); ++bi) {
Craig Topper24064772014-04-15 07:20:03 +00001834 VarInit *Var = nullptr;
Hal Finkel71b2e202013-12-19 16:12:53 +00001835 VarBitInit *BI = dyn_cast<VarBitInit>(Bits.getBit(bi));
1836 if (BI)
1837 Var = dyn_cast<VarInit>(BI->getBitVar());
1838 else
1839 Var = dyn_cast<VarInit>(Bits.getBit(bi));
1840
1841 if (!Var)
1842 break;
1843
1844 if (Var->getName() != Vals[i].getName())
1845 break;
1846
1847 ++bitWidth;
1848 }
1849
1850 unsigned NumberOps = CGI.Operands.size();
1851 while (NumberedOp < NumberOps &&
Hal Finkel5457bd02014-03-13 07:57:54 +00001852 (CGI.Operands.isFlatOperandNotEmitted(NumberedOp) ||
Alexander Kornienko8c0809c2015-01-15 11:41:30 +00001853 (!NamedOpIndices.empty() && NamedOpIndices.count(
Hal Finkel5457bd02014-03-13 07:57:54 +00001854 CGI.Operands.getSubOperandNumber(NumberedOp).first))))
Hal Finkel71b2e202013-12-19 16:12:53 +00001855 ++NumberedOp;
1856
1857 OpIdx = NumberedOp++;
1858
1859 // OpIdx now holds the ordered operand number of Vals[i].
1860 std::pair<unsigned, unsigned> SO =
1861 CGI.Operands.getSubOperandNumber(OpIdx);
1862 const std::string &Name = CGI.Operands[SO.first].Name;
1863
1864 DEBUG(dbgs() << "Numbered operand mapping for " << Def.getName() << ": " <<
1865 Name << "(" << SO.first << ", " << SO.second << ") => " <<
1866 Vals[i].getName() << "\n");
1867
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +00001868 std::string Decoder;
Hal Finkel71b2e202013-12-19 16:12:53 +00001869 Record *TypeRecord = CGI.Operands[SO.first].Rec;
1870
1871 RecordVal *DecoderString = TypeRecord->getValue("DecoderMethod");
1872 StringInit *String = DecoderString ?
Craig Topper24064772014-04-15 07:20:03 +00001873 dyn_cast<StringInit>(DecoderString->getValue()) : nullptr;
Hal Finkel71b2e202013-12-19 16:12:53 +00001874 if (String && String->getValue() != "")
1875 Decoder = String->getValue();
1876
1877 if (Decoder == "" &&
1878 CGI.Operands[SO.first].MIOperandInfo &&
1879 CGI.Operands[SO.first].MIOperandInfo->getNumArgs()) {
1880 Init *Arg = CGI.Operands[SO.first].MIOperandInfo->
1881 getArg(SO.second);
1882 if (TypedInit *TI = cast<TypedInit>(Arg)) {
1883 RecordRecTy *Type = cast<RecordRecTy>(TI->getType());
1884 TypeRecord = Type->getRecord();
1885 }
1886 }
1887
1888 bool isReg = false;
1889 if (TypeRecord->isSubClassOf("RegisterOperand"))
1890 TypeRecord = TypeRecord->getValueAsDef("RegClass");
1891 if (TypeRecord->isSubClassOf("RegisterClass")) {
1892 Decoder = "Decode" + TypeRecord->getName() + "RegisterClass";
1893 isReg = true;
1894 } else if (TypeRecord->isSubClassOf("PointerLikeRegClass")) {
1895 Decoder = "DecodePointerLikeRegClass" +
1896 utostr(TypeRecord->getValueAsInt("RegClassKind"));
1897 isReg = true;
1898 }
1899
1900 DecoderString = TypeRecord->getValue("DecoderMethod");
1901 String = DecoderString ?
Craig Topper24064772014-04-15 07:20:03 +00001902 dyn_cast<StringInit>(DecoderString->getValue()) : nullptr;
Hal Finkel71b2e202013-12-19 16:12:53 +00001903 if (!isReg && String && String->getValue() != "")
1904 Decoder = String->getValue();
1905
Petr Pavlu182b0572015-07-15 08:04:27 +00001906 RecordVal *HasCompleteDecoderVal =
1907 TypeRecord->getValue("hasCompleteDecoder");
1908 BitInit *HasCompleteDecoderBit = HasCompleteDecoderVal ?
1909 dyn_cast<BitInit>(HasCompleteDecoderVal->getValue()) : nullptr;
1910 bool HasCompleteDecoder = HasCompleteDecoderBit ?
1911 HasCompleteDecoderBit->getValue() : true;
1912
1913 OperandInfo OpInfo(Decoder, HasCompleteDecoder);
Hal Finkel71b2e202013-12-19 16:12:53 +00001914 OpInfo.addField(bitStart, bitWidth, 0);
1915
1916 NumberedInsnOperands[Name].push_back(OpInfo);
1917
1918 // FIXME: For complex operands with custom decoders we can't handle tied
1919 // sub-operands automatically. Skip those here and assume that this is
1920 // fixed up elsewhere.
1921 if (CGI.Operands[SO.first].MIOperandInfo &&
1922 CGI.Operands[SO.first].MIOperandInfo->getNumArgs() > 1 &&
1923 String && String->getValue() != "")
1924 NumberedInsnOperandsNoTie.insert(Name);
Owen Andersoncb32ce22011-07-29 18:28:52 +00001925 }
Owen Anderson53562d02011-07-28 23:56:20 +00001926 }
1927
Owen Anderson4e818902011-02-18 21:51:29 +00001928 // For each operand, see if we can figure out where it is encoded.
Craig Topper1f7604d2014-12-13 05:12:19 +00001929 for (const auto &Op : InOutOperands) {
1930 if (!NumberedInsnOperands[Op.second].empty()) {
Hal Finkel71b2e202013-12-19 16:12:53 +00001931 InsnOperands.insert(InsnOperands.end(),
Craig Topper1f7604d2014-12-13 05:12:19 +00001932 NumberedInsnOperands[Op.second].begin(),
1933 NumberedInsnOperands[Op.second].end());
Hal Finkel71b2e202013-12-19 16:12:53 +00001934 continue;
Craig Topper1f7604d2014-12-13 05:12:19 +00001935 }
1936 if (!NumberedInsnOperands[TiedNames[Op.second]].empty()) {
1937 if (!NumberedInsnOperandsNoTie.count(TiedNames[Op.second])) {
Hal Finkel71b2e202013-12-19 16:12:53 +00001938 // Figure out to which (sub)operand we're tied.
Craig Topper1f7604d2014-12-13 05:12:19 +00001939 unsigned i = CGI.Operands.getOperandNamed(TiedNames[Op.second]);
Hal Finkel71b2e202013-12-19 16:12:53 +00001940 int tiedTo = CGI.Operands[i].getTiedRegister();
1941 if (tiedTo == -1) {
Craig Topper1f7604d2014-12-13 05:12:19 +00001942 i = CGI.Operands.getOperandNamed(Op.second);
Hal Finkel71b2e202013-12-19 16:12:53 +00001943 tiedTo = CGI.Operands[i].getTiedRegister();
1944 }
1945
1946 if (tiedTo != -1) {
1947 std::pair<unsigned, unsigned> SO =
1948 CGI.Operands.getSubOperandNumber(tiedTo);
1949
Craig Topper1f7604d2014-12-13 05:12:19 +00001950 InsnOperands.push_back(NumberedInsnOperands[TiedNames[Op.second]]
Hal Finkel71b2e202013-12-19 16:12:53 +00001951 [SO.second]);
1952 }
1953 }
1954 continue;
1955 }
1956
Craig Topper1f7604d2014-12-13 05:12:19 +00001957 TypedInit *TI = cast<TypedInit>(Op.first);
Owen Andersone3591652011-07-28 21:54:31 +00001958
Matt Arsenault4cb438b2016-07-18 23:20:46 +00001959 // At this point, we can locate the decoder field, but we need to know how
1960 // to interpret it. As a first step, require the target to provide
1961 // callbacks for decoding register classes.
1962 std::string Decoder = findOperandDecoderMethod(TI);
1963 Record *TypeRecord = cast<RecordRecTy>(TI->getType())->getRecord();
Owen Andersone3591652011-07-28 21:54:31 +00001964
Petr Pavlu182b0572015-07-15 08:04:27 +00001965 RecordVal *HasCompleteDecoderVal =
1966 TypeRecord->getValue("hasCompleteDecoder");
1967 BitInit *HasCompleteDecoderBit = HasCompleteDecoderVal ?
1968 dyn_cast<BitInit>(HasCompleteDecoderVal->getValue()) : nullptr;
1969 bool HasCompleteDecoder = HasCompleteDecoderBit ?
1970 HasCompleteDecoderBit->getValue() : true;
1971
1972 OperandInfo OpInfo(Decoder, HasCompleteDecoder);
Owen Andersone3591652011-07-28 21:54:31 +00001973 unsigned Base = ~0U;
1974 unsigned Width = 0;
1975 unsigned Offset = 0;
1976
Owen Anderson4e818902011-02-18 21:51:29 +00001977 for (unsigned bi = 0; bi < Bits.getNumBits(); ++bi) {
Craig Topper24064772014-04-15 07:20:03 +00001978 VarInit *Var = nullptr;
Sean Silvafb509ed2012-10-10 20:24:43 +00001979 VarBitInit *BI = dyn_cast<VarBitInit>(Bits.getBit(bi));
Owen Anderson3022d672011-08-01 22:45:43 +00001980 if (BI)
Sean Silvafb509ed2012-10-10 20:24:43 +00001981 Var = dyn_cast<VarInit>(BI->getBitVar());
Owen Anderson3022d672011-08-01 22:45:43 +00001982 else
Sean Silvafb509ed2012-10-10 20:24:43 +00001983 Var = dyn_cast<VarInit>(Bits.getBit(bi));
Owen Anderson3022d672011-08-01 22:45:43 +00001984
1985 if (!Var) {
Owen Andersone3591652011-07-28 21:54:31 +00001986 if (Base != ~0U) {
1987 OpInfo.addField(Base, Width, Offset);
1988 Base = ~0U;
1989 Width = 0;
1990 Offset = 0;
1991 }
1992 continue;
1993 }
Owen Anderson4e818902011-02-18 21:51:29 +00001994
Craig Topper1f7604d2014-12-13 05:12:19 +00001995 if (Var->getName() != Op.second &&
1996 Var->getName() != TiedNames[Op.second]) {
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;
Owen Anderson4e818902011-02-18 21:51:29 +00002004 }
2005
Owen Andersone3591652011-07-28 21:54:31 +00002006 if (Base == ~0U) {
2007 Base = bi;
2008 Width = 1;
Owen Anderson3022d672011-08-01 22:45:43 +00002009 Offset = BI ? BI->getBitNum() : 0;
2010 } else if (BI && BI->getBitNum() != Offset + Width) {
Owen Andersone08f5b52011-07-29 23:01:18 +00002011 OpInfo.addField(Base, Width, Offset);
2012 Base = bi;
2013 Width = 1;
2014 Offset = BI->getBitNum();
Owen Andersone3591652011-07-28 21:54:31 +00002015 } else {
2016 ++Width;
Owen Anderson4e818902011-02-18 21:51:29 +00002017 }
Owen Anderson4e818902011-02-18 21:51:29 +00002018 }
2019
Owen Andersone3591652011-07-28 21:54:31 +00002020 if (Base != ~0U)
2021 OpInfo.addField(Base, Width, Offset);
2022
2023 if (OpInfo.numFields() > 0)
2024 InsnOperands.push_back(OpInfo);
Owen Anderson4e818902011-02-18 21:51:29 +00002025 }
2026
2027 Operands[Opc] = InsnOperands;
2028
Owen Anderson4e818902011-02-18 21:51:29 +00002029#if 0
2030 DEBUG({
2031 // Dumps the instruction encoding bits.
2032 dumpBits(errs(), Bits);
2033
2034 errs() << '\n';
2035
2036 // Dumps the list of operand info.
2037 for (unsigned i = 0, e = CGI.Operands.size(); i != e; ++i) {
2038 const CGIOperandList::OperandInfo &Info = CGI.Operands[i];
2039 const std::string &OperandName = Info.Name;
2040 const Record &OperandDef = *Info.Rec;
2041
2042 errs() << "\t" << OperandName << " (" << OperandDef.getName() << ")\n";
2043 }
2044 });
2045#endif
2046
2047 return true;
2048}
2049
Jim Grosbachecaef492012-08-14 19:06:05 +00002050// emitFieldFromInstruction - Emit the templated helper function
2051// fieldFromInstruction().
2052static void emitFieldFromInstruction(formatted_raw_ostream &OS) {
2053 OS << "// Helper function for extracting fields from encoded instructions.\n"
2054 << "template<typename InsnType>\n"
2055 << "static InsnType fieldFromInstruction(InsnType insn, unsigned startBit,\n"
2056 << " unsigned numBits) {\n"
2057 << " assert(startBit + numBits <= (sizeof(InsnType)*8) &&\n"
2058 << " \"Instruction field out of bounds!\");\n"
2059 << " InsnType fieldMask;\n"
2060 << " if (numBits == sizeof(InsnType)*8)\n"
2061 << " fieldMask = (InsnType)(-1LL);\n"
2062 << " else\n"
NAKAMURA Takumibf99a422012-12-26 06:43:14 +00002063 << " fieldMask = (((InsnType)1 << numBits) - 1) << startBit;\n"
Jim Grosbachecaef492012-08-14 19:06:05 +00002064 << " return (insn & fieldMask) >> startBit;\n"
2065 << "}\n\n";
2066}
Owen Anderson4e818902011-02-18 21:51:29 +00002067
Jim Grosbachecaef492012-08-14 19:06:05 +00002068// emitDecodeInstruction - Emit the templated helper function
2069// decodeInstruction().
2070static void emitDecodeInstruction(formatted_raw_ostream &OS) {
2071 OS << "template<typename InsnType>\n"
2072 << "static DecodeStatus decodeInstruction(const uint8_t DecodeTable[], MCInst &MI,\n"
2073 << " InsnType insn, uint64_t Address,\n"
2074 << " const void *DisAsm,\n"
2075 << " const MCSubtargetInfo &STI) {\n"
Michael Kupersteindb0712f2015-05-26 10:47:10 +00002076 << " const FeatureBitset& Bits = STI.getFeatureBits();\n"
Jim Grosbachecaef492012-08-14 19:06:05 +00002077 << "\n"
2078 << " const uint8_t *Ptr = DecodeTable;\n"
Jim Grosbach4c363492012-09-17 18:00:53 +00002079 << " uint32_t CurFieldValue = 0;\n"
Jim Grosbachecaef492012-08-14 19:06:05 +00002080 << " DecodeStatus S = MCDisassembler::Success;\n"
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +00002081 << " while (true) {\n"
Jim Grosbachecaef492012-08-14 19:06:05 +00002082 << " ptrdiff_t Loc = Ptr - DecodeTable;\n"
2083 << " switch (*Ptr) {\n"
2084 << " default:\n"
2085 << " errs() << Loc << \": Unexpected decode table opcode!\\n\";\n"
2086 << " return MCDisassembler::Fail;\n"
2087 << " case MCD::OPC_ExtractField: {\n"
2088 << " unsigned Start = *++Ptr;\n"
2089 << " unsigned Len = *++Ptr;\n"
2090 << " ++Ptr;\n"
2091 << " CurFieldValue = fieldFromInstruction(insn, Start, Len);\n"
2092 << " DEBUG(dbgs() << Loc << \": OPC_ExtractField(\" << Start << \", \"\n"
2093 << " << Len << \"): \" << CurFieldValue << \"\\n\");\n"
2094 << " break;\n"
2095 << " }\n"
2096 << " case MCD::OPC_FilterValue: {\n"
2097 << " // Decode the field value.\n"
2098 << " unsigned Len;\n"
2099 << " InsnType Val = decodeULEB128(++Ptr, &Len);\n"
2100 << " Ptr += Len;\n"
2101 << " // NumToSkip is a plain 16-bit integer.\n"
2102 << " unsigned NumToSkip = *Ptr++;\n"
2103 << " NumToSkip |= (*Ptr++) << 8;\n"
2104 << "\n"
2105 << " // Perform the filter operation.\n"
2106 << " if (Val != CurFieldValue)\n"
2107 << " Ptr += NumToSkip;\n"
2108 << " DEBUG(dbgs() << Loc << \": OPC_FilterValue(\" << Val << \", \" << NumToSkip\n"
2109 << " << \"): \" << ((Val != CurFieldValue) ? \"FAIL:\" : \"PASS:\")\n"
2110 << " << \" continuing at \" << (Ptr - DecodeTable) << \"\\n\");\n"
2111 << "\n"
2112 << " break;\n"
2113 << " }\n"
2114 << " case MCD::OPC_CheckField: {\n"
2115 << " unsigned Start = *++Ptr;\n"
2116 << " unsigned Len = *++Ptr;\n"
2117 << " InsnType FieldValue = fieldFromInstruction(insn, Start, Len);\n"
2118 << " // Decode the field value.\n"
2119 << " uint32_t ExpectedValue = decodeULEB128(++Ptr, &Len);\n"
2120 << " Ptr += Len;\n"
2121 << " // NumToSkip is a plain 16-bit integer.\n"
2122 << " unsigned NumToSkip = *Ptr++;\n"
2123 << " NumToSkip |= (*Ptr++) << 8;\n"
2124 << "\n"
2125 << " // If the actual and expected values don't match, skip.\n"
2126 << " if (ExpectedValue != FieldValue)\n"
2127 << " Ptr += NumToSkip;\n"
2128 << " DEBUG(dbgs() << Loc << \": OPC_CheckField(\" << Start << \", \"\n"
2129 << " << Len << \", \" << ExpectedValue << \", \" << NumToSkip\n"
2130 << " << \"): FieldValue = \" << FieldValue << \", ExpectedValue = \"\n"
2131 << " << ExpectedValue << \": \"\n"
2132 << " << ((ExpectedValue == FieldValue) ? \"PASS\\n\" : \"FAIL\\n\"));\n"
2133 << " break;\n"
2134 << " }\n"
2135 << " case MCD::OPC_CheckPredicate: {\n"
2136 << " unsigned Len;\n"
2137 << " // Decode the Predicate Index value.\n"
2138 << " unsigned PIdx = decodeULEB128(++Ptr, &Len);\n"
2139 << " Ptr += Len;\n"
2140 << " // NumToSkip is a plain 16-bit integer.\n"
2141 << " unsigned NumToSkip = *Ptr++;\n"
2142 << " NumToSkip |= (*Ptr++) << 8;\n"
2143 << " // Check the predicate.\n"
2144 << " bool Pred;\n"
2145 << " if (!(Pred = checkDecoderPredicate(PIdx, Bits)))\n"
2146 << " Ptr += NumToSkip;\n"
2147 << " (void)Pred;\n"
2148 << " DEBUG(dbgs() << Loc << \": OPC_CheckPredicate(\" << PIdx << \"): \"\n"
2149 << " << (Pred ? \"PASS\\n\" : \"FAIL\\n\"));\n"
2150 << "\n"
2151 << " break;\n"
2152 << " }\n"
2153 << " case MCD::OPC_Decode: {\n"
2154 << " unsigned Len;\n"
2155 << " // Decode the Opcode value.\n"
2156 << " unsigned Opc = decodeULEB128(++Ptr, &Len);\n"
2157 << " Ptr += Len;\n"
2158 << " unsigned DecodeIdx = decodeULEB128(Ptr, &Len);\n"
2159 << " Ptr += Len;\n"
Jim Grosbachecaef492012-08-14 19:06:05 +00002160 << "\n"
Cameron Esfahanif97999d2015-08-11 01:15:07 +00002161 << " MI.clear();\n"
Jim Grosbachecaef492012-08-14 19:06:05 +00002162 << " MI.setOpcode(Opc);\n"
Petr Pavlu182b0572015-07-15 08:04:27 +00002163 << " bool DecodeComplete;\n"
2164 << " S = decodeToMCInst(S, DecodeIdx, insn, MI, Address, DisAsm, DecodeComplete);\n"
2165 << " assert(DecodeComplete);\n"
2166 << "\n"
2167 << " DEBUG(dbgs() << Loc << \": OPC_Decode: opcode \" << Opc\n"
2168 << " << \", using decoder \" << DecodeIdx << \": \"\n"
2169 << " << (S != MCDisassembler::Fail ? \"PASS\" : \"FAIL\") << \"\\n\");\n"
2170 << " return S;\n"
2171 << " }\n"
2172 << " case MCD::OPC_TryDecode: {\n"
2173 << " unsigned Len;\n"
2174 << " // Decode the Opcode value.\n"
2175 << " unsigned Opc = decodeULEB128(++Ptr, &Len);\n"
2176 << " Ptr += Len;\n"
2177 << " unsigned DecodeIdx = decodeULEB128(Ptr, &Len);\n"
2178 << " Ptr += Len;\n"
2179 << " // NumToSkip is a plain 16-bit integer.\n"
2180 << " unsigned NumToSkip = *Ptr++;\n"
2181 << " NumToSkip |= (*Ptr++) << 8;\n"
2182 << "\n"
2183 << " // Perform the decode operation.\n"
2184 << " MCInst TmpMI;\n"
2185 << " TmpMI.setOpcode(Opc);\n"
2186 << " bool DecodeComplete;\n"
2187 << " S = decodeToMCInst(S, DecodeIdx, insn, TmpMI, Address, DisAsm, DecodeComplete);\n"
2188 << " DEBUG(dbgs() << Loc << \": OPC_TryDecode: opcode \" << Opc\n"
2189 << " << \", using decoder \" << DecodeIdx << \": \");\n"
2190 << "\n"
2191 << " if (DecodeComplete) {\n"
2192 << " // Decoding complete.\n"
2193 << " DEBUG(dbgs() << (S != MCDisassembler::Fail ? \"PASS\" : \"FAIL\") << \"\\n\");\n"
2194 << " MI = TmpMI;\n"
2195 << " return S;\n"
2196 << " } else {\n"
2197 << " assert(S == MCDisassembler::Fail);\n"
2198 << " // If the decoding was incomplete, skip.\n"
2199 << " Ptr += NumToSkip;\n"
2200 << " DEBUG(dbgs() << \"FAIL: continuing at \" << (Ptr - DecodeTable) << \"\\n\");\n"
2201 << " // Reset decode status. This also drops a SoftFail status that could be\n"
2202 << " // set before the decode attempt.\n"
2203 << " S = MCDisassembler::Success;\n"
2204 << " }\n"
2205 << " break;\n"
Jim Grosbachecaef492012-08-14 19:06:05 +00002206 << " }\n"
2207 << " case MCD::OPC_SoftFail: {\n"
2208 << " // Decode the mask values.\n"
2209 << " unsigned Len;\n"
2210 << " InsnType PositiveMask = decodeULEB128(++Ptr, &Len);\n"
2211 << " Ptr += Len;\n"
2212 << " InsnType NegativeMask = decodeULEB128(Ptr, &Len);\n"
2213 << " Ptr += Len;\n"
2214 << " bool Fail = (insn & PositiveMask) || (~insn & NegativeMask);\n"
2215 << " if (Fail)\n"
2216 << " S = MCDisassembler::SoftFail;\n"
2217 << " DEBUG(dbgs() << Loc << \": OPC_SoftFail: \" << (Fail ? \"FAIL\\n\":\"PASS\\n\"));\n"
2218 << " break;\n"
2219 << " }\n"
2220 << " case MCD::OPC_Fail: {\n"
2221 << " DEBUG(dbgs() << Loc << \": OPC_Fail\\n\");\n"
2222 << " return MCDisassembler::Fail;\n"
2223 << " }\n"
2224 << " }\n"
2225 << " }\n"
2226 << " llvm_unreachable(\"bogosity detected in disassembler state machine!\");\n"
2227 << "}\n\n";
Owen Anderson4e818902011-02-18 21:51:29 +00002228}
2229
2230// Emits disassembler code for instruction decoding.
Craig Topper82d0d5f2012-03-16 01:19:24 +00002231void FixedLenDecoderEmitter::run(raw_ostream &o) {
Jim Grosbachecaef492012-08-14 19:06:05 +00002232 formatted_raw_ostream OS(o);
2233 OS << "#include \"llvm/MC/MCInst.h\"\n";
2234 OS << "#include \"llvm/Support/Debug.h\"\n";
2235 OS << "#include \"llvm/Support/DataTypes.h\"\n";
2236 OS << "#include \"llvm/Support/LEB128.h\"\n";
2237 OS << "#include \"llvm/Support/raw_ostream.h\"\n";
2238 OS << "#include <assert.h>\n";
2239 OS << '\n';
2240 OS << "namespace llvm {\n\n";
2241
2242 emitFieldFromInstruction(OS);
Owen Anderson4e818902011-02-18 21:51:29 +00002243
Hal Finkel81e6fcc2013-12-17 22:37:50 +00002244 Target.reverseBitsForLittleEndianEncoding();
2245
Owen Andersonc78e03c2011-07-19 21:06:00 +00002246 // Parameterize the decoders based on namespace and instruction width.
Craig Topperf9265322016-01-17 20:38:14 +00002247 NumberedInstructions = Target.getInstructionsByEnumValue();
Owen Andersonc78e03c2011-07-19 21:06:00 +00002248 std::map<std::pair<std::string, unsigned>,
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +00002249 std::vector<unsigned>> OpcMap;
2250 std::map<unsigned, std::vector<OperandInfo>> Operands;
Owen Andersonc78e03c2011-07-19 21:06:00 +00002251
Craig Topperf9265322016-01-17 20:38:14 +00002252 for (unsigned i = 0; i < NumberedInstructions.size(); ++i) {
2253 const CodeGenInstruction *Inst = NumberedInstructions[i];
Craig Topper48c112b2012-03-16 05:58:09 +00002254 const Record *Def = Inst->TheDef;
Owen Andersonc78e03c2011-07-19 21:06:00 +00002255 unsigned Size = Def->getValueAsInt("Size");
2256 if (Def->getValueAsString("Namespace") == "TargetOpcode" ||
2257 Def->getValueAsBit("isPseudo") ||
2258 Def->getValueAsBit("isAsmParserOnly") ||
2259 Def->getValueAsBit("isCodeGenOnly"))
2260 continue;
2261
2262 std::string DecoderNamespace = Def->getValueAsString("DecoderNamespace");
2263
2264 if (Size) {
Hal Finkel71b2e202013-12-19 16:12:53 +00002265 if (populateInstruction(Target, *Inst, i, Operands)) {
Owen Andersonc78e03c2011-07-19 21:06:00 +00002266 OpcMap[std::make_pair(DecoderNamespace, Size)].push_back(i);
2267 }
2268 }
2269 }
2270
Jim Grosbachecaef492012-08-14 19:06:05 +00002271 DecoderTableInfo TableInfo;
Craig Topper1f7604d2014-12-13 05:12:19 +00002272 for (const auto &Opc : OpcMap) {
Owen Andersonc78e03c2011-07-19 21:06:00 +00002273 // Emit the decoder for this namespace+width combination.
Craig Topperf9265322016-01-17 20:38:14 +00002274 FilterChooser FC(NumberedInstructions, Opc.second, Operands,
Craig Topper1f7604d2014-12-13 05:12:19 +00002275 8*Opc.first.second, this);
Jim Grosbachecaef492012-08-14 19:06:05 +00002276
2277 // The decode table is cleared for each top level decoder function. The
2278 // predicates and decoders themselves, however, are shared across all
2279 // decoders to give more opportunities for uniqueing.
2280 TableInfo.Table.clear();
2281 TableInfo.FixupStack.clear();
2282 TableInfo.Table.reserve(16384);
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00002283 TableInfo.FixupStack.emplace_back();
Jim Grosbachecaef492012-08-14 19:06:05 +00002284 FC.emitTableEntries(TableInfo);
2285 // Any NumToSkip fixups in the top level scope can resolve to the
2286 // OPC_Fail at the end of the table.
2287 assert(TableInfo.FixupStack.size() == 1 && "fixup stack phasing error!");
2288 // Resolve any NumToSkip fixups in the current scope.
2289 resolveTableFixups(TableInfo.Table, TableInfo.FixupStack.back(),
2290 TableInfo.Table.size());
2291 TableInfo.FixupStack.clear();
2292
2293 TableInfo.Table.push_back(MCD::OPC_Fail);
2294
2295 // Print the table to the output stream.
Craig Topper1f7604d2014-12-13 05:12:19 +00002296 emitTable(OS, TableInfo.Table, 0, FC.getBitWidth(), Opc.first.first);
Jim Grosbachecaef492012-08-14 19:06:05 +00002297 OS.flush();
Owen Andersonc78e03c2011-07-19 21:06:00 +00002298 }
Owen Anderson4e818902011-02-18 21:51:29 +00002299
Jim Grosbachecaef492012-08-14 19:06:05 +00002300 // Emit the predicate function.
2301 emitPredicateFunction(OS, TableInfo.Predicates, 0);
2302
2303 // Emit the decoder function.
2304 emitDecoderFunction(OS, TableInfo.Decoders, 0);
2305
2306 // Emit the main entry point for the decoder, decodeInstruction().
2307 emitDecodeInstruction(OS);
2308
2309 OS << "\n} // End llvm namespace\n";
Owen Anderson4e818902011-02-18 21:51:29 +00002310}
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +00002311
2312namespace llvm {
2313
2314void EmitFixedLenDecoder(RecordKeeper &RK, raw_ostream &OS,
Benjamin Kramerc321e532016-06-08 19:09:22 +00002315 const std::string &PredicateNamespace,
2316 const std::string &GPrefix,
2317 const std::string &GPostfix, const std::string &ROK,
2318 const std::string &RFail, const std::string &L) {
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +00002319 FixedLenDecoderEmitter(RK, PredicateNamespace, GPrefix, GPostfix,
2320 ROK, RFail, L).run(OS);
2321}
2322
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +00002323} // end namespace llvm