Debian Codegraph @

visa/iga/GEDLibrary/GED_external/Source/ged/xcoder/ged_ins.cpp

raw
1 /*========================== begin_copyright_notice ============================
2
3 Copyright (C) 2017-2021 Intel Corporation
4
5 SPDX-License-Identifier: MIT
6
7 ============================= end_copyright_notice ===========================*/
8
9 #include <cstring>
10 #include <iomanip>
11 #include <algorithm>
12 #include "common/ged_string_utils.h"
13 #include "xcoder/ged_ins.h"
14
15 using std::setw;
16 using std::setfill;
17 using std::hex;
18 using std::memset;
19 #if GED_VALIDATION_API
20 using std::sort;
21 using std::end;
22 using std::next;
23 using std::cout;
24 using std::endl;
25 using std::dec;
26 using std::left;
27 using std::stringstream;
28 #endif
29
30 #if ((!defined _WIN32) && ( !defined __STDC_LIB_EXT1__ ))
31 #include <errno.h>
32 #include <string.h>
33 #include <stdio.h>
34 typedef int errno_t;
35 inline errno_t memcpy_s( void *dst, size_t numberOfElements, const void *src, size_t count )
36 {
37 if( ( dst == NULL ) || ( src == NULL ) )
38 {
39 return EINVAL;
40 }
41 if( numberOfElements < count )
42 {
43 return ERANGE;
44 }
45 memcpy( dst, src, count );
46 return 0;
47 }
48 #endif
49
50
51 /*************************************************************************************************
52 * class GEDIns static data members
53 *************************************************************************************************/
54
55 const int64_t GEDIns::signExtendTable[] =
56 {
57 (int64_t)0xffffffffffffffff, // 0
58 (int64_t)0xfffffffffffffffe, // 1
59 (int64_t)0xfffffffffffffffc, // 2
60 (int64_t)0xfffffffffffffff8, // 3
61 (int64_t)0xfffffffffffffff0, // 4
62 (int64_t)0xffffffffffffffe0, // 5
63 (int64_t)0xffffffffffffffc0, // 6
64 (int64_t)0xffffffffffffff80, // 7
65 (int64_t)0xffffffffffffff00, // 8
66 (int64_t)0xfffffffffffffe00, // 9
67 (int64_t)0xfffffffffffffc00, // 10
68 (int64_t)0xfffffffffffff800, // 11
69 (int64_t)0xfffffffffffff000, // 12
70 (int64_t)0xffffffffffffe000, // 13
71 (int64_t)0xffffffffffffc000, // 14
72 (int64_t)0xffffffffffff8000, // 15
73 (int64_t)0xffffffffffff0000, // 16
74 (int64_t)0xfffffffffffe0000, // 17
75 (int64_t)0xfffffffffffc0000, // 18
76 (int64_t)0xfffffffffff80000, // 19
77 (int64_t)0xfffffffffff00000, // 20
78 (int64_t)0xffffffffffe00000, // 21
79 (int64_t)0xffffffffffc00000, // 22
80 (int64_t)0xffffffffff800000, // 23
81 (int64_t)0xffffffffff000000, // 24
82 (int64_t)0xfffffffffe000000, // 25
83 (int64_t)0xfffffffffc000000, // 26
84 (int64_t)0xfffffffff8000000, // 27
85 (int64_t)0xfffffffff0000000, // 28
86 (int64_t)0xffffffffe0000000, // 29
87 (int64_t)0xffffffffc0000000, // 30
88 (int64_t)0xffffffff80000000, // 31
89 (int64_t)0xffffffff00000000, // 32
90 (int64_t)0xfffffffe00000000, // 33
91 (int64_t)0xfffffffc00000000, // 34
92 (int64_t)0xfffffff800000000, // 35
93 (int64_t)0xfffffff000000000, // 36
94 (int64_t)0xffffffe000000000, // 37
95 (int64_t)0xffffffc000000000, // 38
96 (int64_t)0xffffff8000000000, // 39
97 (int64_t)0xffffff0000000000, // 40
98 (int64_t)0xfffffe0000000000, // 41
99 (int64_t)0xfffffc0000000000, // 42
100 (int64_t)0xfffff80000000000, // 43
101 (int64_t)0xfffff00000000000, // 44
102 (int64_t)0xffffe00000000000, // 45
103 (int64_t)0xffffc00000000000, // 46
104 (int64_t)0xffff800000000000, // 47
105 (int64_t)0xffff000000000000, // 48
106 (int64_t)0xfffe000000000000, // 49
107 (int64_t)0xfffc000000000000, // 50
108 (int64_t)0xfff8000000000000, // 51
109 (int64_t)0xfff0000000000000, // 52
110 (int64_t)0xffe0000000000000, // 53
111 (int64_t)0xffc0000000000000, // 54
112 (int64_t)0xff80000000000000, // 55
113 (int64_t)0xff00000000000000, // 56
114 (int64_t)0xfe00000000000000, // 57
115 (int64_t)0xfc00000000000000, // 58
116 (int64_t)0xf800000000000000, // 59
117 (int64_t)0xf000000000000000, // 60
118 (int64_t)0xe000000000000000, // 61
119 (int64_t)0xc000000000000000, // 62
120 (int64_t)0x8000000000000000, // 63
121 };
122
123
124 /*************************************************************************************************
125 * class GEDIns API functions
126 *************************************************************************************************/
127
128 GED_RETURN_VALUE GEDIns::Init(const /* GED_MODEL */ uint8_t modelId, /* GED_OPCODE */ uint32_t opcode)
129 {
130 GED_RETURN_VALUE ret = GED_RETURN_VALUE_SUCCESS;
131 if (modelId >= numOfSupportedModels)
132 {
133 ret = GED_RETURN_VALUE_INVALID_MODEL;
134 return ret;
135 }
136 _modelId = modelId;
137 _opcode = invalidOpcode;
138 _decodingTable = NULL;
139 ret = SetOpcode(opcode);
140 #if defined(GED_VALIDATE)
141 if (GED_RETURN_VALUE_OPCODE_NOT_SUPPORTED != ret)
142 {
143 GEDASSERT(invalidOpcode != _opcode);
144 GEDASSERT(NULL != _decodingTable);
145 }
146 #endif // GED_VALIDATE
147 return ret;
148 }
149
150
151 GED_RETURN_VALUE GEDIns::Decode(const /* GED_MODEL */ uint8_t modelId, const unsigned char* rawBytes, const unsigned int size)
152 {
153 if (NULL == rawBytes)
154 {
155 return GED_RETURN_VALUE_NULL_POINTER;
156 }
157 if (modelId >= numOfSupportedModels)
158 {
159 return GED_RETURN_VALUE_INVALID_MODEL;
160 }
161 if (size < GED_COMPACT_INS_SIZE)
162 {
163 // Buffer isn't large enough to extract opcode and compact bit.
164 return GED_RETURN_VALUE_BUFFER_TOO_SHORT;
165 }
166 ClearStatus();
167 _modelId = modelId;
168 ExtractOpcode(rawBytes);
169 _decodingTable = GetCurrentModelData().opcodeTables[_opcode].nativeDecoding;
170 if (NULL == _decodingTable)
171 {
172 return GED_RETURN_VALUE_OPCODE_NOT_SUPPORTED;
173 }
174 ExtractCmptCtrl(rawBytes);
175 if (!IsCompactValid())
176 {
177 if (size < GED_NATIVE_INS_SIZE)
178 {
179 // Buffer isn't large enough for the given Native instruction.
180 return GED_RETURN_VALUE_BUFFER_TOO_SHORT;
181 }
182 }
183
184 GED_RETURN_VALUE ret = GED_RETURN_VALUE_SUCCESS;
185 if (IsCompactValid())
186 {
187 SetInstructionBytes(_compactBytes, rawBytes, size, GED_COMPACT_INS_SIZE);
188 ret = BuildNativeInsFromCompact(); // should always succeed, however this is not true, see Mantis 3755
189 if (GED_RETURN_VALUE_SUCCESS != ret) return ret;
190
191 // The API function IsCompact() checks the GED_INS_STATUS_COMPACT_ENCODED bit, so we must enforce the encoding restrictions
192 // and set the instruction's compact form as encoded.
193 ApplyCompactEncodingMasks(_compactBytes); // enforce the per-instruction encoding restrictions for the compact format
194
195 #if defined (GED_VALIDATE)
196 // TODO: Save the current instruction bytes, then call BuildNativeInsFromCompact again and compare the two
197 // to prevent field/padding conflicts in the XMLs.
198 #endif // GED_VALIDATE
199 }
200 else
201 {
202 SetInstructionBytes(_nativeBytes, rawBytes, size, GED_NATIVE_INS_SIZE);
203 SetNativeValid();
204
205 // The API function IsModified() checks the GED_INS_STATUS_NATIVE_ENCODED bit, so we must enforce the encoding restrictions
206 // and set the instruction's native format as encoded.
207 ApplyNativeEncodingMasks(); // enforce the per-instruction encoding restrictions for the native format
208 }
209 GEDASSERT(IsNativeValid());
210 return ret;
211 }
212
213
214 GED_RETURN_VALUE GEDIns::Encode(const GED_INS_TYPE insType, unsigned char* rawBytes)
215 {
216 GED_RETURN_VALUE ret = GED_RETURN_VALUE_SUCCESS;
217 if (GED_INS_TYPE_COMPACT == insType) // retrieve the compact instruction bytes
218 {
219 if (!IsCompactEncoded())
220 {
221 if (!IsCompactValid())
222 {
223 GEDASSERT(IsNativeValid());
224 // Try to build a compact format for this instruction.
225 if (!BuildCompactInsFromNative())
226 {
227 GEDASSERT(!IsCompactValid());
228 ret = GED_RETURN_VALUE_NO_COMPACT_FORM;
229 return ret; // the instruction does not have a compact format in its current state
230 }
231 GEDASSERT(IsCompactValid());
232 }
233 ApplyCompactEncodingMasks(_compactBytes); // enforce the per-instruction encoding restrictions for the compact format
234 }
235 GEDASSERT(IsCompactValid());
236 if (NULL != rawBytes)
237 {
238 memcpy_s(rawBytes, GED_COMPACT_INS_SIZE, _compactBytes, GED_COMPACT_INS_SIZE); // copy the compact instruction bytes
239 }
240 }
241 else // retrieve the native instruction bytes
242 {
243 GEDASSERT(GED_INS_TYPE_NATIVE == insType);
244 if (!IsNativeEncoded())
245 {
246 if (!IsNativeValid())
247 {
248 GEDASSERT(IsCompactValid());
249 BuildNativeInsFromCompact(); // should always succeed, however this is not true, see Mantis 3755
250 GEDASSERT(IsNativeValid());
251 }
252 ApplyNativeEncodingMasks(); // enforce the per-instruction encoding restrictions for the native format
253 }
254 GEDASSERT(IsNativeValid());
255 if (NULL != rawBytes)
256 {
257 memcpy_s(rawBytes, GED_NATIVE_INS_SIZE, _nativeBytes, GED_NATIVE_INS_SIZE); // copy the native instruction bytes
258 }
259 }
260 return ret;
261 }
262
263
264 #if GED_VALIDATION_API
265
266 GED_RETURN_VALUE GEDIns::CountCompacted(unsigned int& count)
267 {
268 if (!IsNativeEncoded())
269 {
270 if (!IsNativeValid())
271 {
272 // Can only use the native format as a reference, so first uncompact the instruction
273 GEDASSERT(IsCompactValid());
274 BuildNativeInsFromCompact(); // Should always succeed, however this is not true, see Mantis 3755
275 GEDASSERT(IsNativeValid());
276 }
277 ApplyNativeEncodingMasks(); // enforce the per-instruction encoding restrictions for the native format
278 }
279 GEDASSERT(IsNativeValid());
280 if (!CountCompactFormats(count))
281 {
282 GEDASSERT(!IsCompactValid());
283 return GED_RETURN_VALUE_NO_COMPACT_FORM; // the instruction does not have a compact form in its current state
284 }
285 return GED_RETURN_VALUE_SUCCESS;
286 }
287
288
289 GED_RETURN_VALUE GEDIns::RetrieveAllCompactedFormats(const unsigned int size, unsigned char* compactBytesArray)
290 {
291 GEDFORASSERT(unsigned int count = 0);
292 GEDASSERT(GED_RETURN_VALUE_SUCCESS == CountCompacted(count));
293 GEDASSERT((size / GED_COMPACT_INS_SIZE) <= count);
294 if (NULL == compactBytesArray)
295 {
296 return GED_RETURN_VALUE_NULL_POINTER;
297 }
298 if (!IsNativeEncoded())
299 {
300 if (!IsNativeValid())
301 {
302 // Can only use the native format as a reference, so first uncompact the instruction
303 GEDASSERT(IsCompactValid());
304 BuildNativeInsFromCompact(); // should always succeed, however this is not true, see Mantis 3755
305 GEDASSERT(IsNativeValid());
306 }
307 ApplyNativeEncodingMasks(); // enforce the per-instruction encoding restrictions for the native format
308 }
309 GEDASSERT(IsNativeValid());
310 if (!BuildAllCompactedFormats(compactBytesArray, size))
311 {
312 GEDASSERT(!IsCompactValid());
313 return GED_RETURN_VALUE_NO_COMPACT_FORM; // the instruction does not have a compact form in its current state
314 }
315 unsigned char* compactBytesPtr = compactBytesArray;
316 for (unsigned int i = 0; i < size / GED_COMPACT_INS_SIZE; ++i)
317 {
318 ApplyCompactEncodingMasks(compactBytesPtr);
319 compactBytesPtr += GED_COMPACT_INS_SIZE;
320 }
321 return GED_RETURN_VALUE_SUCCESS;
322 }
323
324
325 GED_RETURN_VALUE GEDIns::PrintFieldBitLocation(const /* GED_INS_FIELD */ uint32_t field) const
326 {
327 GEDASSERT(field < GetCurrentModelData().numberOfInstructionFields);
328 GED_RETURN_VALUE status = GED_RETURN_VALUE_INVALID_FIELD;
329 ged_ins_decoding_table_t table = _decodingTable;
330 const unsigned char* bytes = _nativeBytes;
331 if (IsCompactValid())
332 {
333 table = GetCurrentModelData().opcodeTables[_opcode].compactDecoding;
334 bytes = _compactBytes;
335 }
336 const string& fieldName = fieldNameByField[field];
337 const ged_ins_field_entry_t* dataEntry = GetInstructionDataEntry(table, field);
338 if (NULL == dataEntry)
339 {
340 cout << "Field " << fieldName << " is invalid for the current instruction." << endl;
341 return status;
342 }
343
344 vector<ged_ins_field_mapping_fragment_t> mappingFragments;
345 bool hasFixedValue = false;
346
347 // Record padding, if exists.
348 hasFixedValue |= RecordPadding(mappingFragments, dataEntry);
349
350 // Record the explicit position fragments, if exists.
351 hasFixedValue |= RecordPosition(mappingFragments, dataEntry);
352
353 // Sort the vector by the from.lowBit
354 sort(mappingFragments.begin(), mappingFragments.end());
355
356 // Merge fragments which are consecutive by both from and to values.
357 MergeFragments(mappingFragments);
358
359 // Print the bit mapping of the field.
360 const uint32_t maxBitPosition = (uint32_t)mappingFragments.back()._from._highBit;
361 const uint32_t maxBitPositionLength = static_cast<uint32_t>(DecStr(maxBitPosition).length());
362 const uint32_t bitSpacing = maxBitPositionLength * 2 + 1; // printing 2 bit positions, plus a colon
363 const uint64_t rawValue = GetField<uint64_t>(bytes, table, field, GED_VALUE_TYPE_ENCODED, status);
364 static const string implicitString = "Implicit";
365 GEDASSERT(GED_RETURN_VALUE_SUCCESS == status);
366 cout << "Field " << fieldName << ", width: " << (uint32_t)dataEntry->_bitSize <<
367 ((uint32_t)dataEntry->_bitSize == 1 ? " bit, " : " bits, ") << "raw value: " <<
368 HexStr(rawValue) << " (" << BinStr(rawValue, dataEntry->_bitSize) << "b)" << endl;
369 for (const auto& it : mappingFragments)
370 {
371 const size_t fragmentBitLength = it._from._highBit - it._from._lowBit + 1;
372 stringstream strm;
373 strm << (uint32_t)it._from._lowBit << ":" << (uint32_t)it._from._highBit;
374 cout << left << setfill(' ') << setw(bitSpacing) << strm.str() << " = ";
375 if (it._fixed)
376 cout << implicitString << " (" << BinStr(it._value, fragmentBitLength) << "b)" << endl;
377 else
378 {
379 strm.str(string()); // clear stream
380 strm.clear();
381 uint64_t mask = 0;
382 for (uint8_t i = it._from._lowBit; i <= it._from._highBit; ++i)
383 {
384 mask |= (1ULL << i);
385 }
386 const uint64_t fragmentVal = ((rawValue & mask) >> it._from._lowBit);
387 strm << (uint32_t)it._to._lowBit << ":" << (uint32_t)it._to._highBit;
388 cout << left << setfill(' ') << setw(hasFixedValue ? implicitString.length() : bitSpacing) << strm.str() << " (" <<
389 BinStr(fragmentVal, fragmentBitLength) << "b)" << endl;
390 }
391 }
392 return GED_RETURN_VALUE_SUCCESS;
393 }
394 #endif //GED_VALIDATION_API
395
396 GED_RETURN_VALUE GEDIns::QueryFieldBitLocation(const /* GED_INS_FIELD */ uint32_t field, uint32_t *fragments, uint32_t *length) const
397 {
398 GEDASSERT(field < GetCurrentModelData().numberOfInstructionFields);
399 GEDASSERT((fragments != NULL) || (length != NULL));
400 GED_RETURN_VALUE status = GED_RETURN_VALUE_INVALID_FIELD;
401 ged_ins_decoding_table_t table = _decodingTable;
402
403 if (length != NULL)
404 {
405 *length = 0;
406 }
407 const ged_ins_field_entry_t* dataEntry = GetInstructionDataEntry(table, field);
408 if (NULL == dataEntry)
409 {
410 return status;
411 }
412
413 vector<ged_ins_field_mapping_fragment_t> mappingFragments;
414 RecordPosition(mappingFragments, dataEntry);
415 sort(mappingFragments.begin(), mappingFragments.end());
416 MergeFragments(mappingFragments);
417
418 uint32_t index = 0;
419 for (const auto& it : mappingFragments)
420 {
421 if (it._fixed)
422 ;
423 else
424 {
425 if (fragments != NULL)
426 {
427 uint32_t len = it._from._highBit - it._from._lowBit + 1;
428 fragments[index++] = (len << 16) | it._to._lowBit;
429 }
430 if (length != NULL)
431 {
432 (*length)++;
433 }
434 }
435 }
436 return GED_RETURN_VALUE_SUCCESS;
437 }
438
439 uint32_t GEDIns::GetFieldSize(const /* GED_INS_FIELD */ uint32_t field) const
440 {
441 if (GetCurrentModelData().numberOfInstructionFields <= field) return 0;
442
443 // First try the native format.
444 const ged_ins_field_entry_t* dataEntry = GetInstructionDataEntry(_decodingTable, field);
445 if (NULL != dataEntry) return (uint32_t)dataEntry->_bitSize;
446
447 // The field was not found in the native format, try the compact format (if it exists).
448 const ged_ins_decoding_table_t compactTable = GetCurrentModelData().opcodeTables[_opcode].compactDecoding;
449 if (NULL != compactTable)
450 {
451 const ged_ins_field_entry_t* compactDataEntry = GetInstructionDataEntry(compactTable, field);
452 if (NULL != compactDataEntry) return (uint32_t)compactDataEntry->_bitSize;
453 }
454
455 // The field is not valid in either format.
456 return 0;
457 }
458
459
460 GED_RETURN_VALUE GEDIns::SetOpcode(/* GED_OPCODE */ uint32_t opcode)
461 {
462 GED_RETURN_VALUE ret = GED_RETURN_VALUE_SUCCESS;
463 const uint32_t highestOpcodeValue = GED_MAX_ENTRIES_IN_OPCODE_TABLE - 1;
464 if (!GEDRestrictionsHandler::ConvertEnumeratedValueToRawEncodedValue(opcode, highestOpcodeValue, GetCurrentModelData().Opcodes))
465 {
466 ret = GED_RETURN_VALUE_OPCODE_NOT_SUPPORTED;
467 return ret;
468 }
469
470 if (opcode == _opcode)
471 {
472 return ret;
473 }
474 _opcode = opcode;
475
476 const ged_ins_decoding_table_t decodingTable = GetCurrentModelData().opcodeTables[opcode].nativeDecoding;
477 GEDASSERT(NULL != decodingTable);
478 if (decodingTable != _decodingTable)
479 {
480 ClearStatus();
481 memset(_nativeBytes, 0, GED_NATIVE_INS_SIZE);
482
483 // Set the new decoding table.
484 _decodingTable = decodingTable;
485 SetNativeValid(); // mark that the native instruction bytes are valid
486 SetNativeOpcode(); // set the opcode in the native instruction bytes
487
488 // Check if the new opcode has a compact format.
489 if (GetCurrentModelData().opcodeTables[_opcode].compactDecoding)
490 {
491 // TODO: Once the compact bit is set in the encoding masks, remove the next line and uncomment the one after that (Mantis 3732).
492 *(reinterpret_cast<uint64_t*>(_compactBytes)) = compactInsInitializer;
493 //memset(_compactBytes, 0, GED_COMPACT_INS_SIZE);
494 SetCompactValid(); // mark that the compact instruction bytes are valid
495 SetCompactOpcode(); // set the opcode in the compact instruction bytes
496 }
497 }
498 GEDASSERT(IsValid()); // at least one format must be valid
499 return ret;
500 }
501
502 # if GED_EXPERIMENTAL
503 GED_RETURN_VALUE GEDIns::SetRawBits(const uint8_t lowBit, const uint8_t highBit, const uint64_t val)
504 {
505 GEDASSERT(lowBit < GED_NATIVE_INS_SIZE_BITS);
506 GEDASSERT(highBit < GED_NATIVE_INS_SIZE_BITS);
507 GEDASSERT(lowBit <= highBit);
508 GEDASSERT(IsNativeValid());
509 const uint8_t lowDword = lowBit / GED_DWORD_BITS;
510 const uint8_t highDword = highBit / GED_DWORD_BITS;
511 //const unsigned int numberOfDwords = highDword - lowDword;
512 ged_ins_field_position_fragment_t pos;
513 if (lowDword == highDword)
514 {
515 pos._lowBit = lowBit;
516 pos._highBit = highBit;
517 pos._dwordIndex = lowBit / GED_DWORD_BITS;
518 pos._shift = lowBit % GED_DWORD_BITS;
519 pos._bitMask = rightShiftedMasks[(highBit - lowBit)] << pos._shift;
520 SetFragment(_nativeBytes, pos, val);
521 }
522 else
523 {
524 NYI;
525 }
526 SetEncodingMasksDisabled();
527 return GED_RETURN_VALUE_SUCCESS;
528 }
529 # endif // GED_EXPERIMENTAL
530
531 /*************************************************************************************************
532 * class GEDIns protected member functions
533 *************************************************************************************************/
534
535 uint8_t GEDIns::GetFieldWidth(const uint16_t field, const bool interpField /* = false */) const
536 {
537 const ged_ins_field_entry_t* entry =
538 GetInstructionDataEntry((interpField) ? GetCurrentModelData().pseudoFields : _decodingTable, field);
539 if (NULL == entry) return 0;
540 if (IsVariableField(entry))
541 {
542 return entry->_restrictions[0]->_fieldType._attr._bits;
543 }
544 else
545 {
546 return entry->_bitSize;
547 }
548 }
549
550
551 string GEDIns::GetInstructionBytes() const
552 {
553 return (IsCompact()) ? GetInstructionBytes(_compactBytes, GED_NUM_OF_COMPACT_INS_DWORDS)
554 : GetInstructionBytes(_nativeBytes, GED_NUM_OF_NATIVE_INS_DWORDS);
555 }
556
557
558 /*************************************************************************************************
559 * class GEDIns private member functions
560 *************************************************************************************************/
561
562 void GEDIns::SetInstructionBytes(unsigned char* dst, const unsigned char* src, unsigned int size, const unsigned int maxSize) const
563 {
564 if (size > maxSize)
565 {
566 size = maxSize; // given buffer is too large, ignore the rest of the bytes.
567 }
568 memcpy_s(dst, size, src, size);
569 }
570
571
572 uint32_t GEDIns::GetMappedField(const /* GED_INS_FIELD */ uint32_t field, const unsigned char* validBits, bool& extracted) const
573 {
574 GEDASSERT(NULL != validBits);
575 GEDASSERT(field < GetCurrentModelData().numberOfInstructionFields);
576 GEDASSERT(field == _decodingTable[field]._field);
577
578 // Traverse the intermediate tables (if necessary).
579 extracted = false;
580 const ged_ins_field_entry_t* dataEntry = GetMappedInstructionDataEntry(_decodingTable, field, validBits, extracted);
581 if (!extracted) return MAX_UINT32_T;
582 GEDASSERT(NULL != dataEntry);
583
584 // Now that we are at the bottommost table, extract the actual data if they were already mapped. The "extracted" out parameter is
585 // already set to TRUE.
586 switch (dataEntry->_entryType)
587 {
588 case GED_TABLE_ENTRY_TYPE_CONSECUTIVE:
589 if (0 != ExtractConsecutiveEntryValue(validBits, dataEntry->_consecutive._position)) break;
590 return ExtractConsecutiveEntryValue(_nativeBytes, dataEntry->_consecutive._position);
591 case GED_TABLE_ENTRY_TYPE_FRAGMENTED:
592 if (0 != ExtractFragmentedEntryValue<uint32_t>(validBits, dataEntry)) break;
593 return ExtractFragmentedEntryValue<uint32_t>(_nativeBytes, dataEntry);
594 case GED_TABLE_ENTRY_TYPE_FIXED_VALUE:
595 return dataEntry->_fixed._value;
596 default:
597 GEDASSERT(0);
598 }
599
600 // Mark that some (or all) necessary bits for this field were not yet mapped.
601 extracted = false;
602 return MAX_UINT32_T;
603 }
604
605
606 const ged_ins_field_entry_t* GEDIns::GetDependentInstructionDataEntry(ged_ins_decoding_table_t table,
607 /* GED_INS_FIELD */ uint32_t tableIndex) const
608 {
609 GEDASSERT(NULL != table);
610 while (GED_TABLE_ENTRY_TYPE_NEXT_TABLE == table[tableIndex]._entryType)
611 {
612 const ged_ins_field_next_table_t* nextTable = &table[tableIndex]._nextTable;
613 GED_RETURN_VALUE ret = GED_RETURN_VALUE_INVALID_FIELD;
614 tableIndex = GetField<uint32_t>(_nativeBytes, _decodingTable, nextTable->_tableKey, GED_VALUE_TYPE_ENCODED, ret);
615
616 // GetField is expected to succeed since the models ensure that the dependent fields are always valid. However, we need to
617 // account for invalid instructions, i.e. instructions with an illegal encoding. Such instructions may have invalid values for
618 // valid fields. If a dependee field is in itself a dependent field, it may even be an invalid field in the given (poorly
619 // encoded) instruction.
620 if (GED_RETURN_VALUE_INVALID_FIELD == ret || GED_RETURN_VALUE_INVALID_VALUE == ret) return NULL;
621 GEDASSERT(GED_RETURN_VALUE_SUCCESS == ret);
622 table = nextTable->_tablePtr;
623 GEDASSERT(NULL != table);
624 }
625
626 // Verify that this is a legal entry.
627 GEDASSERT(table[tableIndex]._entryType < GED_TABLE_ENTRY_TYPE_SIZE);
628
629 // Verify that the field is supported in this format.
630 if (GED_TABLE_ENTRY_TYPE_NOT_SUPPORTED == table[tableIndex]._entryType)
631 {
632 return NULL;
633 }
634
635 // Verify that the final entry actually holds data.
636 GEDASSERT(GED_TABLE_ENTRY_TYPE_NEXT_TABLE != table[tableIndex]._entryType);
637
638 return &table[tableIndex];
639 }
640
641
642 const ged_ins_field_entry_t* GEDIns::GetDependentMappedInstructionDataEntry(ged_ins_decoding_table_t table,
643 /* GED_INS_FIELD */ uint32_t tableIndex,
644 const unsigned char* validBits, bool& extracted) const
645 {
646 GEDASSERT(NULL != table);
647 GEDASSERT(NULL != validBits);
648 while (GED_TABLE_ENTRY_TYPE_NEXT_TABLE == table[tableIndex]._entryType)
649 {
650 // Extract the value from the _nativeBytes array if it is valid (i.e. if it has already been mapped)
651 const ged_ins_field_next_table_t* nextTable = &table[tableIndex]._nextTable;
652 tableIndex = GetMappedField(nextTable->_tableKey, validBits, extracted);
653 if (!extracted) return NULL; // the field is not valid in the _nativeBytes array (i.e. it was not yet mapped)
654 GEDASSERT(MAX_UINT32_T != tableIndex);
655 table = nextTable->_tablePtr;
656 GEDASSERT(NULL != table);
657 }
658
659 // Verify that this is a legal entry.
660 GEDASSERT(table[tableIndex]._entryType < GED_TABLE_ENTRY_TYPE_SIZE);
661
662 // Verify that the field is supported in this format.
663 GEDASSERT(GED_TABLE_ENTRY_TYPE_NOT_SUPPORTED != table[tableIndex]._entryType);
664
665 // Verify that the final entry actually holds data.
666 GEDASSERT(GED_TABLE_ENTRY_TYPE_NEXT_TABLE != table[tableIndex]._entryType);
667
668 extracted = true;
669 return &table[tableIndex];
670 }
671
672
673 GED_RETURN_VALUE GEDIns::BuildNativeInsFromCompact()
674 {
675 GEDASSERT(IsCompactValid()); // nothing to do if the instruction is not compacted
676 memset(_nativeBytes, 0, GED_NATIVE_INS_SIZE);
677
678 const ged_ins_decoding_table_t compactTable = GetCurrentModelData().opcodeTables[_opcode].compactDecoding; // map from this
679 if (NULL == compactTable) return GED_RETURN_VALUE_NO_COMPACT_FORM;
680
681 const ged_compact_mapping_table_t mappingTable = GetCurrentModelData().opcodeTables[_opcode].compactMapping;
682 GEDASSERT(NULL != mappingTable);
683
684 // Mapping algorithm:
685 //
686 // Iterate compactTable. For each valid entry i.e. GED_TABLE_ENTRY_TYPE_CONSECUTIVE, GED_TABLE_ENTRY_TYPE_FRAGMENTED
687 // or GED_TABLE_ENTRY_TYPE_NEXT_TABLE:
688 // a) Get compact field value (from _compactBytes using compactTable). If the field depends on another field which was not
689 // yet mapped, add it to the unmapped list and continue to the next field.
690 // b) Find mapping type:
691 // One of the four combinations between value/index and consecutive/fragmented. The mapping type may have dependencies,
692 // in which case there will be a next table entry and finding the mapping type will require iterating the mapping chain.
693 // The mapping type may be GED_MAPPING_TABLE_ENTRY_TYPE_NOT_SUPPORTED if the field is not supported in this format, in
694 // which case the corresponding entry in the decoding table will be of type GED_TABLE_ENTRY_TYPE_NOT_SUPPORTED as well.
695 // c) If this is a value mapping (either consecutive or fragmented):
696 // Map bits from _compactBytes to _nativeBytes according to the mapping table entry.
697 // d) If this is an index mapping, i.e. mapping from a compaction table:
698 // i) Get the value from the compaction table (ged_compaction_table_t), in which case the field's value serves
699 // as the index of the entry in the compaction table.
700 // ii) Map the bits from the compaction table entry value to _nativeBytes.
701 // e) Repeat steps (a)-(d) for every field in the unmapped list until it is empty.
702
703 // The validBits array will be used to note which bits of the instruction's native format were already mapped (and can be used as
704 // dependencies). We start with all bits set and clear the relevant bits as they are being mapped. Thus, in order to check if a
705 // certain field was mapped or not, the relevant bits are simply compared to zero.
706 unsigned char validBits[GED_NATIVE_INS_SIZE];
707 memset(validBits, 0xff, GED_NATIVE_INS_SIZE);
708 set<uint32_t> unMapped;
709
710 for (uint32_t i = 0; i < GetCurrentModelData().numberOfInstructionFields; ++i)
711 {
712 GEDASSERT(compactTable[i]._entryType < GED_TABLE_ENTRY_TYPE_SIZE); // verify that this is a valid entry
713 if (GED_TABLE_ENTRY_TYPE_NOT_SUPPORTED == compactTable[i]._entryType) continue; // this field is not supported in this format
714 if (!MapCurrentField(compactTable, mappingTable, i, validBits))
715 {
716 // The field depends on another field which was not yet mapped. Add it to the unmapped list for later processing.
717 GEDASSERT(0 == unMapped.count(i));
718 unMapped.insert(i);
719 continue;
720 }
721 }
722
723 // In every iteration of the outer loop, try to map the first unmapped (dependent) field in the unMapped set. If it depends on
724 // another dependent field which was not yet mapped, skip it and try the rest one by one (the inner loop) until one field is
725 // mapped successfully. If no field was mapped successfully, it means that the remaining fields have a cyclic dependency on each
726 // other, in which case an error is emitted.
727 const set<uint32_t>::const_iterator end = unMapped.end();
728 while (!unMapped.empty())
729 {
730 set<uint32_t>::const_iterator it = unMapped.begin();
731 for (; end != it; ++it)
732 {
733 if (MapCurrentField(compactTable, mappingTable, *it, validBits)) break;
734 }
735
736 // Make sure a dependent field was mapped successfully.
737 if (end == it)
738 {
739 // TODO: Call this function after adding logging to GED.
740 // EmitMappingCyclicDependencyError(unMapped, validBits);
741 return GED_RETURN_VALUE_BAD_COMPACT_ENCODING;
742 }
743 unMapped.erase(it);
744 }
745
746 // This instruction is marked as compact in the _status field, but the instruction bits in the _nativeBytes array should reflect
747 // a native instruction now that it is expanded.
748 SetNonCompact();
749 SetNativeValid();
750 return GED_RETURN_VALUE_SUCCESS;
751 }
752
753
754 bool GEDIns::MapCurrentField(const ged_ins_decoding_table_t compactTable, const ged_compact_mapping_table_t mappingTable,
755 const /* GED_INS_FIELD */ uint32_t field, unsigned char* validBits)
756 {
757 GEDASSERT(NULL != compactTable);
758 GEDASSERT(NULL != mappingTable);
759 GEDASSERT(NULL != validBits);
760
761 // Get the mapping table entry for this field.
762 const ged_compact_mapping_entry_t* mappingEntry = GetCompactionMappingEntry(mappingTable, field, validBits);
763 if (NULL == mappingEntry) return false; // when building compact from native but the mapping is invalid
764 if (GED_MAPPING_TABLE_ENTRY_TYPE_NO_MAPPING == mappingEntry->_entryType) return true; // early out
765 GEDASSERT(mappingEntry->_field == field);
766
767 // Get the compact field value.
768 GED_RETURN_VALUE ret = GED_RETURN_VALUE_INVALID_FIELD;
769 uint32_t mappingValue = GetField<uint32_t>(_compactBytes, compactTable, field, GED_VALUE_TYPE_ENCODED, ret);
770 GEDASSERT(GED_RETURN_VALUE_SUCCESS == ret);
771
772 // Map the compact field to the native field(s).
773 switch (mappingEntry->_entryType)
774 {
775 case GED_MAPPING_TABLE_ENTRY_TYPE_INDEX_MAPPING_CONSECUTIVE:
776 GEDASSERT(NULL != mappingEntry->_compactionTable);
777 GEDASSERT(MAX_UINT32_T >= mappingEntry->_compactionTable[mappingValue]);
778 MapRawBytes((uint32_t)mappingEntry->_compactionTable[mappingValue], &mappingEntry->_consecutive._to,
779 mappingEntry->_consecutive._fromMask, validBits);
780 break;
781 case GED_MAPPING_TABLE_ENTRY_TYPE_VALUE_MAPPING_CONSECUTIVE:
782 MapRawBytes(mappingValue, &mappingEntry->_consecutive._to, mappingEntry->_consecutive._fromMask, validBits);
783 break;
784 case GED_MAPPING_TABLE_ENTRY_TYPE_INDEX_MAPPING_FRAGMENTED:
785 GEDASSERT(NULL != mappingEntry->_compactionTable);
786 MapRawBytes(mappingEntry->_compactionTable[mappingValue], mappingEntry->_fragmented._numOfMappingFragments,
787 mappingEntry->_fragmented._fragments, validBits);
788 break;
789 case GED_MAPPING_TABLE_ENTRY_TYPE_VALUE_MAPPING_FRAGMENTED:
790 MapRawBytes(mappingValue, mappingEntry->_fragmented._numOfMappingFragments, mappingEntry->_fragmented._fragments, validBits);
791 break;
792 default:
793 GEDASSERT(0);
794 }
795 return true;
796 }
797
798
799 const ged_compact_mapping_entry_t* GEDIns::GetDependentCompactionMappingEntry(ged_compact_mapping_table_t table,
800 /* GED_INS_FIELD */ uint32_t tableIndex,
801 const unsigned char* validBits) const
802 {
803 GEDASSERT(NULL != table);
804 GEDASSERT(NULL != validBits);
805 while (GED_MAPPING_TABLE_ENTRY_TYPE_NEXT_TABLE == table[tableIndex]._entryType)
806 {
807 const ged_compact_mapping_next_table_t* nextTable = &table[tableIndex]._nextTable;
808 // Extract the value from the _nativeBytes array if it is valid (i.e. if it has already been mapped)
809 bool extracted = false;
810 tableIndex = GetMappedField(nextTable->_tableKey, validBits, extracted);
811 if (!extracted) return NULL; // the field is not valid in the _nativeBytes array (i.e. it was not yet mapped)
812 table = nextTable->_tablePtr;
813 GEDASSERT(NULL != table);
814 }
815
816 // Verify that this is a legal entry.
817 GEDASSERT(table[tableIndex]._entryType < GED_MAPPING_TABLE_ENTRY_TYPE_SIZE);
818
819 // Verify that the field is supported in this format.
820 if (GED_MAPPING_TABLE_ENTRY_TYPE_NOT_SUPPORTED == table[tableIndex]._entryType) return NULL;
821
822 // Verify that the final entry actually holds data.
823 GEDASSERT(GED_MAPPING_TABLE_ENTRY_TYPE_NEXT_TABLE != table[tableIndex]._entryType);
824
825 return &table[tableIndex];
826 }
827
828
829 void GEDIns::MapRawBytes(const uint32_t src, const ged_ins_field_position_fragment_t* to, const uint32_t fromMask,
830 unsigned char* validBits)
831 {
832 GEDASSERT(NULL != to);
833 GEDASSERT(NULL != validBits);
834 uint32_t value = (src & fromMask);
835 GEDASSERT(0 <= to->_shift);
836 value <<= to->_shift;
837 SetMappedBits(to->_dwordIndex, to->_bitMask, value, validBits);
838 }
839
840
841 void GEDIns::MapRawBytes(const uint32_t src, const uint32_t numOfFragments, const ged_compact_mapping_fragment_t* fragments,
842 unsigned char* validBits)
843 {
844 GEDASSERT(NULL != fragments);
845 GEDASSERT(NULL != validBits);
846 for (uint32_t i = 0; i < numOfFragments; ++i)
847 {
848 if (GED_COMPACT_MAPPING_TYPE_REP == fragments[i]._mappingType)
849 {
850 GEDASSERT(0 == fragments[i]._from._dwordIndex); // src only has 32 bits
851 MapReppedValue(src, &fragments[i]._to, &fragments[i]._from, validBits);
852 }
853 else if (GED_COMPACT_MAPPING_TYPE_1x1 == fragments[i]._mappingType)
854 {
855 GEDASSERT(0 == fragments[i]._from._dwordIndex); // src only has 32 bits
856 MapOneToOneValue(src, &fragments[i]._to, &fragments[i]._from, validBits);
857 }
858 else if (GED_COMPACT_MAPPING_TYPE_FIXED == fragments[i]._mappingType)
859 {
860 GEDASSERT(0 == fragments[i]._from._dwordIndex); // src only has 32 bits
861 MapFixedValue(fragments[i]._from._lowBit, &fragments[i]._to, validBits);
862 }
863 else { GEDASSERT(0); }
864 }
865 }
866
867
868 void GEDIns::MapRawBytes(const uint64_t src, const uint32_t numOfFragments, const ged_compact_mapping_fragment_t* fragments,
869 unsigned char* validBits)
870 {
871 GEDASSERT(NULL != fragments);
872 GEDASSERT(NULL != validBits);
873 for (uint32_t i = 0; i < numOfFragments; ++i)
874 {
875 if (GED_COMPACT_MAPPING_TYPE_REP == fragments[i]._mappingType)
876 {
877 GEDASSERT(fragments[i]._from._dwordIndex < 2); // src only has 64 bits
878 MapReppedValue((0 == fragments[i]._from._dwordIndex) ? (uint32_t)src : (uint32_t)(src >> GED_DWORD_BITS),
879 &fragments[i]._to, &fragments[i]._from, validBits);
880 }
881 else if (GED_COMPACT_MAPPING_TYPE_1x1 == fragments[i]._mappingType)
882 {
883 GEDASSERT(fragments[i]._from._dwordIndex < 2); // src only has 64 bits
884 MapOneToOneValue((0 == fragments[i]._from._dwordIndex) ? (uint32_t)src : (uint32_t)(src >> GED_DWORD_BITS),
885 &fragments[i]._to, &fragments[i]._from, validBits);
886 }
887 else if (GED_COMPACT_MAPPING_TYPE_FIXED == fragments[i]._mappingType)
888 {
889 NYI; // no fixed mapping for fragmented index mapping
890 }
891 else { GEDASSERT(0); }
892 }
893 }
894
895
896 void GEDIns::MapReppedValue(const uint32_t src, const ged_ins_field_position_fragment_t* to,
897 const ged_ins_field_position_fragment_t* from, unsigned char* validBits)
898 {
899 GEDASSERT(NULL != to);
900 GEDASSERT(NULL != from);
901 const uint8_t fromSize = FragmentSize(from);
902 const uint8_t toSize = FragmentSize(to);
903 GEDASSERT(fromSize > 0); // verify that the source size is non-zero (about to be used as a denominator)
904 GEDASSERT(toSize >= fromSize); // verify that the target is at least as wide as the source
905 GEDASSERT(0 == (toSize % fromSize)); // verify that the target is a whole multiple of the source
906 const uint8_t numOfReps = toSize / fromSize;
907 const uint32_t rep = ((src & from->_bitMask) >> from->_shift);
908 uint32_t value = rep;
909 for (uint8_t i = 1; i < numOfReps; ++i)
910 {
911 value <<= fromSize;
912 value |= rep;
913 }
914 value <<= to->_shift;
915 SetMappedBits(to->_dwordIndex, to->_bitMask, value, validBits);
916 }
917
918
919 void GEDIns::MapOneToOneValue(const uint32_t src, const ged_ins_field_position_fragment_t* to,
920 const ged_ins_field_position_fragment_t* from, unsigned char* validBits)
921 {
922 GEDASSERT(NULL != to);
923 GEDASSERT(NULL != from);
924 uint32_t value = (src & from->_bitMask);
925 const int8_t shift = from->_shift - to->_shift;
926 if (shift > 0)
927 {
928 value >>= shift;
929 }
930 else
931 {
932 value <<= abs(shift);
933 }
934 SetMappedBits(to->_dwordIndex, to->_bitMask, value, validBits);
935 }
936
937
938 void GEDIns::MapFixedValue(const uint32_t value, const ged_ins_field_position_fragment_t* to, unsigned char* validBits)
939 {
940 GEDASSERT(NULL != to);
941 SetMappedBits(to->_dwordIndex, to->_bitMask, value << to->_shift, validBits);
942 }
943
944
945 void GEDIns::EmitMappingCyclicDependencyError(const set<uint32_t>& unMapped, const unsigned char* validBits) const
946 {
947 GEDASSERT(NULL != validBits);
948 set<uint32_t>::const_iterator it = unMapped.begin();
949 const set<uint32_t>::const_iterator end = unMapped.end();
950 string depErrorStr = DecStr(*it);
951 for (++it; end != it; ++it)
952 {
953 depErrorStr += ", " + DecStr(*it);
954 }
955 #if defined(GED_VALIDATE)
956 stringstream strm;
957 strm << setfill('0') << hex;
958 for (int i = GED_NUM_OF_NATIVE_INS_DWORDS - 1; i >= 0; --i)
959 {
960 strm << setw(8) << ((uint32_t*)validBits)[i];
961 }
962 depErrorStr += "\nValidBits: 0x" + strm.str();
963 #endif // GED_VALIDATE
964 // TODO: This should use GED logs instead of emitting an error. Also, consider changing the function name.
965 GEDERROR("Unable to map remaining unmapped fields, probably due to an implicit dependency cycle: " + depErrorStr);
966 }
967
968
969 bool GEDIns::BuildCompactInsFromNative()
970 {
971 GEDASSERT(IsNativeValid());
972 GEDASSERT(!IsCompactValid());
973 GEDASSERT(!IsCompactEncoded());
974 memset(_compactBytes, 0, GED_COMPACT_INS_SIZE); // clear the compact bytes
975
976 const ged_ins_decoding_table_t compactTable = GetCurrentModelData().opcodeTables[_opcode].compactDecoding; // map to this
977 if (NULL == compactTable) return false; // the instruction doesn't have a compact format
978
979 const ged_compact_mapping_table_t mappingTable = GetCurrentModelData().opcodeTables[_opcode].compactMapping;
980 GEDASSERT(NULL != mappingTable);
981
982 // Traverse all the compact instruction fields. For every valid field, collect its value from the native instruction and set that
983 // value in the compact instruction bytes.
984 unsigned char orMask[GED_NATIVE_INS_SIZE] = { 0 }; // used in CollectCurrentField, see documentation therein for its usage
985 BuildNativeOrMask(orMask); // prepare the or-mask
986 for (uint32_t i = 0; i < GetCurrentModelData().numberOfInstructionFields; ++i)
987 {
988 GEDASSERT(compactTable[i]._entryType < GED_TABLE_ENTRY_TYPE_SIZE); // verify that this is a valid entry
989 if (GED_TABLE_ENTRY_TYPE_NOT_SUPPORTED == compactTable[i]._entryType) continue; // this field is not supported in this format
990 if (!CollectCurrentField(compactTable, mappingTable, orMask, i)) return false;
991 }
992
993 // Set the CmptCtrl bit - is was cleared by the loop above when reverse-mapping the CmptCtrl field from the native instruction.
994 SetCompact(_compactBytes);
995 SetCompactValid(); // the compact format is now valid
996 return true;
997 }
998
999
1000 #if GED_VALIDATION_API
1001 bool GEDIns::CountCompactFormats(unsigned int& count)
1002 {
1003 unsigned int tempCounter = 1;
1004 unsigned char orMask[GED_NATIVE_INS_SIZE] = { 0 }; // used in CountCurrentField, see documentation therein for its usage
1005 BuildNativeOrMask(orMask); // prepare the or-mask
1006 const ged_ins_decoding_table_t compactTable = GetCurrentModelData().opcodeTables[_opcode].compactDecoding; // map to this
1007 if (NULL == compactTable) return false; // the instruction doesn't have a compact format
1008
1009 const ged_compact_mapping_table_t mappingTable = GetCurrentModelData().opcodeTables[_opcode].compactMapping;
1010 GEDASSERT(NULL != mappingTable);
1011 for (uint32_t i = 0; i < GetCurrentModelData().numberOfInstructionFields; ++i)
1012 {
1013 GEDASSERT(compactTable[i]._entryType < GED_TABLE_ENTRY_TYPE_SIZE); // verify that this is a valid entry
1014 if (GED_TABLE_ENTRY_TYPE_NOT_SUPPORTED == compactTable[i]._entryType) continue; // this field is not supported in this format
1015 if (!CountCurrentField(compactTable, mappingTable, orMask, i, tempCounter)) return false;
1016 }
1017 count = tempCounter;
1018 return true;
1019 }
1020
1021
1022 bool GEDIns::CountCurrentField(const ged_ins_decoding_table_t compactTable, const ged_compact_mapping_table_t mappingTable,
1023 const unsigned char* const orMask, const /* GED_INS_FIELD */ uint32_t field, unsigned int& count)
1024 {
1025 GEDASSERT(NULL != compactTable);
1026 GEDASSERT(NULL != mappingTable);
1027 // Get the mapping table entry for this field.
1028 static const unsigned char validBits[GED_NATIVE_INS_SIZE] = { 0 }; // assume that all the native instruction fields are valid
1029 const ged_compact_mapping_entry_t* mappingEntry = GetCompactionMappingEntry(mappingTable, field, validBits);
1030 if (NULL == mappingEntry) return false; // when building compact from native but the mapping is invalid
1031 GEDASSERT(mappingEntry->_field == field);
1032
1033 // For each entry type, count the amount of valid values: Value mappings have 1 valid value, and index mappings require iterating
1034 // over all indexes, counting the valid ones and multiplying in the end.
1035 switch (mappingEntry->_entryType)
1036 {
1037 case GED_MAPPING_TABLE_ENTRY_TYPE_INDEX_MAPPING_CONSECUTIVE:
1038 {
1039 // This is an index field, so the actual value to be encoded is an index in the field's compaction table. Try to find a
1040 // compaction table entry that matches the collected value. If such an entry is found, "count" is multiplied by the amount
1041 // of valid entries in the compact table, otherwise the function returns FALSE without setting the field.
1042 uint64_t qwval = (uint64_t)ExtractConsecutiveEntryValue(_nativeBytes, mappingEntry->_consecutive._to);
1043 const uint64_t valMask = (uint64_t)ExtractConsecutiveEntryValue(orMask, mappingEntry->_consecutive._to);
1044 GEDASSERT(GED_TABLE_ENTRY_TYPE_NEXT_TABLE != compactTable[field]._entryType); // index fields must be explicit
1045 GEDASSERT(MAX_UINT32_T > MaxValue(compactTable[field]));
1046 const uint32_t tableSize = BitsToNumOfValues(compactTable[field]._bitSize); // size of the compaction table
1047 GEDASSERT(NULL != mappingEntry->_compactionTable);
1048 if (!CountCompactionTableEntry(qwval, valMask, tableSize, mappingEntry->_compactionTable, count)) return false;
1049 break;
1050 }
1051 case GED_MAPPING_TABLE_ENTRY_TYPE_VALUE_MAPPING_CONSECUTIVE:
1052 break;
1053 case GED_MAPPING_TABLE_ENTRY_TYPE_INDEX_MAPPING_FRAGMENTED:
1054 {
1055 // See documentation in the GED_MAPPING_TABLE_ENTRY_TYPE_INDEX_MAPPING_CONSECUTIVE case above.
1056 uint64_t qwval = 0;
1057 uint64_t tempValMask = 0;
1058 if (!CollectFragmentedEntryQWValue(qwval, _nativeBytes, mappingEntry)) return false;
1059 if (!CollectFragmentedEntryQWValue(tempValMask, orMask, mappingEntry)) return false;
1060 const uint64_t valMask = tempValMask;
1061 GEDASSERT(GED_TABLE_ENTRY_TYPE_NEXT_TABLE != compactTable[field]._entryType); // index fields must be explicit
1062 GEDASSERT(MAX_UINT32_T > MaxValue(compactTable[field]));
1063 const uint32_t tableSize = BitsToNumOfValues(compactTable[field]._bitSize); // size of the compaction table
1064 GEDASSERT(NULL != mappingEntry->_compactionTable);
1065 if (!CountCompactionTableEntry(qwval, valMask, tableSize, mappingEntry->_compactionTable, count)) return false;
1066 break;
1067 }
1068 case GED_MAPPING_TABLE_ENTRY_TYPE_VALUE_MAPPING_FRAGMENTED:
1069 break;
1070 case GED_MAPPING_TABLE_ENTRY_TYPE_NO_MAPPING:
1071 break;
1072 default:
1073 GEDASSERT(0);
1074 }
1075 return true;
1076 }
1077
1078
1079 bool GEDIns::CountCompactionTableEntry(uint64_t& val, const uint64_t& valMask, const uint32_t tableSize,
1080 ged_compaction_table_t table, unsigned int& count) const
1081 {
1082 uint32_t counter = 0;
1083 GEDASSERT(0 != tableSize);
1084 GEDASSERT(tableSize < GED_MAX_ENTRIES_IN_COMPACT_TABLE); // sanity check
1085 val |= valMask;
1086 for (uint32_t i = 0; i < tableSize; ++i)
1087 {
1088 if ((table[i] | valMask) == val)
1089 {
1090 ++counter;
1091 }
1092 }
1093 count *= counter;
1094 return (0 != counter);
1095 }
1096
1097
1098 bool GEDIns::BuildAllCompactedFormats(unsigned char* compactBytesArray, const unsigned int size)
1099 {
1100 const ged_ins_decoding_table_t compactTable = GetCurrentModelData().opcodeTables[_opcode].compactDecoding; // map to this
1101 if (NULL == compactTable) return false; // the instruction doesn't have a compact format
1102
1103 const ged_compact_mapping_table_t mappingTable = GetCurrentModelData().opcodeTables[_opcode].compactMapping;
1104 GEDASSERT(NULL != mappingTable);
1105
1106 // Traverse all the compact instruction fields. For every valid non-indexed field, collect its value from the native instruction
1107 // and set that value in the compact instruction template.
1108 unsigned char compactBytesTemplate[GED_COMPACT_INS_SIZE] = { 0 };
1109 for (uint32_t i = 0; i < GetCurrentModelData().numberOfInstructionFields; ++i)
1110 {
1111 GEDASSERT(compactTable[i]._entryType < GED_TABLE_ENTRY_TYPE_SIZE); // verify that this is a valid entry
1112 if (GED_TABLE_ENTRY_TYPE_NOT_SUPPORTED == compactTable[i]._entryType) continue; // this field is not supported in this format
1113 if (!CollectCurrentValueField(compactTable, mappingTable, i, compactBytesTemplate)) return false;
1114 }
1115 SetCompact(compactBytesTemplate);
1116
1117 // Traverse all the compact instruction fields. For every valid indexed field, collect all possible options.
1118 // Basically, create a Cartesian product of all possible indexes which create a valid compact encoding.
1119 unsigned char orMask[GED_NATIVE_INS_SIZE] = { 0 }; // used in CollectCurrentMappedFields, see documentation therein for its usage
1120 BuildNativeOrMask(orMask); // prepare the or-mask
1121 bool succeeded = true;
1122 vector<vector<unsigned char> > compactBytesIndexedVector = CollectCurrentMappedFields(compactTable, mappingTable, orMask, 0,
1123 succeeded);
1124 if (!succeeded) return false;
1125
1126 // Merge the mapped values with the indexed ones
1127 memset(compactBytesArray, 0x0, size); // clear the entire preallocated buffer
1128 unsigned char* ptr = compactBytesArray;
1129 for (uint32_t i = 0; i < size / GED_COMPACT_INS_SIZE; ++i)
1130 {
1131 for (uint32_t j = 0; j < GED_NUM_OF_COMPACT_INS_DWORDS; ++j)
1132 {
1133 vector<unsigned char>* tmpVecPtr = &compactBytesIndexedVector[i];
1134 unsigned char* tmpWordPtr = &((*tmpVecPtr)[0]);
1135 ((uint32_t*)ptr)[j] = ((uint32_t*)compactBytesTemplate)[j] | ((uint32_t*)tmpWordPtr)[j];
1136 }
1137 ptr += GED_COMPACT_INS_SIZE;
1138 }
1139 return true;
1140
1141 // Set an arbitrary valid encoding into the instruction's compact bytes.
1142 memcpy_s(_compactBytes, GED_COMPACT_INS_SIZE, compactBytesArray, GED_COMPACT_INS_SIZE);
1143 SetCompactValid();
1144 return true;
1145 }
1146
1147
1148 bool GEDIns::CollectCurrentValueField(const ged_ins_decoding_table_t compactTable, const ged_compact_mapping_table_t mappingTable,
1149 const /* GED_INS_FIELD */ uint32_t field, unsigned char* buf)
1150 {
1151 GEDASSERT(NULL != compactTable);
1152 GEDASSERT(NULL != mappingTable);
1153
1154 // Get the mapping table entry for this field.
1155 static const unsigned char validBits[GED_NATIVE_INS_SIZE] = { 0 }; // assume that all the native instruction fields are valid
1156 const ged_compact_mapping_entry_t* mappingEntry = GetCompactionMappingEntry(mappingTable, field, validBits);
1157 if (NULL == mappingEntry) return false; // when building compact from native but the mapping is invalid
1158 GEDASSERT(mappingEntry->_field == field);
1159
1160 // Collect the compact field from the native field(s).
1161 uint32_t val = MAX_UINT32_T;
1162 switch (mappingEntry->_entryType)
1163 {
1164 case GED_MAPPING_TABLE_ENTRY_TYPE_INDEX_MAPPING_CONSECUTIVE:
1165 return true;
1166 case GED_MAPPING_TABLE_ENTRY_TYPE_VALUE_MAPPING_CONSECUTIVE:
1167 val = ExtractConsecutiveEntryValue(_nativeBytes, mappingEntry->_consecutive._to);
1168 break;
1169 case GED_MAPPING_TABLE_ENTRY_TYPE_INDEX_MAPPING_FRAGMENTED:
1170 return true;
1171 case GED_MAPPING_TABLE_ENTRY_TYPE_VALUE_MAPPING_FRAGMENTED:
1172 if (!CollectFragmentedEntryDWValue(val, _nativeBytes, mappingEntry)) return false;
1173 break;
1174 case GED_MAPPING_TABLE_ENTRY_TYPE_NO_MAPPING:
1175 return true;
1176 default:
1177 GEDASSERT(0);
1178 }
1179
1180 // Set the field in the compact bytes. The given value is already the raw value, no need to convert it if it has an enumeration.
1181 GEDFORASSERT(GED_RETURN_VALUE ret = )
1182 SetField(buf, compactTable, field, GED_VALUE_TYPE_ENCODED, val);
1183 GEDASSERT(GED_RETURN_VALUE_SUCCESS == ret);
1184 return true;
1185 }
1186
1187
1188 vector<vector<unsigned char> > GEDIns::CollectCurrentMappedFields(const ged_ins_decoding_table_t compactTable,
1189 const ged_compact_mapping_table_t mappingTable,
1190 const unsigned char* const orMask,
1191 /* GED_INS_FIELD */ uint32_t field, bool& succeeded)
1192 {
1193 // Collecting all mapped fields algorithm:
1194 //
1195 // CollectCurrentMappedFields is a backtracking recursion designed to generate a Cartesian product of all mapped fields.
1196 // The slight difference from a regular AxBxCx... Cartesian product where each element is on its own in the n-tuple, here each
1197 // element in the n-tuple consists of fields and their location. A is a field, set into its position in the compacted bytes by
1198 // calling SetField()
1199 //
1200 // How the recursion works:
1201 // Stop condition: when finished traversing all fields, return a vector with a single, empty encoding.
1202 // Recursion step:
1203 // 1 Declare temporary vector of compact instruction "res"
1204 // 2 For each Compact Encoding "it" in CollectCurrentMappedFields(..., field + 1, ...):
1205 // 2.1 For each valid index "compactedTableIndex" in the compacted table:
1206 // 2.1.1 Create a buffer "buf" and copy the compact encoding of "it" to it
1207 // 2.1.2 Set the compactedTableIndex in the appropriate location in buf
1208 // 2.1.3 Push "buf" into the vector of compacted instructions "res".
1209 // 3 Return "res".
1210
1211 GEDASSERT(NULL != compactTable);
1212 GEDASSERT(NULL != mappingTable);
1213 GEDASSERT(field < GetCurrentModelData().numberOfInstructionFields);
1214
1215 static const unsigned char validBits[GED_NATIVE_INS_SIZE] = { 0 }; // assume that all the native instruction fields are valid
1216 const ged_compact_mapping_entry_t* mappingEntry;
1217
1218 // Locate the next Index-mapped field.
1219 while (true)
1220 {
1221 if (GetCurrentModelData().numberOfInstructionFields == field)
1222 {
1223 // Stop condition.
1224 vector<vector<unsigned char> > stubVector;
1225 vector<unsigned char> stubEncoding(8); // insert an empty encoding to the vector
1226 stubVector.push_back(stubEncoding);
1227 return stubVector;
1228 }
1229 if (GED_TABLE_ENTRY_TYPE_NOT_SUPPORTED == compactTable[field]._entryType)
1230 {
1231 ++field;
1232 continue;
1233 }
1234 mappingEntry = GetCompactionMappingEntry(mappingTable, field, validBits);
1235 GEDASSERT(NULL != mappingTable); // this is potentially wrong, see other GetCompactionMappingEntry "if" checks
1236 if (GED_MAPPING_TABLE_ENTRY_TYPE_INDEX_MAPPING_FRAGMENTED == mappingEntry->_entryType ||
1237 GED_MAPPING_TABLE_ENTRY_TYPE_INDEX_MAPPING_CONSECUTIVE == mappingEntry->_entryType)
1238 {
1239 break; // Handle index fields - enter the body of the function.
1240 }
1241 ++field;
1242 }
1243
1244 // Step 1
1245 vector<vector<unsigned char> > res;
1246
1247 // Step 2
1248 vector<vector<unsigned char> > v = CollectCurrentMappedFields(compactTable, mappingTable, orMask, field + 1, succeeded);
1249 if (!succeeded) return v;
1250
1251 for (vector<vector<unsigned char> >::const_iterator it = v.begin(); it != v.end(); ++it)
1252 {
1253 switch (mappingEntry->_entryType)
1254 {
1255 case GED_MAPPING_TABLE_ENTRY_TYPE_INDEX_MAPPING_CONSECUTIVE:
1256 {
1257 uint32_t val = MAX_UINT32_T;
1258 uint64_t qwval = (uint64_t)ExtractConsecutiveEntryValue(_nativeBytes, mappingEntry->_consecutive._to);
1259 const uint64_t valMask = (uint64_t)ExtractConsecutiveEntryValue(orMask, mappingEntry->_consecutive._to);
1260 GEDASSERT(GED_TABLE_ENTRY_TYPE_NEXT_TABLE != compactTable[field]._entryType); // index fields must be explicit
1261 GEDASSERT(MAX_UINT32_T > MaxValue(compactTable[field]));
1262 const uint32_t tableSize = BitsToNumOfValues(compactTable[field]._bitSize); // size of the compaction table
1263 GEDASSERT(NULL != mappingEntry->_compactionTable);
1264 GEDASSERT(0 != tableSize);
1265 GEDASSERT(tableSize < GED_MAX_ENTRIES_IN_COMPACT_TABLE); // sanity check
1266 qwval |= valMask;
1267 // Step 2.1
1268 for (unsigned int compactedTableIndex = 0; compactedTableIndex < tableSize; ++compactedTableIndex)
1269 {
1270 if ((mappingEntry->_compactionTable[compactedTableIndex] | valMask) == qwval)
1271 {
1272 val = (uint32_t)compactedTableIndex;
1273 unsigned char buf[GED_COMPACT_INS_SIZE];
1274 // Step 2.1.1
1275 std::copy(it->begin(), it->end(), buf);
1276 // Step 2.1.2
1277 GEDFORASSERT(GED_RETURN_VALUE ret = )
1278 SetField(buf, compactTable, field, GED_VALUE_TYPE_ENCODED, val);
1279 GEDASSERT(GED_RETURN_VALUE_SUCCESS == ret);
1280 // Step 2.1.3
1281 res.push_back(vector<unsigned char>(buf, buf + GED_COMPACT_INS_SIZE * sizeof(buf[0])));
1282 }
1283 }
1284 if (MAX_UINT32_T == val) succeeded = false;
1285 break;
1286 }
1287 case GED_MAPPING_TABLE_ENTRY_TYPE_INDEX_MAPPING_FRAGMENTED:
1288 {
1289 uint32_t val = MAX_UINT32_T;
1290 uint64_t qwval = 0;
1291 uint64_t tempValMask = 0;
1292 if (!CollectFragmentedEntryQWValue(qwval, _nativeBytes, mappingEntry)) succeeded = false;
1293 if (!CollectFragmentedEntryQWValue(tempValMask, orMask, mappingEntry)) succeeded = false;
1294 if (!succeeded) break;
1295 const uint64_t valMask = tempValMask;
1296 GEDASSERT(GED_TABLE_ENTRY_TYPE_NEXT_TABLE != compactTable[field]._entryType); // index fields must be explicit
1297 GEDASSERT(MAX_UINT32_T > MaxValue(compactTable[field]));
1298 const uint32_t tableSize = BitsToNumOfValues(compactTable[field]._bitSize); // size of the compaction table
1299 GEDASSERT(NULL != mappingEntry->_compactionTable);
1300 GEDASSERT(0 != tableSize);
1301 GEDASSERT(tableSize < GED_MAX_ENTRIES_IN_COMPACT_TABLE); // sanity check
1302 qwval |= valMask;
1303 // Step 2.1
1304 for (unsigned int compactedTableIndex = 0; compactedTableIndex < tableSize; ++compactedTableIndex)
1305 {
1306 if ((mappingEntry->_compactionTable[compactedTableIndex] | valMask) == qwval)
1307 {
1308 val = (uint32_t)compactedTableIndex;
1309 unsigned char buf[GED_COMPACT_INS_SIZE];
1310 // Step 2.1.1
1311 std::copy(it->begin(), it->end(), buf);
1312 // Step 2.1.2
1313 GEDFORASSERT(GED_RETURN_VALUE ret = )
1314 SetField(buf, compactTable, field, GED_VALUE_TYPE_ENCODED, val);
1315 GEDASSERT(GED_RETURN_VALUE_SUCCESS == ret);
1316 // Step 2.1.3
1317 res.push_back(vector<unsigned char>(buf, buf + GED_COMPACT_INS_SIZE * sizeof(buf[0])));
1318 }
1319 }
1320 if (MAX_UINT32_T == val) succeeded = false;
1321 break;
1322 }
1323 default:
1324 GEDASSERT(0);
1325 }
1326 }
1327 // Step 3.
1328 return res;
1329 }
1330 #endif // GED_VALIDATION_API
1331
1332
1333 bool GEDIns::CollectCurrentField(const ged_ins_decoding_table_t compactTable, const ged_compact_mapping_table_t mappingTable,
1334 const unsigned char* const orMask, const /* GED_INS_FIELD */ uint32_t field)
1335 {
1336 GEDASSERT(NULL != compactTable);
1337 GEDASSERT(NULL != mappingTable);
1338
1339 // Get the mapping table entry for this field.
1340 static const unsigned char validBits[GED_NATIVE_INS_SIZE] = { 0 }; // assume that all the native instruction fields are valid
1341 const ged_compact_mapping_entry_t* mappingEntry = GetCompactionMappingEntry(mappingTable, field, validBits);
1342 if (NULL == mappingEntry) return false; // when building compact from native but the mapping is invalid
1343 GEDASSERT(mappingEntry->_field == field);
1344
1345 // Collect the compact field from the native field(s).
1346 uint32_t val = MAX_UINT32_T;
1347 switch (mappingEntry->_entryType)
1348 {
1349 case GED_MAPPING_TABLE_ENTRY_TYPE_INDEX_MAPPING_CONSECUTIVE:
1350 {
1351 // This is an index field, so the actual value to be encoded is an index in the field's compaction table. Try to find a
1352 // compaction table entry that matches the collected value. If such an entry is found, "val" is changed to that entry's
1353 // index, otherwise the function returns FALSE without setting the field.
1354
1355 // If a certain bit in a compaction table entry is set but it is mapped to a reserved field in the native instruction, it
1356 // will be cleared in the native instruction. As a result it will also be cleared in the collected value, which means that
1357 // the collected value will not match the compaction table entry. To overcome this, an or-mask of the reserved bits is
1358 // applied to the collected value and to the compaction table entries when they are being compared. This may result in
1359 // several compaction table entries that match the collected value, in which case the first entry found will be returned.
1360
1361 uint64_t qwval = (uint64_t)ExtractConsecutiveEntryValue(_nativeBytes, mappingEntry->_consecutive._to);
1362 const uint64_t valMask = (uint64_t)ExtractConsecutiveEntryValue(orMask, mappingEntry->_consecutive._to);
1363 GEDASSERT(GED_TABLE_ENTRY_TYPE_NEXT_TABLE != compactTable[field]._entryType); // index fields must be explicit
1364 GEDASSERT(MAX_UINT32_T > MaxValue(compactTable[field]));
1365 const uint32_t tableSize = BitsToNumOfValues(compactTable[field]._bitSize); // size of the compaction table
1366 GEDASSERT(NULL != mappingEntry->_compactionTable);
1367 if (!FindCompactionTableEntry(qwval, valMask, tableSize, mappingEntry->_compactionTable)) return false;
1368 GEDASSERT(MAX_UINT32_T >= qwval);
1369 val = (uint32_t)qwval;
1370 break;
1371 }
1372 case GED_MAPPING_TABLE_ENTRY_TYPE_VALUE_MAPPING_CONSECUTIVE:
1373 val = ExtractConsecutiveEntryValue(_nativeBytes, mappingEntry->_consecutive._to);
1374 break;
1375 case GED_MAPPING_TABLE_ENTRY_TYPE_INDEX_MAPPING_FRAGMENTED:
1376 {
1377 // See documentation in the GED_MAPPING_TABLE_ENTRY_TYPE_INDEX_MAPPING_CONSECUTIVE case above.
1378 uint64_t qwval = 0;
1379 uint64_t tempValMask = 0;
1380 if (!CollectFragmentedEntryQWValue(qwval, _nativeBytes, mappingEntry)) return false;
1381 if (!CollectFragmentedEntryQWValue(tempValMask, orMask, mappingEntry)) return false;
1382 const uint64_t valMask = tempValMask;
1383 GEDASSERT(GED_TABLE_ENTRY_TYPE_NEXT_TABLE != compactTable[field]._entryType); // index fields must be explicit
1384 GEDASSERT(MAX_UINT32_T > MaxValue(compactTable[field]));
1385 const uint32_t tableSize = BitsToNumOfValues(compactTable[field]._bitSize); // size of the compaction table
1386 GEDASSERT(NULL != mappingEntry->_compactionTable);
1387 if (!FindCompactionTableEntry(qwval, valMask, tableSize, mappingEntry->_compactionTable)) return false;
1388 GEDASSERT(MAX_UINT32_T >= qwval);
1389 val = (uint32_t)qwval;
1390 break;
1391 }
1392 case GED_MAPPING_TABLE_ENTRY_TYPE_VALUE_MAPPING_FRAGMENTED:
1393 if (!CollectFragmentedEntryDWValue(val, _nativeBytes, mappingEntry)) return false;
1394 break;
1395 case GED_MAPPING_TABLE_ENTRY_TYPE_NO_MAPPING:
1396 return true;
1397 default:
1398 GEDASSERT(0);
1399 }
1400
1401 // Set the field in the compact bytes. The given value is already the raw value, no need to convert it if it has an enumeration.
1402 GEDFORASSERT(GED_RETURN_VALUE ret = )
1403 SetField(_compactBytes, compactTable, field, GED_VALUE_TYPE_ENCODED, val);
1404 GEDASSERT(GED_RETURN_VALUE_SUCCESS == ret);
1405 return true;
1406 }
1407
1408
1409 bool GEDIns::CollectFragmentedEntryDWValue(uint32_t& fullVal, const unsigned char* bytes, const ged_compact_mapping_entry_t* mappingEntry) const
1410 {
1411 GEDASSERT(NULL != bytes);
1412 GEDASSERT(NULL != mappingEntry);
1413 GEDASSERT(GED_MAPPING_TABLE_ENTRY_TYPE_INDEX_MAPPING_FRAGMENTED == mappingEntry->_entryType ||
1414 GED_MAPPING_TABLE_ENTRY_TYPE_VALUE_MAPPING_FRAGMENTED == mappingEntry->_entryType);
1415 GEDASSERT(mappingEntry->_fragmented._numOfMappingFragments > 1);
1416
1417 // The field is fragmented, so all fragments will eventually be gathered in fullVal.
1418 fullVal = 0;
1419 for (unsigned int i = 0; i < mappingEntry->_fragmented._numOfMappingFragments; ++i)
1420 {
1421 GEDASSERT(0 == mappingEntry->_fragmented._fragments[i]._from._dwordIndex); // the mapping source may only have 32 bits
1422 uint32_t fragmentVal = 0;
1423 if (!CollectFragmentValue(fragmentVal, bytes, mappingEntry->_fragmented._fragments[i])) return false;
1424 fullVal |= fragmentVal;
1425 }
1426 return true;
1427 }
1428
1429
1430 bool GEDIns::CollectFragmentedEntryQWValue(uint64_t& val, const unsigned char* bytes, const ged_compact_mapping_entry_t* mappingEntry) const
1431 {
1432 GEDASSERT(NULL != bytes);
1433 GEDASSERT(NULL != mappingEntry);
1434 GEDASSERT(GED_MAPPING_TABLE_ENTRY_TYPE_INDEX_MAPPING_FRAGMENTED == mappingEntry->_entryType ||
1435 GED_MAPPING_TABLE_ENTRY_TYPE_VALUE_MAPPING_FRAGMENTED == mappingEntry->_entryType);
1436 GEDASSERT(mappingEntry->_fragmented._numOfMappingFragments > 1);
1437
1438 // The field is fragmented, so all fragments will eventually be gathered in fullVal. A fragment can't be larger than 32 bits, but
1439 // the full value may be an entry in a compaction table, which may be 64-bit long.
1440 val = 0;
1441 for (unsigned int i = 0; i < mappingEntry->_fragmented._numOfMappingFragments; ++i)
1442 {
1443 GEDASSERT(mappingEntry->_fragmented._fragments[i]._from._dwordIndex < 2); // the mapping source may only have 64 bits
1444 uint32_t fragmentVal = 0;
1445 if (!CollectFragmentValue(fragmentVal, bytes, mappingEntry->_fragmented._fragments[i])) return false;
1446 (reinterpret_cast<uint32_t*>(&val))[mappingEntry->_fragmented._fragments[i]._from._dwordIndex] |= fragmentVal;
1447 }
1448 return true;
1449 }
1450
1451
1452 bool GEDIns::CollectFragmentValue(uint32_t& val, const unsigned char* bytes, const ged_compact_mapping_fragment_t& mapping) const
1453 {
1454 val = ((uint32_t*)bytes)[mapping._to._dwordIndex];
1455 val &= mapping._to._bitMask;
1456 if (0 == val) return true; // early out - nothing to do
1457 const int8_t shift = mapping._to._shift - mapping._from._shift;
1458 if (shift > 0)
1459 {
1460 val >>= shift;
1461 }
1462 else if (shift < 0)
1463 {
1464 val <<= abs(shift);
1465 }
1466
1467 // For 1-to-1 mappings there is nothing more to do.
1468 if (GED_COMPACT_MAPPING_TYPE_1x1 == mapping._mappingType) return true;
1469 if (GED_COMPACT_MAPPING_TYPE_FIXED == mapping._mappingType)
1470 {
1471 return (mapping._from._lowBit == val);
1472 }
1473 // Now handle the repped mapping case.
1474 GEDASSERT(GED_COMPACT_MAPPING_TYPE_REP == mapping._mappingType);
1475 const uint8_t fromSize = FragmentSize(mapping._from);
1476 const uint8_t toSize = FragmentSize(mapping._to);
1477 GEDASSERT(fromSize > 0); // verify that the source size is non-zero
1478 GEDASSERT(toSize >= fromSize); // verify that the target is at least as wide as the source
1479 GEDASSERT(0 == (toSize % fromSize)); // verify that the target is a whole multiple of the source
1480 GEDASSERT(0 <= mapping._from._shift); // verify that the shifting amount is non-negative (in order to shift left)
1481 // Validate the value is repeated by its substring.
1482 const uint32_t maxSourceValue = MaxFragmentValue(mapping._from) << mapping._from._shift; // shift the max value to its position
1483 uint32_t shiftedMask = maxSourceValue;
1484 uint32_t shiftedRep = val & maxSourceValue;
1485 // TODO: optimization opportunity: if FragmentSize(fragment) is 1 (which right now, always is), it's possible to simply
1486 // compare with all ones (using MaxGragmentValue(mapping._to)) or all-zeros.
1487 // The current method used is a general ways, which uses loops and thus slower.
1488 for (unsigned int i = 0; i < toSize; i += fromSize)
1489 {
1490 if (((val & shiftedMask) != shiftedRep)) return false;
1491 shiftedRep <<= fromSize;
1492 shiftedMask <<= fromSize;
1493 }
1494 val &= maxSourceValue;
1495 return true;
1496 }
1497
1498
1499 bool GEDIns::FindCompactionTableEntry(uint64_t& val, const uint64_t& valMask, const uint32_t tableSize,
1500 ged_compaction_table_t table) const
1501 {
1502 GEDASSERT(0 != tableSize);
1503 GEDASSERT(tableSize < GED_MAX_ENTRIES_IN_COMPACT_TABLE); // sanity check
1504 val |= valMask;
1505 for (uint32_t i = 0; i < tableSize; ++i)
1506 {
1507 if ((table[i] | valMask) == val)
1508 {
1509 val = i;
1510 return true;
1511 }
1512 }
1513 return false;
1514 }
1515
1516
1517 void GEDIns::ApplyNativeEncodingMasks()
1518 {
1519 # if GED_EXPERIMENTAL
1520 if (!ShouldApplyEncodingMasks())
1521 {
1522 return;
1523 }
1524 # endif // GED_EXPERIMENTAL
1525 const ged_instruction_masks_table_t topLevelTable = GetCurrentModelData().opcodeTables[_opcode].nativeEncodingMasks;
1526 GEDASSERT(NULL != topLevelTable);
1527
1528 for (unsigned int i = 0; GED_MASKS_TABLE_ENTRY_TYPE_NO_MASKS != topLevelTable[i]._entryType; ++i)
1529 {
1530 // Traverse the intermediate tables (if necessary).
1531 unsigned int tableIndex = i;
1532 ged_instruction_masks_table_t table = topLevelTable;
1533 while (GED_MASKS_TABLE_ENTRY_TYPE_NEXT_TABLE == table[tableIndex]._entryType)
1534 {
1535 const ged_instruction_masks_next_table_t* nextTable = &table[tableIndex]._nextTable;
1536 GED_RETURN_VALUE ret = GED_RETURN_VALUE_INVALID_FIELD;
1537 tableIndex = GetField<uint32_t>(_nativeBytes, _decodingTable, nextTable->_tableKey, GED_VALUE_TYPE_ENCODED, ret);
1538
1539 // GetField is expected to succeed since the models ensure that the dependent fields are always valid. However, we need to
1540 // account for invalid instructions, i.e. instructions with an illegal encoding. Such instructions may have invalid values
1541 // for valid fields. If a dependee field is in itself a dependent field, it may even be an invalid field in the given
1542 // (poorly encoded) instruction.
1543 if (GED_RETURN_VALUE_INVALID_FIELD == ret || GED_RETURN_VALUE_INVALID_VALUE == ret) return;
1544 GEDASSERT(GED_RETURN_VALUE_SUCCESS == ret);
1545 table = nextTable->_tablePtr;
1546 GEDASSERT(NULL != table);
1547 }
1548 if (GED_MASKS_TABLE_ENTRY_TYPE_NO_MASKS == table[tableIndex]._entryType) continue; // no mask necessary
1549
1550 // Verify that this is a masks entry.
1551 GEDASSERTM(GED_MASKS_TABLE_ENTRY_TYPE_MASKS == table[tableIndex]._entryType, DecStr(table[tableIndex]._entryType));
1552 for (unsigned int dword = 0; dword < GED_NUM_OF_NATIVE_INS_DWORDS; ++dword)
1553 {
1554 ((uint32_t*)_nativeBytes)[dword] |= ((uint32_t*)(table[tableIndex]._masks._or))[dword];
1555 ((uint32_t*)_nativeBytes)[dword] &= ((uint32_t*)(table[tableIndex]._masks._and))[dword];
1556 }
1557 }
1558 SetNativeEncoded();
1559 }
1560
1561
1562 void GEDIns::ApplyCompactEncodingMasks(unsigned char* compactBytes)
1563 {
1564 const ged_instruction_masks_table_t topLevelTable = GetCurrentModelData().opcodeTables[_opcode].compactEncodingMasks;
1565 GEDASSERT(NULL != topLevelTable);
1566
1567 for (unsigned int i = 0; GED_MASKS_TABLE_ENTRY_TYPE_NO_MASKS != topLevelTable[i]._entryType; ++i)
1568 {
1569 // Traverse the intermediate tables (if necessary).
1570 unsigned int tableIndex = i;
1571 ged_instruction_masks_table_t table = topLevelTable;
1572 while (GED_MASKS_TABLE_ENTRY_TYPE_NEXT_TABLE == table[tableIndex]._entryType)
1573 {
1574 const ged_instruction_masks_next_table_t* nextTable = &table[tableIndex]._nextTable;
1575 GED_RETURN_VALUE ret = GED_RETURN_VALUE_INVALID_FIELD;
1576 tableIndex = GetField<uint32_t>(_nativeBytes, _decodingTable, nextTable->_tableKey, GED_VALUE_TYPE_ENCODED, ret);
1577
1578 // GetField is expected to succeed since the models ensure that the dependent fields are always valid. However, we need to
1579 // account for invalid instructions, i.e. instructions with an illegal encoding. Such instructions may have invalid values
1580 // for valid fields. If a dependee field is in itself a dependent field, it may even be an invalid field in the given
1581 // (poorly encoded) instruction.
1582 if (GED_RETURN_VALUE_INVALID_FIELD == ret || GED_RETURN_VALUE_INVALID_VALUE == ret) return;
1583 GEDASSERT(GED_RETURN_VALUE_SUCCESS == ret);
1584 table = nextTable->_tablePtr;
1585 GEDASSERT(NULL != table);
1586 }
1587 if (GED_MASKS_TABLE_ENTRY_TYPE_NO_MASKS == table[tableIndex]._entryType) continue; // no mask necessary
1588
1589 // Verify that this is a masks entry.
1590 GEDASSERT(GED_MASKS_TABLE_ENTRY_TYPE_MASKS == table[tableIndex]._entryType);
1591 for (unsigned int dword = 0; dword < GED_NUM_OF_COMPACT_INS_DWORDS; ++dword)
1592 {
1593 ((uint32_t*)compactBytes)[dword] |= ((uint32_t*)(table[tableIndex]._masks._or))[dword];
1594 ((uint32_t*)compactBytes)[dword] &= ((uint32_t*)(table[tableIndex]._masks._and))[dword];
1595 }
1596 }
1597 SetCompactEncoded();
1598 }
1599
1600
1601 void GEDIns::BuildNativeOrMask(unsigned char* orMask) const
1602 {
1603 const ged_instruction_masks_table_t topLevelTable = GetCurrentModelData().opcodeTables[_opcode].nativeEncodingMasks;
1604 GEDASSERT(NULL != topLevelTable);
1605
1606 for (unsigned int i = 0; GED_MASKS_TABLE_ENTRY_TYPE_NO_MASKS != topLevelTable[i]._entryType; ++i)
1607 {
1608 // Traverse the intermediate tables (if necessary).
1609 unsigned int tableIndex = i;
1610 ged_instruction_masks_table_t table = topLevelTable;
1611 while (GED_MASKS_TABLE_ENTRY_TYPE_NEXT_TABLE == table[tableIndex]._entryType)
1612 {
1613 const ged_instruction_masks_next_table_t* nextTable = &table[tableIndex]._nextTable;
1614 GED_RETURN_VALUE ret = GED_RETURN_VALUE_INVALID_FIELD;
1615 tableIndex = GetField<uint32_t>(_nativeBytes, _decodingTable, nextTable->_tableKey, GED_VALUE_TYPE_ENCODED, ret);
1616 GEDASSERT(GED_RETURN_VALUE_SUCCESS == ret);
1617 table = nextTable->_tablePtr;
1618 GEDASSERT(NULL != table);
1619 }
1620 if (GED_MASKS_TABLE_ENTRY_TYPE_NO_MASKS == table[tableIndex]._entryType) continue; // no mask necessary
1621
1622 // Verify that this is a masks entry.
1623 GEDASSERTM(GED_MASKS_TABLE_ENTRY_TYPE_MASKS == table[tableIndex]._entryType, DecStr(table[tableIndex]._entryType));
1624 for (unsigned int dword = 0; dword < GED_NUM_OF_NATIVE_INS_DWORDS; ++dword)
1625 {
1626 ((uint32_t*)orMask)[dword] |= ((uint32_t*)(table[tableIndex]._masks._or))[dword];
1627 ((uint32_t*)orMask)[dword] &= ((uint32_t*)(table[tableIndex]._masks._and))[dword];
1628 }
1629 }
1630 }
1631
1632
1633 string GEDIns::GetInstructionBytes(const unsigned char* instructionBytes, int dwords) const
1634 {
1635 stringstream strm;
1636 strm << "0x" << setfill('0') << hex;
1637 for (--dwords; dwords >= 0; --dwords)
1638 {
1639 strm << setw(8) << reinterpret_cast<const uint32_t*>(instructionBytes)[dwords];
1640 }
1641 return strm.str();
1642 }
1643
1644
1645 #if GED_VALIDATION_API
1646 bool GEDIns::RecordPadding(vector<ged_ins_field_mapping_fragment_t> &mappingFragments, const ged_ins_field_entry_t* dataEntry) const
1647 {
1648 if (dataEntry->_restrictions && (dataEntry->_restrictions[0]->_restrictionType == GED_FIELD_RESTRICTIONS_TYPE_PADDING))
1649 {
1650 const get_field_restriction_padding_t& padding = dataEntry->_restrictions[0]->_padding;
1651 const uint32_t paddingMask = padding._mask;
1652 const uint32_t paddingValue = padding._value;
1653 for (unsigned int i = 0; i < GED_DWORD_BITS; ++i)
1654 {
1655 if (0 == (paddingMask & (1 << i))) continue;
1656
1657 // Bit number i is set to one, count the length of sequential ones.
1658 unsigned int sequenceLength = 0;
1659 for (; paddingMask & (1 << i); ++i)
1660 {
1661 ++sequenceLength;
1662 }
1663
1664 // Record the padding fragment.
1665 const uint8_t lowBit = i - sequenceLength;
1666 const uint8_t mask = (1 << (sequenceLength + 1)) - 1; // starting from LSB
1667 ged_ins_field_mapping_fragment_t fixedFragment = {};
1668 fixedFragment._fixed = true;
1669 fixedFragment._from._lowBit = lowBit;
1670 fixedFragment._from._highBit = i - 1;
1671 fixedFragment._value = (paddingValue >> lowBit) & mask;
1672 mappingFragments.emplace_back(fixedFragment);
1673 }
1674 return true;
1675 }
1676 return false;
1677 }
1678 #endif // GED_VALIDATION_API
1679
1680 bool GEDIns::RecordPosition(vector<ged_ins_field_mapping_fragment_t> &mappingFragments, const ged_ins_field_entry_t* dataEntry) const
1681 {
1682 bool hasFixedValue = false;
1683 switch (dataEntry->_entryType)
1684 {
1685 case GED_TABLE_ENTRY_TYPE_CONSECUTIVE:
1686 {
1687 GEDASSERT(dataEntry->_bitSize <= GED_DWORD_BITS);
1688 if (0 == dataEntry->_consecutive._position._bitMask)
1689 {
1690 // This field consists only from padded positions, which was already recorded previously.
1691 GEDASSERT(dataEntry->_restrictions);
1692 GEDASSERT(dataEntry->_restrictions[0]->_restrictionType == GED_FIELD_RESTRICTIONS_TYPE_PADDING);
1693 break;
1694 }
1695 RecordSingleFragment(mappingFragments, dataEntry->_consecutive._position);
1696 break;
1697 }
1698 case GED_TABLE_ENTRY_TYPE_FRAGMENTED:
1699 {
1700 const ged_ins_field_multiple_fragments_t& fragmentedPosition = dataEntry->_fragmented;
1701 const uint32_t numOfFragments = fragmentedPosition._numOfPositionFragments;
1702 for (uint8_t i = 0; i < numOfFragments; ++i)
1703 {
1704 RecordSingleFragment(mappingFragments, fragmentedPosition._fragments[i]);
1705 }
1706 break;
1707 }
1708 case GED_TABLE_ENTRY_TYPE_FIXED_VALUE:
1709 {
1710 GEDASSERT(dataEntry->_bitSize <= GED_DWORD_BITS);
1711 ged_ins_field_mapping_fragment_t fixedFragment = {};
1712 fixedFragment._fixed = true;
1713 fixedFragment._from._lowBit = 0;
1714 fixedFragment._from._highBit = dataEntry->_bitSize - 1;
1715 fixedFragment._value = dataEntry->_fixed._value;
1716 mappingFragments.emplace_back(fixedFragment);
1717 hasFixedValue = true;
1718 break;
1719 }
1720 default:
1721 GEDASSERT(0);
1722 }
1723 GEDASSERT(!mappingFragments.empty());
1724 return hasFixedValue;
1725 }
1726
1727
1728 void GEDIns::RecordSingleFragment(vector<ged_ins_field_mapping_fragment_t> &mappingFragments,
1729 const ged_ins_field_position_fragment_t &position) const
1730 {
1731 const uint8_t normalizedLowBit = position._lowBit - position._dwordIndex * GED_DWORD_BITS - position._shift;
1732 ged_ins_field_mapping_fragment_t fragment = {};
1733 fragment._fixed = false;
1734 fragment._from._lowBit = normalizedLowBit;
1735 fragment._from._highBit = normalizedLowBit + position._highBit - position._lowBit;
1736 fragment._to = position;
1737 mappingFragments.emplace_back(fragment);
1738 }
1739
1740
1741 void GEDIns::MergeFragments(vector<ged_ins_field_mapping_fragment_t> &mappingFragments) const
1742 {
1743 for (auto iter = mappingFragments.begin(); iter != mappingFragments.end(); ++iter)
1744 {
1745 if (mappingFragments.end() == iter + 1) break;
1746
1747 const auto nextIter = next(iter);
1748 if ((iter->_from._highBit + 1 == nextIter->_from._lowBit) &&
1749 (iter->_fixed == nextIter->_fixed) &&
1750 (iter->_to._highBit + 1 == nextIter->_to._lowBit))
1751 {
1752 // Merge the next cell into current
1753 iter->_from._highBit = nextIter->_from._highBit;
1754 iter->_to._highBit = nextIter->_to._highBit;
1755 mappingFragments.erase(nextIter);
1756 }
1757 }
1758 }
1759