blob: 0a8179f443d92e482c29f797d726826340646bed [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 Toppercf05f912014-09-03 06:07:54 +0000233 std::map<unsigned, std::unique_ptr<const FilterChooser>> FilterChooserMap;
Owen Anderson4e818902011-02-18 21:51:29 +0000234
235 // Number of instructions which fall under FilteredInstructions category.
236 unsigned NumFiltered;
237
238 // Keeps track of the last opcode in the filtered bucket.
239 unsigned LastOpcFiltered;
240
Owen Anderson4e818902011-02-18 21:51:29 +0000241public:
Craig Topper48c112b2012-03-16 05:58:09 +0000242 unsigned getNumFiltered() const { return NumFiltered; }
243 unsigned getSingletonOpc() const {
Owen Anderson4e818902011-02-18 21:51:29 +0000244 assert(NumFiltered == 1);
245 return LastOpcFiltered;
246 }
247 // Return the filter chooser for the group of instructions without constant
248 // segment values.
Craig Topper48c112b2012-03-16 05:58:09 +0000249 const FilterChooser &getVariableFC() const {
Owen Anderson4e818902011-02-18 21:51:29 +0000250 assert(NumFiltered == 1);
251 assert(FilterChooserMap.size() == 1);
252 return *(FilterChooserMap.find((unsigned)-1)->second);
253 }
254
Craig Topper5c2b4ac2014-09-03 05:49:07 +0000255 Filter(Filter &&f);
Owen Anderson4e818902011-02-18 21:51:29 +0000256 Filter(FilterChooser &owner, unsigned startBit, unsigned numBits, bool mixed);
257
258 ~Filter();
259
260 // Divides the decoding task into sub tasks and delegates them to the
261 // inferior FilterChooser's.
262 //
263 // A special case arises when there's only one entry in the filtered
264 // instructions. In order to unambiguously decode the singleton, we need to
265 // match the remaining undecoded encoding bits against the singleton.
266 void recurse();
267
Jim Grosbachecaef492012-08-14 19:06:05 +0000268 // Emit table entries to decode instructions given a segment or segments of
269 // bits.
270 void emitTableEntry(DecoderTableInfo &TableInfo) const;
Owen Anderson4e818902011-02-18 21:51:29 +0000271
272 // Returns the number of fanout produced by the filter. More fanout implies
273 // the filter distinguishes more categories of instructions.
274 unsigned usefulness() const;
275}; // End of class Filter
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +0000276} // End anonymous namespace
Owen Anderson4e818902011-02-18 21:51:29 +0000277
278// These are states of our finite state machines used in FilterChooser's
279// filterProcessor() which produces the filter candidates to use.
280typedef enum {
281 ATTR_NONE,
282 ATTR_FILTERED,
283 ATTR_ALL_SET,
284 ATTR_ALL_UNSET,
285 ATTR_MIXED
286} bitAttr_t;
287
288/// FilterChooser - FilterChooser chooses the best filter among a set of Filters
289/// in order to perform the decoding of instructions at the current level.
290///
291/// Decoding proceeds from the top down. Based on the well-known encoding bits
292/// of instructions available, FilterChooser builds up the possible Filters that
293/// can further the task of decoding by distinguishing among the remaining
294/// candidate instructions.
295///
296/// Once a filter has been chosen, it is called upon to divide the decoding task
297/// into sub-tasks and delegates them to its inferior FilterChoosers for further
298/// processings.
299///
300/// It is useful to think of a Filter as governing the switch stmts of the
301/// decoding tree. And each case is delegated to an inferior FilterChooser to
302/// decide what further remaining bits to look at.
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +0000303namespace {
Owen Anderson4e818902011-02-18 21:51:29 +0000304class FilterChooser {
305protected:
306 friend class Filter;
307
308 // Vector of codegen instructions to choose our filter.
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() {
Owen Anderson4e818902011-02-18 21:51:29 +0000533}
534
535// Divides the decoding task into sub tasks and delegates them to the
536// inferior FilterChooser's.
537//
538// A special case arises when there's only one entry in the filtered
539// instructions. In order to unambiguously decode the singleton, we need to
540// match the remaining undecoded encoding bits against the singleton.
541void Filter::recurse() {
542 std::map<uint64_t, std::vector<unsigned> >::const_iterator mapIterator;
543
Owen Anderson4e818902011-02-18 21:51:29 +0000544 // Starts by inheriting our parent filter chooser's filter bit values.
Owen Andersonc78e03c2011-07-19 21:06:00 +0000545 std::vector<bit_value_t> BitValueArray(Owner->FilterBitValues);
Owen Anderson4e818902011-02-18 21:51:29 +0000546
Owen Anderson4e818902011-02-18 21:51:29 +0000547 if (VariableInstructions.size()) {
548 // Conservatively marks each segment position as BIT_UNSET.
Craig Topper29688ab2012-08-17 05:42:16 +0000549 for (unsigned bitIndex = 0; bitIndex < NumBits; ++bitIndex)
Owen Anderson4e818902011-02-18 21:51:29 +0000550 BitValueArray[StartBit + bitIndex] = BIT_UNSET;
551
Chris Lattner0ab5e2c2011-04-15 05:18:47 +0000552 // Delegates to an inferior filter chooser for further processing on this
Owen Anderson4e818902011-02-18 21:51:29 +0000553 // group of instructions whose segment values are variable.
Craig Toppercf05f912014-09-03 06:07:54 +0000554 FilterChooserMap.insert(std::make_pair(
555 -1U,
556 make_unique<FilterChooser>(Owner->AllInstructions,
557 VariableInstructions,
558 Owner->Operands,
559 BitValueArray,
560 *Owner)));
Owen Anderson4e818902011-02-18 21:51:29 +0000561 }
562
563 // No need to recurse for a singleton filtered instruction.
Jim Grosbachecaef492012-08-14 19:06:05 +0000564 // See also Filter::emit*().
Owen Anderson4e818902011-02-18 21:51:29 +0000565 if (getNumFiltered() == 1) {
566 //Owner->SingletonExists(LastOpcFiltered);
567 assert(FilterChooserMap.size() == 1);
568 return;
569 }
570
571 // Otherwise, create sub choosers.
572 for (mapIterator = FilteredInstructions.begin();
573 mapIterator != FilteredInstructions.end();
574 mapIterator++) {
575
576 // Marks all the segment positions with either BIT_TRUE or BIT_FALSE.
Craig Topper29688ab2012-08-17 05:42:16 +0000577 for (unsigned bitIndex = 0; bitIndex < NumBits; ++bitIndex) {
Owen Anderson4e818902011-02-18 21:51:29 +0000578 if (mapIterator->first & (1ULL << bitIndex))
579 BitValueArray[StartBit + bitIndex] = BIT_TRUE;
580 else
581 BitValueArray[StartBit + bitIndex] = BIT_FALSE;
582 }
583
Chris Lattner0ab5e2c2011-04-15 05:18:47 +0000584 // Delegates to an inferior filter chooser for further processing on this
Owen Anderson4e818902011-02-18 21:51:29 +0000585 // category of instructions.
Craig Toppercf05f912014-09-03 06:07:54 +0000586 FilterChooserMap.insert(std::make_pair(
Craig Topper6cb92c22014-09-03 05:59:23 +0000587 mapIterator->first,
Craig Toppercf05f912014-09-03 06:07:54 +0000588 make_unique<FilterChooser>(Owner->AllInstructions,
589 mapIterator->second,
590 Owner->Operands,
591 BitValueArray,
592 *Owner)));
Owen Anderson4e818902011-02-18 21:51:29 +0000593 }
594}
595
Jim Grosbachecaef492012-08-14 19:06:05 +0000596static void resolveTableFixups(DecoderTable &Table, const FixupList &Fixups,
597 uint32_t DestIdx) {
598 // Any NumToSkip fixups in the current scope can resolve to the
599 // current location.
600 for (FixupList::const_reverse_iterator I = Fixups.rbegin(),
601 E = Fixups.rend();
602 I != E; ++I) {
603 // Calculate the distance from the byte following the fixup entry byte
604 // to the destination. The Target is calculated from after the 16-bit
605 // NumToSkip entry itself, so subtract two from the displacement here
606 // to account for that.
607 uint32_t FixupIdx = *I;
608 uint32_t Delta = DestIdx - FixupIdx - 2;
609 // Our NumToSkip entries are 16-bits. Make sure our table isn't too
610 // big.
611 assert(Delta < 65536U && "disassembler decoding table too large!");
612 Table[FixupIdx] = (uint8_t)Delta;
613 Table[FixupIdx + 1] = (uint8_t)(Delta >> 8);
614 }
615}
Owen Anderson4e818902011-02-18 21:51:29 +0000616
Jim Grosbachecaef492012-08-14 19:06:05 +0000617// Emit table entries to decode instructions given a segment or segments
618// of bits.
619void Filter::emitTableEntry(DecoderTableInfo &TableInfo) const {
620 TableInfo.Table.push_back(MCD::OPC_ExtractField);
621 TableInfo.Table.push_back(StartBit);
622 TableInfo.Table.push_back(NumBits);
Owen Anderson4e818902011-02-18 21:51:29 +0000623
Jim Grosbachecaef492012-08-14 19:06:05 +0000624 // A new filter entry begins a new scope for fixup resolution.
625 TableInfo.FixupStack.push_back(FixupList());
Owen Anderson4e818902011-02-18 21:51:29 +0000626
Craig Toppercf05f912014-09-03 06:07:54 +0000627 std::map<unsigned,
628 std::unique_ptr<const FilterChooser>>::const_iterator filterIterator;
Owen Anderson4e818902011-02-18 21:51:29 +0000629
Jim Grosbachecaef492012-08-14 19:06:05 +0000630 DecoderTable &Table = TableInfo.Table;
631
632 size_t PrevFilter = 0;
633 bool HasFallthrough = false;
Owen Anderson4e818902011-02-18 21:51:29 +0000634 for (filterIterator = FilterChooserMap.begin();
635 filterIterator != FilterChooserMap.end();
636 filterIterator++) {
Owen Anderson4e818902011-02-18 21:51:29 +0000637 // Field value -1 implies a non-empty set of variable instructions.
638 // See also recurse().
639 if (filterIterator->first == (unsigned)-1) {
Jim Grosbachecaef492012-08-14 19:06:05 +0000640 HasFallthrough = true;
Owen Anderson4e818902011-02-18 21:51:29 +0000641
Jim Grosbachecaef492012-08-14 19:06:05 +0000642 // Each scope should always have at least one filter value to check
643 // for.
644 assert(PrevFilter != 0 && "empty filter set!");
645 FixupList &CurScope = TableInfo.FixupStack.back();
646 // Resolve any NumToSkip fixups in the current scope.
647 resolveTableFixups(Table, CurScope, Table.size());
648 CurScope.clear();
649 PrevFilter = 0; // Don't re-process the filter's fallthrough.
650 } else {
651 Table.push_back(MCD::OPC_FilterValue);
652 // Encode and emit the value to filter against.
653 uint8_t Buffer[8];
654 unsigned Len = encodeULEB128(filterIterator->first, Buffer);
655 Table.insert(Table.end(), Buffer, Buffer + Len);
656 // Reserve space for the NumToSkip entry. We'll backpatch the value
657 // later.
658 PrevFilter = Table.size();
659 Table.push_back(0);
660 Table.push_back(0);
661 }
Owen Anderson4e818902011-02-18 21:51:29 +0000662
663 // We arrive at a category of instructions with the same segment value.
664 // Now delegate to the sub filter chooser for further decodings.
665 // The case may fallthrough, which happens if the remaining well-known
666 // encoding bits do not match exactly.
Jim Grosbachecaef492012-08-14 19:06:05 +0000667 filterIterator->second->emitTableEntries(TableInfo);
Owen Anderson4e818902011-02-18 21:51:29 +0000668
Jim Grosbachecaef492012-08-14 19:06:05 +0000669 // Now that we've emitted the body of the handler, update the NumToSkip
670 // of the filter itself to be able to skip forward when false. Subtract
671 // two as to account for the width of the NumToSkip field itself.
672 if (PrevFilter) {
673 uint32_t NumToSkip = Table.size() - PrevFilter - 2;
674 assert(NumToSkip < 65536U && "disassembler decoding table too large!");
675 Table[PrevFilter] = (uint8_t)NumToSkip;
676 Table[PrevFilter + 1] = (uint8_t)(NumToSkip >> 8);
677 }
Owen Anderson4e818902011-02-18 21:51:29 +0000678 }
679
Jim Grosbachecaef492012-08-14 19:06:05 +0000680 // Any remaining unresolved fixups bubble up to the parent fixup scope.
681 assert(TableInfo.FixupStack.size() > 1 && "fixup stack underflow!");
682 FixupScopeList::iterator Source = TableInfo.FixupStack.end() - 1;
683 FixupScopeList::iterator Dest = Source - 1;
684 Dest->insert(Dest->end(), Source->begin(), Source->end());
685 TableInfo.FixupStack.pop_back();
686
687 // If there is no fallthrough, then the final filter should get fixed
688 // up according to the enclosing scope rather than the current position.
689 if (!HasFallthrough)
690 TableInfo.FixupStack.back().push_back(PrevFilter);
Owen Anderson4e818902011-02-18 21:51:29 +0000691}
692
693// Returns the number of fanout produced by the filter. More fanout implies
694// the filter distinguishes more categories of instructions.
695unsigned Filter::usefulness() const {
696 if (VariableInstructions.size())
697 return FilteredInstructions.size();
698 else
699 return FilteredInstructions.size() + 1;
700}
701
702//////////////////////////////////
703// //
704// Filterchooser Implementation //
705// //
706//////////////////////////////////
707
Jim Grosbachecaef492012-08-14 19:06:05 +0000708// Emit the decoder state machine table.
709void FixedLenDecoderEmitter::emitTable(formatted_raw_ostream &OS,
710 DecoderTable &Table,
711 unsigned Indentation,
712 unsigned BitWidth,
713 StringRef Namespace) const {
714 OS.indent(Indentation) << "static const uint8_t DecoderTable" << Namespace
715 << BitWidth << "[] = {\n";
Owen Anderson4e818902011-02-18 21:51:29 +0000716
Jim Grosbachecaef492012-08-14 19:06:05 +0000717 Indentation += 2;
Owen Anderson4e818902011-02-18 21:51:29 +0000718
Jim Grosbachecaef492012-08-14 19:06:05 +0000719 // FIXME: We may be able to use the NumToSkip values to recover
720 // appropriate indentation levels.
721 DecoderTable::const_iterator I = Table.begin();
722 DecoderTable::const_iterator E = Table.end();
723 while (I != E) {
724 assert (I < E && "incomplete decode table entry!");
Owen Anderson4e818902011-02-18 21:51:29 +0000725
Jim Grosbachecaef492012-08-14 19:06:05 +0000726 uint64_t Pos = I - Table.begin();
727 OS << "/* " << Pos << " */";
728 OS.PadToColumn(12);
Owen Anderson4e818902011-02-18 21:51:29 +0000729
Jim Grosbachecaef492012-08-14 19:06:05 +0000730 switch (*I) {
731 default:
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000732 PrintFatalError("invalid decode table opcode");
Jim Grosbachecaef492012-08-14 19:06:05 +0000733 case MCD::OPC_ExtractField: {
734 ++I;
735 unsigned Start = *I++;
736 unsigned Len = *I++;
737 OS.indent(Indentation) << "MCD::OPC_ExtractField, " << Start << ", "
738 << Len << ", // Inst{";
739 if (Len > 1)
740 OS << (Start + Len - 1) << "-";
741 OS << Start << "} ...\n";
742 break;
743 }
744 case MCD::OPC_FilterValue: {
745 ++I;
746 OS.indent(Indentation) << "MCD::OPC_FilterValue, ";
747 // The filter value is ULEB128 encoded.
748 while (*I >= 128)
749 OS << utostr(*I++) << ", ";
750 OS << utostr(*I++) << ", ";
751
752 // 16-bit numtoskip value.
753 uint8_t Byte = *I++;
754 uint32_t NumToSkip = Byte;
755 OS << utostr(Byte) << ", ";
756 Byte = *I++;
757 OS << utostr(Byte) << ", ";
758 NumToSkip |= Byte << 8;
759 OS << "// Skip to: " << ((I - Table.begin()) + NumToSkip) << "\n";
760 break;
761 }
762 case MCD::OPC_CheckField: {
763 ++I;
764 unsigned Start = *I++;
765 unsigned Len = *I++;
766 OS.indent(Indentation) << "MCD::OPC_CheckField, " << Start << ", "
767 << Len << ", ";// << Val << ", " << NumToSkip << ",\n";
768 // ULEB128 encoded field value.
769 for (; *I >= 128; ++I)
770 OS << utostr(*I) << ", ";
771 OS << utostr(*I++) << ", ";
772 // 16-bit numtoskip value.
773 uint8_t Byte = *I++;
774 uint32_t NumToSkip = Byte;
775 OS << utostr(Byte) << ", ";
776 Byte = *I++;
777 OS << utostr(Byte) << ", ";
778 NumToSkip |= Byte << 8;
779 OS << "// Skip to: " << ((I - Table.begin()) + NumToSkip) << "\n";
780 break;
781 }
782 case MCD::OPC_CheckPredicate: {
783 ++I;
784 OS.indent(Indentation) << "MCD::OPC_CheckPredicate, ";
785 for (; *I >= 128; ++I)
786 OS << utostr(*I) << ", ";
787 OS << utostr(*I++) << ", ";
788
789 // 16-bit numtoskip value.
790 uint8_t Byte = *I++;
791 uint32_t NumToSkip = Byte;
792 OS << utostr(Byte) << ", ";
793 Byte = *I++;
794 OS << utostr(Byte) << ", ";
795 NumToSkip |= Byte << 8;
796 OS << "// Skip to: " << ((I - Table.begin()) + NumToSkip) << "\n";
797 break;
798 }
799 case MCD::OPC_Decode: {
800 ++I;
801 // Extract the ULEB128 encoded Opcode to a buffer.
802 uint8_t Buffer[8], *p = Buffer;
803 while ((*p++ = *I++) >= 128)
804 assert((p - Buffer) <= (ptrdiff_t)sizeof(Buffer)
805 && "ULEB128 value too large!");
806 // Decode the Opcode value.
807 unsigned Opc = decodeULEB128(Buffer);
808 OS.indent(Indentation) << "MCD::OPC_Decode, ";
809 for (p = Buffer; *p >= 128; ++p)
810 OS << utostr(*p) << ", ";
811 OS << utostr(*p) << ", ";
812
813 // Decoder index.
814 for (; *I >= 128; ++I)
815 OS << utostr(*I) << ", ";
816 OS << utostr(*I++) << ", ";
817
818 OS << "// Opcode: "
819 << NumberedInstructions->at(Opc)->TheDef->getName() << "\n";
820 break;
821 }
822 case MCD::OPC_SoftFail: {
823 ++I;
824 OS.indent(Indentation) << "MCD::OPC_SoftFail";
825 // Positive mask
826 uint64_t Value = 0;
827 unsigned Shift = 0;
828 do {
829 OS << ", " << utostr(*I);
830 Value += (*I & 0x7f) << Shift;
831 Shift += 7;
832 } while (*I++ >= 128);
833 if (Value > 127)
834 OS << " /* 0x" << utohexstr(Value) << " */";
835 // Negative mask
836 Value = 0;
837 Shift = 0;
838 do {
839 OS << ", " << utostr(*I);
840 Value += (*I & 0x7f) << Shift;
841 Shift += 7;
842 } while (*I++ >= 128);
843 if (Value > 127)
844 OS << " /* 0x" << utohexstr(Value) << " */";
845 OS << ",\n";
846 break;
847 }
848 case MCD::OPC_Fail: {
849 ++I;
850 OS.indent(Indentation) << "MCD::OPC_Fail,\n";
851 break;
852 }
853 }
854 }
855 OS.indent(Indentation) << "0\n";
856
857 Indentation -= 2;
858
859 OS.indent(Indentation) << "};\n\n";
860}
861
862void FixedLenDecoderEmitter::
863emitPredicateFunction(formatted_raw_ostream &OS, PredicateSet &Predicates,
864 unsigned Indentation) const {
865 // The predicate function is just a big switch statement based on the
866 // input predicate index.
867 OS.indent(Indentation) << "static bool checkDecoderPredicate(unsigned Idx, "
868 << "uint64_t Bits) {\n";
869 Indentation += 2;
Aaron Ballmane59e3582013-07-15 16:53:32 +0000870 if (!Predicates.empty()) {
871 OS.indent(Indentation) << "switch (Idx) {\n";
872 OS.indent(Indentation) << "default: llvm_unreachable(\"Invalid index!\");\n";
873 unsigned Index = 0;
874 for (PredicateSet::const_iterator I = Predicates.begin(), E = Predicates.end();
875 I != E; ++I, ++Index) {
876 OS.indent(Indentation) << "case " << Index << ":\n";
877 OS.indent(Indentation+2) << "return (" << *I << ");\n";
878 }
879 OS.indent(Indentation) << "}\n";
880 } else {
881 // No case statement to emit
882 OS.indent(Indentation) << "llvm_unreachable(\"Invalid index!\");\n";
Jim Grosbachecaef492012-08-14 19:06:05 +0000883 }
Jim Grosbachecaef492012-08-14 19:06:05 +0000884 Indentation -= 2;
885 OS.indent(Indentation) << "}\n\n";
886}
887
888void FixedLenDecoderEmitter::
889emitDecoderFunction(formatted_raw_ostream &OS, DecoderSet &Decoders,
890 unsigned Indentation) const {
891 // The decoder function is just a big switch statement based on the
892 // input decoder index.
893 OS.indent(Indentation) << "template<typename InsnType>\n";
894 OS.indent(Indentation) << "static DecodeStatus decodeToMCInst(DecodeStatus S,"
895 << " unsigned Idx, InsnType insn, MCInst &MI,\n";
896 OS.indent(Indentation) << " uint64_t "
Benjamin Kramer26b568d2012-08-15 10:26:44 +0000897 << "Address, const void *Decoder) {\n";
Jim Grosbachecaef492012-08-14 19:06:05 +0000898 Indentation += 2;
899 OS.indent(Indentation) << "InsnType tmp;\n";
900 OS.indent(Indentation) << "switch (Idx) {\n";
901 OS.indent(Indentation) << "default: llvm_unreachable(\"Invalid index!\");\n";
902 unsigned Index = 0;
903 for (DecoderSet::const_iterator I = Decoders.begin(), E = Decoders.end();
904 I != E; ++I, ++Index) {
905 OS.indent(Indentation) << "case " << Index << ":\n";
Craig Topperebc3aa22012-08-17 05:16:15 +0000906 OS << *I;
Jim Grosbachecaef492012-08-14 19:06:05 +0000907 OS.indent(Indentation+2) << "return S;\n";
908 }
909 OS.indent(Indentation) << "}\n";
910 Indentation -= 2;
911 OS.indent(Indentation) << "}\n\n";
Owen Anderson4e818902011-02-18 21:51:29 +0000912}
913
914// Populates the field of the insn given the start position and the number of
915// consecutive bits to scan for.
916//
917// Returns false if and on the first uninitialized bit value encountered.
918// Returns true, otherwise.
919bool FilterChooser::fieldFromInsn(uint64_t &Field, insn_t &Insn,
Craig Topper48c112b2012-03-16 05:58:09 +0000920 unsigned StartBit, unsigned NumBits) const {
Owen Anderson4e818902011-02-18 21:51:29 +0000921 Field = 0;
922
923 for (unsigned i = 0; i < NumBits; ++i) {
924 if (Insn[StartBit + i] == BIT_UNSET)
925 return false;
926
927 if (Insn[StartBit + i] == BIT_TRUE)
928 Field = Field | (1ULL << i);
929 }
930
931 return true;
932}
933
934/// dumpFilterArray - dumpFilterArray prints out debugging info for the given
935/// filter array as a series of chars.
936void FilterChooser::dumpFilterArray(raw_ostream &o,
Craig Topper48c112b2012-03-16 05:58:09 +0000937 const std::vector<bit_value_t> &filter) const {
Craig Topper29688ab2012-08-17 05:42:16 +0000938 for (unsigned bitIndex = BitWidth; bitIndex > 0; bitIndex--) {
Owen Anderson4e818902011-02-18 21:51:29 +0000939 switch (filter[bitIndex - 1]) {
940 case BIT_UNFILTERED:
941 o << ".";
942 break;
943 case BIT_UNSET:
944 o << "_";
945 break;
946 case BIT_TRUE:
947 o << "1";
948 break;
949 case BIT_FALSE:
950 o << "0";
951 break;
952 }
953 }
954}
955
956/// dumpStack - dumpStack traverses the filter chooser chain and calls
957/// dumpFilterArray on each filter chooser up to the top level one.
Craig Topper48c112b2012-03-16 05:58:09 +0000958void FilterChooser::dumpStack(raw_ostream &o, const char *prefix) const {
959 const FilterChooser *current = this;
Owen Anderson4e818902011-02-18 21:51:29 +0000960
961 while (current) {
962 o << prefix;
963 dumpFilterArray(o, current->FilterBitValues);
964 o << '\n';
965 current = current->Parent;
966 }
967}
968
969// Called from Filter::recurse() when singleton exists. For debug purpose.
Craig Topper48c112b2012-03-16 05:58:09 +0000970void FilterChooser::SingletonExists(unsigned Opc) const {
Owen Anderson4e818902011-02-18 21:51:29 +0000971 insn_t Insn0;
972 insnWithID(Insn0, Opc);
973
974 errs() << "Singleton exists: " << nameWithID(Opc)
975 << " with its decoding dominating ";
976 for (unsigned i = 0; i < Opcodes.size(); ++i) {
977 if (Opcodes[i] == Opc) continue;
978 errs() << nameWithID(Opcodes[i]) << ' ';
979 }
980 errs() << '\n';
981
982 dumpStack(errs(), "\t\t");
Craig Topper82d0d5f2012-03-16 01:19:24 +0000983 for (unsigned i = 0; i < Opcodes.size(); ++i) {
Owen Anderson4e818902011-02-18 21:51:29 +0000984 const std::string &Name = nameWithID(Opcodes[i]);
985
986 errs() << '\t' << Name << " ";
987 dumpBits(errs(),
988 getBitsField(*AllInstructions[Opcodes[i]]->TheDef, "Inst"));
989 errs() << '\n';
990 }
991}
992
993// Calculates the island(s) needed to decode the instruction.
994// This returns a list of undecoded bits of an instructions, for example,
995// Inst{20} = 1 && Inst{3-0} == 0b1111 represents two islands of yet-to-be
996// decoded bits in order to verify that the instruction matches the Opcode.
997unsigned FilterChooser::getIslands(std::vector<unsigned> &StartBits,
Craig Topper82d0d5f2012-03-16 01:19:24 +0000998 std::vector<unsigned> &EndBits,
999 std::vector<uint64_t> &FieldVals,
Craig Topper48c112b2012-03-16 05:58:09 +00001000 const insn_t &Insn) const {
Owen Anderson4e818902011-02-18 21:51:29 +00001001 unsigned Num, BitNo;
1002 Num = BitNo = 0;
1003
1004 uint64_t FieldVal = 0;
1005
1006 // 0: Init
1007 // 1: Water (the bit value does not affect decoding)
1008 // 2: Island (well-known bit value needed for decoding)
1009 int State = 0;
1010 int Val = -1;
1011
Owen Andersonc78e03c2011-07-19 21:06:00 +00001012 for (unsigned i = 0; i < BitWidth; ++i) {
Owen Anderson4e818902011-02-18 21:51:29 +00001013 Val = Value(Insn[i]);
1014 bool Filtered = PositionFiltered(i);
1015 switch (State) {
Craig Topperc4965bc2012-02-05 07:21:30 +00001016 default: llvm_unreachable("Unreachable code!");
Owen Anderson4e818902011-02-18 21:51:29 +00001017 case 0:
1018 case 1:
1019 if (Filtered || Val == -1)
1020 State = 1; // Still in Water
1021 else {
1022 State = 2; // Into the Island
1023 BitNo = 0;
1024 StartBits.push_back(i);
1025 FieldVal = Val;
1026 }
1027 break;
1028 case 2:
1029 if (Filtered || Val == -1) {
1030 State = 1; // Into the Water
1031 EndBits.push_back(i - 1);
1032 FieldVals.push_back(FieldVal);
1033 ++Num;
1034 } else {
1035 State = 2; // Still in Island
1036 ++BitNo;
1037 FieldVal = FieldVal | Val << BitNo;
1038 }
1039 break;
1040 }
1041 }
1042 // If we are still in Island after the loop, do some housekeeping.
1043 if (State == 2) {
Owen Andersonc78e03c2011-07-19 21:06:00 +00001044 EndBits.push_back(BitWidth - 1);
Owen Anderson4e818902011-02-18 21:51:29 +00001045 FieldVals.push_back(FieldVal);
1046 ++Num;
1047 }
1048
1049 assert(StartBits.size() == Num && EndBits.size() == Num &&
1050 FieldVals.size() == Num);
1051 return Num;
1052}
1053
Owen Andersone3591652011-07-28 21:54:31 +00001054void FilterChooser::emitBinaryParser(raw_ostream &o, unsigned &Indentation,
Craig Topper48c112b2012-03-16 05:58:09 +00001055 const OperandInfo &OpInfo) const {
1056 const std::string &Decoder = OpInfo.Decoder;
Owen Andersone3591652011-07-28 21:54:31 +00001057
1058 if (OpInfo.numFields() == 1) {
Craig Topper48c112b2012-03-16 05:58:09 +00001059 OperandInfo::const_iterator OI = OpInfo.begin();
Craig Topperebc3aa22012-08-17 05:16:15 +00001060 o.indent(Indentation) << "tmp = fieldFromInstruction"
Jim Grosbachecaef492012-08-14 19:06:05 +00001061 << "(insn, " << OI->Base << ", " << OI->Width
1062 << ");\n";
Owen Andersone3591652011-07-28 21:54:31 +00001063 } else {
Craig Topperebc3aa22012-08-17 05:16:15 +00001064 o.indent(Indentation) << "tmp = 0;\n";
Craig Topper48c112b2012-03-16 05:58:09 +00001065 for (OperandInfo::const_iterator OI = OpInfo.begin(), OE = OpInfo.end();
Owen Andersone3591652011-07-28 21:54:31 +00001066 OI != OE; ++OI) {
Craig Topperebc3aa22012-08-17 05:16:15 +00001067 o.indent(Indentation) << "tmp |= (fieldFromInstruction"
Andrew Trick61abca62011-09-08 05:23:14 +00001068 << "(insn, " << OI->Base << ", " << OI->Width
Owen Andersone3591652011-07-28 21:54:31 +00001069 << ") << " << OI->Offset << ");\n";
1070 }
1071 }
1072
1073 if (Decoder != "")
Craig Topperebc3aa22012-08-17 05:16:15 +00001074 o.indent(Indentation) << Emitter->GuardPrefix << Decoder
Jim Grosbach3f4b2392012-02-29 22:07:56 +00001075 << "(MI, tmp, Address, Decoder)"
1076 << Emitter->GuardPostfix << "\n";
Owen Andersone3591652011-07-28 21:54:31 +00001077 else
Craig Topperebc3aa22012-08-17 05:16:15 +00001078 o.indent(Indentation) << "MI.addOperand(MCOperand::CreateImm(tmp));\n";
Owen Andersone3591652011-07-28 21:54:31 +00001079
1080}
1081
Jim Grosbachecaef492012-08-14 19:06:05 +00001082void FilterChooser::emitDecoder(raw_ostream &OS, unsigned Indentation,
1083 unsigned Opc) const {
1084 std::map<unsigned, std::vector<OperandInfo> >::const_iterator OpIter =
1085 Operands.find(Opc);
1086 const std::vector<OperandInfo>& InsnOperands = OpIter->second;
1087 for (std::vector<OperandInfo>::const_iterator
1088 I = InsnOperands.begin(), E = InsnOperands.end(); I != E; ++I) {
1089 // If a custom instruction decoder was specified, use that.
1090 if (I->numFields() == 0 && I->Decoder.size()) {
Craig Topperebc3aa22012-08-17 05:16:15 +00001091 OS.indent(Indentation) << Emitter->GuardPrefix << I->Decoder
Jim Grosbachecaef492012-08-14 19:06:05 +00001092 << "(MI, insn, Address, Decoder)"
1093 << Emitter->GuardPostfix << "\n";
1094 break;
1095 }
1096
1097 emitBinaryParser(OS, Indentation, *I);
1098 }
1099}
1100
1101unsigned FilterChooser::getDecoderIndex(DecoderSet &Decoders,
1102 unsigned Opc) const {
1103 // Build up the predicate string.
1104 SmallString<256> Decoder;
1105 // FIXME: emitDecoder() function can take a buffer directly rather than
1106 // a stream.
1107 raw_svector_ostream S(Decoder);
Craig Topperebc3aa22012-08-17 05:16:15 +00001108 unsigned I = 4;
Jim Grosbachecaef492012-08-14 19:06:05 +00001109 emitDecoder(S, I, Opc);
1110 S.flush();
1111
1112 // Using the full decoder string as the key value here is a bit
1113 // heavyweight, but is effective. If the string comparisons become a
1114 // performance concern, we can implement a mangling of the predicate
1115 // data easilly enough with a map back to the actual string. That's
1116 // overkill for now, though.
1117
1118 // Make sure the predicate is in the table.
1119 Decoders.insert(Decoder.str());
1120 // Now figure out the index for when we write out the table.
1121 DecoderSet::const_iterator P = std::find(Decoders.begin(),
1122 Decoders.end(),
1123 Decoder.str());
1124 return (unsigned)(P - Decoders.begin());
1125}
1126
James Molloy8067df92011-09-07 19:42:28 +00001127static void emitSinglePredicateMatch(raw_ostream &o, StringRef str,
Craig Topper48c112b2012-03-16 05:58:09 +00001128 const std::string &PredicateNamespace) {
Andrew Trick43674ad2011-09-08 05:25:49 +00001129 if (str[0] == '!')
1130 o << "!(Bits & " << PredicateNamespace << "::"
1131 << str.slice(1,str.size()) << ")";
James Molloy8067df92011-09-07 19:42:28 +00001132 else
Andrew Trick43674ad2011-09-08 05:25:49 +00001133 o << "(Bits & " << PredicateNamespace << "::" << str << ")";
James Molloy8067df92011-09-07 19:42:28 +00001134}
1135
1136bool FilterChooser::emitPredicateMatch(raw_ostream &o, unsigned &Indentation,
Craig Topper48c112b2012-03-16 05:58:09 +00001137 unsigned Opc) const {
Jim Grosbach3f4b2392012-02-29 22:07:56 +00001138 ListInit *Predicates =
1139 AllInstructions[Opc]->TheDef->getValueAsListInit("Predicates");
James Molloy8067df92011-09-07 19:42:28 +00001140 for (unsigned i = 0; i < Predicates->getSize(); ++i) {
1141 Record *Pred = Predicates->getElementAsRecord(i);
1142 if (!Pred->getValue("AssemblerMatcherPredicate"))
1143 continue;
1144
1145 std::string P = Pred->getValueAsString("AssemblerCondString");
1146
1147 if (!P.length())
1148 continue;
1149
1150 if (i != 0)
1151 o << " && ";
1152
1153 StringRef SR(P);
1154 std::pair<StringRef, StringRef> pairs = SR.split(',');
1155 while (pairs.second.size()) {
1156 emitSinglePredicateMatch(o, pairs.first, Emitter->PredicateNamespace);
1157 o << " && ";
1158 pairs = pairs.second.split(',');
1159 }
1160 emitSinglePredicateMatch(o, pairs.first, Emitter->PredicateNamespace);
1161 }
1162 return Predicates->getSize() > 0;
Andrew Trick61abca62011-09-08 05:23:14 +00001163}
James Molloy8067df92011-09-07 19:42:28 +00001164
Jim Grosbachecaef492012-08-14 19:06:05 +00001165bool FilterChooser::doesOpcodeNeedPredicate(unsigned Opc) const {
1166 ListInit *Predicates =
1167 AllInstructions[Opc]->TheDef->getValueAsListInit("Predicates");
1168 for (unsigned i = 0; i < Predicates->getSize(); ++i) {
1169 Record *Pred = Predicates->getElementAsRecord(i);
1170 if (!Pred->getValue("AssemblerMatcherPredicate"))
1171 continue;
1172
1173 std::string P = Pred->getValueAsString("AssemblerCondString");
1174
1175 if (!P.length())
1176 continue;
1177
1178 return true;
1179 }
1180 return false;
1181}
1182
1183unsigned FilterChooser::getPredicateIndex(DecoderTableInfo &TableInfo,
1184 StringRef Predicate) const {
1185 // Using the full predicate string as the key value here is a bit
1186 // heavyweight, but is effective. If the string comparisons become a
1187 // performance concern, we can implement a mangling of the predicate
1188 // data easilly enough with a map back to the actual string. That's
1189 // overkill for now, though.
1190
1191 // Make sure the predicate is in the table.
1192 TableInfo.Predicates.insert(Predicate.str());
1193 // Now figure out the index for when we write out the table.
1194 PredicateSet::const_iterator P = std::find(TableInfo.Predicates.begin(),
1195 TableInfo.Predicates.end(),
1196 Predicate.str());
1197 return (unsigned)(P - TableInfo.Predicates.begin());
1198}
1199
1200void FilterChooser::emitPredicateTableEntry(DecoderTableInfo &TableInfo,
1201 unsigned Opc) const {
1202 if (!doesOpcodeNeedPredicate(Opc))
1203 return;
1204
1205 // Build up the predicate string.
1206 SmallString<256> Predicate;
1207 // FIXME: emitPredicateMatch() functions can take a buffer directly rather
1208 // than a stream.
1209 raw_svector_ostream PS(Predicate);
1210 unsigned I = 0;
1211 emitPredicateMatch(PS, I, Opc);
1212
1213 // Figure out the index into the predicate table for the predicate just
1214 // computed.
1215 unsigned PIdx = getPredicateIndex(TableInfo, PS.str());
1216 SmallString<16> PBytes;
1217 raw_svector_ostream S(PBytes);
1218 encodeULEB128(PIdx, S);
1219 S.flush();
1220
1221 TableInfo.Table.push_back(MCD::OPC_CheckPredicate);
1222 // Predicate index
Craig Topper29688ab2012-08-17 05:42:16 +00001223 for (unsigned i = 0, e = PBytes.size(); i != e; ++i)
Jim Grosbachecaef492012-08-14 19:06:05 +00001224 TableInfo.Table.push_back(PBytes[i]);
1225 // Push location for NumToSkip backpatching.
1226 TableInfo.FixupStack.back().push_back(TableInfo.Table.size());
1227 TableInfo.Table.push_back(0);
1228 TableInfo.Table.push_back(0);
1229}
1230
1231void FilterChooser::emitSoftFailTableEntry(DecoderTableInfo &TableInfo,
1232 unsigned Opc) const {
Jim Grosbach3f4b2392012-02-29 22:07:56 +00001233 BitsInit *SFBits =
1234 AllInstructions[Opc]->TheDef->getValueAsBitsInit("SoftFail");
James Molloyd9ba4fd2012-02-09 10:56:31 +00001235 if (!SFBits) return;
1236 BitsInit *InstBits = AllInstructions[Opc]->TheDef->getValueAsBitsInit("Inst");
1237
1238 APInt PositiveMask(BitWidth, 0ULL);
1239 APInt NegativeMask(BitWidth, 0ULL);
1240 for (unsigned i = 0; i < BitWidth; ++i) {
1241 bit_value_t B = bitFromBits(*SFBits, i);
1242 bit_value_t IB = bitFromBits(*InstBits, i);
1243
1244 if (B != BIT_TRUE) continue;
1245
1246 switch (IB) {
1247 case BIT_FALSE:
1248 // The bit is meant to be false, so emit a check to see if it is true.
1249 PositiveMask.setBit(i);
1250 break;
1251 case BIT_TRUE:
1252 // The bit is meant to be true, so emit a check to see if it is false.
1253 NegativeMask.setBit(i);
1254 break;
1255 default:
1256 // The bit is not set; this must be an error!
1257 StringRef Name = AllInstructions[Opc]->TheDef->getName();
Jim Grosbachecaef492012-08-14 19:06:05 +00001258 errs() << "SoftFail Conflict: bit SoftFail{" << i << "} in " << Name
1259 << " is set but Inst{" << i << "} is unset!\n"
James Molloyd9ba4fd2012-02-09 10:56:31 +00001260 << " - You can only mark a bit as SoftFail if it is fully defined"
1261 << " (1/0 - not '?') in Inst\n";
Jim Grosbachecaef492012-08-14 19:06:05 +00001262 return;
James Molloyd9ba4fd2012-02-09 10:56:31 +00001263 }
1264 }
1265
1266 bool NeedPositiveMask = PositiveMask.getBoolValue();
1267 bool NeedNegativeMask = NegativeMask.getBoolValue();
1268
1269 if (!NeedPositiveMask && !NeedNegativeMask)
1270 return;
1271
Jim Grosbachecaef492012-08-14 19:06:05 +00001272 TableInfo.Table.push_back(MCD::OPC_SoftFail);
James Molloyd9ba4fd2012-02-09 10:56:31 +00001273
Jim Grosbachecaef492012-08-14 19:06:05 +00001274 SmallString<16> MaskBytes;
1275 raw_svector_ostream S(MaskBytes);
1276 if (NeedPositiveMask) {
1277 encodeULEB128(PositiveMask.getZExtValue(), S);
1278 S.flush();
Craig Topper29688ab2012-08-17 05:42:16 +00001279 for (unsigned i = 0, e = MaskBytes.size(); i != e; ++i)
Jim Grosbachecaef492012-08-14 19:06:05 +00001280 TableInfo.Table.push_back(MaskBytes[i]);
1281 } else
1282 TableInfo.Table.push_back(0);
1283 if (NeedNegativeMask) {
1284 MaskBytes.clear();
1285 S.resync();
1286 encodeULEB128(NegativeMask.getZExtValue(), S);
1287 S.flush();
Craig Topper29688ab2012-08-17 05:42:16 +00001288 for (unsigned i = 0, e = MaskBytes.size(); i != e; ++i)
Jim Grosbachecaef492012-08-14 19:06:05 +00001289 TableInfo.Table.push_back(MaskBytes[i]);
1290 } else
1291 TableInfo.Table.push_back(0);
James Molloyd9ba4fd2012-02-09 10:56:31 +00001292}
1293
Jim Grosbachecaef492012-08-14 19:06:05 +00001294// Emits table entries to decode the singleton.
1295void FilterChooser::emitSingletonTableEntry(DecoderTableInfo &TableInfo,
1296 unsigned Opc) const {
Owen Anderson4e818902011-02-18 21:51:29 +00001297 std::vector<unsigned> StartBits;
1298 std::vector<unsigned> EndBits;
1299 std::vector<uint64_t> FieldVals;
1300 insn_t Insn;
1301 insnWithID(Insn, Opc);
1302
1303 // Look for islands of undecoded bits of the singleton.
1304 getIslands(StartBits, EndBits, FieldVals, Insn);
1305
1306 unsigned Size = StartBits.size();
Owen Anderson4e818902011-02-18 21:51:29 +00001307
Jim Grosbachecaef492012-08-14 19:06:05 +00001308 // Emit the predicate table entry if one is needed.
1309 emitPredicateTableEntry(TableInfo, Opc);
Owen Anderson4e818902011-02-18 21:51:29 +00001310
Jim Grosbachecaef492012-08-14 19:06:05 +00001311 // Check any additional encoding fields needed.
Craig Topper29688ab2012-08-17 05:42:16 +00001312 for (unsigned I = Size; I != 0; --I) {
1313 unsigned NumBits = EndBits[I-1] - StartBits[I-1] + 1;
Jim Grosbachecaef492012-08-14 19:06:05 +00001314 TableInfo.Table.push_back(MCD::OPC_CheckField);
1315 TableInfo.Table.push_back(StartBits[I-1]);
1316 TableInfo.Table.push_back(NumBits);
1317 uint8_t Buffer[8], *p;
1318 encodeULEB128(FieldVals[I-1], Buffer);
1319 for (p = Buffer; *p >= 128 ; ++p)
1320 TableInfo.Table.push_back(*p);
1321 TableInfo.Table.push_back(*p);
1322 // Push location for NumToSkip backpatching.
1323 TableInfo.FixupStack.back().push_back(TableInfo.Table.size());
1324 // The fixup is always 16-bits, so go ahead and allocate the space
1325 // in the table so all our relative position calculations work OK even
1326 // before we fully resolve the real value here.
1327 TableInfo.Table.push_back(0);
1328 TableInfo.Table.push_back(0);
Owen Anderson4e818902011-02-18 21:51:29 +00001329 }
Owen Anderson4e818902011-02-18 21:51:29 +00001330
Jim Grosbachecaef492012-08-14 19:06:05 +00001331 // Check for soft failure of the match.
1332 emitSoftFailTableEntry(TableInfo, Opc);
Owen Anderson4e818902011-02-18 21:51:29 +00001333
Jim Grosbachecaef492012-08-14 19:06:05 +00001334 TableInfo.Table.push_back(MCD::OPC_Decode);
1335 uint8_t Buffer[8], *p;
1336 encodeULEB128(Opc, Buffer);
1337 for (p = Buffer; *p >= 128 ; ++p)
1338 TableInfo.Table.push_back(*p);
1339 TableInfo.Table.push_back(*p);
1340
1341 unsigned DIdx = getDecoderIndex(TableInfo.Decoders, Opc);
1342 SmallString<16> Bytes;
1343 raw_svector_ostream S(Bytes);
1344 encodeULEB128(DIdx, S);
1345 S.flush();
1346
1347 // Decoder index
Craig Topper29688ab2012-08-17 05:42:16 +00001348 for (unsigned i = 0, e = Bytes.size(); i != e; ++i)
Jim Grosbachecaef492012-08-14 19:06:05 +00001349 TableInfo.Table.push_back(Bytes[i]);
Owen Anderson4e818902011-02-18 21:51:29 +00001350}
1351
Jim Grosbachecaef492012-08-14 19:06:05 +00001352// Emits table entries to decode the singleton, and then to decode the rest.
1353void FilterChooser::emitSingletonTableEntry(DecoderTableInfo &TableInfo,
1354 const Filter &Best) const {
Owen Anderson4e818902011-02-18 21:51:29 +00001355 unsigned Opc = Best.getSingletonOpc();
1356
Jim Grosbachecaef492012-08-14 19:06:05 +00001357 // complex singletons need predicate checks from the first singleton
1358 // to refer forward to the variable filterchooser that follows.
1359 TableInfo.FixupStack.push_back(FixupList());
Owen Anderson4e818902011-02-18 21:51:29 +00001360
Jim Grosbachecaef492012-08-14 19:06:05 +00001361 emitSingletonTableEntry(TableInfo, Opc);
Owen Anderson4e818902011-02-18 21:51:29 +00001362
Jim Grosbachecaef492012-08-14 19:06:05 +00001363 resolveTableFixups(TableInfo.Table, TableInfo.FixupStack.back(),
1364 TableInfo.Table.size());
1365 TableInfo.FixupStack.pop_back();
1366
1367 Best.getVariableFC().emitTableEntries(TableInfo);
Owen Anderson4e818902011-02-18 21:51:29 +00001368}
1369
Jim Grosbachecaef492012-08-14 19:06:05 +00001370
Owen Anderson4e818902011-02-18 21:51:29 +00001371// Assign a single filter and run with it. Top level API client can initialize
1372// with a single filter to start the filtering process.
Craig Topper48c112b2012-03-16 05:58:09 +00001373void FilterChooser::runSingleFilter(unsigned startBit, unsigned numBit,
1374 bool mixed) {
Owen Anderson4e818902011-02-18 21:51:29 +00001375 Filters.clear();
Craig Topper5c2b4ac2014-09-03 05:49:07 +00001376 Filters.push_back(Filter(*this, startBit, numBit, true));
Owen Anderson4e818902011-02-18 21:51:29 +00001377 BestIndex = 0; // Sole Filter instance to choose from.
1378 bestFilter().recurse();
1379}
1380
1381// reportRegion is a helper function for filterProcessor to mark a region as
1382// eligible for use as a filter region.
1383void FilterChooser::reportRegion(bitAttr_t RA, unsigned StartBit,
Craig Topper82d0d5f2012-03-16 01:19:24 +00001384 unsigned BitIndex, bool AllowMixed) {
Owen Anderson4e818902011-02-18 21:51:29 +00001385 if (RA == ATTR_MIXED && AllowMixed)
1386 Filters.push_back(Filter(*this, StartBit, BitIndex - StartBit, true));
1387 else if (RA == ATTR_ALL_SET && !AllowMixed)
1388 Filters.push_back(Filter(*this, StartBit, BitIndex - StartBit, false));
1389}
1390
1391// FilterProcessor scans the well-known encoding bits of the instructions and
1392// builds up a list of candidate filters. It chooses the best filter and
1393// recursively descends down the decoding tree.
1394bool FilterChooser::filterProcessor(bool AllowMixed, bool Greedy) {
1395 Filters.clear();
1396 BestIndex = -1;
1397 unsigned numInstructions = Opcodes.size();
1398
1399 assert(numInstructions && "Filter created with no instructions");
1400
1401 // No further filtering is necessary.
1402 if (numInstructions == 1)
1403 return true;
1404
1405 // Heuristics. See also doFilter()'s "Heuristics" comment when num of
1406 // instructions is 3.
1407 if (AllowMixed && !Greedy) {
1408 assert(numInstructions == 3);
1409
1410 for (unsigned i = 0; i < Opcodes.size(); ++i) {
1411 std::vector<unsigned> StartBits;
1412 std::vector<unsigned> EndBits;
1413 std::vector<uint64_t> FieldVals;
1414 insn_t Insn;
1415
1416 insnWithID(Insn, Opcodes[i]);
1417
1418 // Look for islands of undecoded bits of any instruction.
1419 if (getIslands(StartBits, EndBits, FieldVals, Insn) > 0) {
1420 // Found an instruction with island(s). Now just assign a filter.
Craig Topper48c112b2012-03-16 05:58:09 +00001421 runSingleFilter(StartBits[0], EndBits[0] - StartBits[0] + 1, true);
Owen Anderson4e818902011-02-18 21:51:29 +00001422 return true;
1423 }
1424 }
1425 }
1426
Craig Topper29688ab2012-08-17 05:42:16 +00001427 unsigned BitIndex;
Owen Anderson4e818902011-02-18 21:51:29 +00001428
1429 // We maintain BIT_WIDTH copies of the bitAttrs automaton.
1430 // The automaton consumes the corresponding bit from each
1431 // instruction.
1432 //
1433 // Input symbols: 0, 1, and _ (unset).
1434 // States: NONE, FILTERED, ALL_SET, ALL_UNSET, and MIXED.
1435 // Initial state: NONE.
1436 //
1437 // (NONE) ------- [01] -> (ALL_SET)
1438 // (NONE) ------- _ ----> (ALL_UNSET)
1439 // (ALL_SET) ---- [01] -> (ALL_SET)
1440 // (ALL_SET) ---- _ ----> (MIXED)
1441 // (ALL_UNSET) -- [01] -> (MIXED)
1442 // (ALL_UNSET) -- _ ----> (ALL_UNSET)
1443 // (MIXED) ------ . ----> (MIXED)
1444 // (FILTERED)---- . ----> (FILTERED)
1445
Owen Andersonc78e03c2011-07-19 21:06:00 +00001446 std::vector<bitAttr_t> bitAttrs;
Owen Anderson4e818902011-02-18 21:51:29 +00001447
1448 // FILTERED bit positions provide no entropy and are not worthy of pursuing.
1449 // Filter::recurse() set either BIT_TRUE or BIT_FALSE for each position.
Owen Andersonc78e03c2011-07-19 21:06:00 +00001450 for (BitIndex = 0; BitIndex < BitWidth; ++BitIndex)
Owen Anderson4e818902011-02-18 21:51:29 +00001451 if (FilterBitValues[BitIndex] == BIT_TRUE ||
1452 FilterBitValues[BitIndex] == BIT_FALSE)
Owen Andersonc78e03c2011-07-19 21:06:00 +00001453 bitAttrs.push_back(ATTR_FILTERED);
Owen Anderson4e818902011-02-18 21:51:29 +00001454 else
Owen Andersonc78e03c2011-07-19 21:06:00 +00001455 bitAttrs.push_back(ATTR_NONE);
Owen Anderson4e818902011-02-18 21:51:29 +00001456
Craig Topper29688ab2012-08-17 05:42:16 +00001457 for (unsigned InsnIndex = 0; InsnIndex < numInstructions; ++InsnIndex) {
Owen Anderson4e818902011-02-18 21:51:29 +00001458 insn_t insn;
1459
1460 insnWithID(insn, Opcodes[InsnIndex]);
1461
Owen Andersonc78e03c2011-07-19 21:06:00 +00001462 for (BitIndex = 0; BitIndex < BitWidth; ++BitIndex) {
Owen Anderson4e818902011-02-18 21:51:29 +00001463 switch (bitAttrs[BitIndex]) {
1464 case ATTR_NONE:
1465 if (insn[BitIndex] == BIT_UNSET)
1466 bitAttrs[BitIndex] = ATTR_ALL_UNSET;
1467 else
1468 bitAttrs[BitIndex] = ATTR_ALL_SET;
1469 break;
1470 case ATTR_ALL_SET:
1471 if (insn[BitIndex] == BIT_UNSET)
1472 bitAttrs[BitIndex] = ATTR_MIXED;
1473 break;
1474 case ATTR_ALL_UNSET:
1475 if (insn[BitIndex] != BIT_UNSET)
1476 bitAttrs[BitIndex] = ATTR_MIXED;
1477 break;
1478 case ATTR_MIXED:
1479 case ATTR_FILTERED:
1480 break;
1481 }
1482 }
1483 }
1484
1485 // The regionAttr automaton consumes the bitAttrs automatons' state,
1486 // lowest-to-highest.
1487 //
1488 // Input symbols: F(iltered), (all_)S(et), (all_)U(nset), M(ixed)
1489 // States: NONE, ALL_SET, MIXED
1490 // Initial state: NONE
1491 //
1492 // (NONE) ----- F --> (NONE)
1493 // (NONE) ----- S --> (ALL_SET) ; and set region start
1494 // (NONE) ----- U --> (NONE)
1495 // (NONE) ----- M --> (MIXED) ; and set region start
1496 // (ALL_SET) -- F --> (NONE) ; and report an ALL_SET region
1497 // (ALL_SET) -- S --> (ALL_SET)
1498 // (ALL_SET) -- U --> (NONE) ; and report an ALL_SET region
1499 // (ALL_SET) -- M --> (MIXED) ; and report an ALL_SET region
1500 // (MIXED) ---- F --> (NONE) ; and report a MIXED region
1501 // (MIXED) ---- S --> (ALL_SET) ; and report a MIXED region
1502 // (MIXED) ---- U --> (NONE) ; and report a MIXED region
1503 // (MIXED) ---- M --> (MIXED)
1504
1505 bitAttr_t RA = ATTR_NONE;
1506 unsigned StartBit = 0;
1507
Craig Topper29688ab2012-08-17 05:42:16 +00001508 for (BitIndex = 0; BitIndex < BitWidth; ++BitIndex) {
Owen Anderson4e818902011-02-18 21:51:29 +00001509 bitAttr_t bitAttr = bitAttrs[BitIndex];
1510
1511 assert(bitAttr != ATTR_NONE && "Bit without attributes");
1512
1513 switch (RA) {
1514 case ATTR_NONE:
1515 switch (bitAttr) {
1516 case ATTR_FILTERED:
1517 break;
1518 case ATTR_ALL_SET:
1519 StartBit = BitIndex;
1520 RA = ATTR_ALL_SET;
1521 break;
1522 case ATTR_ALL_UNSET:
1523 break;
1524 case ATTR_MIXED:
1525 StartBit = BitIndex;
1526 RA = ATTR_MIXED;
1527 break;
1528 default:
Craig Topperc4965bc2012-02-05 07:21:30 +00001529 llvm_unreachable("Unexpected bitAttr!");
Owen Anderson4e818902011-02-18 21:51:29 +00001530 }
1531 break;
1532 case ATTR_ALL_SET:
1533 switch (bitAttr) {
1534 case ATTR_FILTERED:
1535 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1536 RA = ATTR_NONE;
1537 break;
1538 case ATTR_ALL_SET:
1539 break;
1540 case ATTR_ALL_UNSET:
1541 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1542 RA = ATTR_NONE;
1543 break;
1544 case ATTR_MIXED:
1545 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1546 StartBit = BitIndex;
1547 RA = ATTR_MIXED;
1548 break;
1549 default:
Craig Topperc4965bc2012-02-05 07:21:30 +00001550 llvm_unreachable("Unexpected bitAttr!");
Owen Anderson4e818902011-02-18 21:51:29 +00001551 }
1552 break;
1553 case ATTR_MIXED:
1554 switch (bitAttr) {
1555 case ATTR_FILTERED:
1556 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1557 StartBit = BitIndex;
1558 RA = ATTR_NONE;
1559 break;
1560 case ATTR_ALL_SET:
1561 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1562 StartBit = BitIndex;
1563 RA = ATTR_ALL_SET;
1564 break;
1565 case ATTR_ALL_UNSET:
1566 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1567 RA = ATTR_NONE;
1568 break;
1569 case ATTR_MIXED:
1570 break;
1571 default:
Craig Topperc4965bc2012-02-05 07:21:30 +00001572 llvm_unreachable("Unexpected bitAttr!");
Owen Anderson4e818902011-02-18 21:51:29 +00001573 }
1574 break;
1575 case ATTR_ALL_UNSET:
Craig Topperc4965bc2012-02-05 07:21:30 +00001576 llvm_unreachable("regionAttr state machine has no ATTR_UNSET state");
Owen Anderson4e818902011-02-18 21:51:29 +00001577 case ATTR_FILTERED:
Craig Topperc4965bc2012-02-05 07:21:30 +00001578 llvm_unreachable("regionAttr state machine has no ATTR_FILTERED state");
Owen Anderson4e818902011-02-18 21:51:29 +00001579 }
1580 }
1581
1582 // At the end, if we're still in ALL_SET or MIXED states, report a region
1583 switch (RA) {
1584 case ATTR_NONE:
1585 break;
1586 case ATTR_FILTERED:
1587 break;
1588 case ATTR_ALL_SET:
1589 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1590 break;
1591 case ATTR_ALL_UNSET:
1592 break;
1593 case ATTR_MIXED:
1594 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1595 break;
1596 }
1597
1598 // We have finished with the filter processings. Now it's time to choose
1599 // the best performing filter.
1600 BestIndex = 0;
1601 bool AllUseless = true;
1602 unsigned BestScore = 0;
1603
1604 for (unsigned i = 0, e = Filters.size(); i != e; ++i) {
1605 unsigned Usefulness = Filters[i].usefulness();
1606
1607 if (Usefulness)
1608 AllUseless = false;
1609
1610 if (Usefulness > BestScore) {
1611 BestIndex = i;
1612 BestScore = Usefulness;
1613 }
1614 }
1615
1616 if (!AllUseless)
1617 bestFilter().recurse();
1618
1619 return !AllUseless;
1620} // end of FilterChooser::filterProcessor(bool)
1621
1622// Decides on the best configuration of filter(s) to use in order to decode
1623// the instructions. A conflict of instructions may occur, in which case we
1624// dump the conflict set to the standard error.
1625void FilterChooser::doFilter() {
1626 unsigned Num = Opcodes.size();
1627 assert(Num && "FilterChooser created with no instructions");
1628
1629 // Try regions of consecutive known bit values first.
1630 if (filterProcessor(false))
1631 return;
1632
1633 // Then regions of mixed bits (both known and unitialized bit values allowed).
1634 if (filterProcessor(true))
1635 return;
1636
1637 // Heuristics to cope with conflict set {t2CMPrs, t2SUBSrr, t2SUBSrs} where
1638 // no single instruction for the maximum ATTR_MIXED region Inst{14-4} has a
1639 // well-known encoding pattern. In such case, we backtrack and scan for the
1640 // the very first consecutive ATTR_ALL_SET region and assign a filter to it.
1641 if (Num == 3 && filterProcessor(true, false))
1642 return;
1643
1644 // If we come to here, the instruction decoding has failed.
1645 // Set the BestIndex to -1 to indicate so.
1646 BestIndex = -1;
1647}
1648
Jim Grosbachecaef492012-08-14 19:06:05 +00001649// emitTableEntries - Emit state machine entries to decode our share of
1650// instructions.
1651void FilterChooser::emitTableEntries(DecoderTableInfo &TableInfo) const {
1652 if (Opcodes.size() == 1) {
Owen Anderson4e818902011-02-18 21:51:29 +00001653 // There is only one instruction in the set, which is great!
1654 // Call emitSingletonDecoder() to see whether there are any remaining
1655 // encodings bits.
Jim Grosbachecaef492012-08-14 19:06:05 +00001656 emitSingletonTableEntry(TableInfo, Opcodes[0]);
1657 return;
1658 }
Owen Anderson4e818902011-02-18 21:51:29 +00001659
1660 // Choose the best filter to do the decodings!
1661 if (BestIndex != -1) {
Craig Topper48c112b2012-03-16 05:58:09 +00001662 const Filter &Best = Filters[BestIndex];
Owen Anderson4e818902011-02-18 21:51:29 +00001663 if (Best.getNumFiltered() == 1)
Jim Grosbachecaef492012-08-14 19:06:05 +00001664 emitSingletonTableEntry(TableInfo, Best);
Owen Anderson4e818902011-02-18 21:51:29 +00001665 else
Jim Grosbachecaef492012-08-14 19:06:05 +00001666 Best.emitTableEntry(TableInfo);
1667 return;
Owen Anderson4e818902011-02-18 21:51:29 +00001668 }
1669
Jim Grosbachecaef492012-08-14 19:06:05 +00001670 // We don't know how to decode these instructions! Dump the
1671 // conflict set and bail.
Owen Anderson4e818902011-02-18 21:51:29 +00001672
1673 // Print out useful conflict information for postmortem analysis.
1674 errs() << "Decoding Conflict:\n";
1675
1676 dumpStack(errs(), "\t\t");
1677
Craig Topper82d0d5f2012-03-16 01:19:24 +00001678 for (unsigned i = 0; i < Opcodes.size(); ++i) {
Owen Anderson4e818902011-02-18 21:51:29 +00001679 const std::string &Name = nameWithID(Opcodes[i]);
1680
1681 errs() << '\t' << Name << " ";
1682 dumpBits(errs(),
1683 getBitsField(*AllInstructions[Opcodes[i]]->TheDef, "Inst"));
1684 errs() << '\n';
1685 }
Owen Anderson4e818902011-02-18 21:51:29 +00001686}
1687
Hal Finkel71b2e202013-12-19 16:12:53 +00001688static bool populateInstruction(CodeGenTarget &Target,
1689 const CodeGenInstruction &CGI, unsigned Opc,
Craig Topper82d0d5f2012-03-16 01:19:24 +00001690 std::map<unsigned, std::vector<OperandInfo> > &Operands){
Owen Anderson4e818902011-02-18 21:51:29 +00001691 const Record &Def = *CGI.TheDef;
1692 // If all the bit positions are not specified; do not decode this instruction.
1693 // We are bound to fail! For proper disassembly, the well-known encoding bits
1694 // of the instruction must be fully specified.
Owen Anderson4e818902011-02-18 21:51:29 +00001695
David Greeneaf8ee2c2011-07-29 22:43:06 +00001696 BitsInit &Bits = getBitsField(Def, "Inst");
Jim Grosbachf3fd36e2011-07-06 21:33:38 +00001697 if (Bits.allInComplete()) return false;
1698
Owen Anderson4e818902011-02-18 21:51:29 +00001699 std::vector<OperandInfo> InsnOperands;
1700
1701 // If the instruction has specified a custom decoding hook, use that instead
1702 // of trying to auto-generate the decoder.
1703 std::string InstDecoder = Def.getValueAsString("DecoderMethod");
1704 if (InstDecoder != "") {
Owen Andersone3591652011-07-28 21:54:31 +00001705 InsnOperands.push_back(OperandInfo(InstDecoder));
Owen Anderson4e818902011-02-18 21:51:29 +00001706 Operands[Opc] = InsnOperands;
1707 return true;
1708 }
1709
1710 // Generate a description of the operand of the instruction that we know
1711 // how to decode automatically.
1712 // FIXME: We'll need to have a way to manually override this as needed.
1713
1714 // Gather the outputs/inputs of the instruction, so we can find their
1715 // positions in the encoding. This assumes for now that they appear in the
1716 // MCInst in the order that they're listed.
David Greeneaf8ee2c2011-07-29 22:43:06 +00001717 std::vector<std::pair<Init*, std::string> > InOutOperands;
1718 DagInit *Out = Def.getValueAsDag("OutOperandList");
1719 DagInit *In = Def.getValueAsDag("InOperandList");
Owen Anderson4e818902011-02-18 21:51:29 +00001720 for (unsigned i = 0; i < Out->getNumArgs(); ++i)
1721 InOutOperands.push_back(std::make_pair(Out->getArg(i), Out->getArgName(i)));
1722 for (unsigned i = 0; i < In->getNumArgs(); ++i)
1723 InOutOperands.push_back(std::make_pair(In->getArg(i), In->getArgName(i)));
1724
Owen Anderson53562d02011-07-28 23:56:20 +00001725 // Search for tied operands, so that we can correctly instantiate
1726 // operands that are not explicitly represented in the encoding.
Owen Andersoncb32ce22011-07-29 18:28:52 +00001727 std::map<std::string, std::string> TiedNames;
Owen Anderson53562d02011-07-28 23:56:20 +00001728 for (unsigned i = 0; i < CGI.Operands.size(); ++i) {
1729 int tiedTo = CGI.Operands[i].getTiedRegister();
Owen Andersoncb32ce22011-07-29 18:28:52 +00001730 if (tiedTo != -1) {
Hal Finkel71b2e202013-12-19 16:12:53 +00001731 std::pair<unsigned, unsigned> SO =
1732 CGI.Operands.getSubOperandNumber(tiedTo);
1733 TiedNames[InOutOperands[i].second] = InOutOperands[SO.first].second;
1734 TiedNames[InOutOperands[SO.first].second] = InOutOperands[i].second;
1735 }
1736 }
1737
1738 std::map<std::string, std::vector<OperandInfo> > NumberedInsnOperands;
1739 std::set<std::string> NumberedInsnOperandsNoTie;
1740 if (Target.getInstructionSet()->
1741 getValueAsBit("decodePositionallyEncodedOperands")) {
1742 const std::vector<RecordVal> &Vals = Def.getValues();
1743 unsigned NumberedOp = 0;
1744
Hal Finkel5457bd02014-03-13 07:57:54 +00001745 std::set<unsigned> NamedOpIndices;
1746 if (Target.getInstructionSet()->
1747 getValueAsBit("noNamedPositionallyEncodedOperands"))
1748 // Collect the set of operand indices that might correspond to named
1749 // operand, and skip these when assigning operands based on position.
1750 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
1751 unsigned OpIdx;
1752 if (!CGI.Operands.hasOperandNamed(Vals[i].getName(), OpIdx))
1753 continue;
1754
1755 NamedOpIndices.insert(OpIdx);
1756 }
1757
Hal Finkel71b2e202013-12-19 16:12:53 +00001758 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
1759 // Ignore fixed fields in the record, we're looking for values like:
1760 // bits<5> RST = { ?, ?, ?, ?, ? };
1761 if (Vals[i].getPrefix() || Vals[i].getValue()->isComplete())
1762 continue;
1763
1764 // Determine if Vals[i] actually contributes to the Inst encoding.
1765 unsigned bi = 0;
1766 for (; bi < Bits.getNumBits(); ++bi) {
Craig Topper24064772014-04-15 07:20:03 +00001767 VarInit *Var = nullptr;
Hal Finkel71b2e202013-12-19 16:12:53 +00001768 VarBitInit *BI = dyn_cast<VarBitInit>(Bits.getBit(bi));
1769 if (BI)
1770 Var = dyn_cast<VarInit>(BI->getBitVar());
1771 else
1772 Var = dyn_cast<VarInit>(Bits.getBit(bi));
1773
1774 if (Var && Var->getName() == Vals[i].getName())
1775 break;
1776 }
1777
1778 if (bi == Bits.getNumBits())
1779 continue;
1780
1781 // Skip variables that correspond to explicitly-named operands.
1782 unsigned OpIdx;
1783 if (CGI.Operands.hasOperandNamed(Vals[i].getName(), OpIdx))
1784 continue;
1785
1786 // Get the bit range for this operand:
1787 unsigned bitStart = bi++, bitWidth = 1;
1788 for (; bi < Bits.getNumBits(); ++bi) {
Craig Topper24064772014-04-15 07:20:03 +00001789 VarInit *Var = nullptr;
Hal Finkel71b2e202013-12-19 16:12:53 +00001790 VarBitInit *BI = dyn_cast<VarBitInit>(Bits.getBit(bi));
1791 if (BI)
1792 Var = dyn_cast<VarInit>(BI->getBitVar());
1793 else
1794 Var = dyn_cast<VarInit>(Bits.getBit(bi));
1795
1796 if (!Var)
1797 break;
1798
1799 if (Var->getName() != Vals[i].getName())
1800 break;
1801
1802 ++bitWidth;
1803 }
1804
1805 unsigned NumberOps = CGI.Operands.size();
1806 while (NumberedOp < NumberOps &&
Hal Finkel5457bd02014-03-13 07:57:54 +00001807 (CGI.Operands.isFlatOperandNotEmitted(NumberedOp) ||
1808 (NamedOpIndices.size() && NamedOpIndices.count(
1809 CGI.Operands.getSubOperandNumber(NumberedOp).first))))
Hal Finkel71b2e202013-12-19 16:12:53 +00001810 ++NumberedOp;
1811
1812 OpIdx = NumberedOp++;
1813
1814 // OpIdx now holds the ordered operand number of Vals[i].
1815 std::pair<unsigned, unsigned> SO =
1816 CGI.Operands.getSubOperandNumber(OpIdx);
1817 const std::string &Name = CGI.Operands[SO.first].Name;
1818
1819 DEBUG(dbgs() << "Numbered operand mapping for " << Def.getName() << ": " <<
1820 Name << "(" << SO.first << ", " << SO.second << ") => " <<
1821 Vals[i].getName() << "\n");
1822
1823 std::string Decoder = "";
1824 Record *TypeRecord = CGI.Operands[SO.first].Rec;
1825
1826 RecordVal *DecoderString = TypeRecord->getValue("DecoderMethod");
1827 StringInit *String = DecoderString ?
Craig Topper24064772014-04-15 07:20:03 +00001828 dyn_cast<StringInit>(DecoderString->getValue()) : nullptr;
Hal Finkel71b2e202013-12-19 16:12:53 +00001829 if (String && String->getValue() != "")
1830 Decoder = String->getValue();
1831
1832 if (Decoder == "" &&
1833 CGI.Operands[SO.first].MIOperandInfo &&
1834 CGI.Operands[SO.first].MIOperandInfo->getNumArgs()) {
1835 Init *Arg = CGI.Operands[SO.first].MIOperandInfo->
1836 getArg(SO.second);
1837 if (TypedInit *TI = cast<TypedInit>(Arg)) {
1838 RecordRecTy *Type = cast<RecordRecTy>(TI->getType());
1839 TypeRecord = Type->getRecord();
1840 }
1841 }
1842
1843 bool isReg = false;
1844 if (TypeRecord->isSubClassOf("RegisterOperand"))
1845 TypeRecord = TypeRecord->getValueAsDef("RegClass");
1846 if (TypeRecord->isSubClassOf("RegisterClass")) {
1847 Decoder = "Decode" + TypeRecord->getName() + "RegisterClass";
1848 isReg = true;
1849 } else if (TypeRecord->isSubClassOf("PointerLikeRegClass")) {
1850 Decoder = "DecodePointerLikeRegClass" +
1851 utostr(TypeRecord->getValueAsInt("RegClassKind"));
1852 isReg = true;
1853 }
1854
1855 DecoderString = TypeRecord->getValue("DecoderMethod");
1856 String = DecoderString ?
Craig Topper24064772014-04-15 07:20:03 +00001857 dyn_cast<StringInit>(DecoderString->getValue()) : nullptr;
Hal Finkel71b2e202013-12-19 16:12:53 +00001858 if (!isReg && String && String->getValue() != "")
1859 Decoder = String->getValue();
1860
1861 OperandInfo OpInfo(Decoder);
1862 OpInfo.addField(bitStart, bitWidth, 0);
1863
1864 NumberedInsnOperands[Name].push_back(OpInfo);
1865
1866 // FIXME: For complex operands with custom decoders we can't handle tied
1867 // sub-operands automatically. Skip those here and assume that this is
1868 // fixed up elsewhere.
1869 if (CGI.Operands[SO.first].MIOperandInfo &&
1870 CGI.Operands[SO.first].MIOperandInfo->getNumArgs() > 1 &&
1871 String && String->getValue() != "")
1872 NumberedInsnOperandsNoTie.insert(Name);
Owen Andersoncb32ce22011-07-29 18:28:52 +00001873 }
Owen Anderson53562d02011-07-28 23:56:20 +00001874 }
1875
Owen Anderson4e818902011-02-18 21:51:29 +00001876 // For each operand, see if we can figure out where it is encoded.
Craig Topper501d95c2012-03-16 06:52:56 +00001877 for (std::vector<std::pair<Init*, std::string> >::const_iterator
Owen Anderson4e818902011-02-18 21:51:29 +00001878 NI = InOutOperands.begin(), NE = InOutOperands.end(); NI != NE; ++NI) {
Hal Finkel71b2e202013-12-19 16:12:53 +00001879 if (!NumberedInsnOperands[NI->second].empty()) {
1880 InsnOperands.insert(InsnOperands.end(),
1881 NumberedInsnOperands[NI->second].begin(),
1882 NumberedInsnOperands[NI->second].end());
1883 continue;
1884 } else if (!NumberedInsnOperands[TiedNames[NI->second]].empty()) {
1885 if (!NumberedInsnOperandsNoTie.count(TiedNames[NI->second])) {
1886 // Figure out to which (sub)operand we're tied.
1887 unsigned i = CGI.Operands.getOperandNamed(TiedNames[NI->second]);
1888 int tiedTo = CGI.Operands[i].getTiedRegister();
1889 if (tiedTo == -1) {
1890 i = CGI.Operands.getOperandNamed(NI->second);
1891 tiedTo = CGI.Operands[i].getTiedRegister();
1892 }
1893
1894 if (tiedTo != -1) {
1895 std::pair<unsigned, unsigned> SO =
1896 CGI.Operands.getSubOperandNumber(tiedTo);
1897
1898 InsnOperands.push_back(NumberedInsnOperands[TiedNames[NI->second]]
1899 [SO.second]);
1900 }
1901 }
1902 continue;
1903 }
1904
Owen Anderson4e818902011-02-18 21:51:29 +00001905 std::string Decoder = "";
1906
Owen Andersone3591652011-07-28 21:54:31 +00001907 // At this point, we can locate the field, but we need to know how to
1908 // interpret it. As a first step, require the target to provide callbacks
1909 // for decoding register classes.
1910 // FIXME: This need to be extended to handle instructions with custom
1911 // decoder methods, and operands with (simple) MIOperandInfo's.
Sean Silva88eb8dd2012-10-10 20:24:47 +00001912 TypedInit *TI = cast<TypedInit>(NI->first);
1913 RecordRecTy *Type = cast<RecordRecTy>(TI->getType());
Owen Andersone3591652011-07-28 21:54:31 +00001914 Record *TypeRecord = Type->getRecord();
1915 bool isReg = false;
1916 if (TypeRecord->isSubClassOf("RegisterOperand"))
1917 TypeRecord = TypeRecord->getValueAsDef("RegClass");
1918 if (TypeRecord->isSubClassOf("RegisterClass")) {
1919 Decoder = "Decode" + TypeRecord->getName() + "RegisterClass";
1920 isReg = true;
Hal Finkel9d95e8d2013-12-19 14:58:22 +00001921 } else if (TypeRecord->isSubClassOf("PointerLikeRegClass")) {
1922 Decoder = "DecodePointerLikeRegClass" +
1923 utostr(TypeRecord->getValueAsInt("RegClassKind"));
1924 isReg = true;
Owen Andersone3591652011-07-28 21:54:31 +00001925 }
1926
1927 RecordVal *DecoderString = TypeRecord->getValue("DecoderMethod");
David Greeneaf8ee2c2011-07-29 22:43:06 +00001928 StringInit *String = DecoderString ?
Craig Topper24064772014-04-15 07:20:03 +00001929 dyn_cast<StringInit>(DecoderString->getValue()) : nullptr;
Owen Andersone3591652011-07-28 21:54:31 +00001930 if (!isReg && String && String->getValue() != "")
1931 Decoder = String->getValue();
1932
1933 OperandInfo OpInfo(Decoder);
1934 unsigned Base = ~0U;
1935 unsigned Width = 0;
1936 unsigned Offset = 0;
1937
Owen Anderson4e818902011-02-18 21:51:29 +00001938 for (unsigned bi = 0; bi < Bits.getNumBits(); ++bi) {
Craig Topper24064772014-04-15 07:20:03 +00001939 VarInit *Var = nullptr;
Sean Silvafb509ed2012-10-10 20:24:43 +00001940 VarBitInit *BI = dyn_cast<VarBitInit>(Bits.getBit(bi));
Owen Anderson3022d672011-08-01 22:45:43 +00001941 if (BI)
Sean Silvafb509ed2012-10-10 20:24:43 +00001942 Var = dyn_cast<VarInit>(BI->getBitVar());
Owen Anderson3022d672011-08-01 22:45:43 +00001943 else
Sean Silvafb509ed2012-10-10 20:24:43 +00001944 Var = dyn_cast<VarInit>(Bits.getBit(bi));
Owen Anderson3022d672011-08-01 22:45:43 +00001945
1946 if (!Var) {
Owen Andersone3591652011-07-28 21:54:31 +00001947 if (Base != ~0U) {
1948 OpInfo.addField(Base, Width, Offset);
1949 Base = ~0U;
1950 Width = 0;
1951 Offset = 0;
1952 }
1953 continue;
1954 }
Owen Anderson4e818902011-02-18 21:51:29 +00001955
Owen Anderson53562d02011-07-28 23:56:20 +00001956 if (Var->getName() != NI->second &&
Owen Andersoncb32ce22011-07-29 18:28:52 +00001957 Var->getName() != TiedNames[NI->second]) {
Owen Andersone3591652011-07-28 21:54:31 +00001958 if (Base != ~0U) {
1959 OpInfo.addField(Base, Width, Offset);
1960 Base = ~0U;
1961 Width = 0;
1962 Offset = 0;
1963 }
1964 continue;
Owen Anderson4e818902011-02-18 21:51:29 +00001965 }
1966
Owen Andersone3591652011-07-28 21:54:31 +00001967 if (Base == ~0U) {
1968 Base = bi;
1969 Width = 1;
Owen Anderson3022d672011-08-01 22:45:43 +00001970 Offset = BI ? BI->getBitNum() : 0;
1971 } else if (BI && BI->getBitNum() != Offset + Width) {
Owen Andersone08f5b52011-07-29 23:01:18 +00001972 OpInfo.addField(Base, Width, Offset);
1973 Base = bi;
1974 Width = 1;
1975 Offset = BI->getBitNum();
Owen Andersone3591652011-07-28 21:54:31 +00001976 } else {
1977 ++Width;
Owen Anderson4e818902011-02-18 21:51:29 +00001978 }
Owen Anderson4e818902011-02-18 21:51:29 +00001979 }
1980
Owen Andersone3591652011-07-28 21:54:31 +00001981 if (Base != ~0U)
1982 OpInfo.addField(Base, Width, Offset);
1983
1984 if (OpInfo.numFields() > 0)
1985 InsnOperands.push_back(OpInfo);
Owen Anderson4e818902011-02-18 21:51:29 +00001986 }
1987
1988 Operands[Opc] = InsnOperands;
1989
1990
1991#if 0
1992 DEBUG({
1993 // Dumps the instruction encoding bits.
1994 dumpBits(errs(), Bits);
1995
1996 errs() << '\n';
1997
1998 // Dumps the list of operand info.
1999 for (unsigned i = 0, e = CGI.Operands.size(); i != e; ++i) {
2000 const CGIOperandList::OperandInfo &Info = CGI.Operands[i];
2001 const std::string &OperandName = Info.Name;
2002 const Record &OperandDef = *Info.Rec;
2003
2004 errs() << "\t" << OperandName << " (" << OperandDef.getName() << ")\n";
2005 }
2006 });
2007#endif
2008
2009 return true;
2010}
2011
Jim Grosbachecaef492012-08-14 19:06:05 +00002012// emitFieldFromInstruction - Emit the templated helper function
2013// fieldFromInstruction().
2014static void emitFieldFromInstruction(formatted_raw_ostream &OS) {
2015 OS << "// Helper function for extracting fields from encoded instructions.\n"
2016 << "template<typename InsnType>\n"
2017 << "static InsnType fieldFromInstruction(InsnType insn, unsigned startBit,\n"
2018 << " unsigned numBits) {\n"
2019 << " assert(startBit + numBits <= (sizeof(InsnType)*8) &&\n"
2020 << " \"Instruction field out of bounds!\");\n"
2021 << " InsnType fieldMask;\n"
2022 << " if (numBits == sizeof(InsnType)*8)\n"
2023 << " fieldMask = (InsnType)(-1LL);\n"
2024 << " else\n"
NAKAMURA Takumibf99a422012-12-26 06:43:14 +00002025 << " fieldMask = (((InsnType)1 << numBits) - 1) << startBit;\n"
Jim Grosbachecaef492012-08-14 19:06:05 +00002026 << " return (insn & fieldMask) >> startBit;\n"
2027 << "}\n\n";
2028}
Owen Anderson4e818902011-02-18 21:51:29 +00002029
Jim Grosbachecaef492012-08-14 19:06:05 +00002030// emitDecodeInstruction - Emit the templated helper function
2031// decodeInstruction().
2032static void emitDecodeInstruction(formatted_raw_ostream &OS) {
2033 OS << "template<typename InsnType>\n"
2034 << "static DecodeStatus decodeInstruction(const uint8_t DecodeTable[], MCInst &MI,\n"
2035 << " InsnType insn, uint64_t Address,\n"
2036 << " const void *DisAsm,\n"
2037 << " const MCSubtargetInfo &STI) {\n"
2038 << " uint64_t Bits = STI.getFeatureBits();\n"
2039 << "\n"
2040 << " const uint8_t *Ptr = DecodeTable;\n"
Jim Grosbach4c363492012-09-17 18:00:53 +00002041 << " uint32_t CurFieldValue = 0;\n"
Jim Grosbachecaef492012-08-14 19:06:05 +00002042 << " DecodeStatus S = MCDisassembler::Success;\n"
2043 << " for (;;) {\n"
2044 << " ptrdiff_t Loc = Ptr - DecodeTable;\n"
2045 << " switch (*Ptr) {\n"
2046 << " default:\n"
2047 << " errs() << Loc << \": Unexpected decode table opcode!\\n\";\n"
2048 << " return MCDisassembler::Fail;\n"
2049 << " case MCD::OPC_ExtractField: {\n"
2050 << " unsigned Start = *++Ptr;\n"
2051 << " unsigned Len = *++Ptr;\n"
2052 << " ++Ptr;\n"
2053 << " CurFieldValue = fieldFromInstruction(insn, Start, Len);\n"
2054 << " DEBUG(dbgs() << Loc << \": OPC_ExtractField(\" << Start << \", \"\n"
2055 << " << Len << \"): \" << CurFieldValue << \"\\n\");\n"
2056 << " break;\n"
2057 << " }\n"
2058 << " case MCD::OPC_FilterValue: {\n"
2059 << " // Decode the field value.\n"
2060 << " unsigned Len;\n"
2061 << " InsnType Val = decodeULEB128(++Ptr, &Len);\n"
2062 << " Ptr += Len;\n"
2063 << " // NumToSkip is a plain 16-bit integer.\n"
2064 << " unsigned NumToSkip = *Ptr++;\n"
2065 << " NumToSkip |= (*Ptr++) << 8;\n"
2066 << "\n"
2067 << " // Perform the filter operation.\n"
2068 << " if (Val != CurFieldValue)\n"
2069 << " Ptr += NumToSkip;\n"
2070 << " DEBUG(dbgs() << Loc << \": OPC_FilterValue(\" << Val << \", \" << NumToSkip\n"
2071 << " << \"): \" << ((Val != CurFieldValue) ? \"FAIL:\" : \"PASS:\")\n"
2072 << " << \" continuing at \" << (Ptr - DecodeTable) << \"\\n\");\n"
2073 << "\n"
2074 << " break;\n"
2075 << " }\n"
2076 << " case MCD::OPC_CheckField: {\n"
2077 << " unsigned Start = *++Ptr;\n"
2078 << " unsigned Len = *++Ptr;\n"
2079 << " InsnType FieldValue = fieldFromInstruction(insn, Start, Len);\n"
2080 << " // Decode the field value.\n"
2081 << " uint32_t ExpectedValue = decodeULEB128(++Ptr, &Len);\n"
2082 << " Ptr += Len;\n"
2083 << " // NumToSkip is a plain 16-bit integer.\n"
2084 << " unsigned NumToSkip = *Ptr++;\n"
2085 << " NumToSkip |= (*Ptr++) << 8;\n"
2086 << "\n"
2087 << " // If the actual and expected values don't match, skip.\n"
2088 << " if (ExpectedValue != FieldValue)\n"
2089 << " Ptr += NumToSkip;\n"
2090 << " DEBUG(dbgs() << Loc << \": OPC_CheckField(\" << Start << \", \"\n"
2091 << " << Len << \", \" << ExpectedValue << \", \" << NumToSkip\n"
2092 << " << \"): FieldValue = \" << FieldValue << \", ExpectedValue = \"\n"
2093 << " << ExpectedValue << \": \"\n"
2094 << " << ((ExpectedValue == FieldValue) ? \"PASS\\n\" : \"FAIL\\n\"));\n"
2095 << " break;\n"
2096 << " }\n"
2097 << " case MCD::OPC_CheckPredicate: {\n"
2098 << " unsigned Len;\n"
2099 << " // Decode the Predicate Index value.\n"
2100 << " unsigned PIdx = decodeULEB128(++Ptr, &Len);\n"
2101 << " Ptr += Len;\n"
2102 << " // NumToSkip is a plain 16-bit integer.\n"
2103 << " unsigned NumToSkip = *Ptr++;\n"
2104 << " NumToSkip |= (*Ptr++) << 8;\n"
2105 << " // Check the predicate.\n"
2106 << " bool Pred;\n"
2107 << " if (!(Pred = checkDecoderPredicate(PIdx, Bits)))\n"
2108 << " Ptr += NumToSkip;\n"
2109 << " (void)Pred;\n"
2110 << " DEBUG(dbgs() << Loc << \": OPC_CheckPredicate(\" << PIdx << \"): \"\n"
2111 << " << (Pred ? \"PASS\\n\" : \"FAIL\\n\"));\n"
2112 << "\n"
2113 << " break;\n"
2114 << " }\n"
2115 << " case MCD::OPC_Decode: {\n"
2116 << " unsigned Len;\n"
2117 << " // Decode the Opcode value.\n"
2118 << " unsigned Opc = decodeULEB128(++Ptr, &Len);\n"
2119 << " Ptr += Len;\n"
2120 << " unsigned DecodeIdx = decodeULEB128(Ptr, &Len);\n"
2121 << " Ptr += Len;\n"
2122 << " DEBUG(dbgs() << Loc << \": OPC_Decode: opcode \" << Opc\n"
2123 << " << \", using decoder \" << DecodeIdx << \"\\n\" );\n"
2124 << " DEBUG(dbgs() << \"----- DECODE SUCCESSFUL -----\\n\");\n"
2125 << "\n"
2126 << " MI.setOpcode(Opc);\n"
Benjamin Kramer26b568d2012-08-15 10:26:44 +00002127 << " return decodeToMCInst(S, DecodeIdx, insn, MI, Address, DisAsm);\n"
Jim Grosbachecaef492012-08-14 19:06:05 +00002128 << " }\n"
2129 << " case MCD::OPC_SoftFail: {\n"
2130 << " // Decode the mask values.\n"
2131 << " unsigned Len;\n"
2132 << " InsnType PositiveMask = decodeULEB128(++Ptr, &Len);\n"
2133 << " Ptr += Len;\n"
2134 << " InsnType NegativeMask = decodeULEB128(Ptr, &Len);\n"
2135 << " Ptr += Len;\n"
2136 << " bool Fail = (insn & PositiveMask) || (~insn & NegativeMask);\n"
2137 << " if (Fail)\n"
2138 << " S = MCDisassembler::SoftFail;\n"
2139 << " DEBUG(dbgs() << Loc << \": OPC_SoftFail: \" << (Fail ? \"FAIL\\n\":\"PASS\\n\"));\n"
2140 << " break;\n"
2141 << " }\n"
2142 << " case MCD::OPC_Fail: {\n"
2143 << " DEBUG(dbgs() << Loc << \": OPC_Fail\\n\");\n"
2144 << " return MCDisassembler::Fail;\n"
2145 << " }\n"
2146 << " }\n"
2147 << " }\n"
2148 << " llvm_unreachable(\"bogosity detected in disassembler state machine!\");\n"
2149 << "}\n\n";
Owen Anderson4e818902011-02-18 21:51:29 +00002150}
2151
2152// Emits disassembler code for instruction decoding.
Craig Topper82d0d5f2012-03-16 01:19:24 +00002153void FixedLenDecoderEmitter::run(raw_ostream &o) {
Jim Grosbachecaef492012-08-14 19:06:05 +00002154 formatted_raw_ostream OS(o);
2155 OS << "#include \"llvm/MC/MCInst.h\"\n";
2156 OS << "#include \"llvm/Support/Debug.h\"\n";
2157 OS << "#include \"llvm/Support/DataTypes.h\"\n";
2158 OS << "#include \"llvm/Support/LEB128.h\"\n";
2159 OS << "#include \"llvm/Support/raw_ostream.h\"\n";
2160 OS << "#include <assert.h>\n";
2161 OS << '\n';
2162 OS << "namespace llvm {\n\n";
2163
2164 emitFieldFromInstruction(OS);
Owen Anderson4e818902011-02-18 21:51:29 +00002165
Hal Finkel81e6fcc2013-12-17 22:37:50 +00002166 Target.reverseBitsForLittleEndianEncoding();
2167
Owen Andersonc78e03c2011-07-19 21:06:00 +00002168 // Parameterize the decoders based on namespace and instruction width.
Jim Grosbachecaef492012-08-14 19:06:05 +00002169 NumberedInstructions = &Target.getInstructionsByEnumValue();
Owen Andersonc78e03c2011-07-19 21:06:00 +00002170 std::map<std::pair<std::string, unsigned>,
2171 std::vector<unsigned> > OpcMap;
2172 std::map<unsigned, std::vector<OperandInfo> > Operands;
2173
Jim Grosbachecaef492012-08-14 19:06:05 +00002174 for (unsigned i = 0; i < NumberedInstructions->size(); ++i) {
2175 const CodeGenInstruction *Inst = NumberedInstructions->at(i);
Craig Topper48c112b2012-03-16 05:58:09 +00002176 const Record *Def = Inst->TheDef;
Owen Andersonc78e03c2011-07-19 21:06:00 +00002177 unsigned Size = Def->getValueAsInt("Size");
2178 if (Def->getValueAsString("Namespace") == "TargetOpcode" ||
2179 Def->getValueAsBit("isPseudo") ||
2180 Def->getValueAsBit("isAsmParserOnly") ||
2181 Def->getValueAsBit("isCodeGenOnly"))
2182 continue;
2183
2184 std::string DecoderNamespace = Def->getValueAsString("DecoderNamespace");
2185
2186 if (Size) {
Hal Finkel71b2e202013-12-19 16:12:53 +00002187 if (populateInstruction(Target, *Inst, i, Operands)) {
Owen Andersonc78e03c2011-07-19 21:06:00 +00002188 OpcMap[std::make_pair(DecoderNamespace, Size)].push_back(i);
2189 }
2190 }
2191 }
2192
Jim Grosbachecaef492012-08-14 19:06:05 +00002193 DecoderTableInfo TableInfo;
Owen Andersonc78e03c2011-07-19 21:06:00 +00002194 for (std::map<std::pair<std::string, unsigned>,
Craig Topper48c112b2012-03-16 05:58:09 +00002195 std::vector<unsigned> >::const_iterator
Owen Andersonc78e03c2011-07-19 21:06:00 +00002196 I = OpcMap.begin(), E = OpcMap.end(); I != E; ++I) {
Owen Andersonc78e03c2011-07-19 21:06:00 +00002197 // Emit the decoder for this namespace+width combination.
Jim Grosbachecaef492012-08-14 19:06:05 +00002198 FilterChooser FC(*NumberedInstructions, I->second, Operands,
Owen Andersona4043c42011-08-17 17:44:15 +00002199 8*I->first.second, this);
Jim Grosbachecaef492012-08-14 19:06:05 +00002200
2201 // The decode table is cleared for each top level decoder function. The
2202 // predicates and decoders themselves, however, are shared across all
2203 // decoders to give more opportunities for uniqueing.
2204 TableInfo.Table.clear();
2205 TableInfo.FixupStack.clear();
2206 TableInfo.Table.reserve(16384);
2207 TableInfo.FixupStack.push_back(FixupList());
2208 FC.emitTableEntries(TableInfo);
2209 // Any NumToSkip fixups in the top level scope can resolve to the
2210 // OPC_Fail at the end of the table.
2211 assert(TableInfo.FixupStack.size() == 1 && "fixup stack phasing error!");
2212 // Resolve any NumToSkip fixups in the current scope.
2213 resolveTableFixups(TableInfo.Table, TableInfo.FixupStack.back(),
2214 TableInfo.Table.size());
2215 TableInfo.FixupStack.clear();
2216
2217 TableInfo.Table.push_back(MCD::OPC_Fail);
2218
2219 // Print the table to the output stream.
2220 emitTable(OS, TableInfo.Table, 0, FC.getBitWidth(), I->first.first);
2221 OS.flush();
Owen Andersonc78e03c2011-07-19 21:06:00 +00002222 }
Owen Anderson4e818902011-02-18 21:51:29 +00002223
Jim Grosbachecaef492012-08-14 19:06:05 +00002224 // Emit the predicate function.
2225 emitPredicateFunction(OS, TableInfo.Predicates, 0);
2226
2227 // Emit the decoder function.
2228 emitDecoderFunction(OS, TableInfo.Decoders, 0);
2229
2230 // Emit the main entry point for the decoder, decodeInstruction().
2231 emitDecodeInstruction(OS);
2232
2233 OS << "\n} // End llvm namespace\n";
Owen Anderson4e818902011-02-18 21:51:29 +00002234}
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +00002235
2236namespace llvm {
2237
2238void EmitFixedLenDecoder(RecordKeeper &RK, raw_ostream &OS,
2239 std::string PredicateNamespace,
2240 std::string GPrefix,
2241 std::string GPostfix,
2242 std::string ROK,
2243 std::string RFail,
2244 std::string L) {
2245 FixedLenDecoderEmitter(RK, PredicateNamespace, GPrefix, GPostfix,
2246 ROK, RFail, L).run(OS);
2247}
2248
2249} // End llvm namespace