blob: 27114cba5e5460d562c846b47bff532000782423 [file] [log] [blame]
Owen Anderson4e818902011-02-18 21:51:29 +00001//===------------ FixedLenDecoderEmitter.cpp - Decoder Generator ----------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// It contains the tablegen backend that emits the decoder functions for
11// targets with fixed length instruction set.
12//
13//===----------------------------------------------------------------------===//
14
Owen Anderson4e818902011-02-18 21:51:29 +000015#include "CodeGenTarget.h"
James Molloyd9ba4fd2012-02-09 10:56:31 +000016#include "llvm/ADT/APInt.h"
Jim Grosbachecaef492012-08-14 19:06:05 +000017#include "llvm/ADT/SmallString.h"
Owen Anderson4e818902011-02-18 21:51:29 +000018#include "llvm/ADT/StringExtras.h"
Jim Grosbachecaef492012-08-14 19:06:05 +000019#include "llvm/ADT/StringRef.h"
20#include "llvm/ADT/Twine.h"
21#include "llvm/MC/MCFixedLenDisassembler.h"
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +000022#include "llvm/Support/DataTypes.h"
Owen Anderson4e818902011-02-18 21:51:29 +000023#include "llvm/Support/Debug.h"
Jim Grosbachecaef492012-08-14 19:06:05 +000024#include "llvm/Support/FormattedStream.h"
25#include "llvm/Support/LEB128.h"
Owen Anderson4e818902011-02-18 21:51:29 +000026#include "llvm/Support/raw_ostream.h"
Chandler Carruth91d19d82012-12-04 10:37:14 +000027#include "llvm/TableGen/Error.h"
28#include "llvm/TableGen/Record.h"
Owen Anderson4e818902011-02-18 21:51:29 +000029#include <map>
30#include <string>
Chandler Carruth91d19d82012-12-04 10:37:14 +000031#include <vector>
Owen Anderson4e818902011-02-18 21:51:29 +000032
33using namespace llvm;
34
Chandler Carruth97acce22014-04-22 03:06:00 +000035#define DEBUG_TYPE "decoder-emitter"
36
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +000037namespace {
38struct EncodingField {
39 unsigned Base, Width, Offset;
40 EncodingField(unsigned B, unsigned W, unsigned O)
41 : Base(B), Width(W), Offset(O) { }
42};
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +000043
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +000044struct OperandInfo {
45 std::vector<EncodingField> Fields;
46 std::string Decoder;
47
48 OperandInfo(std::string D)
49 : Decoder(D) { }
50
51 void addField(unsigned Base, unsigned Width, unsigned Offset) {
52 Fields.push_back(EncodingField(Base, Width, Offset));
53 }
54
55 unsigned numFields() const { return Fields.size(); }
56
57 typedef std::vector<EncodingField>::const_iterator const_iterator;
58
59 const_iterator begin() const { return Fields.begin(); }
60 const_iterator end() const { return Fields.end(); }
61};
Jim Grosbachecaef492012-08-14 19:06:05 +000062
63typedef std::vector<uint8_t> DecoderTable;
64typedef uint32_t DecoderFixup;
65typedef std::vector<DecoderFixup> FixupList;
66typedef std::vector<FixupList> FixupScopeList;
67typedef SetVector<std::string> PredicateSet;
68typedef SetVector<std::string> DecoderSet;
69struct DecoderTableInfo {
70 DecoderTable Table;
71 FixupScopeList FixupStack;
72 PredicateSet Predicates;
73 DecoderSet Decoders;
74};
75
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +000076} // End anonymous namespace
77
78namespace {
79class FixedLenDecoderEmitter {
Jim Grosbachecaef492012-08-14 19:06:05 +000080 const std::vector<const CodeGenInstruction*> *NumberedInstructions;
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +000081public:
82
83 // Defaults preserved here for documentation, even though they aren't
84 // strictly necessary given the way that this is currently being called.
85 FixedLenDecoderEmitter(RecordKeeper &R,
86 std::string PredicateNamespace,
87 std::string GPrefix = "if (",
88 std::string GPostfix = " == MCDisassembler::Fail)"
89 " return MCDisassembler::Fail;",
90 std::string ROK = "MCDisassembler::Success",
91 std::string RFail = "MCDisassembler::Fail",
92 std::string L = "") :
93 Target(R),
94 PredicateNamespace(PredicateNamespace),
95 GuardPrefix(GPrefix), GuardPostfix(GPostfix),
96 ReturnOK(ROK), ReturnFail(RFail), Locals(L) {}
97
Jim Grosbachecaef492012-08-14 19:06:05 +000098 // Emit the decoder state machine table.
99 void emitTable(formatted_raw_ostream &o, DecoderTable &Table,
100 unsigned Indentation, unsigned BitWidth,
101 StringRef Namespace) const;
102 void emitPredicateFunction(formatted_raw_ostream &OS,
103 PredicateSet &Predicates,
104 unsigned Indentation) const;
105 void emitDecoderFunction(formatted_raw_ostream &OS,
106 DecoderSet &Decoders,
107 unsigned Indentation) const;
108
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +0000109 // run - Output the code emitter
110 void run(raw_ostream &o);
111
112private:
113 CodeGenTarget Target;
114public:
115 std::string PredicateNamespace;
116 std::string GuardPrefix, GuardPostfix;
117 std::string ReturnOK, ReturnFail;
118 std::string Locals;
119};
120} // End anonymous namespace
121
Owen Anderson4e818902011-02-18 21:51:29 +0000122// The set (BIT_TRUE, BIT_FALSE, BIT_UNSET) represents a ternary logic system
123// for a bit value.
124//
125// BIT_UNFILTERED is used as the init value for a filter position. It is used
126// only for filter processings.
127typedef enum {
128 BIT_TRUE, // '1'
129 BIT_FALSE, // '0'
130 BIT_UNSET, // '?'
131 BIT_UNFILTERED // unfiltered
132} bit_value_t;
133
134static bool ValueSet(bit_value_t V) {
135 return (V == BIT_TRUE || V == BIT_FALSE);
136}
137static bool ValueNotSet(bit_value_t V) {
138 return (V == BIT_UNSET);
139}
140static int Value(bit_value_t V) {
141 return ValueNotSet(V) ? -1 : (V == BIT_FALSE ? 0 : 1);
142}
Craig Topper48c112b2012-03-16 05:58:09 +0000143static bit_value_t bitFromBits(const BitsInit &bits, unsigned index) {
Sean Silvafb509ed2012-10-10 20:24:43 +0000144 if (BitInit *bit = dyn_cast<BitInit>(bits.getBit(index)))
Owen Anderson4e818902011-02-18 21:51:29 +0000145 return bit->getValue() ? BIT_TRUE : BIT_FALSE;
146
147 // The bit is uninitialized.
148 return BIT_UNSET;
149}
150// Prints the bit value for each position.
Craig Topper48c112b2012-03-16 05:58:09 +0000151static void dumpBits(raw_ostream &o, const BitsInit &bits) {
Craig Topper29688ab2012-08-17 05:42:16 +0000152 for (unsigned index = bits.getNumBits(); index > 0; --index) {
Owen Anderson4e818902011-02-18 21:51:29 +0000153 switch (bitFromBits(bits, index - 1)) {
154 case BIT_TRUE:
155 o << "1";
156 break;
157 case BIT_FALSE:
158 o << "0";
159 break;
160 case BIT_UNSET:
161 o << "_";
162 break;
163 default:
Craig Topperc4965bc2012-02-05 07:21:30 +0000164 llvm_unreachable("unexpected return value from bitFromBits");
Owen Anderson4e818902011-02-18 21:51:29 +0000165 }
166 }
167}
168
David Greeneaf8ee2c2011-07-29 22:43:06 +0000169static BitsInit &getBitsField(const Record &def, const char *str) {
170 BitsInit *bits = def.getValueAsBitsInit(str);
Owen Anderson4e818902011-02-18 21:51:29 +0000171 return *bits;
172}
173
174// Forward declaration.
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +0000175namespace {
Owen Anderson4e818902011-02-18 21:51:29 +0000176class FilterChooser;
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +0000177} // End anonymous namespace
Owen Anderson4e818902011-02-18 21:51:29 +0000178
Owen Anderson4e818902011-02-18 21:51:29 +0000179// Representation of the instruction to work on.
Owen Andersonc78e03c2011-07-19 21:06:00 +0000180typedef std::vector<bit_value_t> insn_t;
Owen Anderson4e818902011-02-18 21:51:29 +0000181
182/// Filter - Filter works with FilterChooser to produce the decoding tree for
183/// the ISA.
184///
185/// It is useful to think of a Filter as governing the switch stmts of the
186/// decoding tree in a certain level. Each case stmt delegates to an inferior
187/// FilterChooser to decide what further decoding logic to employ, or in another
188/// words, what other remaining bits to look at. The FilterChooser eventually
189/// chooses a best Filter to do its job.
190///
191/// This recursive scheme ends when the number of Opcodes assigned to the
192/// FilterChooser becomes 1 or if there is a conflict. A conflict happens when
193/// the Filter/FilterChooser combo does not know how to distinguish among the
194/// Opcodes assigned.
195///
196/// An example of a conflict is
197///
198/// Conflict:
199/// 111101000.00........00010000....
200/// 111101000.00........0001........
201/// 1111010...00........0001........
202/// 1111010...00....................
203/// 1111010.........................
204/// 1111............................
205/// ................................
206/// VST4q8a 111101000_00________00010000____
207/// VST4q8b 111101000_00________00010000____
208///
209/// The Debug output shows the path that the decoding tree follows to reach the
210/// the conclusion that there is a conflict. VST4q8a is a vst4 to double-spaced
211/// even registers, while VST4q8b is a vst4 to double-spaced odd regsisters.
212///
213/// The encoding info in the .td files does not specify this meta information,
214/// which could have been used by the decoder to resolve the conflict. The
215/// decoder could try to decode the even/odd register numbering and assign to
216/// VST4q8a or VST4q8b, but for the time being, the decoder chooses the "a"
217/// version and return the Opcode since the two have the same Asm format string.
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +0000218namespace {
Owen Anderson4e818902011-02-18 21:51:29 +0000219class Filter {
220protected:
Craig Topper501d95c2012-03-16 06:52:56 +0000221 const FilterChooser *Owner;// points to the FilterChooser who owns this filter
Owen Anderson4e818902011-02-18 21:51:29 +0000222 unsigned StartBit; // the starting bit position
223 unsigned NumBits; // number of bits to filter
224 bool Mixed; // a mixed region contains both set and unset bits
225
226 // Map of well-known segment value to the set of uid's with that value.
227 std::map<uint64_t, std::vector<unsigned> > FilteredInstructions;
228
229 // Set of uid's with non-constant segment values.
230 std::vector<unsigned> VariableInstructions;
231
232 // Map of well-known segment value to its delegate.
Craig Topper6cb92c22014-09-03 05:59:23 +0000233 std::map<unsigned, const FilterChooser*> FilterChooserMap;
Owen Anderson4e818902011-02-18 21:51:29 +0000234
235 // Number of instructions which fall under FilteredInstructions category.
236 unsigned NumFiltered;
237
238 // Keeps track of the last opcode in the filtered bucket.
239 unsigned LastOpcFiltered;
240
Owen Anderson4e818902011-02-18 21:51:29 +0000241public:
Craig Topper48c112b2012-03-16 05:58:09 +0000242 unsigned getNumFiltered() const { return NumFiltered; }
243 unsigned getSingletonOpc() const {
Owen Anderson4e818902011-02-18 21:51:29 +0000244 assert(NumFiltered == 1);
245 return LastOpcFiltered;
246 }
247 // Return the filter chooser for the group of instructions without constant
248 // segment values.
Craig Topper48c112b2012-03-16 05:58:09 +0000249 const FilterChooser &getVariableFC() const {
Owen Anderson4e818902011-02-18 21:51:29 +0000250 assert(NumFiltered == 1);
251 assert(FilterChooserMap.size() == 1);
252 return *(FilterChooserMap.find((unsigned)-1)->second);
253 }
254
Craig Topper5c2b4ac2014-09-03 05:49:07 +0000255 Filter(Filter &&f);
Owen Anderson4e818902011-02-18 21:51:29 +0000256 Filter(FilterChooser &owner, unsigned startBit, unsigned numBits, bool mixed);
257
258 ~Filter();
259
260 // Divides the decoding task into sub tasks and delegates them to the
261 // inferior FilterChooser's.
262 //
263 // A special case arises when there's only one entry in the filtered
264 // instructions. In order to unambiguously decode the singleton, we need to
265 // match the remaining undecoded encoding bits against the singleton.
266 void recurse();
267
Jim Grosbachecaef492012-08-14 19:06:05 +0000268 // Emit table entries to decode instructions given a segment or segments of
269 // bits.
270 void emitTableEntry(DecoderTableInfo &TableInfo) const;
Owen Anderson4e818902011-02-18 21:51:29 +0000271
272 // Returns the number of fanout produced by the filter. More fanout implies
273 // the filter distinguishes more categories of instructions.
274 unsigned usefulness() const;
275}; // End of class Filter
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +0000276} // End anonymous namespace
Owen Anderson4e818902011-02-18 21:51:29 +0000277
278// These are states of our finite state machines used in FilterChooser's
279// filterProcessor() which produces the filter candidates to use.
280typedef enum {
281 ATTR_NONE,
282 ATTR_FILTERED,
283 ATTR_ALL_SET,
284 ATTR_ALL_UNSET,
285 ATTR_MIXED
286} bitAttr_t;
287
288/// FilterChooser - FilterChooser chooses the best filter among a set of Filters
289/// in order to perform the decoding of instructions at the current level.
290///
291/// Decoding proceeds from the top down. Based on the well-known encoding bits
292/// of instructions available, FilterChooser builds up the possible Filters that
293/// can further the task of decoding by distinguishing among the remaining
294/// candidate instructions.
295///
296/// Once a filter has been chosen, it is called upon to divide the decoding task
297/// into sub-tasks and delegates them to its inferior FilterChoosers for further
298/// processings.
299///
300/// It is useful to think of a Filter as governing the switch stmts of the
301/// decoding tree. And each case is delegated to an inferior FilterChooser to
302/// decide what further remaining bits to look at.
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +0000303namespace {
Owen Anderson4e818902011-02-18 21:51:29 +0000304class FilterChooser {
305protected:
306 friend class Filter;
307
308 // Vector of codegen instructions to choose our filter.
309 const std::vector<const CodeGenInstruction*> &AllInstructions;
310
311 // Vector of uid's for this filter chooser to work on.
Craig Topper501d95c2012-03-16 06:52:56 +0000312 const std::vector<unsigned> &Opcodes;
Owen Anderson4e818902011-02-18 21:51:29 +0000313
314 // Lookup table for the operand decoding of instructions.
Craig Topper501d95c2012-03-16 06:52:56 +0000315 const std::map<unsigned, std::vector<OperandInfo> > &Operands;
Owen Anderson4e818902011-02-18 21:51:29 +0000316
317 // Vector of candidate filters.
318 std::vector<Filter> Filters;
319
320 // Array of bit values passed down from our parent.
321 // Set to all BIT_UNFILTERED's for Parent == NULL.
Owen Andersonc78e03c2011-07-19 21:06:00 +0000322 std::vector<bit_value_t> FilterBitValues;
Owen Anderson4e818902011-02-18 21:51:29 +0000323
324 // Links to the FilterChooser above us in the decoding tree.
Craig Topper501d95c2012-03-16 06:52:56 +0000325 const FilterChooser *Parent;
Owen Anderson4e818902011-02-18 21:51:29 +0000326
327 // Index of the best filter from Filters.
328 int BestIndex;
329
Owen Andersonc78e03c2011-07-19 21:06:00 +0000330 // Width of instructions
331 unsigned BitWidth;
332
Owen Andersona4043c42011-08-17 17:44:15 +0000333 // Parent emitter
334 const FixedLenDecoderEmitter *Emitter;
335
Craig Topper5c2b4ac2014-09-03 05:49:07 +0000336 FilterChooser(const FilterChooser &) LLVM_DELETED_FUNCTION;
337 void operator=(const FilterChooser &) LLVM_DELETED_FUNCTION;
Owen Anderson4e818902011-02-18 21:51:29 +0000338public:
Owen Anderson4e818902011-02-18 21:51:29 +0000339
340 FilterChooser(const std::vector<const CodeGenInstruction*> &Insts,
341 const std::vector<unsigned> &IDs,
Craig Topper501d95c2012-03-16 06:52:56 +0000342 const std::map<unsigned, std::vector<OperandInfo> > &Ops,
Owen Andersona4043c42011-08-17 17:44:15 +0000343 unsigned BW,
Craig Topper82d0d5f2012-03-16 01:19:24 +0000344 const FixedLenDecoderEmitter *E)
345 : AllInstructions(Insts), Opcodes(IDs), Operands(Ops), Filters(),
Craig Topper24064772014-04-15 07:20:03 +0000346 Parent(nullptr), BestIndex(-1), BitWidth(BW), Emitter(E) {
Owen Andersonc78e03c2011-07-19 21:06:00 +0000347 for (unsigned i = 0; i < BitWidth; ++i)
348 FilterBitValues.push_back(BIT_UNFILTERED);
Owen Anderson4e818902011-02-18 21:51:29 +0000349
350 doFilter();
351 }
352
353 FilterChooser(const std::vector<const CodeGenInstruction*> &Insts,
354 const std::vector<unsigned> &IDs,
Craig Topper501d95c2012-03-16 06:52:56 +0000355 const std::map<unsigned, std::vector<OperandInfo> > &Ops,
356 const std::vector<bit_value_t> &ParentFilterBitValues,
357 const FilterChooser &parent)
Craig Topper82d0d5f2012-03-16 01:19:24 +0000358 : AllInstructions(Insts), Opcodes(IDs), Operands(Ops),
Owen Andersonc78e03c2011-07-19 21:06:00 +0000359 Filters(), FilterBitValues(ParentFilterBitValues),
Owen Andersona4043c42011-08-17 17:44:15 +0000360 Parent(&parent), BestIndex(-1), BitWidth(parent.BitWidth),
361 Emitter(parent.Emitter) {
Owen Anderson4e818902011-02-18 21:51:29 +0000362 doFilter();
363 }
364
Jim Grosbachecaef492012-08-14 19:06:05 +0000365 unsigned getBitWidth() const { return BitWidth; }
Owen Anderson4e818902011-02-18 21:51:29 +0000366
367protected:
368 // Populates the insn given the uid.
369 void insnWithID(insn_t &Insn, unsigned Opcode) const {
David Greeneaf8ee2c2011-07-29 22:43:06 +0000370 BitsInit &Bits = getBitsField(*AllInstructions[Opcode]->TheDef, "Inst");
Owen Anderson4e818902011-02-18 21:51:29 +0000371
James Molloyd9ba4fd2012-02-09 10:56:31 +0000372 // We may have a SoftFail bitmask, which specifies a mask where an encoding
373 // may differ from the value in "Inst" and yet still be valid, but the
374 // disassembler should return SoftFail instead of Success.
375 //
376 // This is used for marking UNPREDICTABLE instructions in the ARM world.
Jim Grosbach3f4b2392012-02-29 22:07:56 +0000377 BitsInit *SFBits =
378 AllInstructions[Opcode]->TheDef->getValueAsBitsInit("SoftFail");
James Molloyd9ba4fd2012-02-09 10:56:31 +0000379
380 for (unsigned i = 0; i < BitWidth; ++i) {
381 if (SFBits && bitFromBits(*SFBits, i) == BIT_TRUE)
382 Insn.push_back(BIT_UNSET);
383 else
384 Insn.push_back(bitFromBits(Bits, i));
385 }
Owen Anderson4e818902011-02-18 21:51:29 +0000386 }
387
388 // Returns the record name.
389 const std::string &nameWithID(unsigned Opcode) const {
390 return AllInstructions[Opcode]->TheDef->getName();
391 }
392
393 // Populates the field of the insn given the start position and the number of
394 // consecutive bits to scan for.
395 //
396 // Returns false if there exists any uninitialized bit value in the range.
397 // Returns true, otherwise.
398 bool fieldFromInsn(uint64_t &Field, insn_t &Insn, unsigned StartBit,
Craig Topper82d0d5f2012-03-16 01:19:24 +0000399 unsigned NumBits) const;
Owen Anderson4e818902011-02-18 21:51:29 +0000400
401 /// dumpFilterArray - dumpFilterArray prints out debugging info for the given
402 /// filter array as a series of chars.
Craig Topper48c112b2012-03-16 05:58:09 +0000403 void dumpFilterArray(raw_ostream &o,
404 const std::vector<bit_value_t> & filter) const;
Owen Anderson4e818902011-02-18 21:51:29 +0000405
406 /// dumpStack - dumpStack traverses the filter chooser chain and calls
407 /// dumpFilterArray on each filter chooser up to the top level one.
Craig Topper48c112b2012-03-16 05:58:09 +0000408 void dumpStack(raw_ostream &o, const char *prefix) const;
Owen Anderson4e818902011-02-18 21:51:29 +0000409
410 Filter &bestFilter() {
411 assert(BestIndex != -1 && "BestIndex not set");
412 return Filters[BestIndex];
413 }
414
415 // Called from Filter::recurse() when singleton exists. For debug purpose.
Craig Topper48c112b2012-03-16 05:58:09 +0000416 void SingletonExists(unsigned Opc) const;
Owen Anderson4e818902011-02-18 21:51:29 +0000417
Craig Topper48c112b2012-03-16 05:58:09 +0000418 bool PositionFiltered(unsigned i) const {
Owen Anderson4e818902011-02-18 21:51:29 +0000419 return ValueSet(FilterBitValues[i]);
420 }
421
422 // Calculates the island(s) needed to decode the instruction.
423 // This returns a lit of undecoded bits of an instructions, for example,
424 // Inst{20} = 1 && Inst{3-0} == 0b1111 represents two islands of yet-to-be
425 // decoded bits in order to verify that the instruction matches the Opcode.
426 unsigned getIslands(std::vector<unsigned> &StartBits,
Craig Topper82d0d5f2012-03-16 01:19:24 +0000427 std::vector<unsigned> &EndBits,
Craig Topper48c112b2012-03-16 05:58:09 +0000428 std::vector<uint64_t> &FieldVals,
429 const insn_t &Insn) const;
Owen Anderson4e818902011-02-18 21:51:29 +0000430
James Molloy8067df92011-09-07 19:42:28 +0000431 // Emits code to check the Predicates member of an instruction are true.
432 // Returns true if predicate matches were emitted, false otherwise.
Craig Topper48c112b2012-03-16 05:58:09 +0000433 bool emitPredicateMatch(raw_ostream &o, unsigned &Indentation,
434 unsigned Opc) const;
James Molloy8067df92011-09-07 19:42:28 +0000435
Jim Grosbachecaef492012-08-14 19:06:05 +0000436 bool doesOpcodeNeedPredicate(unsigned Opc) const;
437 unsigned getPredicateIndex(DecoderTableInfo &TableInfo, StringRef P) const;
438 void emitPredicateTableEntry(DecoderTableInfo &TableInfo,
439 unsigned Opc) const;
James Molloyd9ba4fd2012-02-09 10:56:31 +0000440
Jim Grosbachecaef492012-08-14 19:06:05 +0000441 void emitSoftFailTableEntry(DecoderTableInfo &TableInfo,
442 unsigned Opc) const;
443
444 // Emits table entries to decode the singleton.
445 void emitSingletonTableEntry(DecoderTableInfo &TableInfo,
446 unsigned Opc) const;
Owen Anderson4e818902011-02-18 21:51:29 +0000447
448 // Emits code to decode the singleton, and then to decode the rest.
Jim Grosbachecaef492012-08-14 19:06:05 +0000449 void emitSingletonTableEntry(DecoderTableInfo &TableInfo,
450 const Filter &Best) const;
Owen Anderson4e818902011-02-18 21:51:29 +0000451
Jim Grosbachecaef492012-08-14 19:06:05 +0000452 void emitBinaryParser(raw_ostream &o, unsigned &Indentation,
Craig Topper48c112b2012-03-16 05:58:09 +0000453 const OperandInfo &OpInfo) const;
Owen Andersone3591652011-07-28 21:54:31 +0000454
Jim Grosbachecaef492012-08-14 19:06:05 +0000455 void emitDecoder(raw_ostream &OS, unsigned Indentation, unsigned Opc) const;
456 unsigned getDecoderIndex(DecoderSet &Decoders, unsigned Opc) const;
457
Owen Anderson4e818902011-02-18 21:51:29 +0000458 // Assign a single filter and run with it.
Craig Topper48c112b2012-03-16 05:58:09 +0000459 void runSingleFilter(unsigned startBit, unsigned numBit, bool mixed);
Owen Anderson4e818902011-02-18 21:51:29 +0000460
461 // reportRegion is a helper function for filterProcessor to mark a region as
462 // eligible for use as a filter region.
463 void reportRegion(bitAttr_t RA, unsigned StartBit, unsigned BitIndex,
Craig Topper82d0d5f2012-03-16 01:19:24 +0000464 bool AllowMixed);
Owen Anderson4e818902011-02-18 21:51:29 +0000465
466 // FilterProcessor scans the well-known encoding bits of the instructions and
467 // builds up a list of candidate filters. It chooses the best filter and
468 // recursively descends down the decoding tree.
469 bool filterProcessor(bool AllowMixed, bool Greedy = true);
470
471 // Decides on the best configuration of filter(s) to use in order to decode
472 // the instructions. A conflict of instructions may occur, in which case we
473 // dump the conflict set to the standard error.
474 void doFilter();
475
Jim Grosbachecaef492012-08-14 19:06:05 +0000476public:
477 // emitTableEntries - Emit state machine entries to decode our share of
478 // instructions.
479 void emitTableEntries(DecoderTableInfo &TableInfo) const;
Owen Anderson4e818902011-02-18 21:51:29 +0000480};
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +0000481} // End anonymous namespace
Owen Anderson4e818902011-02-18 21:51:29 +0000482
483///////////////////////////
484// //
Craig Topper93e64342012-03-16 00:56:01 +0000485// Filter Implementation //
Owen Anderson4e818902011-02-18 21:51:29 +0000486// //
487///////////////////////////
488
Craig Topper5c2b4ac2014-09-03 05:49:07 +0000489Filter::Filter(Filter &&f)
Craig Topper82d0d5f2012-03-16 01:19:24 +0000490 : Owner(f.Owner), StartBit(f.StartBit), NumBits(f.NumBits), Mixed(f.Mixed),
Craig Topper5c2b4ac2014-09-03 05:49:07 +0000491 FilteredInstructions(std::move(f.FilteredInstructions)),
492 VariableInstructions(std::move(f.VariableInstructions)),
493 FilterChooserMap(std::move(f.FilterChooserMap)), NumFiltered(f.NumFiltered),
Craig Topper82d0d5f2012-03-16 01:19:24 +0000494 LastOpcFiltered(f.LastOpcFiltered) {
Owen Anderson4e818902011-02-18 21:51:29 +0000495}
496
497Filter::Filter(FilterChooser &owner, unsigned startBit, unsigned numBits,
Craig Topper82d0d5f2012-03-16 01:19:24 +0000498 bool mixed)
499 : Owner(&owner), StartBit(startBit), NumBits(numBits), Mixed(mixed) {
Owen Andersonc78e03c2011-07-19 21:06:00 +0000500 assert(StartBit + NumBits - 1 < Owner->BitWidth);
Owen Anderson4e818902011-02-18 21:51:29 +0000501
502 NumFiltered = 0;
503 LastOpcFiltered = 0;
Owen Anderson4e818902011-02-18 21:51:29 +0000504
505 for (unsigned i = 0, e = Owner->Opcodes.size(); i != e; ++i) {
506 insn_t Insn;
507
508 // Populates the insn given the uid.
509 Owner->insnWithID(Insn, Owner->Opcodes[i]);
510
511 uint64_t Field;
512 // Scans the segment for possibly well-specified encoding bits.
513 bool ok = Owner->fieldFromInsn(Field, Insn, StartBit, NumBits);
514
515 if (ok) {
516 // The encoding bits are well-known. Lets add the uid of the
517 // instruction into the bucket keyed off the constant field value.
518 LastOpcFiltered = Owner->Opcodes[i];
519 FilteredInstructions[Field].push_back(LastOpcFiltered);
520 ++NumFiltered;
521 } else {
Craig Topper93e64342012-03-16 00:56:01 +0000522 // Some of the encoding bit(s) are unspecified. This contributes to
Owen Anderson4e818902011-02-18 21:51:29 +0000523 // one additional member of "Variable" instructions.
524 VariableInstructions.push_back(Owner->Opcodes[i]);
Owen Anderson4e818902011-02-18 21:51:29 +0000525 }
526 }
527
528 assert((FilteredInstructions.size() + VariableInstructions.size() > 0)
529 && "Filter returns no instruction categories");
530}
531
532Filter::~Filter() {
Craig Topper6cb92c22014-09-03 05:59:23 +0000533 std::map<unsigned, const FilterChooser*>::iterator filterIterator;
534 for (filterIterator = FilterChooserMap.begin();
535 filterIterator != FilterChooserMap.end();
536 filterIterator++) {
537 delete filterIterator->second;
538 }
Owen Anderson4e818902011-02-18 21:51:29 +0000539}
540
541// Divides the decoding task into sub tasks and delegates them to the
542// inferior FilterChooser's.
543//
544// A special case arises when there's only one entry in the filtered
545// instructions. In order to unambiguously decode the singleton, we need to
546// match the remaining undecoded encoding bits against the singleton.
547void Filter::recurse() {
548 std::map<uint64_t, std::vector<unsigned> >::const_iterator mapIterator;
549
Owen Anderson4e818902011-02-18 21:51:29 +0000550 // Starts by inheriting our parent filter chooser's filter bit values.
Owen Andersonc78e03c2011-07-19 21:06:00 +0000551 std::vector<bit_value_t> BitValueArray(Owner->FilterBitValues);
Owen Anderson4e818902011-02-18 21:51:29 +0000552
Owen Anderson4e818902011-02-18 21:51:29 +0000553 if (VariableInstructions.size()) {
554 // Conservatively marks each segment position as BIT_UNSET.
Craig Topper29688ab2012-08-17 05:42:16 +0000555 for (unsigned bitIndex = 0; bitIndex < NumBits; ++bitIndex)
Owen Anderson4e818902011-02-18 21:51:29 +0000556 BitValueArray[StartBit + bitIndex] = BIT_UNSET;
557
Chris Lattner0ab5e2c2011-04-15 05:18:47 +0000558 // Delegates to an inferior filter chooser for further processing on this
Owen Anderson4e818902011-02-18 21:51:29 +0000559 // group of instructions whose segment values are variable.
Craig Topper6cb92c22014-09-03 05:59:23 +0000560 FilterChooserMap.insert(std::pair<unsigned, const FilterChooser*>(
561 (unsigned)-1,
562 new FilterChooser(Owner->AllInstructions,
563 VariableInstructions,
564 Owner->Operands,
565 BitValueArray,
566 *Owner)
567 ));
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) {
573 //Owner->SingletonExists(LastOpcFiltered);
574 assert(FilterChooserMap.size() == 1);
575 return;
576 }
577
578 // Otherwise, create sub choosers.
579 for (mapIterator = FilteredInstructions.begin();
580 mapIterator != FilteredInstructions.end();
581 mapIterator++) {
582
583 // Marks all the segment positions with either BIT_TRUE or BIT_FALSE.
Craig Topper29688ab2012-08-17 05:42:16 +0000584 for (unsigned bitIndex = 0; bitIndex < NumBits; ++bitIndex) {
Owen Anderson4e818902011-02-18 21:51:29 +0000585 if (mapIterator->first & (1ULL << bitIndex))
586 BitValueArray[StartBit + bitIndex] = BIT_TRUE;
587 else
588 BitValueArray[StartBit + bitIndex] = BIT_FALSE;
589 }
590
Chris Lattner0ab5e2c2011-04-15 05:18:47 +0000591 // Delegates to an inferior filter chooser for further processing on this
Owen Anderson4e818902011-02-18 21:51:29 +0000592 // category of instructions.
Craig Topper6cb92c22014-09-03 05:59:23 +0000593 FilterChooserMap.insert(std::pair<unsigned, const FilterChooser*>(
594 mapIterator->first,
595 new FilterChooser(Owner->AllInstructions,
596 mapIterator->second,
597 Owner->Operands,
598 BitValueArray,
599 *Owner)
600 ));
Owen Anderson4e818902011-02-18 21:51:29 +0000601 }
602}
603
Jim Grosbachecaef492012-08-14 19:06:05 +0000604static void resolveTableFixups(DecoderTable &Table, const FixupList &Fixups,
605 uint32_t DestIdx) {
606 // Any NumToSkip fixups in the current scope can resolve to the
607 // current location.
608 for (FixupList::const_reverse_iterator I = Fixups.rbegin(),
609 E = Fixups.rend();
610 I != E; ++I) {
611 // Calculate the distance from the byte following the fixup entry byte
612 // to the destination. The Target is calculated from after the 16-bit
613 // NumToSkip entry itself, so subtract two from the displacement here
614 // to account for that.
615 uint32_t FixupIdx = *I;
616 uint32_t Delta = DestIdx - FixupIdx - 2;
617 // Our NumToSkip entries are 16-bits. Make sure our table isn't too
618 // big.
619 assert(Delta < 65536U && "disassembler decoding table too large!");
620 Table[FixupIdx] = (uint8_t)Delta;
621 Table[FixupIdx + 1] = (uint8_t)(Delta >> 8);
622 }
623}
Owen Anderson4e818902011-02-18 21:51:29 +0000624
Jim Grosbachecaef492012-08-14 19:06:05 +0000625// Emit table entries to decode instructions given a segment or segments
626// of bits.
627void Filter::emitTableEntry(DecoderTableInfo &TableInfo) const {
628 TableInfo.Table.push_back(MCD::OPC_ExtractField);
629 TableInfo.Table.push_back(StartBit);
630 TableInfo.Table.push_back(NumBits);
Owen Anderson4e818902011-02-18 21:51:29 +0000631
Jim Grosbachecaef492012-08-14 19:06:05 +0000632 // A new filter entry begins a new scope for fixup resolution.
633 TableInfo.FixupStack.push_back(FixupList());
Owen Anderson4e818902011-02-18 21:51:29 +0000634
Craig Topper6cb92c22014-09-03 05:59:23 +0000635 std::map<unsigned, const FilterChooser*>::const_iterator filterIterator;
Owen Anderson4e818902011-02-18 21:51:29 +0000636
Jim Grosbachecaef492012-08-14 19:06:05 +0000637 DecoderTable &Table = TableInfo.Table;
638
639 size_t PrevFilter = 0;
640 bool HasFallthrough = false;
Owen Anderson4e818902011-02-18 21:51:29 +0000641 for (filterIterator = FilterChooserMap.begin();
642 filterIterator != FilterChooserMap.end();
643 filterIterator++) {
Owen Anderson4e818902011-02-18 21:51:29 +0000644 // Field value -1 implies a non-empty set of variable instructions.
645 // See also recurse().
646 if (filterIterator->first == (unsigned)-1) {
Jim Grosbachecaef492012-08-14 19:06:05 +0000647 HasFallthrough = true;
Owen Anderson4e818902011-02-18 21:51:29 +0000648
Jim Grosbachecaef492012-08-14 19:06:05 +0000649 // Each scope should always have at least one filter value to check
650 // for.
651 assert(PrevFilter != 0 && "empty filter set!");
652 FixupList &CurScope = TableInfo.FixupStack.back();
653 // Resolve any NumToSkip fixups in the current scope.
654 resolveTableFixups(Table, CurScope, Table.size());
655 CurScope.clear();
656 PrevFilter = 0; // Don't re-process the filter's fallthrough.
657 } else {
658 Table.push_back(MCD::OPC_FilterValue);
659 // Encode and emit the value to filter against.
660 uint8_t Buffer[8];
661 unsigned Len = encodeULEB128(filterIterator->first, Buffer);
662 Table.insert(Table.end(), Buffer, Buffer + Len);
663 // Reserve space for the NumToSkip entry. We'll backpatch the value
664 // later.
665 PrevFilter = Table.size();
666 Table.push_back(0);
667 Table.push_back(0);
668 }
Owen Anderson4e818902011-02-18 21:51:29 +0000669
670 // We arrive at a category of instructions with the same segment value.
671 // Now delegate to the sub filter chooser for further decodings.
672 // The case may fallthrough, which happens if the remaining well-known
673 // encoding bits do not match exactly.
Jim Grosbachecaef492012-08-14 19:06:05 +0000674 filterIterator->second->emitTableEntries(TableInfo);
Owen Anderson4e818902011-02-18 21:51:29 +0000675
Jim Grosbachecaef492012-08-14 19:06:05 +0000676 // Now that we've emitted the body of the handler, update the NumToSkip
677 // of the filter itself to be able to skip forward when false. Subtract
678 // two as to account for the width of the NumToSkip field itself.
679 if (PrevFilter) {
680 uint32_t NumToSkip = Table.size() - PrevFilter - 2;
681 assert(NumToSkip < 65536U && "disassembler decoding table too large!");
682 Table[PrevFilter] = (uint8_t)NumToSkip;
683 Table[PrevFilter + 1] = (uint8_t)(NumToSkip >> 8);
684 }
Owen Anderson4e818902011-02-18 21:51:29 +0000685 }
686
Jim Grosbachecaef492012-08-14 19:06:05 +0000687 // Any remaining unresolved fixups bubble up to the parent fixup scope.
688 assert(TableInfo.FixupStack.size() > 1 && "fixup stack underflow!");
689 FixupScopeList::iterator Source = TableInfo.FixupStack.end() - 1;
690 FixupScopeList::iterator Dest = Source - 1;
691 Dest->insert(Dest->end(), Source->begin(), Source->end());
692 TableInfo.FixupStack.pop_back();
693
694 // If there is no fallthrough, then the final filter should get fixed
695 // up according to the enclosing scope rather than the current position.
696 if (!HasFallthrough)
697 TableInfo.FixupStack.back().push_back(PrevFilter);
Owen Anderson4e818902011-02-18 21:51:29 +0000698}
699
700// Returns the number of fanout produced by the filter. More fanout implies
701// the filter distinguishes more categories of instructions.
702unsigned Filter::usefulness() const {
703 if (VariableInstructions.size())
704 return FilteredInstructions.size();
705 else
706 return FilteredInstructions.size() + 1;
707}
708
709//////////////////////////////////
710// //
711// Filterchooser Implementation //
712// //
713//////////////////////////////////
714
Jim Grosbachecaef492012-08-14 19:06:05 +0000715// Emit the decoder state machine table.
716void FixedLenDecoderEmitter::emitTable(formatted_raw_ostream &OS,
717 DecoderTable &Table,
718 unsigned Indentation,
719 unsigned BitWidth,
720 StringRef Namespace) const {
721 OS.indent(Indentation) << "static const uint8_t DecoderTable" << Namespace
722 << BitWidth << "[] = {\n";
Owen Anderson4e818902011-02-18 21:51:29 +0000723
Jim Grosbachecaef492012-08-14 19:06:05 +0000724 Indentation += 2;
Owen Anderson4e818902011-02-18 21:51:29 +0000725
Jim Grosbachecaef492012-08-14 19:06:05 +0000726 // FIXME: We may be able to use the NumToSkip values to recover
727 // appropriate indentation levels.
728 DecoderTable::const_iterator I = Table.begin();
729 DecoderTable::const_iterator E = Table.end();
730 while (I != E) {
731 assert (I < E && "incomplete decode table entry!");
Owen Anderson4e818902011-02-18 21:51:29 +0000732
Jim Grosbachecaef492012-08-14 19:06:05 +0000733 uint64_t Pos = I - Table.begin();
734 OS << "/* " << Pos << " */";
735 OS.PadToColumn(12);
Owen Anderson4e818902011-02-18 21:51:29 +0000736
Jim Grosbachecaef492012-08-14 19:06:05 +0000737 switch (*I) {
738 default:
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000739 PrintFatalError("invalid decode table opcode");
Jim Grosbachecaef492012-08-14 19:06:05 +0000740 case MCD::OPC_ExtractField: {
741 ++I;
742 unsigned Start = *I++;
743 unsigned Len = *I++;
744 OS.indent(Indentation) << "MCD::OPC_ExtractField, " << Start << ", "
745 << Len << ", // Inst{";
746 if (Len > 1)
747 OS << (Start + Len - 1) << "-";
748 OS << Start << "} ...\n";
749 break;
750 }
751 case MCD::OPC_FilterValue: {
752 ++I;
753 OS.indent(Indentation) << "MCD::OPC_FilterValue, ";
754 // The filter value is ULEB128 encoded.
755 while (*I >= 128)
756 OS << utostr(*I++) << ", ";
757 OS << utostr(*I++) << ", ";
758
759 // 16-bit numtoskip value.
760 uint8_t Byte = *I++;
761 uint32_t NumToSkip = Byte;
762 OS << utostr(Byte) << ", ";
763 Byte = *I++;
764 OS << utostr(Byte) << ", ";
765 NumToSkip |= Byte << 8;
766 OS << "// Skip to: " << ((I - Table.begin()) + NumToSkip) << "\n";
767 break;
768 }
769 case MCD::OPC_CheckField: {
770 ++I;
771 unsigned Start = *I++;
772 unsigned Len = *I++;
773 OS.indent(Indentation) << "MCD::OPC_CheckField, " << Start << ", "
774 << Len << ", ";// << Val << ", " << NumToSkip << ",\n";
775 // ULEB128 encoded field value.
776 for (; *I >= 128; ++I)
777 OS << utostr(*I) << ", ";
778 OS << utostr(*I++) << ", ";
779 // 16-bit numtoskip value.
780 uint8_t Byte = *I++;
781 uint32_t NumToSkip = Byte;
782 OS << utostr(Byte) << ", ";
783 Byte = *I++;
784 OS << utostr(Byte) << ", ";
785 NumToSkip |= Byte << 8;
786 OS << "// Skip to: " << ((I - Table.begin()) + NumToSkip) << "\n";
787 break;
788 }
789 case MCD::OPC_CheckPredicate: {
790 ++I;
791 OS.indent(Indentation) << "MCD::OPC_CheckPredicate, ";
792 for (; *I >= 128; ++I)
793 OS << utostr(*I) << ", ";
794 OS << utostr(*I++) << ", ";
795
796 // 16-bit numtoskip value.
797 uint8_t Byte = *I++;
798 uint32_t NumToSkip = Byte;
799 OS << utostr(Byte) << ", ";
800 Byte = *I++;
801 OS << utostr(Byte) << ", ";
802 NumToSkip |= Byte << 8;
803 OS << "// Skip to: " << ((I - Table.begin()) + NumToSkip) << "\n";
804 break;
805 }
806 case MCD::OPC_Decode: {
807 ++I;
808 // Extract the ULEB128 encoded Opcode to a buffer.
809 uint8_t Buffer[8], *p = Buffer;
810 while ((*p++ = *I++) >= 128)
811 assert((p - Buffer) <= (ptrdiff_t)sizeof(Buffer)
812 && "ULEB128 value too large!");
813 // Decode the Opcode value.
814 unsigned Opc = decodeULEB128(Buffer);
815 OS.indent(Indentation) << "MCD::OPC_Decode, ";
816 for (p = Buffer; *p >= 128; ++p)
817 OS << utostr(*p) << ", ";
818 OS << utostr(*p) << ", ";
819
820 // Decoder index.
821 for (; *I >= 128; ++I)
822 OS << utostr(*I) << ", ";
823 OS << utostr(*I++) << ", ";
824
825 OS << "// Opcode: "
826 << NumberedInstructions->at(Opc)->TheDef->getName() << "\n";
827 break;
828 }
829 case MCD::OPC_SoftFail: {
830 ++I;
831 OS.indent(Indentation) << "MCD::OPC_SoftFail";
832 // Positive mask
833 uint64_t Value = 0;
834 unsigned Shift = 0;
835 do {
836 OS << ", " << utostr(*I);
837 Value += (*I & 0x7f) << Shift;
838 Shift += 7;
839 } while (*I++ >= 128);
840 if (Value > 127)
841 OS << " /* 0x" << utohexstr(Value) << " */";
842 // Negative mask
843 Value = 0;
844 Shift = 0;
845 do {
846 OS << ", " << utostr(*I);
847 Value += (*I & 0x7f) << Shift;
848 Shift += 7;
849 } while (*I++ >= 128);
850 if (Value > 127)
851 OS << " /* 0x" << utohexstr(Value) << " */";
852 OS << ",\n";
853 break;
854 }
855 case MCD::OPC_Fail: {
856 ++I;
857 OS.indent(Indentation) << "MCD::OPC_Fail,\n";
858 break;
859 }
860 }
861 }
862 OS.indent(Indentation) << "0\n";
863
864 Indentation -= 2;
865
866 OS.indent(Indentation) << "};\n\n";
867}
868
869void FixedLenDecoderEmitter::
870emitPredicateFunction(formatted_raw_ostream &OS, PredicateSet &Predicates,
871 unsigned Indentation) const {
872 // The predicate function is just a big switch statement based on the
873 // input predicate index.
874 OS.indent(Indentation) << "static bool checkDecoderPredicate(unsigned Idx, "
875 << "uint64_t Bits) {\n";
876 Indentation += 2;
Aaron Ballmane59e3582013-07-15 16:53:32 +0000877 if (!Predicates.empty()) {
878 OS.indent(Indentation) << "switch (Idx) {\n";
879 OS.indent(Indentation) << "default: llvm_unreachable(\"Invalid index!\");\n";
880 unsigned Index = 0;
881 for (PredicateSet::const_iterator I = Predicates.begin(), E = Predicates.end();
882 I != E; ++I, ++Index) {
883 OS.indent(Indentation) << "case " << Index << ":\n";
884 OS.indent(Indentation+2) << "return (" << *I << ");\n";
885 }
886 OS.indent(Indentation) << "}\n";
887 } else {
888 // No case statement to emit
889 OS.indent(Indentation) << "llvm_unreachable(\"Invalid index!\");\n";
Jim Grosbachecaef492012-08-14 19:06:05 +0000890 }
Jim Grosbachecaef492012-08-14 19:06:05 +0000891 Indentation -= 2;
892 OS.indent(Indentation) << "}\n\n";
893}
894
895void FixedLenDecoderEmitter::
896emitDecoderFunction(formatted_raw_ostream &OS, DecoderSet &Decoders,
897 unsigned Indentation) const {
898 // The decoder function is just a big switch statement based on the
899 // input decoder index.
900 OS.indent(Indentation) << "template<typename InsnType>\n";
901 OS.indent(Indentation) << "static DecodeStatus decodeToMCInst(DecodeStatus S,"
902 << " unsigned Idx, InsnType insn, MCInst &MI,\n";
903 OS.indent(Indentation) << " uint64_t "
Benjamin Kramer26b568d2012-08-15 10:26:44 +0000904 << "Address, const void *Decoder) {\n";
Jim Grosbachecaef492012-08-14 19:06:05 +0000905 Indentation += 2;
906 OS.indent(Indentation) << "InsnType tmp;\n";
907 OS.indent(Indentation) << "switch (Idx) {\n";
908 OS.indent(Indentation) << "default: llvm_unreachable(\"Invalid index!\");\n";
909 unsigned Index = 0;
910 for (DecoderSet::const_iterator I = Decoders.begin(), E = Decoders.end();
911 I != E; ++I, ++Index) {
912 OS.indent(Indentation) << "case " << Index << ":\n";
Craig Topperebc3aa22012-08-17 05:16:15 +0000913 OS << *I;
Jim Grosbachecaef492012-08-14 19:06:05 +0000914 OS.indent(Indentation+2) << "return S;\n";
915 }
916 OS.indent(Indentation) << "}\n";
917 Indentation -= 2;
918 OS.indent(Indentation) << "}\n\n";
Owen Anderson4e818902011-02-18 21:51:29 +0000919}
920
921// Populates the field of the insn given the start position and the number of
922// consecutive bits to scan for.
923//
924// Returns false if and on the first uninitialized bit value encountered.
925// Returns true, otherwise.
926bool FilterChooser::fieldFromInsn(uint64_t &Field, insn_t &Insn,
Craig Topper48c112b2012-03-16 05:58:09 +0000927 unsigned StartBit, unsigned NumBits) const {
Owen Anderson4e818902011-02-18 21:51:29 +0000928 Field = 0;
929
930 for (unsigned i = 0; i < NumBits; ++i) {
931 if (Insn[StartBit + i] == BIT_UNSET)
932 return false;
933
934 if (Insn[StartBit + i] == BIT_TRUE)
935 Field = Field | (1ULL << i);
936 }
937
938 return true;
939}
940
941/// dumpFilterArray - dumpFilterArray prints out debugging info for the given
942/// filter array as a series of chars.
943void FilterChooser::dumpFilterArray(raw_ostream &o,
Craig Topper48c112b2012-03-16 05:58:09 +0000944 const std::vector<bit_value_t> &filter) const {
Craig Topper29688ab2012-08-17 05:42:16 +0000945 for (unsigned bitIndex = BitWidth; bitIndex > 0; bitIndex--) {
Owen Anderson4e818902011-02-18 21:51:29 +0000946 switch (filter[bitIndex - 1]) {
947 case BIT_UNFILTERED:
948 o << ".";
949 break;
950 case BIT_UNSET:
951 o << "_";
952 break;
953 case BIT_TRUE:
954 o << "1";
955 break;
956 case BIT_FALSE:
957 o << "0";
958 break;
959 }
960 }
961}
962
963/// dumpStack - dumpStack traverses the filter chooser chain and calls
964/// dumpFilterArray on each filter chooser up to the top level one.
Craig Topper48c112b2012-03-16 05:58:09 +0000965void FilterChooser::dumpStack(raw_ostream &o, const char *prefix) const {
966 const FilterChooser *current = this;
Owen Anderson4e818902011-02-18 21:51:29 +0000967
968 while (current) {
969 o << prefix;
970 dumpFilterArray(o, current->FilterBitValues);
971 o << '\n';
972 current = current->Parent;
973 }
974}
975
976// Called from Filter::recurse() when singleton exists. For debug purpose.
Craig Topper48c112b2012-03-16 05:58:09 +0000977void FilterChooser::SingletonExists(unsigned Opc) const {
Owen Anderson4e818902011-02-18 21:51:29 +0000978 insn_t Insn0;
979 insnWithID(Insn0, Opc);
980
981 errs() << "Singleton exists: " << nameWithID(Opc)
982 << " with its decoding dominating ";
983 for (unsigned i = 0; i < Opcodes.size(); ++i) {
984 if (Opcodes[i] == Opc) continue;
985 errs() << nameWithID(Opcodes[i]) << ' ';
986 }
987 errs() << '\n';
988
989 dumpStack(errs(), "\t\t");
Craig Topper82d0d5f2012-03-16 01:19:24 +0000990 for (unsigned i = 0; i < Opcodes.size(); ++i) {
Owen Anderson4e818902011-02-18 21:51:29 +0000991 const std::string &Name = nameWithID(Opcodes[i]);
992
993 errs() << '\t' << Name << " ";
994 dumpBits(errs(),
995 getBitsField(*AllInstructions[Opcodes[i]]->TheDef, "Inst"));
996 errs() << '\n';
997 }
998}
999
1000// Calculates the island(s) needed to decode the instruction.
1001// This returns a list of undecoded bits of an instructions, for example,
1002// Inst{20} = 1 && Inst{3-0} == 0b1111 represents two islands of yet-to-be
1003// decoded bits in order to verify that the instruction matches the Opcode.
1004unsigned FilterChooser::getIslands(std::vector<unsigned> &StartBits,
Craig Topper82d0d5f2012-03-16 01:19:24 +00001005 std::vector<unsigned> &EndBits,
1006 std::vector<uint64_t> &FieldVals,
Craig Topper48c112b2012-03-16 05:58:09 +00001007 const insn_t &Insn) const {
Owen Anderson4e818902011-02-18 21:51:29 +00001008 unsigned Num, BitNo;
1009 Num = BitNo = 0;
1010
1011 uint64_t FieldVal = 0;
1012
1013 // 0: Init
1014 // 1: Water (the bit value does not affect decoding)
1015 // 2: Island (well-known bit value needed for decoding)
1016 int State = 0;
1017 int Val = -1;
1018
Owen Andersonc78e03c2011-07-19 21:06:00 +00001019 for (unsigned i = 0; i < BitWidth; ++i) {
Owen Anderson4e818902011-02-18 21:51:29 +00001020 Val = Value(Insn[i]);
1021 bool Filtered = PositionFiltered(i);
1022 switch (State) {
Craig Topperc4965bc2012-02-05 07:21:30 +00001023 default: llvm_unreachable("Unreachable code!");
Owen Anderson4e818902011-02-18 21:51:29 +00001024 case 0:
1025 case 1:
1026 if (Filtered || Val == -1)
1027 State = 1; // Still in Water
1028 else {
1029 State = 2; // Into the Island
1030 BitNo = 0;
1031 StartBits.push_back(i);
1032 FieldVal = Val;
1033 }
1034 break;
1035 case 2:
1036 if (Filtered || Val == -1) {
1037 State = 1; // Into the Water
1038 EndBits.push_back(i - 1);
1039 FieldVals.push_back(FieldVal);
1040 ++Num;
1041 } else {
1042 State = 2; // Still in Island
1043 ++BitNo;
1044 FieldVal = FieldVal | Val << BitNo;
1045 }
1046 break;
1047 }
1048 }
1049 // If we are still in Island after the loop, do some housekeeping.
1050 if (State == 2) {
Owen Andersonc78e03c2011-07-19 21:06:00 +00001051 EndBits.push_back(BitWidth - 1);
Owen Anderson4e818902011-02-18 21:51:29 +00001052 FieldVals.push_back(FieldVal);
1053 ++Num;
1054 }
1055
1056 assert(StartBits.size() == Num && EndBits.size() == Num &&
1057 FieldVals.size() == Num);
1058 return Num;
1059}
1060
Owen Andersone3591652011-07-28 21:54:31 +00001061void FilterChooser::emitBinaryParser(raw_ostream &o, unsigned &Indentation,
Craig Topper48c112b2012-03-16 05:58:09 +00001062 const OperandInfo &OpInfo) const {
1063 const std::string &Decoder = OpInfo.Decoder;
Owen Andersone3591652011-07-28 21:54:31 +00001064
1065 if (OpInfo.numFields() == 1) {
Craig Topper48c112b2012-03-16 05:58:09 +00001066 OperandInfo::const_iterator OI = OpInfo.begin();
Craig Topperebc3aa22012-08-17 05:16:15 +00001067 o.indent(Indentation) << "tmp = fieldFromInstruction"
Jim Grosbachecaef492012-08-14 19:06:05 +00001068 << "(insn, " << OI->Base << ", " << OI->Width
1069 << ");\n";
Owen Andersone3591652011-07-28 21:54:31 +00001070 } else {
Craig Topperebc3aa22012-08-17 05:16:15 +00001071 o.indent(Indentation) << "tmp = 0;\n";
Craig Topper48c112b2012-03-16 05:58:09 +00001072 for (OperandInfo::const_iterator OI = OpInfo.begin(), OE = OpInfo.end();
Owen Andersone3591652011-07-28 21:54:31 +00001073 OI != OE; ++OI) {
Craig Topperebc3aa22012-08-17 05:16:15 +00001074 o.indent(Indentation) << "tmp |= (fieldFromInstruction"
Andrew Trick61abca62011-09-08 05:23:14 +00001075 << "(insn, " << OI->Base << ", " << OI->Width
Owen Andersone3591652011-07-28 21:54:31 +00001076 << ") << " << OI->Offset << ");\n";
1077 }
1078 }
1079
1080 if (Decoder != "")
Craig Topperebc3aa22012-08-17 05:16:15 +00001081 o.indent(Indentation) << Emitter->GuardPrefix << Decoder
Jim Grosbach3f4b2392012-02-29 22:07:56 +00001082 << "(MI, tmp, Address, Decoder)"
1083 << Emitter->GuardPostfix << "\n";
Owen Andersone3591652011-07-28 21:54:31 +00001084 else
Craig Topperebc3aa22012-08-17 05:16:15 +00001085 o.indent(Indentation) << "MI.addOperand(MCOperand::CreateImm(tmp));\n";
Owen Andersone3591652011-07-28 21:54:31 +00001086
1087}
1088
Jim Grosbachecaef492012-08-14 19:06:05 +00001089void FilterChooser::emitDecoder(raw_ostream &OS, unsigned Indentation,
1090 unsigned Opc) const {
1091 std::map<unsigned, std::vector<OperandInfo> >::const_iterator OpIter =
1092 Operands.find(Opc);
1093 const std::vector<OperandInfo>& InsnOperands = OpIter->second;
1094 for (std::vector<OperandInfo>::const_iterator
1095 I = InsnOperands.begin(), E = InsnOperands.end(); I != E; ++I) {
1096 // If a custom instruction decoder was specified, use that.
1097 if (I->numFields() == 0 && I->Decoder.size()) {
Craig Topperebc3aa22012-08-17 05:16:15 +00001098 OS.indent(Indentation) << Emitter->GuardPrefix << I->Decoder
Jim Grosbachecaef492012-08-14 19:06:05 +00001099 << "(MI, insn, Address, Decoder)"
1100 << Emitter->GuardPostfix << "\n";
1101 break;
1102 }
1103
1104 emitBinaryParser(OS, Indentation, *I);
1105 }
1106}
1107
1108unsigned FilterChooser::getDecoderIndex(DecoderSet &Decoders,
1109 unsigned Opc) const {
1110 // Build up the predicate string.
1111 SmallString<256> Decoder;
1112 // FIXME: emitDecoder() function can take a buffer directly rather than
1113 // a stream.
1114 raw_svector_ostream S(Decoder);
Craig Topperebc3aa22012-08-17 05:16:15 +00001115 unsigned I = 4;
Jim Grosbachecaef492012-08-14 19:06:05 +00001116 emitDecoder(S, I, Opc);
1117 S.flush();
1118
1119 // Using the full decoder string as the key value here is a bit
1120 // heavyweight, but is effective. If the string comparisons become a
1121 // performance concern, we can implement a mangling of the predicate
1122 // data easilly enough with a map back to the actual string. That's
1123 // overkill for now, though.
1124
1125 // Make sure the predicate is in the table.
1126 Decoders.insert(Decoder.str());
1127 // Now figure out the index for when we write out the table.
1128 DecoderSet::const_iterator P = std::find(Decoders.begin(),
1129 Decoders.end(),
1130 Decoder.str());
1131 return (unsigned)(P - Decoders.begin());
1132}
1133
James Molloy8067df92011-09-07 19:42:28 +00001134static void emitSinglePredicateMatch(raw_ostream &o, StringRef str,
Craig Topper48c112b2012-03-16 05:58:09 +00001135 const std::string &PredicateNamespace) {
Andrew Trick43674ad2011-09-08 05:25:49 +00001136 if (str[0] == '!')
1137 o << "!(Bits & " << PredicateNamespace << "::"
1138 << str.slice(1,str.size()) << ")";
James Molloy8067df92011-09-07 19:42:28 +00001139 else
Andrew Trick43674ad2011-09-08 05:25:49 +00001140 o << "(Bits & " << PredicateNamespace << "::" << str << ")";
James Molloy8067df92011-09-07 19:42:28 +00001141}
1142
1143bool FilterChooser::emitPredicateMatch(raw_ostream &o, unsigned &Indentation,
Craig Topper48c112b2012-03-16 05:58:09 +00001144 unsigned Opc) const {
Jim Grosbach3f4b2392012-02-29 22:07:56 +00001145 ListInit *Predicates =
1146 AllInstructions[Opc]->TheDef->getValueAsListInit("Predicates");
James Molloy8067df92011-09-07 19:42:28 +00001147 for (unsigned i = 0; i < Predicates->getSize(); ++i) {
1148 Record *Pred = Predicates->getElementAsRecord(i);
1149 if (!Pred->getValue("AssemblerMatcherPredicate"))
1150 continue;
1151
1152 std::string P = Pred->getValueAsString("AssemblerCondString");
1153
1154 if (!P.length())
1155 continue;
1156
1157 if (i != 0)
1158 o << " && ";
1159
1160 StringRef SR(P);
1161 std::pair<StringRef, StringRef> pairs = SR.split(',');
1162 while (pairs.second.size()) {
1163 emitSinglePredicateMatch(o, pairs.first, Emitter->PredicateNamespace);
1164 o << " && ";
1165 pairs = pairs.second.split(',');
1166 }
1167 emitSinglePredicateMatch(o, pairs.first, Emitter->PredicateNamespace);
1168 }
1169 return Predicates->getSize() > 0;
Andrew Trick61abca62011-09-08 05:23:14 +00001170}
James Molloy8067df92011-09-07 19:42:28 +00001171
Jim Grosbachecaef492012-08-14 19:06:05 +00001172bool FilterChooser::doesOpcodeNeedPredicate(unsigned Opc) const {
1173 ListInit *Predicates =
1174 AllInstructions[Opc]->TheDef->getValueAsListInit("Predicates");
1175 for (unsigned i = 0; i < Predicates->getSize(); ++i) {
1176 Record *Pred = Predicates->getElementAsRecord(i);
1177 if (!Pred->getValue("AssemblerMatcherPredicate"))
1178 continue;
1179
1180 std::string P = Pred->getValueAsString("AssemblerCondString");
1181
1182 if (!P.length())
1183 continue;
1184
1185 return true;
1186 }
1187 return false;
1188}
1189
1190unsigned FilterChooser::getPredicateIndex(DecoderTableInfo &TableInfo,
1191 StringRef Predicate) const {
1192 // Using the full predicate string as the key value here is a bit
1193 // heavyweight, but is effective. If the string comparisons become a
1194 // performance concern, we can implement a mangling of the predicate
1195 // data easilly enough with a map back to the actual string. That's
1196 // overkill for now, though.
1197
1198 // Make sure the predicate is in the table.
1199 TableInfo.Predicates.insert(Predicate.str());
1200 // Now figure out the index for when we write out the table.
1201 PredicateSet::const_iterator P = std::find(TableInfo.Predicates.begin(),
1202 TableInfo.Predicates.end(),
1203 Predicate.str());
1204 return (unsigned)(P - TableInfo.Predicates.begin());
1205}
1206
1207void FilterChooser::emitPredicateTableEntry(DecoderTableInfo &TableInfo,
1208 unsigned Opc) const {
1209 if (!doesOpcodeNeedPredicate(Opc))
1210 return;
1211
1212 // Build up the predicate string.
1213 SmallString<256> Predicate;
1214 // FIXME: emitPredicateMatch() functions can take a buffer directly rather
1215 // than a stream.
1216 raw_svector_ostream PS(Predicate);
1217 unsigned I = 0;
1218 emitPredicateMatch(PS, I, Opc);
1219
1220 // Figure out the index into the predicate table for the predicate just
1221 // computed.
1222 unsigned PIdx = getPredicateIndex(TableInfo, PS.str());
1223 SmallString<16> PBytes;
1224 raw_svector_ostream S(PBytes);
1225 encodeULEB128(PIdx, S);
1226 S.flush();
1227
1228 TableInfo.Table.push_back(MCD::OPC_CheckPredicate);
1229 // Predicate index
Craig Topper29688ab2012-08-17 05:42:16 +00001230 for (unsigned i = 0, e = PBytes.size(); i != e; ++i)
Jim Grosbachecaef492012-08-14 19:06:05 +00001231 TableInfo.Table.push_back(PBytes[i]);
1232 // Push location for NumToSkip backpatching.
1233 TableInfo.FixupStack.back().push_back(TableInfo.Table.size());
1234 TableInfo.Table.push_back(0);
1235 TableInfo.Table.push_back(0);
1236}
1237
1238void FilterChooser::emitSoftFailTableEntry(DecoderTableInfo &TableInfo,
1239 unsigned Opc) const {
Jim Grosbach3f4b2392012-02-29 22:07:56 +00001240 BitsInit *SFBits =
1241 AllInstructions[Opc]->TheDef->getValueAsBitsInit("SoftFail");
James Molloyd9ba4fd2012-02-09 10:56:31 +00001242 if (!SFBits) return;
1243 BitsInit *InstBits = AllInstructions[Opc]->TheDef->getValueAsBitsInit("Inst");
1244
1245 APInt PositiveMask(BitWidth, 0ULL);
1246 APInt NegativeMask(BitWidth, 0ULL);
1247 for (unsigned i = 0; i < BitWidth; ++i) {
1248 bit_value_t B = bitFromBits(*SFBits, i);
1249 bit_value_t IB = bitFromBits(*InstBits, i);
1250
1251 if (B != BIT_TRUE) continue;
1252
1253 switch (IB) {
1254 case BIT_FALSE:
1255 // The bit is meant to be false, so emit a check to see if it is true.
1256 PositiveMask.setBit(i);
1257 break;
1258 case BIT_TRUE:
1259 // The bit is meant to be true, so emit a check to see if it is false.
1260 NegativeMask.setBit(i);
1261 break;
1262 default:
1263 // The bit is not set; this must be an error!
1264 StringRef Name = AllInstructions[Opc]->TheDef->getName();
Jim Grosbachecaef492012-08-14 19:06:05 +00001265 errs() << "SoftFail Conflict: bit SoftFail{" << i << "} in " << Name
1266 << " is set but Inst{" << i << "} is unset!\n"
James Molloyd9ba4fd2012-02-09 10:56:31 +00001267 << " - You can only mark a bit as SoftFail if it is fully defined"
1268 << " (1/0 - not '?') in Inst\n";
Jim Grosbachecaef492012-08-14 19:06:05 +00001269 return;
James Molloyd9ba4fd2012-02-09 10:56:31 +00001270 }
1271 }
1272
1273 bool NeedPositiveMask = PositiveMask.getBoolValue();
1274 bool NeedNegativeMask = NegativeMask.getBoolValue();
1275
1276 if (!NeedPositiveMask && !NeedNegativeMask)
1277 return;
1278
Jim Grosbachecaef492012-08-14 19:06:05 +00001279 TableInfo.Table.push_back(MCD::OPC_SoftFail);
James Molloyd9ba4fd2012-02-09 10:56:31 +00001280
Jim Grosbachecaef492012-08-14 19:06:05 +00001281 SmallString<16> MaskBytes;
1282 raw_svector_ostream S(MaskBytes);
1283 if (NeedPositiveMask) {
1284 encodeULEB128(PositiveMask.getZExtValue(), S);
1285 S.flush();
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);
1290 if (NeedNegativeMask) {
1291 MaskBytes.clear();
1292 S.resync();
1293 encodeULEB128(NegativeMask.getZExtValue(), S);
1294 S.flush();
Craig Topper29688ab2012-08-17 05:42:16 +00001295 for (unsigned i = 0, e = MaskBytes.size(); i != e; ++i)
Jim Grosbachecaef492012-08-14 19:06:05 +00001296 TableInfo.Table.push_back(MaskBytes[i]);
1297 } else
1298 TableInfo.Table.push_back(0);
James Molloyd9ba4fd2012-02-09 10:56:31 +00001299}
1300
Jim Grosbachecaef492012-08-14 19:06:05 +00001301// Emits table entries to decode the singleton.
1302void FilterChooser::emitSingletonTableEntry(DecoderTableInfo &TableInfo,
1303 unsigned Opc) const {
Owen Anderson4e818902011-02-18 21:51:29 +00001304 std::vector<unsigned> StartBits;
1305 std::vector<unsigned> EndBits;
1306 std::vector<uint64_t> FieldVals;
1307 insn_t Insn;
1308 insnWithID(Insn, Opc);
1309
1310 // Look for islands of undecoded bits of the singleton.
1311 getIslands(StartBits, EndBits, FieldVals, Insn);
1312
1313 unsigned Size = StartBits.size();
Owen Anderson4e818902011-02-18 21:51:29 +00001314
Jim Grosbachecaef492012-08-14 19:06:05 +00001315 // Emit the predicate table entry if one is needed.
1316 emitPredicateTableEntry(TableInfo, Opc);
Owen Anderson4e818902011-02-18 21:51:29 +00001317
Jim Grosbachecaef492012-08-14 19:06:05 +00001318 // Check any additional encoding fields needed.
Craig Topper29688ab2012-08-17 05:42:16 +00001319 for (unsigned I = Size; I != 0; --I) {
1320 unsigned NumBits = EndBits[I-1] - StartBits[I-1] + 1;
Jim Grosbachecaef492012-08-14 19:06:05 +00001321 TableInfo.Table.push_back(MCD::OPC_CheckField);
1322 TableInfo.Table.push_back(StartBits[I-1]);
1323 TableInfo.Table.push_back(NumBits);
1324 uint8_t Buffer[8], *p;
1325 encodeULEB128(FieldVals[I-1], Buffer);
1326 for (p = Buffer; *p >= 128 ; ++p)
1327 TableInfo.Table.push_back(*p);
1328 TableInfo.Table.push_back(*p);
1329 // Push location for NumToSkip backpatching.
1330 TableInfo.FixupStack.back().push_back(TableInfo.Table.size());
1331 // The fixup is always 16-bits, so go ahead and allocate the space
1332 // in the table so all our relative position calculations work OK even
1333 // before we fully resolve the real value here.
1334 TableInfo.Table.push_back(0);
1335 TableInfo.Table.push_back(0);
Owen Anderson4e818902011-02-18 21:51:29 +00001336 }
Owen Anderson4e818902011-02-18 21:51:29 +00001337
Jim Grosbachecaef492012-08-14 19:06:05 +00001338 // Check for soft failure of the match.
1339 emitSoftFailTableEntry(TableInfo, Opc);
Owen Anderson4e818902011-02-18 21:51:29 +00001340
Jim Grosbachecaef492012-08-14 19:06:05 +00001341 TableInfo.Table.push_back(MCD::OPC_Decode);
1342 uint8_t Buffer[8], *p;
1343 encodeULEB128(Opc, Buffer);
1344 for (p = Buffer; *p >= 128 ; ++p)
1345 TableInfo.Table.push_back(*p);
1346 TableInfo.Table.push_back(*p);
1347
1348 unsigned DIdx = getDecoderIndex(TableInfo.Decoders, Opc);
1349 SmallString<16> Bytes;
1350 raw_svector_ostream S(Bytes);
1351 encodeULEB128(DIdx, S);
1352 S.flush();
1353
1354 // Decoder index
Craig Topper29688ab2012-08-17 05:42:16 +00001355 for (unsigned i = 0, e = Bytes.size(); i != e; ++i)
Jim Grosbachecaef492012-08-14 19:06:05 +00001356 TableInfo.Table.push_back(Bytes[i]);
Owen Anderson4e818902011-02-18 21:51:29 +00001357}
1358
Jim Grosbachecaef492012-08-14 19:06:05 +00001359// Emits table entries to decode the singleton, and then to decode the rest.
1360void FilterChooser::emitSingletonTableEntry(DecoderTableInfo &TableInfo,
1361 const Filter &Best) const {
Owen Anderson4e818902011-02-18 21:51:29 +00001362 unsigned Opc = Best.getSingletonOpc();
1363
Jim Grosbachecaef492012-08-14 19:06:05 +00001364 // complex singletons need predicate checks from the first singleton
1365 // to refer forward to the variable filterchooser that follows.
1366 TableInfo.FixupStack.push_back(FixupList());
Owen Anderson4e818902011-02-18 21:51:29 +00001367
Jim Grosbachecaef492012-08-14 19:06:05 +00001368 emitSingletonTableEntry(TableInfo, Opc);
Owen Anderson4e818902011-02-18 21:51:29 +00001369
Jim Grosbachecaef492012-08-14 19:06:05 +00001370 resolveTableFixups(TableInfo.Table, TableInfo.FixupStack.back(),
1371 TableInfo.Table.size());
1372 TableInfo.FixupStack.pop_back();
1373
1374 Best.getVariableFC().emitTableEntries(TableInfo);
Owen Anderson4e818902011-02-18 21:51:29 +00001375}
1376
Jim Grosbachecaef492012-08-14 19:06:05 +00001377
Owen Anderson4e818902011-02-18 21:51:29 +00001378// Assign a single filter and run with it. Top level API client can initialize
1379// with a single filter to start the filtering process.
Craig Topper48c112b2012-03-16 05:58:09 +00001380void FilterChooser::runSingleFilter(unsigned startBit, unsigned numBit,
1381 bool mixed) {
Owen Anderson4e818902011-02-18 21:51:29 +00001382 Filters.clear();
Craig Topper5c2b4ac2014-09-03 05:49:07 +00001383 Filters.push_back(Filter(*this, startBit, numBit, true));
Owen Anderson4e818902011-02-18 21:51:29 +00001384 BestIndex = 0; // Sole Filter instance to choose from.
1385 bestFilter().recurse();
1386}
1387
1388// reportRegion is a helper function for filterProcessor to mark a region as
1389// eligible for use as a filter region.
1390void FilterChooser::reportRegion(bitAttr_t RA, unsigned StartBit,
Craig Topper82d0d5f2012-03-16 01:19:24 +00001391 unsigned BitIndex, bool AllowMixed) {
Owen Anderson4e818902011-02-18 21:51:29 +00001392 if (RA == ATTR_MIXED && AllowMixed)
1393 Filters.push_back(Filter(*this, StartBit, BitIndex - StartBit, true));
1394 else if (RA == ATTR_ALL_SET && !AllowMixed)
1395 Filters.push_back(Filter(*this, StartBit, BitIndex - StartBit, false));
1396}
1397
1398// FilterProcessor scans the well-known encoding bits of the instructions and
1399// builds up a list of candidate filters. It chooses the best filter and
1400// recursively descends down the decoding tree.
1401bool FilterChooser::filterProcessor(bool AllowMixed, bool Greedy) {
1402 Filters.clear();
1403 BestIndex = -1;
1404 unsigned numInstructions = Opcodes.size();
1405
1406 assert(numInstructions && "Filter created with no instructions");
1407
1408 // No further filtering is necessary.
1409 if (numInstructions == 1)
1410 return true;
1411
1412 // Heuristics. See also doFilter()'s "Heuristics" comment when num of
1413 // instructions is 3.
1414 if (AllowMixed && !Greedy) {
1415 assert(numInstructions == 3);
1416
1417 for (unsigned i = 0; i < Opcodes.size(); ++i) {
1418 std::vector<unsigned> StartBits;
1419 std::vector<unsigned> EndBits;
1420 std::vector<uint64_t> FieldVals;
1421 insn_t Insn;
1422
1423 insnWithID(Insn, Opcodes[i]);
1424
1425 // Look for islands of undecoded bits of any instruction.
1426 if (getIslands(StartBits, EndBits, FieldVals, Insn) > 0) {
1427 // Found an instruction with island(s). Now just assign a filter.
Craig Topper48c112b2012-03-16 05:58:09 +00001428 runSingleFilter(StartBits[0], EndBits[0] - StartBits[0] + 1, true);
Owen Anderson4e818902011-02-18 21:51:29 +00001429 return true;
1430 }
1431 }
1432 }
1433
Craig Topper29688ab2012-08-17 05:42:16 +00001434 unsigned BitIndex;
Owen Anderson4e818902011-02-18 21:51:29 +00001435
1436 // We maintain BIT_WIDTH copies of the bitAttrs automaton.
1437 // The automaton consumes the corresponding bit from each
1438 // instruction.
1439 //
1440 // Input symbols: 0, 1, and _ (unset).
1441 // States: NONE, FILTERED, ALL_SET, ALL_UNSET, and MIXED.
1442 // Initial state: NONE.
1443 //
1444 // (NONE) ------- [01] -> (ALL_SET)
1445 // (NONE) ------- _ ----> (ALL_UNSET)
1446 // (ALL_SET) ---- [01] -> (ALL_SET)
1447 // (ALL_SET) ---- _ ----> (MIXED)
1448 // (ALL_UNSET) -- [01] -> (MIXED)
1449 // (ALL_UNSET) -- _ ----> (ALL_UNSET)
1450 // (MIXED) ------ . ----> (MIXED)
1451 // (FILTERED)---- . ----> (FILTERED)
1452
Owen Andersonc78e03c2011-07-19 21:06:00 +00001453 std::vector<bitAttr_t> bitAttrs;
Owen Anderson4e818902011-02-18 21:51:29 +00001454
1455 // FILTERED bit positions provide no entropy and are not worthy of pursuing.
1456 // Filter::recurse() set either BIT_TRUE or BIT_FALSE for each position.
Owen Andersonc78e03c2011-07-19 21:06:00 +00001457 for (BitIndex = 0; BitIndex < BitWidth; ++BitIndex)
Owen Anderson4e818902011-02-18 21:51:29 +00001458 if (FilterBitValues[BitIndex] == BIT_TRUE ||
1459 FilterBitValues[BitIndex] == BIT_FALSE)
Owen Andersonc78e03c2011-07-19 21:06:00 +00001460 bitAttrs.push_back(ATTR_FILTERED);
Owen Anderson4e818902011-02-18 21:51:29 +00001461 else
Owen Andersonc78e03c2011-07-19 21:06:00 +00001462 bitAttrs.push_back(ATTR_NONE);
Owen Anderson4e818902011-02-18 21:51:29 +00001463
Craig Topper29688ab2012-08-17 05:42:16 +00001464 for (unsigned InsnIndex = 0; InsnIndex < numInstructions; ++InsnIndex) {
Owen Anderson4e818902011-02-18 21:51:29 +00001465 insn_t insn;
1466
1467 insnWithID(insn, Opcodes[InsnIndex]);
1468
Owen Andersonc78e03c2011-07-19 21:06:00 +00001469 for (BitIndex = 0; BitIndex < BitWidth; ++BitIndex) {
Owen Anderson4e818902011-02-18 21:51:29 +00001470 switch (bitAttrs[BitIndex]) {
1471 case ATTR_NONE:
1472 if (insn[BitIndex] == BIT_UNSET)
1473 bitAttrs[BitIndex] = ATTR_ALL_UNSET;
1474 else
1475 bitAttrs[BitIndex] = ATTR_ALL_SET;
1476 break;
1477 case ATTR_ALL_SET:
1478 if (insn[BitIndex] == BIT_UNSET)
1479 bitAttrs[BitIndex] = ATTR_MIXED;
1480 break;
1481 case ATTR_ALL_UNSET:
1482 if (insn[BitIndex] != BIT_UNSET)
1483 bitAttrs[BitIndex] = ATTR_MIXED;
1484 break;
1485 case ATTR_MIXED:
1486 case ATTR_FILTERED:
1487 break;
1488 }
1489 }
1490 }
1491
1492 // The regionAttr automaton consumes the bitAttrs automatons' state,
1493 // lowest-to-highest.
1494 //
1495 // Input symbols: F(iltered), (all_)S(et), (all_)U(nset), M(ixed)
1496 // States: NONE, ALL_SET, MIXED
1497 // Initial state: NONE
1498 //
1499 // (NONE) ----- F --> (NONE)
1500 // (NONE) ----- S --> (ALL_SET) ; and set region start
1501 // (NONE) ----- U --> (NONE)
1502 // (NONE) ----- M --> (MIXED) ; and set region start
1503 // (ALL_SET) -- F --> (NONE) ; and report an ALL_SET region
1504 // (ALL_SET) -- S --> (ALL_SET)
1505 // (ALL_SET) -- U --> (NONE) ; and report an ALL_SET region
1506 // (ALL_SET) -- M --> (MIXED) ; and report an ALL_SET region
1507 // (MIXED) ---- F --> (NONE) ; and report a MIXED region
1508 // (MIXED) ---- S --> (ALL_SET) ; and report a MIXED region
1509 // (MIXED) ---- U --> (NONE) ; and report a MIXED region
1510 // (MIXED) ---- M --> (MIXED)
1511
1512 bitAttr_t RA = ATTR_NONE;
1513 unsigned StartBit = 0;
1514
Craig Topper29688ab2012-08-17 05:42:16 +00001515 for (BitIndex = 0; BitIndex < BitWidth; ++BitIndex) {
Owen Anderson4e818902011-02-18 21:51:29 +00001516 bitAttr_t bitAttr = bitAttrs[BitIndex];
1517
1518 assert(bitAttr != ATTR_NONE && "Bit without attributes");
1519
1520 switch (RA) {
1521 case ATTR_NONE:
1522 switch (bitAttr) {
1523 case ATTR_FILTERED:
1524 break;
1525 case ATTR_ALL_SET:
1526 StartBit = BitIndex;
1527 RA = ATTR_ALL_SET;
1528 break;
1529 case ATTR_ALL_UNSET:
1530 break;
1531 case ATTR_MIXED:
1532 StartBit = BitIndex;
1533 RA = ATTR_MIXED;
1534 break;
1535 default:
Craig Topperc4965bc2012-02-05 07:21:30 +00001536 llvm_unreachable("Unexpected bitAttr!");
Owen Anderson4e818902011-02-18 21:51:29 +00001537 }
1538 break;
1539 case ATTR_ALL_SET:
1540 switch (bitAttr) {
1541 case ATTR_FILTERED:
1542 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1543 RA = ATTR_NONE;
1544 break;
1545 case ATTR_ALL_SET:
1546 break;
1547 case ATTR_ALL_UNSET:
1548 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1549 RA = ATTR_NONE;
1550 break;
1551 case ATTR_MIXED:
1552 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1553 StartBit = BitIndex;
1554 RA = ATTR_MIXED;
1555 break;
1556 default:
Craig Topperc4965bc2012-02-05 07:21:30 +00001557 llvm_unreachable("Unexpected bitAttr!");
Owen Anderson4e818902011-02-18 21:51:29 +00001558 }
1559 break;
1560 case ATTR_MIXED:
1561 switch (bitAttr) {
1562 case ATTR_FILTERED:
1563 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1564 StartBit = BitIndex;
1565 RA = ATTR_NONE;
1566 break;
1567 case ATTR_ALL_SET:
1568 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1569 StartBit = BitIndex;
1570 RA = ATTR_ALL_SET;
1571 break;
1572 case ATTR_ALL_UNSET:
1573 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1574 RA = ATTR_NONE;
1575 break;
1576 case ATTR_MIXED:
1577 break;
1578 default:
Craig Topperc4965bc2012-02-05 07:21:30 +00001579 llvm_unreachable("Unexpected bitAttr!");
Owen Anderson4e818902011-02-18 21:51:29 +00001580 }
1581 break;
1582 case ATTR_ALL_UNSET:
Craig Topperc4965bc2012-02-05 07:21:30 +00001583 llvm_unreachable("regionAttr state machine has no ATTR_UNSET state");
Owen Anderson4e818902011-02-18 21:51:29 +00001584 case ATTR_FILTERED:
Craig Topperc4965bc2012-02-05 07:21:30 +00001585 llvm_unreachable("regionAttr state machine has no ATTR_FILTERED state");
Owen Anderson4e818902011-02-18 21:51:29 +00001586 }
1587 }
1588
1589 // At the end, if we're still in ALL_SET or MIXED states, report a region
1590 switch (RA) {
1591 case ATTR_NONE:
1592 break;
1593 case ATTR_FILTERED:
1594 break;
1595 case ATTR_ALL_SET:
1596 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1597 break;
1598 case ATTR_ALL_UNSET:
1599 break;
1600 case ATTR_MIXED:
1601 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1602 break;
1603 }
1604
1605 // We have finished with the filter processings. Now it's time to choose
1606 // the best performing filter.
1607 BestIndex = 0;
1608 bool AllUseless = true;
1609 unsigned BestScore = 0;
1610
1611 for (unsigned i = 0, e = Filters.size(); i != e; ++i) {
1612 unsigned Usefulness = Filters[i].usefulness();
1613
1614 if (Usefulness)
1615 AllUseless = false;
1616
1617 if (Usefulness > BestScore) {
1618 BestIndex = i;
1619 BestScore = Usefulness;
1620 }
1621 }
1622
1623 if (!AllUseless)
1624 bestFilter().recurse();
1625
1626 return !AllUseless;
1627} // end of FilterChooser::filterProcessor(bool)
1628
1629// Decides on the best configuration of filter(s) to use in order to decode
1630// the instructions. A conflict of instructions may occur, in which case we
1631// dump the conflict set to the standard error.
1632void FilterChooser::doFilter() {
1633 unsigned Num = Opcodes.size();
1634 assert(Num && "FilterChooser created with no instructions");
1635
1636 // Try regions of consecutive known bit values first.
1637 if (filterProcessor(false))
1638 return;
1639
1640 // Then regions of mixed bits (both known and unitialized bit values allowed).
1641 if (filterProcessor(true))
1642 return;
1643
1644 // Heuristics to cope with conflict set {t2CMPrs, t2SUBSrr, t2SUBSrs} where
1645 // no single instruction for the maximum ATTR_MIXED region Inst{14-4} has a
1646 // well-known encoding pattern. In such case, we backtrack and scan for the
1647 // the very first consecutive ATTR_ALL_SET region and assign a filter to it.
1648 if (Num == 3 && filterProcessor(true, false))
1649 return;
1650
1651 // If we come to here, the instruction decoding has failed.
1652 // Set the BestIndex to -1 to indicate so.
1653 BestIndex = -1;
1654}
1655
Jim Grosbachecaef492012-08-14 19:06:05 +00001656// emitTableEntries - Emit state machine entries to decode our share of
1657// instructions.
1658void FilterChooser::emitTableEntries(DecoderTableInfo &TableInfo) const {
1659 if (Opcodes.size() == 1) {
Owen Anderson4e818902011-02-18 21:51:29 +00001660 // There is only one instruction in the set, which is great!
1661 // Call emitSingletonDecoder() to see whether there are any remaining
1662 // encodings bits.
Jim Grosbachecaef492012-08-14 19:06:05 +00001663 emitSingletonTableEntry(TableInfo, Opcodes[0]);
1664 return;
1665 }
Owen Anderson4e818902011-02-18 21:51:29 +00001666
1667 // Choose the best filter to do the decodings!
1668 if (BestIndex != -1) {
Craig Topper48c112b2012-03-16 05:58:09 +00001669 const Filter &Best = Filters[BestIndex];
Owen Anderson4e818902011-02-18 21:51:29 +00001670 if (Best.getNumFiltered() == 1)
Jim Grosbachecaef492012-08-14 19:06:05 +00001671 emitSingletonTableEntry(TableInfo, Best);
Owen Anderson4e818902011-02-18 21:51:29 +00001672 else
Jim Grosbachecaef492012-08-14 19:06:05 +00001673 Best.emitTableEntry(TableInfo);
1674 return;
Owen Anderson4e818902011-02-18 21:51:29 +00001675 }
1676
Jim Grosbachecaef492012-08-14 19:06:05 +00001677 // We don't know how to decode these instructions! Dump the
1678 // conflict set and bail.
Owen Anderson4e818902011-02-18 21:51:29 +00001679
1680 // Print out useful conflict information for postmortem analysis.
1681 errs() << "Decoding Conflict:\n";
1682
1683 dumpStack(errs(), "\t\t");
1684
Craig Topper82d0d5f2012-03-16 01:19:24 +00001685 for (unsigned i = 0; i < Opcodes.size(); ++i) {
Owen Anderson4e818902011-02-18 21:51:29 +00001686 const std::string &Name = nameWithID(Opcodes[i]);
1687
1688 errs() << '\t' << Name << " ";
1689 dumpBits(errs(),
1690 getBitsField(*AllInstructions[Opcodes[i]]->TheDef, "Inst"));
1691 errs() << '\n';
1692 }
Owen Anderson4e818902011-02-18 21:51:29 +00001693}
1694
Hal Finkel71b2e202013-12-19 16:12:53 +00001695static bool populateInstruction(CodeGenTarget &Target,
1696 const CodeGenInstruction &CGI, unsigned Opc,
Craig Topper82d0d5f2012-03-16 01:19:24 +00001697 std::map<unsigned, std::vector<OperandInfo> > &Operands){
Owen Anderson4e818902011-02-18 21:51:29 +00001698 const Record &Def = *CGI.TheDef;
1699 // If all the bit positions are not specified; do not decode this instruction.
1700 // We are bound to fail! For proper disassembly, the well-known encoding bits
1701 // of the instruction must be fully specified.
Owen Anderson4e818902011-02-18 21:51:29 +00001702
David Greeneaf8ee2c2011-07-29 22:43:06 +00001703 BitsInit &Bits = getBitsField(Def, "Inst");
Jim Grosbachf3fd36e2011-07-06 21:33:38 +00001704 if (Bits.allInComplete()) return false;
1705
Owen Anderson4e818902011-02-18 21:51:29 +00001706 std::vector<OperandInfo> InsnOperands;
1707
1708 // If the instruction has specified a custom decoding hook, use that instead
1709 // of trying to auto-generate the decoder.
1710 std::string InstDecoder = Def.getValueAsString("DecoderMethod");
1711 if (InstDecoder != "") {
Owen Andersone3591652011-07-28 21:54:31 +00001712 InsnOperands.push_back(OperandInfo(InstDecoder));
Owen Anderson4e818902011-02-18 21:51:29 +00001713 Operands[Opc] = InsnOperands;
1714 return true;
1715 }
1716
1717 // Generate a description of the operand of the instruction that we know
1718 // how to decode automatically.
1719 // FIXME: We'll need to have a way to manually override this as needed.
1720
1721 // Gather the outputs/inputs of the instruction, so we can find their
1722 // positions in the encoding. This assumes for now that they appear in the
1723 // MCInst in the order that they're listed.
David Greeneaf8ee2c2011-07-29 22:43:06 +00001724 std::vector<std::pair<Init*, std::string> > InOutOperands;
1725 DagInit *Out = Def.getValueAsDag("OutOperandList");
1726 DagInit *In = Def.getValueAsDag("InOperandList");
Owen Anderson4e818902011-02-18 21:51:29 +00001727 for (unsigned i = 0; i < Out->getNumArgs(); ++i)
1728 InOutOperands.push_back(std::make_pair(Out->getArg(i), Out->getArgName(i)));
1729 for (unsigned i = 0; i < In->getNumArgs(); ++i)
1730 InOutOperands.push_back(std::make_pair(In->getArg(i), In->getArgName(i)));
1731
Owen Anderson53562d02011-07-28 23:56:20 +00001732 // Search for tied operands, so that we can correctly instantiate
1733 // operands that are not explicitly represented in the encoding.
Owen Andersoncb32ce22011-07-29 18:28:52 +00001734 std::map<std::string, std::string> TiedNames;
Owen Anderson53562d02011-07-28 23:56:20 +00001735 for (unsigned i = 0; i < CGI.Operands.size(); ++i) {
1736 int tiedTo = CGI.Operands[i].getTiedRegister();
Owen Andersoncb32ce22011-07-29 18:28:52 +00001737 if (tiedTo != -1) {
Hal Finkel71b2e202013-12-19 16:12:53 +00001738 std::pair<unsigned, unsigned> SO =
1739 CGI.Operands.getSubOperandNumber(tiedTo);
1740 TiedNames[InOutOperands[i].second] = InOutOperands[SO.first].second;
1741 TiedNames[InOutOperands[SO.first].second] = InOutOperands[i].second;
1742 }
1743 }
1744
1745 std::map<std::string, std::vector<OperandInfo> > NumberedInsnOperands;
1746 std::set<std::string> NumberedInsnOperandsNoTie;
1747 if (Target.getInstructionSet()->
1748 getValueAsBit("decodePositionallyEncodedOperands")) {
1749 const std::vector<RecordVal> &Vals = Def.getValues();
1750 unsigned NumberedOp = 0;
1751
Hal Finkel5457bd02014-03-13 07:57:54 +00001752 std::set<unsigned> NamedOpIndices;
1753 if (Target.getInstructionSet()->
1754 getValueAsBit("noNamedPositionallyEncodedOperands"))
1755 // Collect the set of operand indices that might correspond to named
1756 // operand, and skip these when assigning operands based on position.
1757 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
1758 unsigned OpIdx;
1759 if (!CGI.Operands.hasOperandNamed(Vals[i].getName(), OpIdx))
1760 continue;
1761
1762 NamedOpIndices.insert(OpIdx);
1763 }
1764
Hal Finkel71b2e202013-12-19 16:12:53 +00001765 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
1766 // Ignore fixed fields in the record, we're looking for values like:
1767 // bits<5> RST = { ?, ?, ?, ?, ? };
1768 if (Vals[i].getPrefix() || Vals[i].getValue()->isComplete())
1769 continue;
1770
1771 // Determine if Vals[i] actually contributes to the Inst encoding.
1772 unsigned bi = 0;
1773 for (; bi < Bits.getNumBits(); ++bi) {
Craig Topper24064772014-04-15 07:20:03 +00001774 VarInit *Var = nullptr;
Hal Finkel71b2e202013-12-19 16:12:53 +00001775 VarBitInit *BI = dyn_cast<VarBitInit>(Bits.getBit(bi));
1776 if (BI)
1777 Var = dyn_cast<VarInit>(BI->getBitVar());
1778 else
1779 Var = dyn_cast<VarInit>(Bits.getBit(bi));
1780
1781 if (Var && Var->getName() == Vals[i].getName())
1782 break;
1783 }
1784
1785 if (bi == Bits.getNumBits())
1786 continue;
1787
1788 // Skip variables that correspond to explicitly-named operands.
1789 unsigned OpIdx;
1790 if (CGI.Operands.hasOperandNamed(Vals[i].getName(), OpIdx))
1791 continue;
1792
1793 // Get the bit range for this operand:
1794 unsigned bitStart = bi++, bitWidth = 1;
1795 for (; bi < Bits.getNumBits(); ++bi) {
Craig Topper24064772014-04-15 07:20:03 +00001796 VarInit *Var = nullptr;
Hal Finkel71b2e202013-12-19 16:12:53 +00001797 VarBitInit *BI = dyn_cast<VarBitInit>(Bits.getBit(bi));
1798 if (BI)
1799 Var = dyn_cast<VarInit>(BI->getBitVar());
1800 else
1801 Var = dyn_cast<VarInit>(Bits.getBit(bi));
1802
1803 if (!Var)
1804 break;
1805
1806 if (Var->getName() != Vals[i].getName())
1807 break;
1808
1809 ++bitWidth;
1810 }
1811
1812 unsigned NumberOps = CGI.Operands.size();
1813 while (NumberedOp < NumberOps &&
Hal Finkel5457bd02014-03-13 07:57:54 +00001814 (CGI.Operands.isFlatOperandNotEmitted(NumberedOp) ||
1815 (NamedOpIndices.size() && NamedOpIndices.count(
1816 CGI.Operands.getSubOperandNumber(NumberedOp).first))))
Hal Finkel71b2e202013-12-19 16:12:53 +00001817 ++NumberedOp;
1818
1819 OpIdx = NumberedOp++;
1820
1821 // OpIdx now holds the ordered operand number of Vals[i].
1822 std::pair<unsigned, unsigned> SO =
1823 CGI.Operands.getSubOperandNumber(OpIdx);
1824 const std::string &Name = CGI.Operands[SO.first].Name;
1825
1826 DEBUG(dbgs() << "Numbered operand mapping for " << Def.getName() << ": " <<
1827 Name << "(" << SO.first << ", " << SO.second << ") => " <<
1828 Vals[i].getName() << "\n");
1829
1830 std::string Decoder = "";
1831 Record *TypeRecord = CGI.Operands[SO.first].Rec;
1832
1833 RecordVal *DecoderString = TypeRecord->getValue("DecoderMethod");
1834 StringInit *String = DecoderString ?
Craig Topper24064772014-04-15 07:20:03 +00001835 dyn_cast<StringInit>(DecoderString->getValue()) : nullptr;
Hal Finkel71b2e202013-12-19 16:12:53 +00001836 if (String && String->getValue() != "")
1837 Decoder = String->getValue();
1838
1839 if (Decoder == "" &&
1840 CGI.Operands[SO.first].MIOperandInfo &&
1841 CGI.Operands[SO.first].MIOperandInfo->getNumArgs()) {
1842 Init *Arg = CGI.Operands[SO.first].MIOperandInfo->
1843 getArg(SO.second);
1844 if (TypedInit *TI = cast<TypedInit>(Arg)) {
1845 RecordRecTy *Type = cast<RecordRecTy>(TI->getType());
1846 TypeRecord = Type->getRecord();
1847 }
1848 }
1849
1850 bool isReg = false;
1851 if (TypeRecord->isSubClassOf("RegisterOperand"))
1852 TypeRecord = TypeRecord->getValueAsDef("RegClass");
1853 if (TypeRecord->isSubClassOf("RegisterClass")) {
1854 Decoder = "Decode" + TypeRecord->getName() + "RegisterClass";
1855 isReg = true;
1856 } else if (TypeRecord->isSubClassOf("PointerLikeRegClass")) {
1857 Decoder = "DecodePointerLikeRegClass" +
1858 utostr(TypeRecord->getValueAsInt("RegClassKind"));
1859 isReg = true;
1860 }
1861
1862 DecoderString = TypeRecord->getValue("DecoderMethod");
1863 String = DecoderString ?
Craig Topper24064772014-04-15 07:20:03 +00001864 dyn_cast<StringInit>(DecoderString->getValue()) : nullptr;
Hal Finkel71b2e202013-12-19 16:12:53 +00001865 if (!isReg && String && String->getValue() != "")
1866 Decoder = String->getValue();
1867
1868 OperandInfo OpInfo(Decoder);
1869 OpInfo.addField(bitStart, bitWidth, 0);
1870
1871 NumberedInsnOperands[Name].push_back(OpInfo);
1872
1873 // FIXME: For complex operands with custom decoders we can't handle tied
1874 // sub-operands automatically. Skip those here and assume that this is
1875 // fixed up elsewhere.
1876 if (CGI.Operands[SO.first].MIOperandInfo &&
1877 CGI.Operands[SO.first].MIOperandInfo->getNumArgs() > 1 &&
1878 String && String->getValue() != "")
1879 NumberedInsnOperandsNoTie.insert(Name);
Owen Andersoncb32ce22011-07-29 18:28:52 +00001880 }
Owen Anderson53562d02011-07-28 23:56:20 +00001881 }
1882
Owen Anderson4e818902011-02-18 21:51:29 +00001883 // For each operand, see if we can figure out where it is encoded.
Craig Topper501d95c2012-03-16 06:52:56 +00001884 for (std::vector<std::pair<Init*, std::string> >::const_iterator
Owen Anderson4e818902011-02-18 21:51:29 +00001885 NI = InOutOperands.begin(), NE = InOutOperands.end(); NI != NE; ++NI) {
Hal Finkel71b2e202013-12-19 16:12:53 +00001886 if (!NumberedInsnOperands[NI->second].empty()) {
1887 InsnOperands.insert(InsnOperands.end(),
1888 NumberedInsnOperands[NI->second].begin(),
1889 NumberedInsnOperands[NI->second].end());
1890 continue;
1891 } else if (!NumberedInsnOperands[TiedNames[NI->second]].empty()) {
1892 if (!NumberedInsnOperandsNoTie.count(TiedNames[NI->second])) {
1893 // Figure out to which (sub)operand we're tied.
1894 unsigned i = CGI.Operands.getOperandNamed(TiedNames[NI->second]);
1895 int tiedTo = CGI.Operands[i].getTiedRegister();
1896 if (tiedTo == -1) {
1897 i = CGI.Operands.getOperandNamed(NI->second);
1898 tiedTo = CGI.Operands[i].getTiedRegister();
1899 }
1900
1901 if (tiedTo != -1) {
1902 std::pair<unsigned, unsigned> SO =
1903 CGI.Operands.getSubOperandNumber(tiedTo);
1904
1905 InsnOperands.push_back(NumberedInsnOperands[TiedNames[NI->second]]
1906 [SO.second]);
1907 }
1908 }
1909 continue;
1910 }
1911
Owen Anderson4e818902011-02-18 21:51:29 +00001912 std::string Decoder = "";
1913
Owen Andersone3591652011-07-28 21:54:31 +00001914 // At this point, we can locate the field, but we need to know how to
1915 // interpret it. As a first step, require the target to provide callbacks
1916 // for decoding register classes.
1917 // FIXME: This need to be extended to handle instructions with custom
1918 // decoder methods, and operands with (simple) MIOperandInfo's.
Sean Silva88eb8dd2012-10-10 20:24:47 +00001919 TypedInit *TI = cast<TypedInit>(NI->first);
1920 RecordRecTy *Type = cast<RecordRecTy>(TI->getType());
Owen Andersone3591652011-07-28 21:54:31 +00001921 Record *TypeRecord = Type->getRecord();
1922 bool isReg = false;
1923 if (TypeRecord->isSubClassOf("RegisterOperand"))
1924 TypeRecord = TypeRecord->getValueAsDef("RegClass");
1925 if (TypeRecord->isSubClassOf("RegisterClass")) {
1926 Decoder = "Decode" + TypeRecord->getName() + "RegisterClass";
1927 isReg = true;
Hal Finkel9d95e8d2013-12-19 14:58:22 +00001928 } else if (TypeRecord->isSubClassOf("PointerLikeRegClass")) {
1929 Decoder = "DecodePointerLikeRegClass" +
1930 utostr(TypeRecord->getValueAsInt("RegClassKind"));
1931 isReg = true;
Owen Andersone3591652011-07-28 21:54:31 +00001932 }
1933
1934 RecordVal *DecoderString = TypeRecord->getValue("DecoderMethod");
David Greeneaf8ee2c2011-07-29 22:43:06 +00001935 StringInit *String = DecoderString ?
Craig Topper24064772014-04-15 07:20:03 +00001936 dyn_cast<StringInit>(DecoderString->getValue()) : nullptr;
Owen Andersone3591652011-07-28 21:54:31 +00001937 if (!isReg && String && String->getValue() != "")
1938 Decoder = String->getValue();
1939
1940 OperandInfo OpInfo(Decoder);
1941 unsigned Base = ~0U;
1942 unsigned Width = 0;
1943 unsigned Offset = 0;
1944
Owen Anderson4e818902011-02-18 21:51:29 +00001945 for (unsigned bi = 0; bi < Bits.getNumBits(); ++bi) {
Craig Topper24064772014-04-15 07:20:03 +00001946 VarInit *Var = nullptr;
Sean Silvafb509ed2012-10-10 20:24:43 +00001947 VarBitInit *BI = dyn_cast<VarBitInit>(Bits.getBit(bi));
Owen Anderson3022d672011-08-01 22:45:43 +00001948 if (BI)
Sean Silvafb509ed2012-10-10 20:24:43 +00001949 Var = dyn_cast<VarInit>(BI->getBitVar());
Owen Anderson3022d672011-08-01 22:45:43 +00001950 else
Sean Silvafb509ed2012-10-10 20:24:43 +00001951 Var = dyn_cast<VarInit>(Bits.getBit(bi));
Owen Anderson3022d672011-08-01 22:45:43 +00001952
1953 if (!Var) {
Owen Andersone3591652011-07-28 21:54:31 +00001954 if (Base != ~0U) {
1955 OpInfo.addField(Base, Width, Offset);
1956 Base = ~0U;
1957 Width = 0;
1958 Offset = 0;
1959 }
1960 continue;
1961 }
Owen Anderson4e818902011-02-18 21:51:29 +00001962
Owen Anderson53562d02011-07-28 23:56:20 +00001963 if (Var->getName() != NI->second &&
Owen Andersoncb32ce22011-07-29 18:28:52 +00001964 Var->getName() != TiedNames[NI->second]) {
Owen Andersone3591652011-07-28 21:54:31 +00001965 if (Base != ~0U) {
1966 OpInfo.addField(Base, Width, Offset);
1967 Base = ~0U;
1968 Width = 0;
1969 Offset = 0;
1970 }
1971 continue;
Owen Anderson4e818902011-02-18 21:51:29 +00001972 }
1973
Owen Andersone3591652011-07-28 21:54:31 +00001974 if (Base == ~0U) {
1975 Base = bi;
1976 Width = 1;
Owen Anderson3022d672011-08-01 22:45:43 +00001977 Offset = BI ? BI->getBitNum() : 0;
1978 } else if (BI && BI->getBitNum() != Offset + Width) {
Owen Andersone08f5b52011-07-29 23:01:18 +00001979 OpInfo.addField(Base, Width, Offset);
1980 Base = bi;
1981 Width = 1;
1982 Offset = BI->getBitNum();
Owen Andersone3591652011-07-28 21:54:31 +00001983 } else {
1984 ++Width;
Owen Anderson4e818902011-02-18 21:51:29 +00001985 }
Owen Anderson4e818902011-02-18 21:51:29 +00001986 }
1987
Owen Andersone3591652011-07-28 21:54:31 +00001988 if (Base != ~0U)
1989 OpInfo.addField(Base, Width, Offset);
1990
1991 if (OpInfo.numFields() > 0)
1992 InsnOperands.push_back(OpInfo);
Owen Anderson4e818902011-02-18 21:51:29 +00001993 }
1994
1995 Operands[Opc] = InsnOperands;
1996
1997
1998#if 0
1999 DEBUG({
2000 // Dumps the instruction encoding bits.
2001 dumpBits(errs(), Bits);
2002
2003 errs() << '\n';
2004
2005 // Dumps the list of operand info.
2006 for (unsigned i = 0, e = CGI.Operands.size(); i != e; ++i) {
2007 const CGIOperandList::OperandInfo &Info = CGI.Operands[i];
2008 const std::string &OperandName = Info.Name;
2009 const Record &OperandDef = *Info.Rec;
2010
2011 errs() << "\t" << OperandName << " (" << OperandDef.getName() << ")\n";
2012 }
2013 });
2014#endif
2015
2016 return true;
2017}
2018
Jim Grosbachecaef492012-08-14 19:06:05 +00002019// emitFieldFromInstruction - Emit the templated helper function
2020// fieldFromInstruction().
2021static void emitFieldFromInstruction(formatted_raw_ostream &OS) {
2022 OS << "// Helper function for extracting fields from encoded instructions.\n"
2023 << "template<typename InsnType>\n"
2024 << "static InsnType fieldFromInstruction(InsnType insn, unsigned startBit,\n"
2025 << " unsigned numBits) {\n"
2026 << " assert(startBit + numBits <= (sizeof(InsnType)*8) &&\n"
2027 << " \"Instruction field out of bounds!\");\n"
2028 << " InsnType fieldMask;\n"
2029 << " if (numBits == sizeof(InsnType)*8)\n"
2030 << " fieldMask = (InsnType)(-1LL);\n"
2031 << " else\n"
NAKAMURA Takumibf99a422012-12-26 06:43:14 +00002032 << " fieldMask = (((InsnType)1 << numBits) - 1) << startBit;\n"
Jim Grosbachecaef492012-08-14 19:06:05 +00002033 << " return (insn & fieldMask) >> startBit;\n"
2034 << "}\n\n";
2035}
Owen Anderson4e818902011-02-18 21:51:29 +00002036
Jim Grosbachecaef492012-08-14 19:06:05 +00002037// emitDecodeInstruction - Emit the templated helper function
2038// decodeInstruction().
2039static void emitDecodeInstruction(formatted_raw_ostream &OS) {
2040 OS << "template<typename InsnType>\n"
2041 << "static DecodeStatus decodeInstruction(const uint8_t DecodeTable[], MCInst &MI,\n"
2042 << " InsnType insn, uint64_t Address,\n"
2043 << " const void *DisAsm,\n"
2044 << " const MCSubtargetInfo &STI) {\n"
2045 << " uint64_t Bits = STI.getFeatureBits();\n"
2046 << "\n"
2047 << " const uint8_t *Ptr = DecodeTable;\n"
Jim Grosbach4c363492012-09-17 18:00:53 +00002048 << " uint32_t CurFieldValue = 0;\n"
Jim Grosbachecaef492012-08-14 19:06:05 +00002049 << " DecodeStatus S = MCDisassembler::Success;\n"
2050 << " for (;;) {\n"
2051 << " ptrdiff_t Loc = Ptr - DecodeTable;\n"
2052 << " switch (*Ptr) {\n"
2053 << " default:\n"
2054 << " errs() << Loc << \": Unexpected decode table opcode!\\n\";\n"
2055 << " return MCDisassembler::Fail;\n"
2056 << " case MCD::OPC_ExtractField: {\n"
2057 << " unsigned Start = *++Ptr;\n"
2058 << " unsigned Len = *++Ptr;\n"
2059 << " ++Ptr;\n"
2060 << " CurFieldValue = fieldFromInstruction(insn, Start, Len);\n"
2061 << " DEBUG(dbgs() << Loc << \": OPC_ExtractField(\" << Start << \", \"\n"
2062 << " << Len << \"): \" << CurFieldValue << \"\\n\");\n"
2063 << " break;\n"
2064 << " }\n"
2065 << " case MCD::OPC_FilterValue: {\n"
2066 << " // Decode the field value.\n"
2067 << " unsigned Len;\n"
2068 << " InsnType Val = decodeULEB128(++Ptr, &Len);\n"
2069 << " Ptr += Len;\n"
2070 << " // NumToSkip is a plain 16-bit integer.\n"
2071 << " unsigned NumToSkip = *Ptr++;\n"
2072 << " NumToSkip |= (*Ptr++) << 8;\n"
2073 << "\n"
2074 << " // Perform the filter operation.\n"
2075 << " if (Val != CurFieldValue)\n"
2076 << " Ptr += NumToSkip;\n"
2077 << " DEBUG(dbgs() << Loc << \": OPC_FilterValue(\" << Val << \", \" << NumToSkip\n"
2078 << " << \"): \" << ((Val != CurFieldValue) ? \"FAIL:\" : \"PASS:\")\n"
2079 << " << \" continuing at \" << (Ptr - DecodeTable) << \"\\n\");\n"
2080 << "\n"
2081 << " break;\n"
2082 << " }\n"
2083 << " case MCD::OPC_CheckField: {\n"
2084 << " unsigned Start = *++Ptr;\n"
2085 << " unsigned Len = *++Ptr;\n"
2086 << " InsnType FieldValue = fieldFromInstruction(insn, Start, Len);\n"
2087 << " // Decode the field value.\n"
2088 << " uint32_t ExpectedValue = decodeULEB128(++Ptr, &Len);\n"
2089 << " Ptr += Len;\n"
2090 << " // NumToSkip is a plain 16-bit integer.\n"
2091 << " unsigned NumToSkip = *Ptr++;\n"
2092 << " NumToSkip |= (*Ptr++) << 8;\n"
2093 << "\n"
2094 << " // If the actual and expected values don't match, skip.\n"
2095 << " if (ExpectedValue != FieldValue)\n"
2096 << " Ptr += NumToSkip;\n"
2097 << " DEBUG(dbgs() << Loc << \": OPC_CheckField(\" << Start << \", \"\n"
2098 << " << Len << \", \" << ExpectedValue << \", \" << NumToSkip\n"
2099 << " << \"): FieldValue = \" << FieldValue << \", ExpectedValue = \"\n"
2100 << " << ExpectedValue << \": \"\n"
2101 << " << ((ExpectedValue == FieldValue) ? \"PASS\\n\" : \"FAIL\\n\"));\n"
2102 << " break;\n"
2103 << " }\n"
2104 << " case MCD::OPC_CheckPredicate: {\n"
2105 << " unsigned Len;\n"
2106 << " // Decode the Predicate Index value.\n"
2107 << " unsigned PIdx = decodeULEB128(++Ptr, &Len);\n"
2108 << " Ptr += Len;\n"
2109 << " // NumToSkip is a plain 16-bit integer.\n"
2110 << " unsigned NumToSkip = *Ptr++;\n"
2111 << " NumToSkip |= (*Ptr++) << 8;\n"
2112 << " // Check the predicate.\n"
2113 << " bool Pred;\n"
2114 << " if (!(Pred = checkDecoderPredicate(PIdx, Bits)))\n"
2115 << " Ptr += NumToSkip;\n"
2116 << " (void)Pred;\n"
2117 << " DEBUG(dbgs() << Loc << \": OPC_CheckPredicate(\" << PIdx << \"): \"\n"
2118 << " << (Pred ? \"PASS\\n\" : \"FAIL\\n\"));\n"
2119 << "\n"
2120 << " break;\n"
2121 << " }\n"
2122 << " case MCD::OPC_Decode: {\n"
2123 << " unsigned Len;\n"
2124 << " // Decode the Opcode value.\n"
2125 << " unsigned Opc = decodeULEB128(++Ptr, &Len);\n"
2126 << " Ptr += Len;\n"
2127 << " unsigned DecodeIdx = decodeULEB128(Ptr, &Len);\n"
2128 << " Ptr += Len;\n"
2129 << " DEBUG(dbgs() << Loc << \": OPC_Decode: opcode \" << Opc\n"
2130 << " << \", using decoder \" << DecodeIdx << \"\\n\" );\n"
2131 << " DEBUG(dbgs() << \"----- DECODE SUCCESSFUL -----\\n\");\n"
2132 << "\n"
2133 << " MI.setOpcode(Opc);\n"
Benjamin Kramer26b568d2012-08-15 10:26:44 +00002134 << " return decodeToMCInst(S, DecodeIdx, insn, MI, Address, DisAsm);\n"
Jim Grosbachecaef492012-08-14 19:06:05 +00002135 << " }\n"
2136 << " case MCD::OPC_SoftFail: {\n"
2137 << " // Decode the mask values.\n"
2138 << " unsigned Len;\n"
2139 << " InsnType PositiveMask = decodeULEB128(++Ptr, &Len);\n"
2140 << " Ptr += Len;\n"
2141 << " InsnType NegativeMask = decodeULEB128(Ptr, &Len);\n"
2142 << " Ptr += Len;\n"
2143 << " bool Fail = (insn & PositiveMask) || (~insn & NegativeMask);\n"
2144 << " if (Fail)\n"
2145 << " S = MCDisassembler::SoftFail;\n"
2146 << " DEBUG(dbgs() << Loc << \": OPC_SoftFail: \" << (Fail ? \"FAIL\\n\":\"PASS\\n\"));\n"
2147 << " break;\n"
2148 << " }\n"
2149 << " case MCD::OPC_Fail: {\n"
2150 << " DEBUG(dbgs() << Loc << \": OPC_Fail\\n\");\n"
2151 << " return MCDisassembler::Fail;\n"
2152 << " }\n"
2153 << " }\n"
2154 << " }\n"
2155 << " llvm_unreachable(\"bogosity detected in disassembler state machine!\");\n"
2156 << "}\n\n";
Owen Anderson4e818902011-02-18 21:51:29 +00002157}
2158
2159// Emits disassembler code for instruction decoding.
Craig Topper82d0d5f2012-03-16 01:19:24 +00002160void FixedLenDecoderEmitter::run(raw_ostream &o) {
Jim Grosbachecaef492012-08-14 19:06:05 +00002161 formatted_raw_ostream OS(o);
2162 OS << "#include \"llvm/MC/MCInst.h\"\n";
2163 OS << "#include \"llvm/Support/Debug.h\"\n";
2164 OS << "#include \"llvm/Support/DataTypes.h\"\n";
2165 OS << "#include \"llvm/Support/LEB128.h\"\n";
2166 OS << "#include \"llvm/Support/raw_ostream.h\"\n";
2167 OS << "#include <assert.h>\n";
2168 OS << '\n';
2169 OS << "namespace llvm {\n\n";
2170
2171 emitFieldFromInstruction(OS);
Owen Anderson4e818902011-02-18 21:51:29 +00002172
Hal Finkel81e6fcc2013-12-17 22:37:50 +00002173 Target.reverseBitsForLittleEndianEncoding();
2174
Owen Andersonc78e03c2011-07-19 21:06:00 +00002175 // Parameterize the decoders based on namespace and instruction width.
Jim Grosbachecaef492012-08-14 19:06:05 +00002176 NumberedInstructions = &Target.getInstructionsByEnumValue();
Owen Andersonc78e03c2011-07-19 21:06:00 +00002177 std::map<std::pair<std::string, unsigned>,
2178 std::vector<unsigned> > OpcMap;
2179 std::map<unsigned, std::vector<OperandInfo> > Operands;
2180
Jim Grosbachecaef492012-08-14 19:06:05 +00002181 for (unsigned i = 0; i < NumberedInstructions->size(); ++i) {
2182 const CodeGenInstruction *Inst = NumberedInstructions->at(i);
Craig Topper48c112b2012-03-16 05:58:09 +00002183 const Record *Def = Inst->TheDef;
Owen Andersonc78e03c2011-07-19 21:06:00 +00002184 unsigned Size = Def->getValueAsInt("Size");
2185 if (Def->getValueAsString("Namespace") == "TargetOpcode" ||
2186 Def->getValueAsBit("isPseudo") ||
2187 Def->getValueAsBit("isAsmParserOnly") ||
2188 Def->getValueAsBit("isCodeGenOnly"))
2189 continue;
2190
2191 std::string DecoderNamespace = Def->getValueAsString("DecoderNamespace");
2192
2193 if (Size) {
Hal Finkel71b2e202013-12-19 16:12:53 +00002194 if (populateInstruction(Target, *Inst, i, Operands)) {
Owen Andersonc78e03c2011-07-19 21:06:00 +00002195 OpcMap[std::make_pair(DecoderNamespace, Size)].push_back(i);
2196 }
2197 }
2198 }
2199
Jim Grosbachecaef492012-08-14 19:06:05 +00002200 DecoderTableInfo TableInfo;
Owen Andersonc78e03c2011-07-19 21:06:00 +00002201 for (std::map<std::pair<std::string, unsigned>,
Craig Topper48c112b2012-03-16 05:58:09 +00002202 std::vector<unsigned> >::const_iterator
Owen Andersonc78e03c2011-07-19 21:06:00 +00002203 I = OpcMap.begin(), E = OpcMap.end(); I != E; ++I) {
Owen Andersonc78e03c2011-07-19 21:06:00 +00002204 // Emit the decoder for this namespace+width combination.
Jim Grosbachecaef492012-08-14 19:06:05 +00002205 FilterChooser FC(*NumberedInstructions, I->second, Operands,
Owen Andersona4043c42011-08-17 17:44:15 +00002206 8*I->first.second, this);
Jim Grosbachecaef492012-08-14 19:06:05 +00002207
2208 // The decode table is cleared for each top level decoder function. The
2209 // predicates and decoders themselves, however, are shared across all
2210 // decoders to give more opportunities for uniqueing.
2211 TableInfo.Table.clear();
2212 TableInfo.FixupStack.clear();
2213 TableInfo.Table.reserve(16384);
2214 TableInfo.FixupStack.push_back(FixupList());
2215 FC.emitTableEntries(TableInfo);
2216 // Any NumToSkip fixups in the top level scope can resolve to the
2217 // OPC_Fail at the end of the table.
2218 assert(TableInfo.FixupStack.size() == 1 && "fixup stack phasing error!");
2219 // Resolve any NumToSkip fixups in the current scope.
2220 resolveTableFixups(TableInfo.Table, TableInfo.FixupStack.back(),
2221 TableInfo.Table.size());
2222 TableInfo.FixupStack.clear();
2223
2224 TableInfo.Table.push_back(MCD::OPC_Fail);
2225
2226 // Print the table to the output stream.
2227 emitTable(OS, TableInfo.Table, 0, FC.getBitWidth(), I->first.first);
2228 OS.flush();
Owen Andersonc78e03c2011-07-19 21:06:00 +00002229 }
Owen Anderson4e818902011-02-18 21:51:29 +00002230
Jim Grosbachecaef492012-08-14 19:06:05 +00002231 // Emit the predicate function.
2232 emitPredicateFunction(OS, TableInfo.Predicates, 0);
2233
2234 // Emit the decoder function.
2235 emitDecoderFunction(OS, TableInfo.Decoders, 0);
2236
2237 // Emit the main entry point for the decoder, decodeInstruction().
2238 emitDecodeInstruction(OS);
2239
2240 OS << "\n} // End llvm namespace\n";
Owen Anderson4e818902011-02-18 21:51:29 +00002241}
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +00002242
2243namespace llvm {
2244
2245void EmitFixedLenDecoder(RecordKeeper &RK, raw_ostream &OS,
2246 std::string PredicateNamespace,
2247 std::string GPrefix,
2248 std::string GPostfix,
2249 std::string ROK,
2250 std::string RFail,
2251 std::string L) {
2252 FixedLenDecoderEmitter(RK, PredicateNamespace, GPrefix, GPostfix,
2253 ROK, RFail, L).run(OS);
2254}
2255
2256} // End llvm namespace