Coverage Report

Created: 2020-02-25 14:32

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/utils/TableGen/MveEmitter.cpp
Line
Count
Source (jump to first uncovered line)
1
//===- MveEmitter.cpp - Generate arm_mve.h for use with clang -*- C++ -*-=====//
2
//
3
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
// See https://llvm.org/LICENSE.txt for license information.
5
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
//
7
//===----------------------------------------------------------------------===//
8
//
9
// This set of linked tablegen backends is responsible for emitting the bits
10
// and pieces that implement <arm_mve.h>, which is defined by the ACLE standard
11
// and provides a set of types and functions for (more or less) direct access
12
// to the MVE instruction set, including the scalar shifts as well as the
13
// vector instructions.
14
//
15
// MVE's standard intrinsic functions are unusual in that they have a system of
16
// polymorphism. For example, the function vaddq() can behave like vaddq_u16(),
17
// vaddq_f32(), vaddq_s8(), etc., depending on the types of the vector
18
// arguments you give it.
19
//
20
// This constrains the implementation strategies. The usual approach to making
21
// the user-facing functions polymorphic would be to either use
22
// __attribute__((overloadable)) to make a set of vaddq() functions that are
23
// all inline wrappers on the underlying clang builtins, or to define a single
24
// vaddq() macro which expands to an instance of _Generic.
25
//
26
// The inline-wrappers approach would work fine for most intrinsics, except for
27
// the ones that take an argument required to be a compile-time constant,
28
// because if you wrap an inline function around a call to a builtin, the
29
// constant nature of the argument is not passed through.
30
//
31
// The _Generic approach can be made to work with enough effort, but it takes a
32
// lot of machinery, because of the design feature of _Generic that even the
33
// untaken branches are required to pass all front-end validity checks such as
34
// type-correctness. You can work around that by nesting further _Generics all
35
// over the place to coerce things to the right type in untaken branches, but
36
// what you get out is complicated, hard to guarantee its correctness, and
37
// worst of all, gives _completely unreadable_ error messages if the user gets
38
// the types wrong for an intrinsic call.
39
//
40
// Therefore, my strategy is to introduce a new __attribute__ that allows a
41
// function to be mapped to a clang builtin even though it doesn't have the
42
// same name, and then declare all the user-facing MVE function names with that
43
// attribute, mapping each one directly to the clang builtin. And the
44
// polymorphic ones have __attribute__((overloadable)) as well. So once the
45
// compiler has resolved the overload, it knows the internal builtin ID of the
46
// selected function, and can check the immediate arguments against that; and
47
// if the user gets the types wrong in a call to a polymorphic intrinsic, they
48
// get a completely clear error message showing all the declarations of that
49
// function in the header file and explaining why each one doesn't fit their
50
// call.
51
//
52
// The downside of this is that if every clang builtin has to correspond
53
// exactly to a user-facing ACLE intrinsic, then you can't save work in the
54
// frontend by doing it in the header file: CGBuiltin.cpp has to do the entire
55
// job of converting an ACLE intrinsic call into LLVM IR. So the Tablegen
56
// description for an MVE intrinsic has to contain a full description of the
57
// sequence of IRBuilder calls that clang will need to make.
58
//
59
//===----------------------------------------------------------------------===//
60
61
#include "llvm/ADT/APInt.h"
62
#include "llvm/ADT/StringRef.h"
63
#include "llvm/Support/Casting.h"
64
#include "llvm/Support/raw_ostream.h"
65
#include "llvm/TableGen/Error.h"
66
#include "llvm/TableGen/Record.h"
67
#include "llvm/TableGen/StringToOffsetTable.h"
68
#include <cassert>
69
#include <cstddef>
70
#include <cstdint>
71
#include <list>
72
#include <map>
73
#include <memory>
74
#include <set>
75
#include <string>
76
#include <vector>
77
78
using namespace llvm;
79
80
namespace {
81
82
class MveEmitter;
83
class Result;
84
85
// -----------------------------------------------------------------------------
86
// A system of classes to represent all the types we'll need to deal with in
87
// the prototypes of intrinsics.
88
//
89
// Query methods include finding out the C name of a type; the "LLVM name" in
90
// the sense of a C++ code snippet that can be used in the codegen function;
91
// the suffix that represents the type in the ACLE intrinsic naming scheme
92
// (e.g. 's32' represents int32_t in intrinsics such as vaddq_s32); whether the
93
// type is floating-point related (hence should be under #ifdef in the MVE
94
// header so that it isn't included in integer-only MVE mode); and the type's
95
// size in bits. Not all subtypes support all these queries.
96
97
class Type {
98
public:
99
  enum class TypeKind {
100
    // Void appears as a return type (for store intrinsics, which are pure
101
    // side-effect). It's also used as the parameter type in the Tablegen
102
    // when an intrinsic doesn't need to come in various suffixed forms like
103
    // vfooq_s8,vfooq_u16,vfooq_f32.
104
    Void,
105
106
    // Scalar is used for ordinary int and float types of all sizes.
107
    Scalar,
108
109
    // Vector is used for anything that occupies exactly one MVE vector
110
    // register, i.e. {uint,int,float}NxM_t.
111
    Vector,
112
113
    // MultiVector is used for the {uint,int,float}NxMxK_t types used by the
114
    // interleaving load/store intrinsics v{ld,st}{2,4}q.
115
    MultiVector,
116
117
    // Predicate is used by all the predicated intrinsics. Its C
118
    // representation is mve_pred16_t (which is just an alias for uint16_t).
119
    // But we give more detail here, by indicating that a given predicate
120
    // instruction is logically regarded as a vector of i1 containing the
121
    // same number of lanes as the input vector type. So our Predicate type
122
    // comes with a lane count, which we use to decide which kind of <n x i1>
123
    // we'll invoke the pred_i2v IR intrinsic to translate it into.
124
    Predicate,
125
126
    // Pointer is used for pointer types (obviously), and comes with a flag
127
    // indicating whether it's a pointer to a const or mutable instance of
128
    // the pointee type.
129
    Pointer,
130
  };
131
132
private:
133
  const TypeKind TKind;
134
135
protected:
136
0
  Type(TypeKind K) : TKind(K) {}
137
138
public:
139
0
  TypeKind typeKind() const { return TKind; }
140
0
  virtual ~Type() = default;
141
  virtual bool requiresFloat() const = 0;
142
  virtual unsigned sizeInBits() const = 0;
143
  virtual std::string cName() const = 0;
144
0
  virtual std::string llvmName() const {
145
0
    PrintFatalError("no LLVM type name available for type " + cName());
146
0
  }
147
0
  virtual std::string acleSuffix(std::string) const {
148
0
    PrintFatalError("no ACLE suffix available for this type");
149
0
  }
150
};
151
152
enum class ScalarTypeKind { SignedInt, UnsignedInt, Float };
153
0
inline std::string toLetter(ScalarTypeKind kind) {
154
0
  switch (kind) {
155
0
  case ScalarTypeKind::SignedInt:
156
0
    return "s";
157
0
  case ScalarTypeKind::UnsignedInt:
158
0
    return "u";
159
0
  case ScalarTypeKind::Float:
160
0
    return "f";
161
0
  }
162
0
  llvm_unreachable("Unhandled ScalarTypeKind enum");
163
0
}
164
0
inline std::string toCPrefix(ScalarTypeKind kind) {
165
0
  switch (kind) {
166
0
  case ScalarTypeKind::SignedInt:
167
0
    return "int";
168
0
  case ScalarTypeKind::UnsignedInt:
169
0
    return "uint";
170
0
  case ScalarTypeKind::Float:
171
0
    return "float";
172
0
  }
173
0
  llvm_unreachable("Unhandled ScalarTypeKind enum");
174
0
}
175
176
class VoidType : public Type {
177
public:
178
0
  VoidType() : Type(TypeKind::Void) {}
179
0
  unsigned sizeInBits() const override { return 0; }
180
0
  bool requiresFloat() const override { return false; }
181
0
  std::string cName() const override { return "void"; }
182
183
0
  static bool classof(const Type *T) { return T->typeKind() == TypeKind::Void; }
184
0
  std::string acleSuffix(std::string) const override { return ""; }
185
};
186
187
class PointerType : public Type {
188
  const Type *Pointee;
189
  bool Const;
190
191
public:
192
  PointerType(const Type *Pointee, bool Const)
193
0
      : Type(TypeKind::Pointer), Pointee(Pointee), Const(Const) {}
194
0
  unsigned sizeInBits() const override { return 32; }
195
0
  bool requiresFloat() const override { return Pointee->requiresFloat(); }
196
0
  std::string cName() const override {
197
0
    std::string Name = Pointee->cName();
198
0
199
0
    // The syntax for a pointer in C is different when the pointee is
200
0
    // itself a pointer. The MVE intrinsics don't contain any double
201
0
    // pointers, so we don't need to worry about that wrinkle.
202
0
    assert(!isa<PointerType>(Pointee) && "Pointer to pointer not supported");
203
0
204
0
    if (Const)
205
0
      Name = "const " + Name;
206
0
    return Name + " *";
207
0
  }
208
0
  std::string llvmName() const override {
209
0
    return "llvm::PointerType::getUnqual(" + Pointee->llvmName() + ")";
210
0
  }
211
212
0
  static bool classof(const Type *T) {
213
0
    return T->typeKind() == TypeKind::Pointer;
214
0
  }
215
};
216
217
// Base class for all the types that have a name of the form
218
// [prefix][numbers]_t, like int32_t, uint16x8_t, float32x4x2_t.
219
//
220
// For this sub-hierarchy we invent a cNameBase() method which returns the
221
// whole name except for the trailing "_t", so that Vector and MultiVector can
222
// append an extra "x2" or whatever to their element type's cNameBase(). Then
223
// the main cName() query method puts "_t" on the end for the final type name.
224
225
class CRegularNamedType : public Type {
226
  using Type::Type;
227
  virtual std::string cNameBase() const = 0;
228
229
public:
230
0
  std::string cName() const override { return cNameBase() + "_t"; }
231
};
232
233
class ScalarType : public CRegularNamedType {
234
  ScalarTypeKind Kind;
235
  unsigned Bits;
236
  std::string NameOverride;
237
238
public:
239
0
  ScalarType(const Record *Record) : CRegularNamedType(TypeKind::Scalar) {
240
0
    Kind = StringSwitch<ScalarTypeKind>(Record->getValueAsString("kind"))
241
0
               .Case("s", ScalarTypeKind::SignedInt)
242
0
               .Case("u", ScalarTypeKind::UnsignedInt)
243
0
               .Case("f", ScalarTypeKind::Float);
244
0
    Bits = Record->getValueAsInt("size");
245
0
    NameOverride = std::string(Record->getValueAsString("nameOverride"));
246
0
  }
247
0
  unsigned sizeInBits() const override { return Bits; }
248
0
  ScalarTypeKind kind() const { return Kind; }
249
0
  std::string suffix() const { return toLetter(Kind) + utostr(Bits); }
250
0
  std::string cNameBase() const override {
251
0
    return toCPrefix(Kind) + utostr(Bits);
252
0
  }
253
0
  std::string cName() const override {
254
0
    if (NameOverride.empty())
255
0
      return CRegularNamedType::cName();
256
0
    return NameOverride;
257
0
  }
258
0
  std::string llvmName() const override {
259
0
    if (Kind == ScalarTypeKind::Float) {
260
0
      if (Bits == 16)
261
0
        return "HalfTy";
262
0
      if (Bits == 32)
263
0
        return "FloatTy";
264
0
      if (Bits == 64)
265
0
        return "DoubleTy";
266
0
      PrintFatalError("bad size for floating type");
267
0
    }
268
0
    return "Int" + utostr(Bits) + "Ty";
269
0
  }
270
0
  std::string acleSuffix(std::string overrideLetter) const override {
271
0
    return "_" + (overrideLetter.size() ? overrideLetter : toLetter(Kind))
272
0
               + utostr(Bits);
273
0
  }
274
0
  bool isInteger() const { return Kind != ScalarTypeKind::Float; }
275
0
  bool requiresFloat() const override { return !isInteger(); }
276
0
  bool hasNonstandardName() const { return !NameOverride.empty(); }
277
278
0
  static bool classof(const Type *T) {
279
0
    return T->typeKind() == TypeKind::Scalar;
280
0
  }
281
};
282
283
class VectorType : public CRegularNamedType {
284
  const ScalarType *Element;
285
  unsigned Lanes;
286
287
public:
288
  VectorType(const ScalarType *Element, unsigned Lanes)
289
0
      : CRegularNamedType(TypeKind::Vector), Element(Element), Lanes(Lanes) {}
290
0
  unsigned sizeInBits() const override { return Lanes * Element->sizeInBits(); }
291
0
  unsigned lanes() const { return Lanes; }
292
0
  bool requiresFloat() const override { return Element->requiresFloat(); }
293
0
  std::string cNameBase() const override {
294
0
    return Element->cNameBase() + "x" + utostr(Lanes);
295
0
  }
296
0
  std::string llvmName() const override {
297
0
    return "llvm::VectorType::get(" + Element->llvmName() + ", " +
298
0
           utostr(Lanes) + ")";
299
0
  }
300
301
0
  static bool classof(const Type *T) {
302
0
    return T->typeKind() == TypeKind::Vector;
303
0
  }
304
};
305
306
class MultiVectorType : public CRegularNamedType {
307
  const VectorType *Element;
308
  unsigned Registers;
309
310
public:
311
  MultiVectorType(unsigned Registers, const VectorType *Element)
312
      : CRegularNamedType(TypeKind::MultiVector), Element(Element),
313
0
        Registers(Registers) {}
314
0
  unsigned sizeInBits() const override {
315
0
    return Registers * Element->sizeInBits();
316
0
  }
317
0
  unsigned registers() const { return Registers; }
318
0
  bool requiresFloat() const override { return Element->requiresFloat(); }
319
0
  std::string cNameBase() const override {
320
0
    return Element->cNameBase() + "x" + utostr(Registers);
321
0
  }
322
323
  // MultiVectorType doesn't override llvmName, because we don't expect to do
324
  // automatic code generation for the MVE intrinsics that use it: the {vld2,
325
  // vld4, vst2, vst4} family are the only ones that use these types, so it was
326
  // easier to hand-write the codegen for dealing with these structs than to
327
  // build in lots of extra automatic machinery that would only be used once.
328
329
0
  static bool classof(const Type *T) {
330
0
    return T->typeKind() == TypeKind::MultiVector;
331
0
  }
332
};
333
334
class PredicateType : public CRegularNamedType {
335
  unsigned Lanes;
336
337
public:
338
  PredicateType(unsigned Lanes)
339
0
      : CRegularNamedType(TypeKind::Predicate), Lanes(Lanes) {}
340
0
  unsigned sizeInBits() const override { return 16; }
341
0
  std::string cNameBase() const override { return "mve_pred16"; }
342
0
  bool requiresFloat() const override { return false; };
343
0
  std::string llvmName() const override {
344
0
    // Use <4 x i1> instead of <2 x i1> for two-lane vector types. See
345
0
    // the comment in llvm/lib/Target/ARM/ARMInstrMVE.td for further
346
0
    // explanation.
347
0
    unsigned ModifiedLanes = (Lanes == 2 ? 4 : Lanes);
348
0
349
0
    return "llvm::VectorType::get(Builder.getInt1Ty(), " +
350
0
           utostr(ModifiedLanes) + ")";
351
0
  }
352
353
0
  static bool classof(const Type *T) {
354
0
    return T->typeKind() == TypeKind::Predicate;
355
0
  }
356
};
357
358
// -----------------------------------------------------------------------------
359
// Class to facilitate merging together the code generation for many intrinsics
360
// by means of varying a few constant or type parameters.
361
//
362
// Most obviously, the intrinsics in a single parametrised family will have
363
// code generation sequences that only differ in a type or two, e.g. vaddq_s8
364
// and vaddq_u16 will look the same apart from putting a different vector type
365
// in the call to CGM.getIntrinsic(). But also, completely different intrinsics
366
// will often code-generate in the same way, with only a different choice of
367
// _which_ IR intrinsic they lower to (e.g. vaddq_m_s8 and vmulq_m_s8), but
368
// marshalling the arguments and return values of the IR intrinsic in exactly
369
// the same way. And others might differ only in some other kind of constant,
370
// such as a lane index.
371
//
372
// So, when we generate the IR-building code for all these intrinsics, we keep
373
// track of every value that could possibly be pulled out of the code and
374
// stored ahead of time in a local variable. Then we group together intrinsics
375
// by textual equivalence of the code that would result if _all_ those
376
// parameters were stored in local variables. That gives us maximal sets that
377
// can be implemented by a single piece of IR-building code by changing
378
// parameter values ahead of time.
379
//
380
// After we've done that, we do a second pass in which we only allocate _some_
381
// of the parameters into local variables, by tracking which ones have the same
382
// values as each other (so that a single variable can be reused) and which
383
// ones are the same across the whole set (so that no variable is needed at
384
// all).
385
//
386
// Hence the class below. Its allocParam method is invoked during code
387
// generation by every method of a Result subclass (see below) that wants to
388
// give it the opportunity to pull something out into a switchable parameter.
389
// It returns a variable name for the parameter, or (if it's being used in the
390
// second pass once we've decided that some parameters don't need to be stored
391
// in variables after all) it might just return the input expression unchanged.
392
393
struct CodeGenParamAllocator {
394
  // Accumulated during code generation
395
  std::vector<std::string> *ParamTypes = nullptr;
396
  std::vector<std::string> *ParamValues = nullptr;
397
398
  // Provided ahead of time in pass 2, to indicate which parameters are being
399
  // assigned to what. This vector contains an entry for each call to
400
  // allocParam expected during code gen (which we counted up in pass 1), and
401
  // indicates the number of the parameter variable that should be returned, or
402
  // -1 if this call shouldn't allocate a parameter variable at all.
403
  //
404
  // We rely on the recursive code generation working identically in passes 1
405
  // and 2, so that the same list of calls to allocParam happen in the same
406
  // order. That guarantees that the parameter numbers recorded in pass 1 will
407
  // match the entries in this vector that store what MveEmitter::EmitBuiltinCG
408
  // decided to do about each one in pass 2.
409
  std::vector<int> *ParamNumberMap = nullptr;
410
411
  // Internally track how many things we've allocated
412
  unsigned nparams = 0;
413
414
0
  std::string allocParam(StringRef Type, StringRef Value) {
415
0
    unsigned ParamNumber;
416
0
417
0
    if (!ParamNumberMap) {
418
0
      // In pass 1, unconditionally assign a new parameter variable to every
419
0
      // value we're asked to process.
420
0
      ParamNumber = nparams++;
421
0
    } else {
422
0
      // In pass 2, consult the map provided by the caller to find out which
423
0
      // variable we should be keeping things in.
424
0
      int MapValue = (*ParamNumberMap)[nparams++];
425
0
      if (MapValue < 0)
426
0
        return std::string(Value);
427
0
      ParamNumber = MapValue;
428
0
    }
429
0
430
0
    // If we've allocated a new parameter variable for the first time, store
431
0
    // its type and value to be retrieved after codegen.
432
0
    if (ParamTypes && ParamTypes->size() == ParamNumber)
433
0
      ParamTypes->push_back(std::string(Type));
434
0
    if (ParamValues && ParamValues->size() == ParamNumber)
435
0
      ParamValues->push_back(std::string(Value));
436
0
437
0
    // Unimaginative naming scheme for parameter variables.
438
0
    return "Param" + utostr(ParamNumber);
439
0
  }
440
};
441
442
// -----------------------------------------------------------------------------
443
// System of classes that represent all the intermediate values used during
444
// code-generation for an intrinsic.
445
//
446
// The base class 'Result' can represent a value of the LLVM type 'Value', or
447
// sometimes 'Address' (for loads/stores, including an alignment requirement).
448
//
449
// In the case where the Tablegen provides a value in the codegen dag as a
450
// plain integer literal, the Result object we construct here will be one that
451
// returns true from hasIntegerConstantValue(). This allows the generated C++
452
// code to use the constant directly in contexts which can take a literal
453
// integer, such as Builder.CreateExtractValue(thing, 1), without going to the
454
// effort of calling llvm::ConstantInt::get() and then pulling the constant
455
// back out of the resulting llvm:Value later.
456
457
class Result {
458
public:
459
  // Convenient shorthand for the pointer type we'll be using everywhere.
460
  using Ptr = std::shared_ptr<Result>;
461
462
private:
463
  Ptr Predecessor;
464
  std::string VarName;
465
  bool VarNameUsed = false;
466
  unsigned Visited = 0;
467
468
public:
469
0
  virtual ~Result() = default;
470
  using Scope = std::map<std::string, Ptr>;
471
  virtual void genCode(raw_ostream &OS, CodeGenParamAllocator &) const = 0;
472
0
  virtual bool hasIntegerConstantValue() const { return false; }
473
0
  virtual uint32_t integerConstantValue() const { return 0; }
474
0
  virtual bool hasIntegerValue() const { return false; }
475
0
  virtual std::string getIntegerValue(const std::string &) {
476
0
    llvm_unreachable("non-working Result::getIntegerValue called");
477
0
  }
478
0
  virtual std::string typeName() const { return "Value *"; }
479
480
  // Mostly, when a code-generation operation has a dependency on prior
481
  // operations, it's because it uses the output values of those operations as
482
  // inputs. But there's one exception, which is the use of 'seq' in Tablegen
483
  // to indicate that operations have to be performed in sequence regardless of
484
  // whether they use each others' output values.
485
  //
486
  // So, the actual generation of code is done by depth-first search, using the
487
  // prerequisites() method to get a list of all the other Results that have to
488
  // be computed before this one. That method divides into the 'predecessor',
489
  // set by setPredecessor() while processing a 'seq' dag node, and the list
490
  // returned by 'morePrerequisites', which each subclass implements to return
491
  // a list of the Results it uses as input to whatever its own computation is
492
  // doing.
493
494
0
  virtual void morePrerequisites(std::vector<Ptr> &output) const {}
495
0
  std::vector<Ptr> prerequisites() const {
496
0
    std::vector<Ptr> ToRet;
497
0
    if (Predecessor)
498
0
      ToRet.push_back(Predecessor);
499
0
    morePrerequisites(ToRet);
500
0
    return ToRet;
501
0
  }
502
503
0
  void setPredecessor(Ptr p) {
504
0
    // If the user has nested one 'seq' node inside another, and this
505
0
    // method is called on the return value of the inner 'seq' (i.e.
506
0
    // the final item inside it), then we can't link _this_ node to p,
507
0
    // because it already has a predecessor. Instead, walk the chain
508
0
    // until we find the first item in the inner seq, and link that to
509
0
    // p, so that nesting seqs has the obvious effect of linking
510
0
    // everything together into one long sequential chain.
511
0
    Result *r = this;
512
0
    while (r->Predecessor)
513
0
      r = r->Predecessor.get();
514
0
    r->Predecessor = p;
515
0
  }
516
517
  // Each Result will be assigned a variable name in the output code, but not
518
  // all those variable names will actually be used (e.g. the return value of
519
  // Builder.CreateStore has void type, so nobody will want to refer to it). To
520
  // prevent annoying compiler warnings, we track whether each Result's
521
  // variable name was ever actually mentioned in subsequent statements, so
522
  // that it can be left out of the final generated code.
523
0
  std::string varname() {
524
0
    VarNameUsed = true;
525
0
    return VarName;
526
0
  }
527
0
  void setVarname(const StringRef s) { VarName = std::string(s); }
528
0
  bool varnameUsed() const { return VarNameUsed; }
529
530
  // Emit code to generate this result as a Value *.
531
0
  virtual std::string asValue() {
532
0
    return varname();
533
0
  }
534
535
  // Code generation happens in multiple passes. This method tracks whether a
536
  // Result has yet been visited in a given pass, without the need for a
537
  // tedious loop in between passes that goes through and resets a 'visited'
538
  // flag back to false: you just set Pass=1 the first time round, and Pass=2
539
  // the second time.
540
0
  bool needsVisiting(unsigned Pass) {
541
0
    bool ToRet = Visited < Pass;
542
0
    Visited = Pass;
543
0
    return ToRet;
544
0
  }
545
};
546
547
// Result subclass that retrieves one of the arguments to the clang builtin
548
// function. In cases where the argument has pointer type, we call
549
// EmitPointerWithAlignment and store the result in a variable of type Address,
550
// so that load and store IR nodes can know the right alignment. Otherwise, we
551
// call EmitScalarExpr.
552
//
553
// There are aggregate parameters in the MVE intrinsics API, but we don't deal
554
// with them in this Tablegen back end: they only arise in the vld2q/vld4q and
555
// vst2q/vst4q family, which is few enough that we just write the code by hand
556
// for those in CGBuiltin.cpp.
557
class BuiltinArgResult : public Result {
558
public:
559
  unsigned ArgNum;
560
  bool AddressType;
561
  bool Immediate;
562
  BuiltinArgResult(unsigned ArgNum, bool AddressType, bool Immediate)
563
0
      : ArgNum(ArgNum), AddressType(AddressType), Immediate(Immediate) {}
564
0
  void genCode(raw_ostream &OS, CodeGenParamAllocator &) const override {
565
0
    OS << (AddressType ? "EmitPointerWithAlignment" : "EmitScalarExpr")
566
0
       << "(E->getArg(" << ArgNum << "))";
567
0
  }
568
0
  std::string typeName() const override {
569
0
    return AddressType ? "Address" : Result::typeName();
570
0
  }
571
  // Emit code to generate this result as a Value *.
572
0
  std::string asValue() override {
573
0
    if (AddressType)
574
0
      return "(" + varname() + ".getPointer())";
575
0
    return Result::asValue();
576
0
  }
577
0
  bool hasIntegerValue() const override { return Immediate; }
578
0
  std::string getIntegerValue(const std::string &IntType) override {
579
0
    return "GetIntegerConstantValue<" + IntType + ">(E->getArg(" +
580
0
           utostr(ArgNum) + "), getContext())";
581
0
  }
582
};
583
584
// Result subclass for an integer literal appearing in Tablegen. This may need
585
// to be turned into an llvm::Result by means of llvm::ConstantInt::get(), or
586
// it may be used directly as an integer, depending on which IRBuilder method
587
// it's being passed to.
588
class IntLiteralResult : public Result {
589
public:
590
  const ScalarType *IntegerType;
591
  uint32_t IntegerValue;
592
  IntLiteralResult(const ScalarType *IntegerType, uint32_t IntegerValue)
593
0
      : IntegerType(IntegerType), IntegerValue(IntegerValue) {}
594
  void genCode(raw_ostream &OS,
595
0
               CodeGenParamAllocator &ParamAlloc) const override {
596
0
    OS << "llvm::ConstantInt::get("
597
0
       << ParamAlloc.allocParam("llvm::Type *", IntegerType->llvmName())
598
0
       << ", ";
599
0
    OS << ParamAlloc.allocParam(IntegerType->cName(), utostr(IntegerValue))
600
0
       << ")";
601
0
  }
602
0
  bool hasIntegerConstantValue() const override { return true; }
603
0
  uint32_t integerConstantValue() const override { return IntegerValue; }
604
};
605
606
// Result subclass representing a cast between different integer types. We use
607
// our own ScalarType abstraction as the representation of the target type,
608
// which gives both size and signedness.
609
class IntCastResult : public Result {
610
public:
611
  const ScalarType *IntegerType;
612
  Ptr V;
613
  IntCastResult(const ScalarType *IntegerType, Ptr V)
614
0
      : IntegerType(IntegerType), V(V) {}
615
  void genCode(raw_ostream &OS,
616
0
               CodeGenParamAllocator &ParamAlloc) const override {
617
0
    OS << "Builder.CreateIntCast(" << V->varname() << ", "
618
0
       << ParamAlloc.allocParam("llvm::Type *", IntegerType->llvmName()) << ", "
619
0
       << ParamAlloc.allocParam("bool",
620
0
                                IntegerType->kind() == ScalarTypeKind::SignedInt
621
0
                                    ? "true"
622
0
                                    : "false")
623
0
       << ")";
624
0
  }
625
0
  void morePrerequisites(std::vector<Ptr> &output) const override {
626
0
    output.push_back(V);
627
0
  }
628
};
629
630
// Result subclass representing a cast between different pointer types.
631
class PointerCastResult : public Result {
632
public:
633
  const PointerType *PtrType;
634
  Ptr V;
635
  PointerCastResult(const PointerType *PtrType, Ptr V)
636
0
      : PtrType(PtrType), V(V) {}
637
  void genCode(raw_ostream &OS,
638
0
               CodeGenParamAllocator &ParamAlloc) const override {
639
0
    OS << "Builder.CreatePointerCast(" << V->asValue() << ", "
640
0
       << ParamAlloc.allocParam("llvm::Type *", PtrType->llvmName()) << ")";
641
0
  }
642
0
  void morePrerequisites(std::vector<Ptr> &output) const override {
643
0
    output.push_back(V);
644
0
  }
645
};
646
647
// Result subclass representing a call to an IRBuilder method. Each IRBuilder
648
// method we want to use will have a Tablegen record giving the method name and
649
// describing any important details of how to call it, such as whether a
650
// particular argument should be an integer constant instead of an llvm::Value.
651
class IRBuilderResult : public Result {
652
public:
653
  StringRef CallPrefix;
654
  std::vector<Ptr> Args;
655
  std::set<unsigned> AddressArgs;
656
  std::map<unsigned, std::string> IntegerArgs;
657
  IRBuilderResult(StringRef CallPrefix, std::vector<Ptr> Args,
658
                  std::set<unsigned> AddressArgs,
659
                  std::map<unsigned, std::string> IntegerArgs)
660
      : CallPrefix(CallPrefix), Args(Args), AddressArgs(AddressArgs),
661
0
        IntegerArgs(IntegerArgs) {}
662
  void genCode(raw_ostream &OS,
663
0
               CodeGenParamAllocator &ParamAlloc) const override {
664
0
    OS << CallPrefix;
665
0
    const char *Sep = "";
666
0
    for (unsigned i = 0, e = Args.size(); i < e; ++i) {
667
0
      Ptr Arg = Args[i];
668
0
      auto it = IntegerArgs.find(i);
669
0
670
0
      OS << Sep;
671
0
      Sep = ", ";
672
0
673
0
      if (it != IntegerArgs.end()) {
674
0
        if (Arg->hasIntegerConstantValue())
675
0
          OS << "static_cast<" << it->second << ">("
676
0
             << ParamAlloc.allocParam(it->second,
677
0
                                      utostr(Arg->integerConstantValue()))
678
0
             << ")";
679
0
        else if (Arg->hasIntegerValue())
680
0
          OS << ParamAlloc.allocParam(it->second,
681
0
                                      Arg->getIntegerValue(it->second));
682
0
      } else {
683
0
        OS << Arg->varname();
684
0
      }
685
0
    }
686
0
    OS << ")";
687
0
  }
688
0
  void morePrerequisites(std::vector<Ptr> &output) const override {
689
0
    for (unsigned i = 0, e = Args.size(); i < e; ++i) {
690
0
      Ptr Arg = Args[i];
691
0
      if (IntegerArgs.find(i) != IntegerArgs.end())
692
0
        continue;
693
0
      output.push_back(Arg);
694
0
    }
695
0
  }
696
};
697
698
// Result subclass representing making an Address out of a Value.
699
class AddressResult : public Result {
700
public:
701
  Ptr Arg;
702
  unsigned Align;
703
0
  AddressResult(Ptr Arg, unsigned Align) : Arg(Arg), Align(Align) {}
704
  void genCode(raw_ostream &OS,
705
0
               CodeGenParamAllocator &ParamAlloc) const override {
706
0
    OS << "Address(" << Arg->varname() << ", CharUnits::fromQuantity("
707
0
       << Align << "))";
708
0
  }
709
0
  std::string typeName() const override {
710
0
    return "Address";
711
0
  }
712
0
  void morePrerequisites(std::vector<Ptr> &output) const override {
713
0
    output.push_back(Arg);
714
0
  }
715
};
716
717
// Result subclass representing a call to an IR intrinsic, which we first have
718
// to look up using an Intrinsic::ID constant and an array of types.
719
class IRIntrinsicResult : public Result {
720
public:
721
  std::string IntrinsicID;
722
  std::vector<const Type *> ParamTypes;
723
  std::vector<Ptr> Args;
724
  IRIntrinsicResult(StringRef IntrinsicID, std::vector<const Type *> ParamTypes,
725
                    std::vector<Ptr> Args)
726
      : IntrinsicID(std::string(IntrinsicID)), ParamTypes(ParamTypes),
727
0
        Args(Args) {}
728
  void genCode(raw_ostream &OS,
729
0
               CodeGenParamAllocator &ParamAlloc) const override {
730
0
    std::string IntNo = ParamAlloc.allocParam(
731
0
        "Intrinsic::ID", "Intrinsic::" + IntrinsicID);
732
0
    OS << "Builder.CreateCall(CGM.getIntrinsic(" << IntNo;
733
0
    if (!ParamTypes.empty()) {
734
0
      OS << ", llvm::SmallVector<llvm::Type *, " << ParamTypes.size() << "> {";
735
0
      const char *Sep = "";
736
0
      for (auto T : ParamTypes) {
737
0
        OS << Sep << ParamAlloc.allocParam("llvm::Type *", T->llvmName());
738
0
        Sep = ", ";
739
0
      }
740
0
      OS << "}";
741
0
    }
742
0
    OS << "), llvm::SmallVector<Value *, " << Args.size() << "> {";
743
0
    const char *Sep = "";
744
0
    for (auto Arg : Args) {
745
0
      OS << Sep << Arg->asValue();
746
0
      Sep = ", ";
747
0
    }
748
0
    OS << "})";
749
0
  }
750
0
  void morePrerequisites(std::vector<Ptr> &output) const override {
751
0
    output.insert(output.end(), Args.begin(), Args.end());
752
0
  }
753
};
754
755
// Result subclass that specifies a type, for use in IRBuilder operations such
756
// as CreateBitCast that take a type argument.
757
class TypeResult : public Result {
758
public:
759
  const Type *T;
760
0
  TypeResult(const Type *T) : T(T) {}
761
0
  void genCode(raw_ostream &OS, CodeGenParamAllocator &) const override {
762
0
    OS << T->llvmName();
763
0
  }
764
0
  std::string typeName() const override {
765
0
    return "llvm::Type *";
766
0
  }
767
};
768
769
// -----------------------------------------------------------------------------
770
// Class that describes a single ACLE intrinsic.
771
//
772
// A Tablegen record will typically describe more than one ACLE intrinsic, by
773
// means of setting the 'list<Type> Params' field to a list of multiple
774
// parameter types, so as to define vaddq_{s8,u8,...,f16,f32} all in one go.
775
// We'll end up with one instance of ACLEIntrinsic for *each* parameter type,
776
// rather than a single one for all of them. Hence, the constructor takes both
777
// a Tablegen record and the current value of the parameter type.
778
779
class ACLEIntrinsic {
780
  // Structure documenting that one of the intrinsic's arguments is required to
781
  // be a compile-time constant integer, and what constraints there are on its
782
  // value. Used when generating Sema checking code.
783
  struct ImmediateArg {
784
    enum class BoundsType { ExplicitRange, UInt };
785
    BoundsType boundsType;
786
    int64_t i1, i2;
787
    StringRef ExtraCheckType, ExtraCheckArgs;
788
    const Type *ArgType;
789
  };
790
791
  // For polymorphic intrinsics, FullName is the explicit name that uniquely
792
  // identifies this variant of the intrinsic, and ShortName is the name it
793
  // shares with at least one other intrinsic.
794
  std::string ShortName, FullName;
795
796
  // A very small number of intrinsics _only_ have a polymorphic
797
  // variant (vuninitializedq taking an unevaluated argument).
798
  bool PolymorphicOnly;
799
800
  // Another rarely-used flag indicating that the builtin doesn't
801
  // evaluate its argument(s) at all.
802
  bool NonEvaluating;
803
804
  const Type *ReturnType;
805
  std::vector<const Type *> ArgTypes;
806
  std::map<unsigned, ImmediateArg> ImmediateArgs;
807
  Result::Ptr Code;
808
809
  std::map<std::string, std::string> CustomCodeGenArgs;
810
811
  // Recursive function that does the internals of code generation.
812
  void genCodeDfs(Result::Ptr V, std::list<Result::Ptr> &Used,
813
0
                  unsigned Pass) const {
814
0
    if (!V->needsVisiting(Pass))
815
0
      return;
816
0
817
0
    for (Result::Ptr W : V->prerequisites())
818
0
      genCodeDfs(W, Used, Pass);
819
0
820
0
    Used.push_back(V);
821
0
  }
822
823
public:
824
0
  const std::string &shortName() const { return ShortName; }
825
0
  const std::string &fullName() const { return FullName; }
826
0
  const Type *returnType() const { return ReturnType; }
827
0
  const std::vector<const Type *> &argTypes() const { return ArgTypes; }
828
0
  bool requiresFloat() const {
829
0
    if (ReturnType->requiresFloat())
830
0
      return true;
831
0
    for (const Type *T : ArgTypes)
832
0
      if (T->requiresFloat())
833
0
        return true;
834
0
    return false;
835
0
  }
836
0
  bool polymorphic() const { return ShortName != FullName; }
837
0
  bool polymorphicOnly() const { return PolymorphicOnly; }
838
0
  bool nonEvaluating() const { return NonEvaluating; }
839
840
  // External entry point for code generation, called from MveEmitter.
841
  void genCode(raw_ostream &OS, CodeGenParamAllocator &ParamAlloc,
842
0
               unsigned Pass) const {
843
0
    if (!hasCode()) {
844
0
      for (auto kv : CustomCodeGenArgs)
845
0
        OS << "  " << kv.first << " = " << kv.second << ";\n";
846
0
      OS << "  break; // custom code gen\n";
847
0
      return;
848
0
    }
849
0
    std::list<Result::Ptr> Used;
850
0
    genCodeDfs(Code, Used, Pass);
851
0
852
0
    unsigned varindex = 0;
853
0
    for (Result::Ptr V : Used)
854
0
      if (V->varnameUsed())
855
0
        V->setVarname("Val" + utostr(varindex++));
856
0
857
0
    for (Result::Ptr V : Used) {
858
0
      OS << "  ";
859
0
      if (V == Used.back()) {
860
0
        assert(!V->varnameUsed());
861
0
        OS << "return "; // FIXME: what if the top-level thing is void?
862
0
      } else if (V->varnameUsed()) {
863
0
        std::string Type = V->typeName();
864
0
        OS << V->typeName();
865
0
        if (!StringRef(Type).endswith("*"))
866
0
          OS << " ";
867
0
        OS << V->varname() << " = ";
868
0
      }
869
0
      V->genCode(OS, ParamAlloc);
870
0
      OS << ";\n";
871
0
    }
872
0
  }
873
0
  bool hasCode() const { return Code != nullptr; }
874
875
0
  static std::string signedHexLiteral(const llvm::APInt &iOrig) {
876
0
    llvm::APInt i = iOrig.trunc(64);
877
0
    SmallString<40> s;
878
0
    i.toString(s, 16, true, true);
879
0
    return std::string(s.str());
880
0
  }
881
882
0
  std::string genSema() const {
883
0
    std::vector<std::string> SemaChecks;
884
0
885
0
    for (const auto &kv : ImmediateArgs) {
886
0
      const ImmediateArg &IA = kv.second;
887
0
888
0
      llvm::APInt lo(128, 0), hi(128, 0);
889
0
      switch (IA.boundsType) {
890
0
      case ImmediateArg::BoundsType::ExplicitRange:
891
0
        lo = IA.i1;
892
0
        hi = IA.i2;
893
0
        break;
894
0
      case ImmediateArg::BoundsType::UInt:
895
0
        lo = 0;
896
0
        hi = llvm::APInt::getMaxValue(IA.i1).zext(128);
897
0
        break;
898
0
      }
899
0
900
0
      std::string Index = utostr(kv.first);
901
0
902
0
      // Emit a range check if the legal range of values for the
903
0
      // immediate is smaller than the _possible_ range of values for
904
0
      // its type.
905
0
      unsigned ArgTypeBits = IA.ArgType->sizeInBits();
906
0
      llvm::APInt ArgTypeRange = llvm::APInt::getMaxValue(ArgTypeBits).zext(128);
907
0
      llvm::APInt ActualRange = (hi-lo).trunc(64).sext(128);
908
0
      if (ActualRange.ult(ArgTypeRange))
909
0
        SemaChecks.push_back("SemaBuiltinConstantArgRange(TheCall, " + Index +
910
0
                             ", " + signedHexLiteral(lo) + ", " +
911
0
                             signedHexLiteral(hi) + ")");
912
0
913
0
      if (!IA.ExtraCheckType.empty()) {
914
0
        std::string Suffix;
915
0
        if (!IA.ExtraCheckArgs.empty()) {
916
0
          std::string tmp;
917
0
          StringRef Arg = IA.ExtraCheckArgs;
918
0
          if (Arg == "!lanesize") {
919
0
            tmp = utostr(IA.ArgType->sizeInBits());
920
0
            Arg = tmp;
921
0
          }
922
0
          Suffix = (Twine(", ") + Arg).str();
923
0
        }
924
0
        SemaChecks.push_back((Twine("SemaBuiltinConstantArg") +
925
0
                              IA.ExtraCheckType + "(TheCall, " + Index +
926
0
                              Suffix + ")")
927
0
                                 .str());
928
0
      }
929
0
930
0
      assert(!SemaChecks.empty());
931
0
    }
932
0
    if (SemaChecks.empty())
933
0
      return "";
934
0
    return (Twine("  return ") +
935
0
            join(std::begin(SemaChecks), std::end(SemaChecks),
936
0
                 " ||\n         ") +
937
0
            ";\n")
938
0
        .str();
939
0
  }
940
941
  ACLEIntrinsic(MveEmitter &ME, Record *R, const Type *Param);
942
};
943
944
// -----------------------------------------------------------------------------
945
// The top-level class that holds all the state from analyzing the entire
946
// Tablegen input.
947
948
class MveEmitter {
949
  // MveEmitter holds a collection of all the types we've instantiated.
950
  VoidType Void;
951
  std::map<std::string, std::unique_ptr<ScalarType>> ScalarTypes;
952
  std::map<std::tuple<ScalarTypeKind, unsigned, unsigned>,
953
           std::unique_ptr<VectorType>>
954
      VectorTypes;
955
  std::map<std::pair<std::string, unsigned>, std::unique_ptr<MultiVectorType>>
956
      MultiVectorTypes;
957
  std::map<unsigned, std::unique_ptr<PredicateType>> PredicateTypes;
958
  std::map<std::string, std::unique_ptr<PointerType>> PointerTypes;
959
960
  // And all the ACLEIntrinsic instances we've created.
961
  std::map<std::string, std::unique_ptr<ACLEIntrinsic>> ACLEIntrinsics;
962
963
public:
964
  // Methods to create a Type object, or return the right existing one from the
965
  // maps stored in this object.
966
0
  const VoidType *getVoidType() { return &Void; }
967
0
  const ScalarType *getScalarType(StringRef Name) {
968
0
    return ScalarTypes[std::string(Name)].get();
969
0
  }
970
0
  const ScalarType *getScalarType(Record *R) {
971
0
    return getScalarType(R->getName());
972
0
  }
973
0
  const VectorType *getVectorType(const ScalarType *ST, unsigned Lanes) {
974
0
    std::tuple<ScalarTypeKind, unsigned, unsigned> key(ST->kind(),
975
0
                                                       ST->sizeInBits(), Lanes);
976
0
    if (VectorTypes.find(key) == VectorTypes.end())
977
0
      VectorTypes[key] = std::make_unique<VectorType>(ST, Lanes);
978
0
    return VectorTypes[key].get();
979
0
  }
980
0
  const VectorType *getVectorType(const ScalarType *ST) {
981
0
    return getVectorType(ST, 128 / ST->sizeInBits());
982
0
  }
983
  const MultiVectorType *getMultiVectorType(unsigned Registers,
984
0
                                            const VectorType *VT) {
985
0
    std::pair<std::string, unsigned> key(VT->cNameBase(), Registers);
986
0
    if (MultiVectorTypes.find(key) == MultiVectorTypes.end())
987
0
      MultiVectorTypes[key] = std::make_unique<MultiVectorType>(Registers, VT);
988
0
    return MultiVectorTypes[key].get();
989
0
  }
990
0
  const PredicateType *getPredicateType(unsigned Lanes) {
991
0
    unsigned key = Lanes;
992
0
    if (PredicateTypes.find(key) == PredicateTypes.end())
993
0
      PredicateTypes[key] = std::make_unique<PredicateType>(Lanes);
994
0
    return PredicateTypes[key].get();
995
0
  }
996
0
  const PointerType *getPointerType(const Type *T, bool Const) {
997
0
    PointerType PT(T, Const);
998
0
    std::string key = PT.cName();
999
0
    if (PointerTypes.find(key) == PointerTypes.end())
1000
0
      PointerTypes[key] = std::make_unique<PointerType>(PT);
1001
0
    return PointerTypes[key].get();
1002
0
  }
1003
1004
  // Methods to construct a type from various pieces of Tablegen. These are
1005
  // always called in the context of setting up a particular ACLEIntrinsic, so
1006
  // there's always an ambient parameter type (because we're iterating through
1007
  // the Params list in the Tablegen record for the intrinsic), which is used
1008
  // to expand Tablegen classes like 'Vector' which mean something different in
1009
  // each member of a parametric family.
1010
  const Type *getType(Record *R, const Type *Param);
1011
  const Type *getType(DagInit *D, const Type *Param);
1012
  const Type *getType(Init *I, const Type *Param);
1013
1014
  // Functions that translate the Tablegen representation of an intrinsic's
1015
  // code generation into a collection of Value objects (which will then be
1016
  // reprocessed to read out the actual C++ code included by CGBuiltin.cpp).
1017
  Result::Ptr getCodeForDag(DagInit *D, const Result::Scope &Scope,
1018
                            const Type *Param);
1019
  Result::Ptr getCodeForDagArg(DagInit *D, unsigned ArgNum,
1020
                               const Result::Scope &Scope, const Type *Param);
1021
  Result::Ptr getCodeForArg(unsigned ArgNum, const Type *ArgType, bool Promote,
1022
                            bool Immediate);
1023
1024
  // Constructor and top-level functions.
1025
1026
  MveEmitter(RecordKeeper &Records);
1027
1028
  void EmitHeader(raw_ostream &OS);
1029
  void EmitBuiltinDef(raw_ostream &OS);
1030
  void EmitBuiltinSema(raw_ostream &OS);
1031
  void EmitBuiltinCG(raw_ostream &OS);
1032
  void EmitBuiltinAliases(raw_ostream &OS);
1033
};
1034
1035
0
const Type *MveEmitter::getType(Init *I, const Type *Param) {
1036
0
  if (auto Dag = dyn_cast<DagInit>(I))
1037
0
    return getType(Dag, Param);
1038
0
  if (auto Def = dyn_cast<DefInit>(I))
1039
0
    return getType(Def->getDef(), Param);
1040
0
1041
0
  PrintFatalError("Could not convert this value into a type");
1042
0
}
1043
1044
0
const Type *MveEmitter::getType(Record *R, const Type *Param) {
1045
0
  // Pass to a subfield of any wrapper records. We don't expect more than one
1046
0
  // of these: immediate operands are used as plain numbers rather than as
1047
0
  // llvm::Value, so it's meaningless to promote their type anyway.
1048
0
  if (R->isSubClassOf("Immediate"))
1049
0
    R = R->getValueAsDef("type");
1050
0
  else if (R->isSubClassOf("unpromoted"))
1051
0
    R = R->getValueAsDef("underlying_type");
1052
0
1053
0
  if (R->getName() == "Void")
1054
0
    return getVoidType();
1055
0
  if (R->isSubClassOf("PrimitiveType"))
1056
0
    return getScalarType(R);
1057
0
  if (R->isSubClassOf("ComplexType"))
1058
0
    return getType(R->getValueAsDag("spec"), Param);
1059
0
1060
0
  PrintFatalError(R->getLoc(), "Could not convert this record into a type");
1061
0
}
1062
1063
0
const Type *MveEmitter::getType(DagInit *D, const Type *Param) {
1064
0
  // The meat of the getType system: types in the Tablegen are represented by a
1065
0
  // dag whose operators select sub-cases of this function.
1066
0
1067
0
  Record *Op = cast<DefInit>(D->getOperator())->getDef();
1068
0
  if (!Op->isSubClassOf("ComplexTypeOp"))
1069
0
    PrintFatalError(
1070
0
        "Expected ComplexTypeOp as dag operator in type expression");
1071
0
1072
0
  if (Op->getName() == "CTO_Parameter") {
1073
0
    if (isa<VoidType>(Param))
1074
0
      PrintFatalError("Parametric type in unparametrised context");
1075
0
    return Param;
1076
0
  }
1077
0
1078
0
  if (Op->getName() == "CTO_Vec") {
1079
0
    const Type *Element = getType(D->getArg(0), Param);
1080
0
    if (D->getNumArgs() == 1) {
1081
0
      return getVectorType(cast<ScalarType>(Element));
1082
0
    } else {
1083
0
      const Type *ExistingVector = getType(D->getArg(1), Param);
1084
0
      return getVectorType(cast<ScalarType>(Element),
1085
0
                           cast<VectorType>(ExistingVector)->lanes());
1086
0
    }
1087
0
  }
1088
0
1089
0
  if (Op->getName() == "CTO_Pred") {
1090
0
    const Type *Element = getType(D->getArg(0), Param);
1091
0
    return getPredicateType(128 / Element->sizeInBits());
1092
0
  }
1093
0
1094
0
  if (Op->isSubClassOf("CTO_Tuple")) {
1095
0
    unsigned Registers = Op->getValueAsInt("n");
1096
0
    const Type *Element = getType(D->getArg(0), Param);
1097
0
    return getMultiVectorType(Registers, cast<VectorType>(Element));
1098
0
  }
1099
0
1100
0
  if (Op->isSubClassOf("CTO_Pointer")) {
1101
0
    const Type *Pointee = getType(D->getArg(0), Param);
1102
0
    return getPointerType(Pointee, Op->getValueAsBit("const"));
1103
0
  }
1104
0
1105
0
  if (Op->getName() == "CTO_CopyKind") {
1106
0
    const ScalarType *STSize = cast<ScalarType>(getType(D->getArg(0), Param));
1107
0
    const ScalarType *STKind = cast<ScalarType>(getType(D->getArg(1), Param));
1108
0
    for (const auto &kv : ScalarTypes) {
1109
0
      const ScalarType *RT = kv.second.get();
1110
0
      if (RT->kind() == STKind->kind() && RT->sizeInBits() == STSize->sizeInBits())
1111
0
        return RT;
1112
0
    }
1113
0
    PrintFatalError("Cannot find a type to satisfy CopyKind");
1114
0
  }
1115
0
1116
0
  if (Op->isSubClassOf("CTO_ScaleSize")) {
1117
0
    const ScalarType *STKind = cast<ScalarType>(getType(D->getArg(0), Param));
1118
0
    int Num = Op->getValueAsInt("num"), Denom = Op->getValueAsInt("denom");
1119
0
    unsigned DesiredSize = STKind->sizeInBits() * Num / Denom;
1120
0
    for (const auto &kv : ScalarTypes) {
1121
0
      const ScalarType *RT = kv.second.get();
1122
0
      if (RT->kind() == STKind->kind() && RT->sizeInBits() == DesiredSize)
1123
0
        return RT;
1124
0
    }
1125
0
    PrintFatalError("Cannot find a type to satisfy ScaleSize");
1126
0
  }
1127
0
1128
0
  PrintFatalError("Bad operator in type dag expression");
1129
0
}
1130
1131
Result::Ptr MveEmitter::getCodeForDag(DagInit *D, const Result::Scope &Scope,
1132
0
                                      const Type *Param) {
1133
0
  Record *Op = cast<DefInit>(D->getOperator())->getDef();
1134
0
1135
0
  if (Op->getName() == "seq") {
1136
0
    Result::Scope SubScope = Scope;
1137
0
    Result::Ptr PrevV = nullptr;
1138
0
    for (unsigned i = 0, e = D->getNumArgs(); i < e; ++i) {
1139
0
      // We don't use getCodeForDagArg here, because the argument name
1140
0
      // has different semantics in a seq
1141
0
      Result::Ptr V =
1142
0
          getCodeForDag(cast<DagInit>(D->getArg(i)), SubScope, Param);
1143
0
      StringRef ArgName = D->getArgNameStr(i);
1144
0
      if (!ArgName.empty())
1145
0
        SubScope[std::string(ArgName)] = V;
1146
0
      if (PrevV)
1147
0
        V->setPredecessor(PrevV);
1148
0
      PrevV = V;
1149
0
    }
1150
0
    return PrevV;
1151
0
  } else if (Op->isSubClassOf("Type")) {
1152
0
    if (D->getNumArgs() != 1)
1153
0
      PrintFatalError("Type casts should have exactly one argument");
1154
0
    const Type *CastType = getType(Op, Param);
1155
0
    Result::Ptr Arg = getCodeForDagArg(D, 0, Scope, Param);
1156
0
    if (const auto *ST = dyn_cast<ScalarType>(CastType)) {
1157
0
      if (!ST->requiresFloat()) {
1158
0
        if (Arg->hasIntegerConstantValue())
1159
0
          return std::make_shared<IntLiteralResult>(
1160
0
              ST, Arg->integerConstantValue());
1161
0
        else
1162
0
          return std::make_shared<IntCastResult>(ST, Arg);
1163
0
      }
1164
0
    } else if (const auto *PT = dyn_cast<PointerType>(CastType)) {
1165
0
      return std::make_shared<PointerCastResult>(PT, Arg);
1166
0
    }
1167
0
    PrintFatalError("Unsupported type cast");
1168
0
  } else if (Op->getName() == "address") {
1169
0
    if (D->getNumArgs() != 2)
1170
0
      PrintFatalError("'address' should have two arguments");
1171
0
    Result::Ptr Arg = getCodeForDagArg(D, 0, Scope, Param);
1172
0
    unsigned Alignment;
1173
0
    if (auto *II = dyn_cast<IntInit>(D->getArg(1))) {
1174
0
      Alignment = II->getValue();
1175
0
    } else {
1176
0
      PrintFatalError("'address' alignment argument should be an integer");
1177
0
    }
1178
0
    return std::make_shared<AddressResult>(Arg, Alignment);
1179
0
  } else if (Op->getName() == "unsignedflag") {
1180
0
    if (D->getNumArgs() != 1)
1181
0
      PrintFatalError("unsignedflag should have exactly one argument");
1182
0
    Record *TypeRec = cast<DefInit>(D->getArg(0))->getDef();
1183
0
    if (!TypeRec->isSubClassOf("Type"))
1184
0
      PrintFatalError("unsignedflag's argument should be a type");
1185
0
    if (const auto *ST = dyn_cast<ScalarType>(getType(TypeRec, Param))) {
1186
0
      return std::make_shared<IntLiteralResult>(
1187
0
        getScalarType("u32"), ST->kind() == ScalarTypeKind::UnsignedInt);
1188
0
    } else {
1189
0
      PrintFatalError("unsignedflag's argument should be a scalar type");
1190
0
    }
1191
0
  } else if (Op->getName() == "bitsize") {
1192
0
    if (D->getNumArgs() != 1)
1193
0
      PrintFatalError("bitsize should have exactly one argument");
1194
0
    Record *TypeRec = cast<DefInit>(D->getArg(0))->getDef();
1195
0
    if (!TypeRec->isSubClassOf("Type"))
1196
0
      PrintFatalError("bitsize's argument should be a type");
1197
0
    if (const auto *ST = dyn_cast<ScalarType>(getType(TypeRec, Param))) {
1198
0
      return std::make_shared<IntLiteralResult>(getScalarType("u32"),
1199
0
                                                ST->sizeInBits());
1200
0
    } else {
1201
0
      PrintFatalError("bitsize's argument should be a scalar type");
1202
0
    }
1203
0
  } else {
1204
0
    std::vector<Result::Ptr> Args;
1205
0
    for (unsigned i = 0, e = D->getNumArgs(); i < e; ++i)
1206
0
      Args.push_back(getCodeForDagArg(D, i, Scope, Param));
1207
0
    if (Op->isSubClassOf("IRBuilderBase")) {
1208
0
      std::set<unsigned> AddressArgs;
1209
0
      std::map<unsigned, std::string> IntegerArgs;
1210
0
      for (Record *sp : Op->getValueAsListOfDefs("special_params")) {
1211
0
        unsigned Index = sp->getValueAsInt("index");
1212
0
        if (sp->isSubClassOf("IRBuilderAddrParam")) {
1213
0
          AddressArgs.insert(Index);
1214
0
        } else if (sp->isSubClassOf("IRBuilderIntParam")) {
1215
0
          IntegerArgs[Index] = std::string(sp->getValueAsString("type"));
1216
0
        }
1217
0
      }
1218
0
      return std::make_shared<IRBuilderResult>(Op->getValueAsString("prefix"),
1219
0
                                               Args, AddressArgs, IntegerArgs);
1220
0
    } else if (Op->isSubClassOf("IRIntBase")) {
1221
0
      std::vector<const Type *> ParamTypes;
1222
0
      for (Record *RParam : Op->getValueAsListOfDefs("params"))
1223
0
        ParamTypes.push_back(getType(RParam, Param));
1224
0
      std::string IntName = std::string(Op->getValueAsString("intname"));
1225
0
      if (Op->getValueAsBit("appendKind"))
1226
0
        IntName += "_" + toLetter(cast<ScalarType>(Param)->kind());
1227
0
      return std::make_shared<IRIntrinsicResult>(IntName, ParamTypes, Args);
1228
0
    } else {
1229
0
      PrintFatalError("Unsupported dag node " + Op->getName());
1230
0
    }
1231
0
  }
1232
0
}
1233
1234
Result::Ptr MveEmitter::getCodeForDagArg(DagInit *D, unsigned ArgNum,
1235
                                         const Result::Scope &Scope,
1236
0
                                         const Type *Param) {
1237
0
  Init *Arg = D->getArg(ArgNum);
1238
0
  StringRef Name = D->getArgNameStr(ArgNum);
1239
0
1240
0
  if (!Name.empty()) {
1241
0
    if (!isa<UnsetInit>(Arg))
1242
0
      PrintFatalError(
1243
0
          "dag operator argument should not have both a value and a name");
1244
0
    auto it = Scope.find(std::string(Name));
1245
0
    if (it == Scope.end())
1246
0
      PrintFatalError("unrecognized variable name '" + Name + "'");
1247
0
    return it->second;
1248
0
  }
1249
0
1250
0
  if (auto *II = dyn_cast<IntInit>(Arg))
1251
0
    return std::make_shared<IntLiteralResult>(getScalarType("u32"),
1252
0
                                              II->getValue());
1253
0
1254
0
  if (auto *DI = dyn_cast<DagInit>(Arg))
1255
0
    return getCodeForDag(DI, Scope, Param);
1256
0
1257
0
  if (auto *DI = dyn_cast<DefInit>(Arg)) {
1258
0
    Record *Rec = DI->getDef();
1259
0
    if (Rec->isSubClassOf("Type")) {
1260
0
      const Type *T = getType(Rec, Param);
1261
0
      return std::make_shared<TypeResult>(T);
1262
0
    }
1263
0
  }
1264
0
1265
0
  PrintFatalError("bad dag argument type for code generation");
1266
0
}
1267
1268
Result::Ptr MveEmitter::getCodeForArg(unsigned ArgNum, const Type *ArgType,
1269
0
                                      bool Promote, bool Immediate) {
1270
0
  Result::Ptr V = std::make_shared<BuiltinArgResult>(
1271
0
      ArgNum, isa<PointerType>(ArgType), Immediate);
1272
0
1273
0
  if (Promote) {
1274
0
    if (const auto *ST = dyn_cast<ScalarType>(ArgType)) {
1275
0
      if (ST->isInteger() && ST->sizeInBits() < 32)
1276
0
        V = std::make_shared<IntCastResult>(getScalarType("u32"), V);
1277
0
    } else if (const auto *PT = dyn_cast<PredicateType>(ArgType)) {
1278
0
      V = std::make_shared<IntCastResult>(getScalarType("u32"), V);
1279
0
      V = std::make_shared<IRIntrinsicResult>("arm_mve_pred_i2v",
1280
0
                                              std::vector<const Type *>{PT},
1281
0
                                              std::vector<Result::Ptr>{V});
1282
0
    }
1283
0
  }
1284
0
1285
0
  return V;
1286
0
}
1287
1288
ACLEIntrinsic::ACLEIntrinsic(MveEmitter &ME, Record *R, const Type *Param)
1289
0
    : ReturnType(ME.getType(R->getValueAsDef("ret"), Param)) {
1290
0
  // Derive the intrinsic's full name, by taking the name of the
1291
0
  // Tablegen record (or override) and appending the suffix from its
1292
0
  // parameter type. (If the intrinsic is unparametrised, its
1293
0
  // parameter type will be given as Void, which returns the empty
1294
0
  // string for acleSuffix.)
1295
0
  StringRef BaseName =
1296
0
      (R->isSubClassOf("NameOverride") ? R->getValueAsString("basename")
1297
0
                                       : R->getName());
1298
0
  StringRef overrideLetter = R->getValueAsString("overrideKindLetter");
1299
0
  FullName =
1300
0
      (Twine(BaseName) + Param->acleSuffix(std::string(overrideLetter))).str();
1301
0
1302
0
  // Derive the intrinsic's polymorphic name, by removing components from the
1303
0
  // full name as specified by its 'pnt' member ('polymorphic name type'),
1304
0
  // which indicates how many type suffixes to remove, and any other piece of
1305
0
  // the name that should be removed.
1306
0
  Record *PolymorphicNameType = R->getValueAsDef("pnt");
1307
0
  SmallVector<StringRef, 8> NameParts;
1308
0
  StringRef(FullName).split(NameParts, '_');
1309
0
  for (unsigned i = 0, e = PolymorphicNameType->getValueAsInt(
1310
0
                           "NumTypeSuffixesToDiscard");
1311
0
       i < e; ++i)
1312
0
    NameParts.pop_back();
1313
0
  if (!PolymorphicNameType->isValueUnset("ExtraSuffixToDiscard")) {
1314
0
    StringRef ExtraSuffix =
1315
0
        PolymorphicNameType->getValueAsString("ExtraSuffixToDiscard");
1316
0
    auto it = NameParts.end();
1317
0
    while (it != NameParts.begin()) {
1318
0
      --it;
1319
0
      if (*it == ExtraSuffix) {
1320
0
        NameParts.erase(it);
1321
0
        break;
1322
0
      }
1323
0
    }
1324
0
  }
1325
0
  ShortName = join(std::begin(NameParts), std::end(NameParts), "_");
1326
0
1327
0
  PolymorphicOnly = R->getValueAsBit("polymorphicOnly");
1328
0
  NonEvaluating = R->getValueAsBit("nonEvaluating");
1329
0
1330
0
  // Process the intrinsic's argument list.
1331
0
  DagInit *ArgsDag = R->getValueAsDag("args");
1332
0
  Result::Scope Scope;
1333
0
  for (unsigned i = 0, e = ArgsDag->getNumArgs(); i < e; ++i) {
1334
0
    Init *TypeInit = ArgsDag->getArg(i);
1335
0
1336
0
    bool Promote = true;
1337
0
    if (auto TypeDI = dyn_cast<DefInit>(TypeInit))
1338
0
      if (TypeDI->getDef()->isSubClassOf("unpromoted"))
1339
0
        Promote = false;
1340
0
1341
0
    // Work out the type of the argument, for use in the function prototype in
1342
0
    // the header file.
1343
0
    const Type *ArgType = ME.getType(TypeInit, Param);
1344
0
    ArgTypes.push_back(ArgType);
1345
0
1346
0
    // If the argument is a subclass of Immediate, record the details about
1347
0
    // what values it can take, for Sema checking.
1348
0
    bool Immediate = false;
1349
0
    if (auto TypeDI = dyn_cast<DefInit>(TypeInit)) {
1350
0
      Record *TypeRec = TypeDI->getDef();
1351
0
      if (TypeRec->isSubClassOf("Immediate")) {
1352
0
        Immediate = true;
1353
0
1354
0
        Record *Bounds = TypeRec->getValueAsDef("bounds");
1355
0
        ImmediateArg &IA = ImmediateArgs[i];
1356
0
        if (Bounds->isSubClassOf("IB_ConstRange")) {
1357
0
          IA.boundsType = ImmediateArg::BoundsType::ExplicitRange;
1358
0
          IA.i1 = Bounds->getValueAsInt("lo");
1359
0
          IA.i2 = Bounds->getValueAsInt("hi");
1360
0
        } else if (Bounds->getName() == "IB_UEltValue") {
1361
0
          IA.boundsType = ImmediateArg::BoundsType::UInt;
1362
0
          IA.i1 = Param->sizeInBits();
1363
0
        } else if (Bounds->getName() == "IB_LaneIndex") {
1364
0
          IA.boundsType = ImmediateArg::BoundsType::ExplicitRange;
1365
0
          IA.i1 = 0;
1366
0
          IA.i2 = 128 / Param->sizeInBits() - 1;
1367
0
        } else if (Bounds->isSubClassOf("IB_EltBit")) {
1368
0
          IA.boundsType = ImmediateArg::BoundsType::ExplicitRange;
1369
0
          IA.i1 = Bounds->getValueAsInt("base");
1370
0
          const Type *T = ME.getType(Bounds->getValueAsDef("type"), Param);
1371
0
          IA.i2 = IA.i1 + T->sizeInBits() - 1;
1372
0
        } else {
1373
0
          PrintFatalError("unrecognised ImmediateBounds subclass");
1374
0
        }
1375
0
1376
0
        IA.ArgType = ArgType;
1377
0
1378
0
        if (!TypeRec->isValueUnset("extra")) {
1379
0
          IA.ExtraCheckType = TypeRec->getValueAsString("extra");
1380
0
          if (!TypeRec->isValueUnset("extraarg"))
1381
0
            IA.ExtraCheckArgs = TypeRec->getValueAsString("extraarg");
1382
0
        }
1383
0
      }
1384
0
    }
1385
0
1386
0
    // The argument will usually have a name in the arguments dag, which goes
1387
0
    // into the variable-name scope that the code gen will refer to.
1388
0
    StringRef ArgName = ArgsDag->getArgNameStr(i);
1389
0
    if (!ArgName.empty())
1390
0
      Scope[std::string(ArgName)] =
1391
0
          ME.getCodeForArg(i, ArgType, Promote, Immediate);
1392
0
  }
1393
0
1394
0
  // Finally, go through the codegen dag and translate it into a Result object
1395
0
  // (with an arbitrary DAG of depended-on Results hanging off it).
1396
0
  DagInit *CodeDag = R->getValueAsDag("codegen");
1397
0
  Record *MainOp = cast<DefInit>(CodeDag->getOperator())->getDef();
1398
0
  if (MainOp->isSubClassOf("CustomCodegen")) {
1399
0
    // Or, if it's the special case of CustomCodegen, just accumulate
1400
0
    // a list of parameters we're going to assign to variables before
1401
0
    // breaking from the loop.
1402
0
    CustomCodeGenArgs["CustomCodeGenType"] =
1403
0
        (Twine("CustomCodeGen::") + MainOp->getValueAsString("type")).str();
1404
0
    for (unsigned i = 0, e = CodeDag->getNumArgs(); i < e; ++i) {
1405
0
      StringRef Name = CodeDag->getArgNameStr(i);
1406
0
      if (Name.empty()) {
1407
0
        PrintFatalError("Operands to CustomCodegen should have names");
1408
0
      } else if (auto *II = dyn_cast<IntInit>(CodeDag->getArg(i))) {
1409
0
        CustomCodeGenArgs[std::string(Name)] = itostr(II->getValue());
1410
0
      } else if (auto *SI = dyn_cast<StringInit>(CodeDag->getArg(i))) {
1411
0
        CustomCodeGenArgs[std::string(Name)] = std::string(SI->getValue());
1412
0
      } else {
1413
0
        PrintFatalError("Operands to CustomCodegen should be integers");
1414
0
      }
1415
0
    }
1416
0
  } else {
1417
0
    Code = ME.getCodeForDag(CodeDag, Scope, Param);
1418
0
  }
1419
0
}
1420
1421
0
MveEmitter::MveEmitter(RecordKeeper &Records) {
1422
0
  // Construct the whole MveEmitter.
1423
0
1424
0
  // First, look up all the instances of PrimitiveType. This gives us the list
1425
0
  // of vector typedefs we have to put in arm_mve.h, and also allows us to
1426
0
  // collect all the useful ScalarType instances into a big list so that we can
1427
0
  // use it for operations such as 'find the unsigned version of this signed
1428
0
  // integer type'.
1429
0
  for (Record *R : Records.getAllDerivedDefinitions("PrimitiveType"))
1430
0
    ScalarTypes[std::string(R->getName())] = std::make_unique<ScalarType>(R);
1431
0
1432
0
  // Now go through the instances of Intrinsic, and for each one, iterate
1433
0
  // through its list of type parameters making an ACLEIntrinsic for each one.
1434
0
  for (Record *R : Records.getAllDerivedDefinitions("Intrinsic")) {
1435
0
    for (Record *RParam : R->getValueAsListOfDefs("params")) {
1436
0
      const Type *Param = getType(RParam, getVoidType());
1437
0
      auto Intrinsic = std::make_unique<ACLEIntrinsic>(*this, R, Param);
1438
0
      ACLEIntrinsics[Intrinsic->fullName()] = std::move(Intrinsic);
1439
0
    }
1440
0
  }
1441
0
}
1442
1443
/// A wrapper on raw_string_ostream that contains its own buffer rather than
1444
/// having to point it at one elsewhere. (In other words, it works just like
1445
/// std::ostringstream; also, this makes it convenient to declare a whole array
1446
/// of them at once.)
1447
///
1448
/// We have to set this up using multiple inheritance, to ensure that the
1449
/// string member has been constructed before raw_string_ostream's constructor
1450
/// is given a pointer to it.
1451
class string_holder {
1452
protected:
1453
  std::string S;
1454
};
1455
class raw_self_contained_string_ostream : private string_holder,
1456
                                          public raw_string_ostream {
1457
public:
1458
  raw_self_contained_string_ostream()
1459
0
      : string_holder(), raw_string_ostream(S) {}
1460
};
1461
1462
0
void MveEmitter::EmitHeader(raw_ostream &OS) {
1463
0
  // Accumulate pieces of the header file that will be enabled under various
1464
0
  // different combinations of #ifdef. The index into parts[] is made up of
1465
0
  // the following bit flags.
1466
0
  constexpr unsigned Float = 1;
1467
0
  constexpr unsigned UseUserNamespace = 2;
1468
0
1469
0
  constexpr unsigned NumParts = 4;
1470
0
  raw_self_contained_string_ostream parts[NumParts];
1471
0
1472
0
  // Write typedefs for all the required vector types, and a few scalar
1473
0
  // types that don't already have the name we want them to have.
1474
0
1475
0
  parts[0] << "typedef uint16_t mve_pred16_t;\n";
1476
0
  parts[Float] << "typedef __fp16 float16_t;\n"
1477
0
                  "typedef float float32_t;\n";
1478
0
  for (const auto &kv : ScalarTypes) {
1479
0
    const ScalarType *ST = kv.second.get();
1480
0
    if (ST->hasNonstandardName())
1481
0
      continue;
1482
0
    raw_ostream &OS = parts[ST->requiresFloat() ? Float : 0];
1483
0
    const VectorType *VT = getVectorType(ST);
1484
0
1485
0
    OS << "typedef __attribute__((__neon_vector_type__(" << VT->lanes()
1486
0
       << "), __clang_arm_mve_strict_polymorphism)) " << ST->cName() << " "
1487
0
       << VT->cName() << ";\n";
1488
0
1489
0
    // Every vector type also comes with a pair of multi-vector types for
1490
0
    // the VLD2 and VLD4 instructions.
1491
0
    for (unsigned n = 2; n <= 4; n += 2) {
1492
0
      const MultiVectorType *MT = getMultiVectorType(n, VT);
1493
0
      OS << "typedef struct { " << VT->cName() << " val[" << n << "]; } "
1494
0
         << MT->cName() << ";\n";
1495
0
    }
1496
0
  }
1497
0
  parts[0] << "\n";
1498
0
  parts[Float] << "\n";
1499
0
1500
0
  // Write declarations for all the intrinsics.
1501
0
1502
0
  for (const auto &kv : ACLEIntrinsics) {
1503
0
    const ACLEIntrinsic &Int = *kv.second;
1504
0
1505
0
    // We generate each intrinsic twice, under its full unambiguous
1506
0
    // name and its shorter polymorphic name (if the latter exists).
1507
0
    for (bool Polymorphic : {false, true}) {
1508
0
      if (Polymorphic && !Int.polymorphic())
1509
0
        continue;
1510
0
      if (!Polymorphic && Int.polymorphicOnly())
1511
0
        continue;
1512
0
1513
0
      // We also generate each intrinsic under a name like __arm_vfooq
1514
0
      // (which is in C language implementation namespace, so it's
1515
0
      // safe to define in any conforming user program) and a shorter
1516
0
      // one like vfooq (which is in user namespace, so a user might
1517
0
      // reasonably have used it for something already). If so, they
1518
0
      // can #define __ARM_MVE_PRESERVE_USER_NAMESPACE before
1519
0
      // including the header, which will suppress the shorter names
1520
0
      // and leave only the implementation-namespace ones. Then they
1521
0
      // have to write __arm_vfooq everywhere, of course.
1522
0
1523
0
      for (bool UserNamespace : {false, true}) {
1524
0
        raw_ostream &OS = parts[(Int.requiresFloat() ? Float : 0) |
1525
0
                                (UserNamespace ? UseUserNamespace : 0)];
1526
0
1527
0
        // Make the name of the function in this declaration.
1528
0
1529
0
        std::string FunctionName =
1530
0
            Polymorphic ? Int.shortName() : Int.fullName();
1531
0
        if (!UserNamespace)
1532
0
          FunctionName = "__arm_" + FunctionName;
1533
0
1534
0
        // Make strings for the types involved in the function's
1535
0
        // prototype.
1536
0
1537
0
        std::string RetTypeName = Int.returnType()->cName();
1538
0
        if (!StringRef(RetTypeName).endswith("*"))
1539
0
          RetTypeName += " ";
1540
0
1541
0
        std::vector<std::string> ArgTypeNames;
1542
0
        for (const Type *ArgTypePtr : Int.argTypes())
1543
0
          ArgTypeNames.push_back(ArgTypePtr->cName());
1544
0
        std::string ArgTypesString =
1545
0
            join(std::begin(ArgTypeNames), std::end(ArgTypeNames), ", ");
1546
0
1547
0
        // Emit the actual declaration. All these functions are
1548
0
        // declared 'static inline' without a body, which is fine
1549
0
        // provided clang recognizes them as builtins, and has the
1550
0
        // effect that this type signature is used in place of the one
1551
0
        // that Builtins.def didn't provide. That's how we can get
1552
0
        // structure types that weren't defined until this header was
1553
0
        // included to be part of the type signature of a builtin that
1554
0
        // was known to clang already.
1555
0
        //
1556
0
        // The declarations use __attribute__(__clang_arm_mve_alias),
1557
0
        // so that each function declared will be recognized as the
1558
0
        // appropriate MVE builtin in spite of its user-facing name.
1559
0
        //
1560
0
        // (That's better than making them all wrapper functions,
1561
0
        // partly because it avoids any compiler error message citing
1562
0
        // the wrapper function definition instead of the user's code,
1563
0
        // and mostly because some MVE intrinsics have arguments
1564
0
        // required to be compile-time constants, and that property
1565
0
        // can't be propagated through a wrapper function. It can be
1566
0
        // propagated through a macro, but macros can't be overloaded
1567
0
        // on argument types very easily - you have to use _Generic,
1568
0
        // which makes error messages very confusing when the user
1569
0
        // gets it wrong.)
1570
0
        //
1571
0
        // Finally, the polymorphic versions of the intrinsics are
1572
0
        // also defined with __attribute__(overloadable), so that when
1573
0
        // the same name is defined with several type signatures, the
1574
0
        // right thing happens. Each one of the overloaded
1575
0
        // declarations is given a different builtin id, which
1576
0
        // has exactly the effect we want: first clang resolves the
1577
0
        // overload to the right function, then it knows which builtin
1578
0
        // it's referring to, and then the Sema checking for that
1579
0
        // builtin can check further things like the constant
1580
0
        // arguments.
1581
0
        //
1582
0
        // One more subtlety is the newline just before the return
1583
0
        // type name. That's a cosmetic tweak to make the error
1584
0
        // messages legible if the user gets the types wrong in a call
1585
0
        // to a polymorphic function: this way, clang will print just
1586
0
        // the _final_ line of each declaration in the header, to show
1587
0
        // the type signatures that would have been legal. So all the
1588
0
        // confusing machinery with __attribute__ is left out of the
1589
0
        // error message, and the user sees something that's more or
1590
0
        // less self-documenting: "here's a list of actually readable
1591
0
        // type signatures for vfooq(), and here's why each one didn't
1592
0
        // match your call".
1593
0
1594
0
        OS << "static __inline__ __attribute__(("
1595
0
           << (Polymorphic ? "overloadable, " : "")
1596
0
           << "__clang_arm_mve_alias(__builtin_arm_mve_" << Int.fullName()
1597
0
           << ")))\n"
1598
0
           << RetTypeName << FunctionName << "(" << ArgTypesString << ");\n";
1599
0
      }
1600
0
    }
1601
0
  }
1602
0
  for (auto &part : parts)
1603
0
    part << "\n";
1604
0
1605
0
  // Now we've finished accumulating bits and pieces into the parts[] array.
1606
0
  // Put it all together to write the final output file.
1607
0
1608
0
  OS << "/*===---- arm_mve.h - ARM MVE intrinsics "
1609
0
        "-----------------------------------===\n"
1610
0
        " *\n"
1611
0
        " *\n"
1612
0
        " * Part of the LLVM Project, under the Apache License v2.0 with LLVM "
1613
0
        "Exceptions.\n"
1614
0
        " * See https://llvm.org/LICENSE.txt for license information.\n"
1615
0
        " * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n"
1616
0
        " *\n"
1617
0
        " *===-------------------------------------------------------------"
1618
0
        "----"
1619
0
        "------===\n"
1620
0
        " */\n"
1621
0
        "\n"
1622
0
        "#ifndef __ARM_MVE_H\n"
1623
0
        "#define __ARM_MVE_H\n"
1624
0
        "\n"
1625
0
        "#if !__ARM_FEATURE_MVE\n"
1626
0
        "#error \"MVE support not enabled\"\n"
1627
0
        "#endif\n"
1628
0
        "\n"
1629
0
        "#include <stdint.h>\n"
1630
0
        "\n"
1631
0
        "#ifdef __cplusplus\n"
1632
0
        "extern \"C\" {\n"
1633
0
        "#endif\n"
1634
0
        "\n";
1635
0
1636
0
  for (size_t i = 0; i < NumParts; ++i) {
1637
0
    std::vector<std::string> conditions;
1638
0
    if (i & Float)
1639
0
      conditions.push_back("(__ARM_FEATURE_MVE & 2)");
1640
0
    if (i & UseUserNamespace)
1641
0
      conditions.push_back("(!defined __ARM_MVE_PRESERVE_USER_NAMESPACE)");
1642
0
1643
0
    std::string condition =
1644
0
        join(std::begin(conditions), std::end(conditions), " && ");
1645
0
    if (!condition.empty())
1646
0
      OS << "#if " << condition << "\n\n";
1647
0
    OS << parts[i].str();
1648
0
    if (!condition.empty())
1649
0
      OS << "#endif /* " << condition << " */\n\n";
1650
0
  }
1651
0
1652
0
  OS << "#ifdef __cplusplus\n"
1653
0
        "} /* extern \"C\" */\n"
1654
0
        "#endif\n"
1655
0
        "\n"
1656
0
        "#endif /* __ARM_MVE_H */\n";
1657
0
}
1658
1659
0
void MveEmitter::EmitBuiltinDef(raw_ostream &OS) {
1660
0
  for (const auto &kv : ACLEIntrinsics) {
1661
0
    const ACLEIntrinsic &Int = *kv.second;
1662
0
    OS << "TARGET_HEADER_BUILTIN(__builtin_arm_mve_" << Int.fullName()
1663
0
       << ", \"\", \"n\", \"arm_mve.h\", ALL_LANGUAGES, \"\")\n";
1664
0
  }
1665
0
1666
0
  std::set<std::string> ShortNamesSeen;
1667
0
1668
0
  for (const auto &kv : ACLEIntrinsics) {
1669
0
    const ACLEIntrinsic &Int = *kv.second;
1670
0
    if (Int.polymorphic()) {
1671
0
      StringRef Name = Int.shortName();
1672
0
      if (ShortNamesSeen.find(std::string(Name)) == ShortNamesSeen.end()) {
1673
0
        OS << "BUILTIN(__builtin_arm_mve_" << Name << ", \"vi.\", \"nt";
1674
0
        if (Int.nonEvaluating())
1675
0
          OS << "u"; // indicate that this builtin doesn't evaluate its args
1676
0
        OS << "\")\n";
1677
0
        ShortNamesSeen.insert(std::string(Name));
1678
0
      }
1679
0
    }
1680
0
  }
1681
0
}
1682
1683
0
void MveEmitter::EmitBuiltinSema(raw_ostream &OS) {
1684
0
  std::map<std::string, std::set<std::string>> Checks;
1685
0
1686
0
  for (const auto &kv : ACLEIntrinsics) {
1687
0
    const ACLEIntrinsic &Int = *kv.second;
1688
0
    std::string Check = Int.genSema();
1689
0
    if (!Check.empty())
1690
0
      Checks[Check].insert(Int.fullName());
1691
0
  }
1692
0
1693
0
  for (const auto &kv : Checks) {
1694
0
    for (StringRef Name : kv.second)
1695
0
      OS << "case ARM::BI__builtin_arm_mve_" << Name << ":\n";
1696
0
    OS << kv.first;
1697
0
  }
1698
0
}
1699
1700
// Machinery for the grouping of intrinsics by similar codegen.
1701
//
1702
// The general setup is that 'MergeableGroup' stores the things that a set of
1703
// similarly shaped intrinsics have in common: the text of their code
1704
// generation, and the number and type of their parameter variables.
1705
// MergeableGroup is the key in a std::map whose value is a set of
1706
// OutputIntrinsic, which stores the ways in which a particular intrinsic
1707
// specializes the MergeableGroup's generic description: the function name and
1708
// the _values_ of the parameter variables.
1709
1710
struct ComparableStringVector : std::vector<std::string> {
1711
  // Infrastructure: a derived class of vector<string> which comes with an
1712
  // ordering, so that it can be used as a key in maps and an element in sets.
1713
  // There's no requirement on the ordering beyond being deterministic.
1714
0
  bool operator<(const ComparableStringVector &rhs) const {
1715
0
    if (size() != rhs.size())
1716
0
      return size() < rhs.size();
1717
0
    for (size_t i = 0, e = size(); i < e; ++i)
1718
0
      if ((*this)[i] != rhs[i])
1719
0
        return (*this)[i] < rhs[i];
1720
0
    return false;
1721
0
  }
1722
};
1723
1724
struct OutputIntrinsic {
1725
  const ACLEIntrinsic *Int;
1726
  std::string Name;
1727
  ComparableStringVector ParamValues;
1728
0
  bool operator<(const OutputIntrinsic &rhs) const {
1729
0
    if (Name != rhs.Name)
1730
0
      return Name < rhs.Name;
1731
0
    return ParamValues < rhs.ParamValues;
1732
0
  }
1733
};
1734
struct MergeableGroup {
1735
  std::string Code;
1736
  ComparableStringVector ParamTypes;
1737
0
  bool operator<(const MergeableGroup &rhs) const {
1738
0
    if (Code != rhs.Code)
1739
0
      return Code < rhs.Code;
1740
0
    return ParamTypes < rhs.ParamTypes;
1741
0
  }
1742
};
1743
1744
0
void MveEmitter::EmitBuiltinCG(raw_ostream &OS) {
1745
0
  // Pass 1: generate code for all the intrinsics as if every type or constant
1746
0
  // that can possibly be abstracted out into a parameter variable will be.
1747
0
  // This identifies the sets of intrinsics we'll group together into a single
1748
0
  // piece of code generation.
1749
0
1750
0
  std::map<MergeableGroup, std::set<OutputIntrinsic>> MergeableGroupsPrelim;
1751
0
1752
0
  for (const auto &kv : ACLEIntrinsics) {
1753
0
    const ACLEIntrinsic &Int = *kv.second;
1754
0
1755
0
    MergeableGroup MG;
1756
0
    OutputIntrinsic OI;
1757
0
1758
0
    OI.Int = &Int;
1759
0
    OI.Name = Int.fullName();
1760
0
    CodeGenParamAllocator ParamAllocPrelim{&MG.ParamTypes, &OI.ParamValues};
1761
0
    raw_string_ostream OS(MG.Code);
1762
0
    Int.genCode(OS, ParamAllocPrelim, 1);
1763
0
    OS.flush();
1764
0
1765
0
    MergeableGroupsPrelim[MG].insert(OI);
1766
0
  }
1767
0
1768
0
  // Pass 2: for each of those groups, optimize the parameter variable set by
1769
0
  // eliminating 'parameters' that are the same for all intrinsics in the
1770
0
  // group, and merging together pairs of parameter variables that take the
1771
0
  // same values as each other for all intrinsics in the group.
1772
0
1773
0
  std::map<MergeableGroup, std::set<OutputIntrinsic>> MergeableGroups;
1774
0
1775
0
  for (const auto &kv : MergeableGroupsPrelim) {
1776
0
    const MergeableGroup &MG = kv.first;
1777
0
    std::vector<int> ParamNumbers;
1778
0
    std::map<ComparableStringVector, int> ParamNumberMap;
1779
0
1780
0
    // Loop over the parameters for this group.
1781
0
    for (size_t i = 0, e = MG.ParamTypes.size(); i < e; ++i) {
1782
0
      // Is this parameter the same for all intrinsics in the group?
1783
0
      const OutputIntrinsic &OI_first = *kv.second.begin();
1784
0
      bool Constant = all_of(kv.second, [&](const OutputIntrinsic &OI) {
1785
0
        return OI.ParamValues[i] == OI_first.ParamValues[i];
1786
0
      });
1787
0
1788
0
      // If so, record it as -1, meaning 'no parameter variable needed'. Then
1789
0
      // the corresponding call to allocParam in pass 2 will not generate a
1790
0
      // variable at all, and just use the value inline.
1791
0
      if (Constant) {
1792
0
        ParamNumbers.push_back(-1);
1793
0
        continue;
1794
0
      }
1795
0
1796
0
      // Otherwise, make a list of the values this parameter takes for each
1797
0
      // intrinsic, and see if that value vector matches anything we already
1798
0
      // have. We also record the parameter type, so that we don't accidentally
1799
0
      // match up two parameter variables with different types. (Not that
1800
0
      // there's much chance of them having textually equivalent values, but in
1801
0
      // _principle_ it could happen.)
1802
0
      ComparableStringVector key;
1803
0
      key.push_back(MG.ParamTypes[i]);
1804
0
      for (const auto &OI : kv.second)
1805
0
        key.push_back(OI.ParamValues[i]);
1806
0
1807
0
      auto Found = ParamNumberMap.find(key);
1808
0
      if (Found != ParamNumberMap.end()) {
1809
0
        // Yes, an existing parameter variable can be reused for this.
1810
0
        ParamNumbers.push_back(Found->second);
1811
0
        continue;
1812
0
      }
1813
0
1814
0
      // No, we need a new parameter variable.
1815
0
      int ExistingIndex = ParamNumberMap.size();
1816
0
      ParamNumberMap[key] = ExistingIndex;
1817
0
      ParamNumbers.push_back(ExistingIndex);
1818
0
    }
1819
0
1820
0
    // Now we're ready to do the pass 2 code generation, which will emit the
1821
0
    // reduced set of parameter variables we've just worked out.
1822
0
1823
0
    for (const auto &OI_prelim : kv.second) {
1824
0
      const ACLEIntrinsic *Int = OI_prelim.Int;
1825
0
1826
0
      MergeableGroup MG;
1827
0
      OutputIntrinsic OI;
1828
0
1829
0
      OI.Int = OI_prelim.Int;
1830
0
      OI.Name = OI_prelim.Name;
1831
0
      CodeGenParamAllocator ParamAlloc{&MG.ParamTypes, &OI.ParamValues,
1832
0
                                       &ParamNumbers};
1833
0
      raw_string_ostream OS(MG.Code);
1834
0
      Int->genCode(OS, ParamAlloc, 2);
1835
0
      OS.flush();
1836
0
1837
0
      MergeableGroups[MG].insert(OI);
1838
0
    }
1839
0
  }
1840
0
1841
0
  // Output the actual C++ code.
1842
0
1843
0
  for (const auto &kv : MergeableGroups) {
1844
0
    const MergeableGroup &MG = kv.first;
1845
0
1846
0
    // List of case statements in the main switch on BuiltinID, and an open
1847
0
    // brace.
1848
0
    const char *prefix = "";
1849
0
    for (const auto &OI : kv.second) {
1850
0
      OS << prefix << "case ARM::BI__builtin_arm_mve_" << OI.Name << ":";
1851
0
      prefix = "\n";
1852
0
    }
1853
0
    OS << " {\n";
1854
0
1855
0
    if (!MG.ParamTypes.empty()) {
1856
0
      // If we've got some parameter variables, then emit their declarations...
1857
0
      for (size_t i = 0, e = MG.ParamTypes.size(); i < e; ++i) {
1858
0
        StringRef Type = MG.ParamTypes[i];
1859
0
        OS << "  " << Type;
1860
0
        if (!Type.endswith("*"))
1861
0
          OS << " ";
1862
0
        OS << " Param" << utostr(i) << ";\n";
1863
0
      }
1864
0
1865
0
      // ... and an inner switch on BuiltinID that will fill them in with each
1866
0
      // individual intrinsic's values.
1867
0
      OS << "  switch (BuiltinID) {\n";
1868
0
      for (const auto &OI : kv.second) {
1869
0
        OS << "  case ARM::BI__builtin_arm_mve_" << OI.Name << ":\n";
1870
0
        for (size_t i = 0, e = MG.ParamTypes.size(); i < e; ++i)
1871
0
          OS << "    Param" << utostr(i) << " = " << OI.ParamValues[i] << ";\n";
1872
0
        OS << "    break;\n";
1873
0
      }
1874
0
      OS << "  }\n";
1875
0
    }
1876
0
1877
0
    // And finally, output the code, and close the outer pair of braces. (The
1878
0
    // code will always end with a 'return' statement, so we need not insert a
1879
0
    // 'break' here.)
1880
0
    OS << MG.Code << "}\n";
1881
0
  }
1882
0
}
1883
1884
0
void MveEmitter::EmitBuiltinAliases(raw_ostream &OS) {
1885
0
  // Build a sorted table of:
1886
0
  // - intrinsic id number
1887
0
  // - full name
1888
0
  // - polymorphic name or -1
1889
0
  StringToOffsetTable StringTable;
1890
0
  OS << "struct IntrinToName {\n"
1891
0
        "  uint32_t Id;\n"
1892
0
        "  int32_t FullName;\n"
1893
0
        "  int32_t ShortName;\n"
1894
0
        "};\n";
1895
0
  OS << "static const IntrinToName Map[] = {\n";
1896
0
  for (const auto &kv : ACLEIntrinsics) {
1897
0
    const ACLEIntrinsic &Int = *kv.second;
1898
0
    int32_t ShortNameOffset =
1899
0
        Int.polymorphic() ? StringTable.GetOrAddStringOffset(Int.shortName())
1900
0
                          : -1;
1901
0
    OS << "  { ARM::BI__builtin_arm_mve_" << Int.fullName() << ", "
1902
0
       << StringTable.GetOrAddStringOffset(Int.fullName()) << ", "
1903
0
       << ShortNameOffset << "},\n";
1904
0
  }
1905
0
  OS << "};\n\n";
1906
0
1907
0
  OS << "static const char IntrinNames[] = {\n";
1908
0
  StringTable.EmitString(OS);
1909
0
  OS << "};\n\n";
1910
0
1911
0
  OS << "auto It = std::lower_bound(std::begin(Map), "
1912
0
        "std::end(Map), BuiltinID,\n"
1913
0
        "  [](const IntrinToName &L, unsigned Id) {\n"
1914
0
        "    return L.Id < Id;\n"
1915
0
        "  });\n";
1916
0
  OS << "if (It == std::end(Map) || It->Id != BuiltinID)\n"
1917
0
        "  return false;\n";
1918
0
  OS << "StringRef FullName(&IntrinNames[It->FullName]);\n";
1919
0
  OS << "if (AliasName == FullName)\n"
1920
0
        "  return true;\n";
1921
0
  OS << "if (It->ShortName == -1)\n"
1922
0
        "  return false;\n";
1923
0
  OS << "StringRef ShortName(&IntrinNames[It->ShortName]);\n";
1924
0
  OS << "return AliasName == ShortName;\n";
1925
0
}
1926
1927
} // namespace
1928
1929
namespace clang {
1930
1931
0
void EmitMveHeader(RecordKeeper &Records, raw_ostream &OS) {
1932
0
  MveEmitter(Records).EmitHeader(OS);
1933
0
}
1934
1935
0
void EmitMveBuiltinDef(RecordKeeper &Records, raw_ostream &OS) {
1936
0
  MveEmitter(Records).EmitBuiltinDef(OS);
1937
0
}
1938
1939
0
void EmitMveBuiltinSema(RecordKeeper &Records, raw_ostream &OS) {
1940
0
  MveEmitter(Records).EmitBuiltinSema(OS);
1941
0
}
1942
1943
0
void EmitMveBuiltinCG(RecordKeeper &Records, raw_ostream &OS) {
1944
0
  MveEmitter(Records).EmitBuiltinCG(OS);
1945
0
}
1946
1947
0
void EmitMveBuiltinAliases(RecordKeeper &Records, raw_ostream &OS) {
1948
0
  MveEmitter(Records).EmitBuiltinAliases(OS);
1949
0
}
1950
1951
} // end namespace clang