Debian Codegraph @

visa/iga/IGALibrary/api/igax.hpp

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 /*
10 * Experimental IGA C++ wrapper interface
11 */
12 #ifndef _IGAX_HPP
13 #define _IGAX_HPP
14
15 #include "common/secure_mem.h"
16 #include "iga.h"
17 #include "iga_bxml_ops.hpp"
18
19 #include <cstdarg>
20 #include <cstring>
21 #include <exception>
22 #include <iomanip>
23 #include <malloc.h>
24 #include <ostream>
25 #include <sstream>
26 #include <string>
27 #include <tuple>
28 #include <vector>
29
30 namespace igax {
31
32 enum class Platform {
33 GEN_INVALID = IGA_GEN_INVALID,
34 GEN7 = IGA_GEN7,
35 GEN7P5 = IGA_GEN7p5,
36 GEN8 = IGA_GEN8,
37 GEN8LP = IGA_GEN8lp,
38 GEN9 = IGA_GEN9,
39 GEN9LP = IGA_GEN9lp,
40 GEN9P5 = IGA_GEN9p5,
41 GEN10 = IGA_GEN10,
42 GEN11 = IGA_GEN11,
43 XE = IGA_XE,
44 XE_HP = IGA_XE_HP,
45 XE_HPG = IGA_XE_HPG,
46 XE_HPC = IGA_XE_HPC
47 ,
48 XE2 = IGA_XE2,
49 XE3 = IGA_XE3
50 };
51
52 struct PlatformInfo {
53 Platform platform;
54 std::string suffix;
55 std::vector<std::string> names;
56
57 iga_gen_t toGen() const { return static_cast<iga_gen_t>(platform); }
58 };
59 static std::vector<PlatformInfo> QueryPlatforms();
60
61 struct Diagnostic {
62 std::string message; // diagnostic message
63 int line, col; // line and column (text only)
64 int off; // byte offset (text or binary diagnostics)
65 int ext; // length of region (text only?)
66
67 Diagnostic(const char *msg, int ln, int cl, int o, int e)
68 : message(msg), line(ln), col(cl), off(o), ext(e) {}
69
70 // emits the error diagnostic to an output stream
71 // includes emitLoc, emitContext, and some other info
72 void emit(std::ostream &os, const std::string &source = "",
73 const void *bits = nullptr, size_t bitsLen = 0) const;
74 // emits just the location
75 void emitLoc(std::ostream &os) const;
76 // emits information about the location (e.g. marked source line)
77 void emitContext(std::ostream &os, const std::string &source = "",
78 const void *bits = nullptr, size_t bitsLen = 0) const;
79
80 // converts the error diagnostic to a string
81 // (emit() using std::stringstream)
82 // No context info is passed to emit
83 std::string str() const { return str(""); }
84 // Passes source the context
85 std::string str(const std::string &source) const;
86 // Passes the binary source to the context
87 std::string str(const void *bits, size_t bitsLen) const;
88 };
89
90 // Product type grouping an output result output with all the warnings
91 // returned in its creation.
92 template <typename T> struct Result {
93 T value;
94 std::vector<Diagnostic> warnings;
95 };
96 typedef std::vector<unsigned char> Bits;
97 struct AsmResult : Result<Bits> {};
98 struct DisResult : Result<std::string> {};
99
100 // a context manages memory and state across the module boundary
101 class Context {
102 iga_context_t context;
103 Platform platform;
104
105 public:
106 Context(const iga_context_options_t &copts);
107 Context(Platform p) : Context(static_cast<iga_gen_t>(p)) {}
108 Context(iga_gen_t p) : Context(IGA_CONTEXT_OPTIONS_INIT(p)) {}
109 ~Context();
110 Context(const Context&) = delete;
111 Context& operator=(const Context&) = delete;
112
113 Platform getPlatform() const { return platform; }
114
115 // assembles a string into bits, returns warning if applicable
116 // failure will throw an igax::AssembleError of some sort
117 // (see subclasses below)
118 AsmResult assembleFromString(
119 const std::string &text,
120 const iga_assemble_options_t &opts = IGA_ASSEMBLE_OPTIONS_INIT());
121 // Disassembles a sequence of bits to a string
122 DisResult disassembleToString(
123 const void *bits, const size_t bitsLen,
124 const iga_disassemble_options_t &opts = IGA_DISASSEMBLE_OPTIONS_INIT());
125 };
126
127 // parent class for all IGA API errors
128 // subclasses contain more specific information
129 // some obscure errors (e.g. out of memory) lack a subclass and
130 // will be instances of this class, typically you shouldn't handle these
131 struct Error : std::exception {
132 iga_status_t status; // the error code returned
133 const char *api; // the C-API that was called
134
135 Error(iga_status_t _status, const char *_api) : status(_status), api(_api) {}
136
137 // emits the error to an output stream
138 // sub-errors override this to offer more specific information
139 virtual void emit(std::ostream &os) const;
140
141 // converts the error to a string message (via emit and std::stringstream)
142 std::string str() const;
143 };
144
145 // indicates a failure to assemble (typically a parse error or encoding error)
146 struct AssembleError : Error {
147 std::vector<Diagnostic> errors;
148 std::string source;
149
150 AssembleError(iga_status_t st, const char *api,
151 const std::vector<Diagnostic> &errs, const std::string &src)
152 : Error(st, api), errors(errs), source(src) {}
153
154 // overrides default implementation to emit the diagnostics instead
155 virtual void emit(std::ostream &os) const;
156 };
157 // thrown when a syntax error(s) are encountered during assembly
158 struct SyntaxError : AssembleError {
159 SyntaxError(const char *api, const std::vector<Diagnostic> &errs,
160 const std::string &src)
161 : AssembleError(IGA_PARSE_ERROR, api, errs, src) {}
162 };
163 // thrown when assembly encounters an encoding error
164 // E.g. we cannot compact an instruction
165 struct EncodeError : AssembleError {
166 EncodeError(const char *api, const std::vector<Diagnostic>& errs,
167 const std::string& src)
168 : AssembleError(IGA_ENCODE_ERROR, api, errs, src) {}
169 };
170
171 // indicates a failure to disassemble (malformed bits?)
172 struct DisassembleError : Error {
173 std::vector<Diagnostic> errors;
174 const void *bits;
175 size_t bitsLen;
176 std::string outputText;
177
178 DisassembleError(iga_status_t st, const char *api,
179 const std::vector<Diagnostic> &errs, const void *_bits,
180 size_t _bitsLen, std::string &text)
181 : Error(st, api), errors(errs), bits(_bits), bitsLen(_bitsLen),
182 outputText(text) {}
183
184 virtual void emit(std::ostream &os) const;
185 };
186 // most specific case that one wants to react to in DisassembleError
187 // something is wrong with the bits being decoded
188 struct DecodeError : DisassembleError {
189 DecodeError(const char *api, const std::vector<Diagnostic> &errs,
190 const void *_bits, size_t _bitsLen, std::string &text)
191 : DisassembleError(IGA_DECODE_ERROR, api, errs, _bits, _bitsLen, text) {}
192 };
193
194 ///////////////////////////////////////////////
195 // IGA OPSPEC API
196 //
197 // Lists information about ops for a given platform
198 class OpSpec {
199 Platform m_platform;
200 iga_opspec_t m_op;
201
202 public:
203 OpSpec(Platform p, iga_opspec_t op) : m_platform(p), m_op(op) {}
204 iga::Op op() const;
205 std::string menmonic() const;
206 std::string name() const;
207 std::string description() const;
208
209 // enumerates all the operations for a given platform
210 static std::vector<OpSpec> enumerate(Platform p);
211 };
212
213 ///////////////////////////////////////////////////////////////////////////////
214 /////////////////////////////// IMPLEMENTATION ////////////////////////////////
215 ///////////////////////////////////////////////////////////////////////////////
216 // The API user shouldn't have to directly interact with this code. It might
217 // prove helpful in debugging, but our hope is that you can treat this as
218 // an abstraction.
219
220 #define IGA_CHECKED_CALL(API, ...) \
221 do { \
222 iga_status_t _st = API(__VA_ARGS__); \
223 if (_st != IGA_SUCCESS) \
224 throw Error(_st, #API); \
225 } while (0)
226
227 static inline std::vector<PlatformInfo> QueryPlatforms() {
228 size_t nps = 0;
229 IGA_CHECKED_CALL(iga_platforms_list, 0, nullptr, &nps);
230 std::vector<iga_gen_t> gens;
231 gens.resize(nps / sizeof(iga_gen_t));
232 IGA_CHECKED_CALL(iga_platforms_list, gens.size() * sizeof(iga_gen_t),
233 gens.data(), nullptr);
234 //
235 std::vector<PlatformInfo> pis;
236 pis.reserve(gens.size());
237 for (size_t piIx = 0; piIx < gens.size(); piIx++) {
238 const char *suffix = nullptr;
239 IGA_CHECKED_CALL(iga_platform_symbol_suffix, gens[piIx], &suffix);
240 size_t names_bytes_needed = 0;
241 IGA_CHECKED_CALL(iga_platform_names, gens[piIx], 0, nullptr,
242 &names_bytes_needed);
243 std::vector<const char *> names_cstr;
244 names_cstr.resize(names_bytes_needed / sizeof(const char *));
245 IGA_CHECKED_CALL(iga_platform_names, gens[piIx],
246 names_cstr.size() * sizeof(const char *),
247 names_cstr.data(), nullptr);
248 std::vector<std::string> names;
249 names.reserve(names_cstr.size());
250 for (const char *nm : names_cstr)
251 names.push_back(nm);
252 //
253 pis.emplace_back();
254 auto &pi = pis.back();
255 pi.platform = static_cast<igax::Platform>(gens[piIx]);
256 pi.suffix = suffix;
257 pi.names = std::move(names);
258 }
259 //
260 return pis;
261 }
262
263 static inline std::vector<Diagnostic>
264 getDiagnostics(const iga_context_t &context, bool errs) {
265 std::vector<Diagnostic> out;
266 const iga_diagnostic_t *ds = nullptr;
267 uint32_t dsLen = 0;
268 if (errs) {
269 IGA_CHECKED_CALL(iga_get_errors, context, &ds, &dsLen);
270 } else {
271 IGA_CHECKED_CALL(iga_get_warnings, context, &ds, &dsLen);
272 }
273 for (uint32_t i = 0; i < dsLen; i++) {
274 const char *msg;
275 IGA_CHECKED_CALL(iga_diagnostic_get_message, ds + i, &msg);
276 uint32_t off;
277 IGA_CHECKED_CALL(iga_diagnostic_get_offset, ds + i, &off);
278
279 iga_diagnostic_type_t dt;
280 IGA_CHECKED_CALL(iga_diagnostic_get_type, ds + i, &dt);
281 if (dt == IGA_DIAGNOSTIC_TEXT) {
282 uint32_t line, col, ext;
283 IGA_CHECKED_CALL(iga_diagnostic_get_text_line, ds + i, &line);
284 IGA_CHECKED_CALL(iga_diagnostic_get_text_column, ds + i, &col);
285 IGA_CHECKED_CALL(iga_diagnostic_get_text_extent, ds + i, &ext);
286 out.emplace_back(msg, line, col, off, ext);
287 } else { // binary
288 out.emplace_back(msg, 0, 0, off, 0);
289 }
290 }
291 return out;
292 }
293 static inline std::vector<Diagnostic> getWarnings(const iga_context_t &ctx) {
294 return igax::getDiagnostics(ctx, false);
295 }
296 static inline std::vector<Diagnostic> getErrors(const iga_context_t &ctx) {
297 return igax::getDiagnostics(ctx, true);
298 }
299
300 inline Context::Context(const iga_context_options_t &copts)
301 : context(nullptr), platform(static_cast<igax::Platform>(copts.gen)) {
302 IGA_CHECKED_CALL(iga_create_context, &copts, &context);
303 }
304
305 inline Context::~Context() {
306 (void)iga_release_context(context);
307 context = nullptr;
308 }
309
310 inline AsmResult
311 Context::assembleFromString(const std::string &text,
312 const iga_assemble_options_t &opts) {
313 AsmResult result;
314 void *bits;
315 uint32_t bitsLen;
316
317 iga_status_t st = iga_assemble(context, &opts, text.c_str(), &bits, &bitsLen);
318 if (st != IGA_SUCCESS) {
319 if (st == IGA_UNSUPPORTED_PLATFORM) {
320 std::vector<Diagnostic> errs;
321 throw AssembleError(st, "iga_assemble", errs, text);
322 }
323 std::vector<Diagnostic> errs = igax::getErrors(context);
324 if (st == IGA_PARSE_ERROR) {
325 throw SyntaxError("iga_assemble", errs, text);
326 } else if (st == IGA_ENCODE_ERROR) {
327 throw EncodeError("iga_assemble", errs, text);
328 } else {
329 throw AssembleError(st, "iga_assemble", errs, text);
330 }
331 }
332
333 // copy out the warnings
334 result.warnings = igax::getWarnings(context);
335 // copy out the bits
336 if (bitsLen > 0) {
337 result.value.resize(bitsLen);
338 memcpy_s(result.value.data(), bitsLen, bits, bitsLen);
339 }
340
341 return result;
342 }
343
344 inline DisResult
345 Context::disassembleToString(const void *bits, const size_t bitsLen,
346 const iga_disassemble_options_t &opts) {
347 char *text;
348 iga_status_t st = iga_disassemble(context, &opts, bits, (uint32_t)bitsLen,
349 nullptr, nullptr, &text);
350 if (st != IGA_SUCCESS) {
351 if (st == IGA_UNSUPPORTED_PLATFORM) {
352 std::vector<Diagnostic> errs;
353 std::string text_str = text;
354 throw DisassembleError(st, "iga_disassemble", errs, bits, bitsLen,
355 text_str);
356 }
357 std::vector<Diagnostic> errs = igax::getErrors(context);
358 if (st == IGA_DECODE_ERROR) {
359 std::string text_str = text;
360 throw DecodeError("iga_disassemble", errs, bits, bitsLen, text_str);
361 } else {
362 std::string text_str = text;
363 throw DisassembleError(st, "iga_disassemble", errs, bits, bitsLen,
364 text_str);
365 }
366 }
367
368 DisResult result;
369 result.value = text;
370 result.warnings = getWarnings(context);
371 return result;
372 }
373
374 inline void Error::emit(std::ostream &os) const {
375 os << api << ": " << iga_status_to_string(status);
376 }
377 inline std::string Error::str() const {
378 std::stringstream ss;
379 emit(ss);
380 return ss.str();
381 }
382
383 inline void AssembleError::emit(std::ostream &os) const {
384 if (status != IGA_PARSE_ERROR && status != IGA_ENCODE_ERROR) {
385 os << api << ": " << iga_status_to_string(status) << "\n";
386 }
387 for (auto &e : errors) {
388 e.emit(os, source);
389 }
390 }
391
392 inline void DisassembleError::emit(std::ostream &os) const {
393 if (status != IGA_DECODE_ERROR) {
394 os << api << ": " << iga_status_to_string(status) << "\n";
395 }
396 for (auto &e : errors) {
397 e.emit(os, "", bits, bitsLen);
398 }
399 }
400
401 inline void Diagnostic::emitLoc(std::ostream &os) const {
402 if (line > 0) { // text error
403 os << std::dec << "line " << line << "." << col << ":";
404 } else { // binary error
405 os << std::hex << "byte offset 0x" << off << ":";
406 }
407 }
408
409 inline void Diagnostic::emitContext(std::ostream &os, const std::string &src,
410 const void *bytes, size_t bytesLen) const {
411 if (line > 0) {
412 // text error
413 if (off <= (int)src.length()) {
414 // we have context too, print that
415 int ix = off;
416 while (ix > 0 && src[ix - 1] != '\r' && src[ix - 1] != '\n') {
417 ix--;
418 }
419 do {
420 os << src[ix++];
421 } while (ix < (int)src.size() && src[ix] != '\r' && src[ix] != '\n');
422 os << "\n";
423 for (int i = 1; i < col; i++) {
424 os << ' ';
425 }
426 os << "^\n";
427 }
428 } else {
429 // binary offset
430 const unsigned char *bits = (const unsigned char *)bytes;
431 if (bits && off + 3 < (int)bytesLen) {
432 size_t iLen = (bits[off + 3] & 0x20) ? 8 : 16;
433 if ((size_t)off + iLen < (int)bytesLen) {
434 for (size_t i = 0; i < iLen && i + off < bytesLen; i++) {
435 if (i > 0)
436 os << ' ';
437 os << std::hex << std::setw(2) << std::setfill('0')
438 << (unsigned)bits[off + i];
439 if (i % 4 == 3)
440 os << ' ';
441 }
442 os << "\n";
443 }
444 }
445 }
446 }
447 inline void Diagnostic::emit(std::ostream &os, const std::string &src,
448 const void *bytes, size_t bytesLen) const {
449 emitLoc(os);
450 os << " " << message << "\n";
451 emitContext(os, src, bytes, bytesLen);
452 }
453
454 inline std::string Diagnostic::str(const std::string &src) const {
455 std::stringstream ss;
456 emit(ss, src);
457 return ss.str();
458 }
459 inline std::string Diagnostic::str(const void *bytes, size_t bytesLen) const {
460 std::stringstream ss;
461 emit(ss, "", bytes, bytesLen);
462 return ss.str();
463 }
464
465 inline std::vector<OpSpec> OpSpec::enumerate(Platform p) {
466 iga_opspec_t arrAuto[128];
467 iga_opspec_t *arrPtr = &arrAuto[0];
468 size_t arrLen = sizeof(arrAuto) / sizeof(arrAuto[0]);
469 IGA_CHECKED_CALL(iga_opspec_enumerate, (iga_gen_t)p, arrPtr, &arrLen);
470 if (arrLen > sizeof(arrAuto) / sizeof(arrAuto[0])) {
471 arrPtr = (iga_opspec_t *)alloca(arrLen * sizeof(iga_opspec_t));
472 IGA_CHECKED_CALL(iga_opspec_enumerate, (iga_gen_t)p, arrPtr, &arrLen);
473 }
474 std::vector<OpSpec> vec;
475 vec.reserve(arrLen);
476 for (size_t i = 0; i < arrLen; i++) {
477 vec.emplace_back(p, arrPtr[i]);
478 }
479 return vec;
480 }
481
482 inline iga::Op OpSpec::op() const {
483 uint32_t iga_op;
484 IGA_CHECKED_CALL(iga_opspec_op, m_op, &iga_op);
485 return static_cast<iga::Op>(iga_op);
486 }
487
488 #define IGA_OPSPEC_STRING_GETTER(API, INITSIZE) \
489 { \
490 char _staticBuf[INITSIZE]; \
491 char *strPtr = &_staticBuf[0]; \
492 size_t strCap = sizeof(_staticBuf); \
493 IGA_CHECKED_CALL(API, m_op, strPtr, &strCap); \
494 if (strCap > sizeof(_staticBuf)) { \
495 strPtr = (char *)malloc(strCap); \
496 IGA_CHECKED_CALL(API, m_op, strPtr, &strCap); \
497 std::string res(strPtr); \
498 free(strPtr); \
499 return res; \
500 } \
501 return std::string(strPtr); \
502 }
503 inline std::string OpSpec::menmonic() const
504 IGA_OPSPEC_STRING_GETTER(iga_opspec_mnemonic, 16);
505 inline std::string OpSpec::name() const
506 IGA_OPSPEC_STRING_GETTER(iga_opspec_name, 32);
507 inline std::string OpSpec::description() const
508 IGA_OPSPEC_STRING_GETTER(iga_opspec_description, 128);
509
510 #undef IGA_OPSPEC_STRING_GETTER
511
512 } // namespace igax
513
514 #endif /* _IGAX_HPP */