Coverage Report

Created: 2022-01-25 06:29

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/utils/TableGen/NeonEmitter.cpp
Line
Count
Source (jump to first uncovered line)
1
//===- NeonEmitter.cpp - Generate arm_neon.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 tablegen backend is responsible for emitting arm_neon.h, which includes
10
// a declaration and definition of each function specified by the ARM NEON
11
// compiler interface.  See ARM document DUI0348B.
12
//
13
// Each NEON instruction is implemented in terms of 1 or more functions which
14
// are suffixed with the element type of the input vectors.  Functions may be
15
// implemented in terms of generic vector operations such as +, *, -, etc. or
16
// by calling a __builtin_-prefixed function which will be handled by clang's
17
// CodeGen library.
18
//
19
// Additional validation code can be generated by this file when runHeader() is
20
// called, rather than the normal run() entry point.
21
//
22
// See also the documentation in include/clang/Basic/arm_neon.td.
23
//
24
//===----------------------------------------------------------------------===//
25
26
#include "TableGenBackends.h"
27
#include "llvm/ADT/ArrayRef.h"
28
#include "llvm/ADT/DenseMap.h"
29
#include "llvm/ADT/None.h"
30
#include "llvm/ADT/Optional.h"
31
#include "llvm/ADT/STLExtras.h"
32
#include "llvm/ADT/SmallVector.h"
33
#include "llvm/ADT/StringExtras.h"
34
#include "llvm/ADT/StringRef.h"
35
#include "llvm/Support/Casting.h"
36
#include "llvm/Support/ErrorHandling.h"
37
#include "llvm/Support/raw_ostream.h"
38
#include "llvm/TableGen/Error.h"
39
#include "llvm/TableGen/Record.h"
40
#include "llvm/TableGen/SetTheory.h"
41
#include <algorithm>
42
#include <cassert>
43
#include <cctype>
44
#include <cstddef>
45
#include <cstdint>
46
#include <deque>
47
#include <map>
48
#include <set>
49
#include <sstream>
50
#include <string>
51
#include <utility>
52
#include <vector>
53
54
using namespace llvm;
55
56
namespace {
57
58
// While globals are generally bad, this one allows us to perform assertions
59
// liberally and somehow still trace them back to the def they indirectly
60
// came from.
61
static Record *CurrentRecord = nullptr;
62
0
static void assert_with_loc(bool Assertion, const std::string &Str) {
63
0
  if (!Assertion) {
64
0
    if (CurrentRecord)
65
0
      PrintFatalError(CurrentRecord->getLoc(), Str);
66
0
    else
67
0
      PrintFatalError(Str);
68
0
  }
69
0
}
70
71
enum ClassKind {
72
  ClassNone,
73
  ClassI,     // generic integer instruction, e.g., "i8" suffix
74
  ClassS,     // signed/unsigned/poly, e.g., "s8", "u8" or "p8" suffix
75
  ClassW,     // width-specific instruction, e.g., "8" suffix
76
  ClassB,     // bitcast arguments with enum argument to specify type
77
  ClassL,     // Logical instructions which are op instructions
78
              // but we need to not emit any suffix for in our
79
              // tests.
80
  ClassNoTest // Instructions which we do not test since they are
81
              // not TRUE instructions.
82
};
83
84
/// NeonTypeFlags - Flags to identify the types for overloaded Neon
85
/// builtins.  These must be kept in sync with the flags in
86
/// include/clang/Basic/TargetBuiltins.h.
87
namespace NeonTypeFlags {
88
89
enum { EltTypeMask = 0xf, UnsignedFlag = 0x10, QuadFlag = 0x20 };
90
91
enum EltType {
92
  Int8,
93
  Int16,
94
  Int32,
95
  Int64,
96
  Poly8,
97
  Poly16,
98
  Poly64,
99
  Poly128,
100
  Float16,
101
  Float32,
102
  Float64,
103
  BFloat16
104
};
105
106
} // end namespace NeonTypeFlags
107
108
class NeonEmitter;
109
110
//===----------------------------------------------------------------------===//
111
// TypeSpec
112
//===----------------------------------------------------------------------===//
113
114
/// A TypeSpec is just a simple wrapper around a string, but gets its own type
115
/// for strong typing purposes.
116
///
117
/// A TypeSpec can be used to create a type.
118
class TypeSpec : public std::string {
119
public:
120
0
  static std::vector<TypeSpec> fromTypeSpecs(StringRef Str) {
121
0
    std::vector<TypeSpec> Ret;
122
0
    TypeSpec Acc;
123
0
    for (char I : Str.str()) {
124
0
      if (islower(I)) {
125
0
        Acc.push_back(I);
126
0
        Ret.push_back(TypeSpec(Acc));
127
0
        Acc.clear();
128
0
      } else {
129
0
        Acc.push_back(I);
130
0
      }
131
0
    }
132
0
    return Ret;
133
0
  }
134
};
135
136
//===----------------------------------------------------------------------===//
137
// Type
138
//===----------------------------------------------------------------------===//
139
140
/// A Type. Not much more to say here.
141
class Type {
142
private:
143
  TypeSpec TS;
144
145
  enum TypeKind {
146
    Void,
147
    Float,
148
    SInt,
149
    UInt,
150
    Poly,
151
    BFloat16,
152
  };
153
  TypeKind Kind;
154
  bool Immediate, Constant, Pointer;
155
  // ScalarForMangling and NoManglingQ are really not suited to live here as
156
  // they are not related to the type. But they live in the TypeSpec (not the
157
  // prototype), so this is really the only place to store them.
158
  bool ScalarForMangling, NoManglingQ;
159
  unsigned Bitwidth, ElementBitwidth, NumVectors;
160
161
public:
162
  Type()
163
      : Kind(Void), Immediate(false), Constant(false),
164
        Pointer(false), ScalarForMangling(false), NoManglingQ(false),
165
0
        Bitwidth(0), ElementBitwidth(0), NumVectors(0) {}
166
167
  Type(TypeSpec TS, StringRef CharMods)
168
      : TS(std::move(TS)), Kind(Void), Immediate(false),
169
        Constant(false), Pointer(false), ScalarForMangling(false),
170
0
        NoManglingQ(false), Bitwidth(0), ElementBitwidth(0), NumVectors(0) {
171
0
    applyModifiers(CharMods);
172
0
  }
173
174
  /// Returns a type representing "void".
175
0
  static Type getVoid() { return Type(); }
176
177
0
  bool operator==(const Type &Other) const { return str() == Other.str(); }
178
0
  bool operator!=(const Type &Other) const { return !operator==(Other); }
179
180
  //
181
  // Query functions
182
  //
183
0
  bool isScalarForMangling() const { return ScalarForMangling; }
184
0
  bool noManglingQ() const { return NoManglingQ; }
185
186
0
  bool isPointer() const { return Pointer; }
187
0
  bool isValue() const { return !isVoid() && !isPointer(); }
188
0
  bool isScalar() const { return isValue() && NumVectors == 0; }
189
0
  bool isVector() const { return isValue() && NumVectors > 0; }
190
0
  bool isConstPointer() const { return Constant; }
191
0
  bool isFloating() const { return Kind == Float; }
192
0
  bool isInteger() const { return Kind == SInt || Kind == UInt; }
193
0
  bool isPoly() const { return Kind == Poly; }
194
0
  bool isSigned() const { return Kind == SInt; }
195
0
  bool isImmediate() const { return Immediate; }
196
0
  bool isFloat() const { return isFloating() && ElementBitwidth == 32; }
197
0
  bool isDouble() const { return isFloating() && ElementBitwidth == 64; }
198
0
  bool isHalf() const { return isFloating() && ElementBitwidth == 16; }
199
0
  bool isChar() const { return ElementBitwidth == 8; }
200
0
  bool isShort() const { return isInteger() && ElementBitwidth == 16; }
201
0
  bool isInt() const { return isInteger() && ElementBitwidth == 32; }
202
0
  bool isLong() const { return isInteger() && ElementBitwidth == 64; }
203
0
  bool isVoid() const { return Kind == Void; }
204
0
  bool isBFloat16() const { return Kind == BFloat16; }
205
0
  unsigned getNumElements() const { return Bitwidth / ElementBitwidth; }
206
0
  unsigned getSizeInBits() const { return Bitwidth; }
207
0
  unsigned getElementSizeInBits() const { return ElementBitwidth; }
208
0
  unsigned getNumVectors() const { return NumVectors; }
209
210
  //
211
  // Mutator functions
212
  //
213
0
  void makeUnsigned() {
214
0
    assert(!isVoid() && "not a potentially signed type");
215
0
    Kind = UInt;
216
0
  }
217
0
  void makeSigned() {
218
0
    assert(!isVoid() && "not a potentially signed type");
219
0
    Kind = SInt;
220
0
  }
221
222
0
  void makeInteger(unsigned ElemWidth, bool Sign) {
223
0
    assert(!isVoid() && "converting void to int probably not useful");
224
0
    Kind = Sign ? SInt : UInt;
225
0
    Immediate = false;
226
0
    ElementBitwidth = ElemWidth;
227
0
  }
228
229
0
  void makeImmediate(unsigned ElemWidth) {
230
0
    Kind = SInt;
231
0
    Immediate = true;
232
0
    ElementBitwidth = ElemWidth;
233
0
  }
234
235
0
  void makeScalar() {
236
0
    Bitwidth = ElementBitwidth;
237
0
    NumVectors = 0;
238
0
  }
239
240
0
  void makeOneVector() {
241
0
    assert(isVector());
242
0
    NumVectors = 1;
243
0
  }
244
245
0
  void make32BitElement() {
246
0
    assert_with_loc(Bitwidth > 32, "Not enough bits to make it 32!");
247
0
    ElementBitwidth = 32;
248
0
  }
249
250
0
  void doubleLanes() {
251
0
    assert_with_loc(Bitwidth != 128, "Can't get bigger than 128!");
252
0
    Bitwidth = 128;
253
0
  }
254
255
0
  void halveLanes() {
256
0
    assert_with_loc(Bitwidth != 64, "Can't get smaller than 64!");
257
0
    Bitwidth = 64;
258
0
  }
259
260
  /// Return the C string representation of a type, which is the typename
261
  /// defined in stdint.h or arm_neon.h.
262
  std::string str() const;
263
264
  /// Return the string representation of a type, which is an encoded
265
  /// string for passing to the BUILTIN() macro in Builtins.def.
266
  std::string builtin_str() const;
267
268
  /// Return the value in NeonTypeFlags for this type.
269
  unsigned getNeonEnum() const;
270
271
  /// Parse a type from a stdint.h or arm_neon.h typedef name,
272
  /// for example uint32x2_t or int64_t.
273
  static Type fromTypedefName(StringRef Name);
274
275
private:
276
  /// Creates the type based on the typespec string in TS.
277
  /// Sets "Quad" to true if the "Q" or "H" modifiers were
278
  /// seen. This is needed by applyModifier as some modifiers
279
  /// only take effect if the type size was changed by "Q" or "H".
280
  void applyTypespec(bool &Quad);
281
  /// Applies prototype modifiers to the type.
282
  void applyModifiers(StringRef Mods);
283
};
284
285
//===----------------------------------------------------------------------===//
286
// Variable
287
//===----------------------------------------------------------------------===//
288
289
/// A variable is a simple class that just has a type and a name.
290
class Variable {
291
  Type T;
292
  std::string N;
293
294
public:
295
0
  Variable() : T(Type::getVoid()) {}
296
0
  Variable(Type T, std::string N) : T(std::move(T)), N(std::move(N)) {}
297
298
0
  Type getType() const { return T; }
299
0
  std::string getName() const { return "__" + N; }
300
};
301
302
//===----------------------------------------------------------------------===//
303
// Intrinsic
304
//===----------------------------------------------------------------------===//
305
306
/// The main grunt class. This represents an instantiation of an intrinsic with
307
/// a particular typespec and prototype.
308
class Intrinsic {
309
  /// The Record this intrinsic was created from.
310
  Record *R;
311
  /// The unmangled name.
312
  std::string Name;
313
  /// The input and output typespecs. InTS == OutTS except when
314
  /// CartesianProductWith is non-empty - this is the case for vreinterpret.
315
  TypeSpec OutTS, InTS;
316
  /// The base class kind. Most intrinsics use ClassS, which has full type
317
  /// info for integers (s32/u32). Some use ClassI, which doesn't care about
318
  /// signedness (i32), while some (ClassB) have no type at all, only a width
319
  /// (32).
320
  ClassKind CK;
321
  /// The list of DAGs for the body. May be empty, in which case we should
322
  /// emit a builtin call.
323
  ListInit *Body;
324
  /// The architectural #ifdef guard.
325
  std::string Guard;
326
  /// Set if the Unavailable bit is 1. This means we don't generate a body,
327
  /// just an "unavailable" attribute on a declaration.
328
  bool IsUnavailable;
329
  /// Is this intrinsic safe for big-endian? or does it need its arguments
330
  /// reversing?
331
  bool BigEndianSafe;
332
333
  /// The types of return value [0] and parameters [1..].
334
  std::vector<Type> Types;
335
  /// The index of the key type passed to CGBuiltin.cpp for polymorphic calls.
336
  int PolymorphicKeyType;
337
  /// The local variables defined.
338
  std::map<std::string, Variable> Variables;
339
  /// NeededEarly - set if any other intrinsic depends on this intrinsic.
340
  bool NeededEarly;
341
  /// UseMacro - set if we should implement using a macro or unset for a
342
  ///            function.
343
  bool UseMacro;
344
  /// The set of intrinsics that this intrinsic uses/requires.
345
  std::set<Intrinsic *> Dependencies;
346
  /// The "base type", which is Type('d', OutTS). InBaseType is only
347
  /// different if CartesianProductWith is non-empty (for vreinterpret).
348
  Type BaseType, InBaseType;
349
  /// The return variable.
350
  Variable RetVar;
351
  /// A postfix to apply to every variable. Defaults to "".
352
  std::string VariablePostfix;
353
354
  NeonEmitter &Emitter;
355
  std::stringstream OS;
356
357
0
  bool isBigEndianSafe() const {
358
0
    if (BigEndianSafe)
359
0
      return true;
360
361
0
    for (const auto &T : Types){
362
0
      if (T.isVector() && T.getNumElements() > 1)
363
0
        return false;
364
0
    }
365
0
    return true;
366
0
  }
367
368
public:
369
  Intrinsic(Record *R, StringRef Name, StringRef Proto, TypeSpec OutTS,
370
            TypeSpec InTS, ClassKind CK, ListInit *Body, NeonEmitter &Emitter,
371
            StringRef Guard, bool IsUnavailable, bool BigEndianSafe)
372
      : R(R), Name(Name.str()), OutTS(OutTS), InTS(InTS), CK(CK), Body(Body),
373
        Guard(Guard.str()), IsUnavailable(IsUnavailable),
374
        BigEndianSafe(BigEndianSafe), PolymorphicKeyType(0), NeededEarly(false),
375
        UseMacro(false), BaseType(OutTS, "."), InBaseType(InTS, "."),
376
0
        Emitter(Emitter) {
377
    // Modify the TypeSpec per-argument to get a concrete Type, and create
378
    // known variables for each.
379
    // Types[0] is the return value.
380
0
    unsigned Pos = 0;
381
0
    Types.emplace_back(OutTS, getNextModifiers(Proto, Pos));
382
0
    StringRef Mods = getNextModifiers(Proto, Pos);
383
0
    while (!Mods.empty()) {
384
0
      Types.emplace_back(InTS, Mods);
385
0
      if (Mods.contains('!'))
386
0
        PolymorphicKeyType = Types.size() - 1;
387
388
0
      Mods = getNextModifiers(Proto, Pos);
389
0
    }
390
391
0
    for (auto Type : Types) {
392
      // If this builtin takes an immediate argument, we need to #define it rather
393
      // than use a standard declaration, so that SemaChecking can range check
394
      // the immediate passed by the user.
395
396
      // Pointer arguments need to use macros to avoid hiding aligned attributes
397
      // from the pointer type.
398
399
      // It is not permitted to pass or return an __fp16 by value, so intrinsics
400
      // taking a scalar float16_t must be implemented as macros.
401
0
      if (Type.isImmediate() || Type.isPointer() ||
402
0
          (Type.isScalar() && Type.isHalf()))
403
0
        UseMacro = true;
404
0
    }
405
0
  }
406
407
  /// Get the Record that this intrinsic is based off.
408
0
  Record *getRecord() const { return R; }
409
  /// Get the set of Intrinsics that this intrinsic calls.
410
  /// this is the set of immediate dependencies, NOT the
411
  /// transitive closure.
412
0
  const std::set<Intrinsic *> &getDependencies() const { return Dependencies; }
413
  /// Get the architectural guard string (#ifdef).
414
0
  std::string getGuard() const { return Guard; }
415
  /// Get the non-mangled name.
416
0
  std::string getName() const { return Name; }
417
418
  /// Return true if the intrinsic takes an immediate operand.
419
0
  bool hasImmediate() const {
420
0
    return llvm::any_of(Types, [](const Type &T) { return T.isImmediate(); });
421
0
  }
422
423
  /// Return the parameter index of the immediate operand.
424
0
  unsigned getImmediateIdx() const {
425
0
    for (unsigned Idx = 0; Idx < Types.size(); ++Idx)
426
0
      if (Types[Idx].isImmediate())
427
0
        return Idx - 1;
428
0
    llvm_unreachable("Intrinsic has no immediate");
429
0
  }
430
431
432
0
  unsigned getNumParams() const { return Types.size() - 1; }
433
0
  Type getReturnType() const { return Types[0]; }
434
0
  Type getParamType(unsigned I) const { return Types[I + 1]; }
435
0
  Type getBaseType() const { return BaseType; }
436
0
  Type getPolymorphicKeyType() const { return Types[PolymorphicKeyType]; }
437
438
  /// Return true if the prototype has a scalar argument.
439
  bool protoHasScalar() const;
440
441
  /// Return the index that parameter PIndex will sit at
442
  /// in a generated function call. This is often just PIndex,
443
  /// but may not be as things such as multiple-vector operands
444
  /// and sret parameters need to be taken into accont.
445
0
  unsigned getGeneratedParamIdx(unsigned PIndex) {
446
0
    unsigned Idx = 0;
447
0
    if (getReturnType().getNumVectors() > 1)
448
      // Multiple vectors are passed as sret.
449
0
      ++Idx;
450
451
0
    for (unsigned I = 0; I < PIndex; ++I)
452
0
      Idx += std::max(1U, getParamType(I).getNumVectors());
453
454
0
    return Idx;
455
0
  }
456
457
0
  bool hasBody() const { return Body && !Body->getValues().empty(); }
458
459
0
  void setNeededEarly() { NeededEarly = true; }
460
461
0
  bool operator<(const Intrinsic &Other) const {
462
    // Sort lexicographically on a two-tuple (Guard, Name)
463
0
    if (Guard != Other.Guard)
464
0
      return Guard < Other.Guard;
465
0
    return Name < Other.Name;
466
0
  }
467
468
0
  ClassKind getClassKind(bool UseClassBIfScalar = false) {
469
0
    if (UseClassBIfScalar && !protoHasScalar())
470
0
      return ClassB;
471
0
    return CK;
472
0
  }
473
474
  /// Return the name, mangled with type information.
475
  /// If ForceClassS is true, use ClassS (u32/s32) instead
476
  /// of the intrinsic's own type class.
477
  std::string getMangledName(bool ForceClassS = false) const;
478
  /// Return the type code for a builtin function call.
479
  std::string getInstTypeCode(Type T, ClassKind CK) const;
480
  /// Return the type string for a BUILTIN() macro in Builtins.def.
481
  std::string getBuiltinTypeStr();
482
483
  /// Generate the intrinsic, returning code.
484
  std::string generate();
485
  /// Perform type checking and populate the dependency graph, but
486
  /// don't generate code yet.
487
  void indexBody();
488
489
private:
490
  StringRef getNextModifiers(StringRef Proto, unsigned &Pos) const;
491
492
  std::string mangleName(std::string Name, ClassKind CK) const;
493
494
  void initVariables();
495
  std::string replaceParamsIn(std::string S);
496
497
  void emitBodyAsBuiltinCall();
498
499
  void generateImpl(bool ReverseArguments,
500
                    StringRef NamePrefix, StringRef CallPrefix);
501
  void emitReturn();
502
  void emitBody(StringRef CallPrefix);
503
  void emitShadowedArgs();
504
  void emitArgumentReversal();
505
  void emitReturnReversal();
506
  void emitReverseVariable(Variable &Dest, Variable &Src);
507
  void emitNewLine();
508
  void emitClosingBrace();
509
  void emitOpeningBrace();
510
  void emitPrototype(StringRef NamePrefix);
511
512
  class DagEmitter {
513
    Intrinsic &Intr;
514
    StringRef CallPrefix;
515
516
  public:
517
    DagEmitter(Intrinsic &Intr, StringRef CallPrefix) :
518
0
      Intr(Intr), CallPrefix(CallPrefix) {
519
0
    }
520
    std::pair<Type, std::string> emitDagArg(Init *Arg, std::string ArgName);
521
    std::pair<Type, std::string> emitDagSaveTemp(DagInit *DI);
522
    std::pair<Type, std::string> emitDagSplat(DagInit *DI);
523
    std::pair<Type, std::string> emitDagDup(DagInit *DI);
524
    std::pair<Type, std::string> emitDagDupTyped(DagInit *DI);
525
    std::pair<Type, std::string> emitDagShuffle(DagInit *DI);
526
    std::pair<Type, std::string> emitDagCast(DagInit *DI, bool IsBitCast);
527
    std::pair<Type, std::string> emitDagCall(DagInit *DI,
528
                                             bool MatchMangledName);
529
    std::pair<Type, std::string> emitDagNameReplace(DagInit *DI);
530
    std::pair<Type, std::string> emitDagLiteral(DagInit *DI);
531
    std::pair<Type, std::string> emitDagOp(DagInit *DI);
532
    std::pair<Type, std::string> emitDag(DagInit *DI);
533
  };
534
};
535
536
//===----------------------------------------------------------------------===//
537
// NeonEmitter
538
//===----------------------------------------------------------------------===//
539
540
class NeonEmitter {
541
  RecordKeeper &Records;
542
  DenseMap<Record *, ClassKind> ClassMap;
543
  std::map<std::string, std::deque<Intrinsic>> IntrinsicMap;
544
  unsigned UniqueNumber;
545
546
  void createIntrinsic(Record *R, SmallVectorImpl<Intrinsic *> &Out);
547
  void genBuiltinsDef(raw_ostream &OS, SmallVectorImpl<Intrinsic *> &Defs);
548
  void genOverloadTypeCheckCode(raw_ostream &OS,
549
                                SmallVectorImpl<Intrinsic *> &Defs);
550
  void genIntrinsicRangeCheckCode(raw_ostream &OS,
551
                                  SmallVectorImpl<Intrinsic *> &Defs);
552
553
public:
554
  /// Called by Intrinsic - this attempts to get an intrinsic that takes
555
  /// the given types as arguments.
556
  Intrinsic &getIntrinsic(StringRef Name, ArrayRef<Type> Types,
557
                          Optional<std::string> MangledName);
558
559
  /// Called by Intrinsic - returns a globally-unique number.
560
0
  unsigned getUniqueNumber() { return UniqueNumber++; }
561
562
0
  NeonEmitter(RecordKeeper &R) : Records(R), UniqueNumber(0) {
563
0
    Record *SI = R.getClass("SInst");
564
0
    Record *II = R.getClass("IInst");
565
0
    Record *WI = R.getClass("WInst");
566
0
    Record *SOpI = R.getClass("SOpInst");
567
0
    Record *IOpI = R.getClass("IOpInst");
568
0
    Record *WOpI = R.getClass("WOpInst");
569
0
    Record *LOpI = R.getClass("LOpInst");
570
0
    Record *NoTestOpI = R.getClass("NoTestOpInst");
571
572
0
    ClassMap[SI] = ClassS;
573
0
    ClassMap[II] = ClassI;
574
0
    ClassMap[WI] = ClassW;
575
0
    ClassMap[SOpI] = ClassS;
576
0
    ClassMap[IOpI] = ClassI;
577
0
    ClassMap[WOpI] = ClassW;
578
0
    ClassMap[LOpI] = ClassL;
579
0
    ClassMap[NoTestOpI] = ClassNoTest;
580
0
  }
581
582
  // Emit arm_neon.h.inc
583
  void run(raw_ostream &o);
584
585
  // Emit arm_fp16.h.inc
586
  void runFP16(raw_ostream &o);
587
588
  // Emit arm_bf16.h.inc
589
  void runBF16(raw_ostream &o);
590
591
  // Emit all the __builtin prototypes used in arm_neon.h, arm_fp16.h and
592
  // arm_bf16.h
593
  void runHeader(raw_ostream &o);
594
};
595
596
} // end anonymous namespace
597
598
//===----------------------------------------------------------------------===//
599
// Type implementation
600
//===----------------------------------------------------------------------===//
601
602
0
std::string Type::str() const {
603
0
  if (isVoid())
604
0
    return "void";
605
0
  std::string S;
606
607
0
  if (isInteger() && !isSigned())
608
0
    S += "u";
609
610
0
  if (isPoly())
611
0
    S += "poly";
612
0
  else if (isFloating())
613
0
    S += "float";
614
0
  else if (isBFloat16())
615
0
    S += "bfloat";
616
0
  else
617
0
    S += "int";
618
619
0
  S += utostr(ElementBitwidth);
620
0
  if (isVector())
621
0
    S += "x" + utostr(getNumElements());
622
0
  if (NumVectors > 1)
623
0
    S += "x" + utostr(NumVectors);
624
0
  S += "_t";
625
626
0
  if (Constant)
627
0
    S += " const";
628
0
  if (Pointer)
629
0
    S += " *";
630
631
0
  return S;
632
0
}
633
634
0
std::string Type::builtin_str() const {
635
0
  std::string S;
636
0
  if (isVoid())
637
0
    return "v";
638
639
0
  if (isPointer()) {
640
    // All pointers are void pointers.
641
0
    S = "v";
642
0
    if (isConstPointer())
643
0
      S += "C";
644
0
    S += "*";
645
0
    return S;
646
0
  } else if (isInteger())
647
0
    switch (ElementBitwidth) {
648
0
    case 8: S += "c"; break;
649
0
    case 16: S += "s"; break;
650
0
    case 32: S += "i"; break;
651
0
    case 64: S += "Wi"; break;
652
0
    case 128: S += "LLLi"; break;
653
0
    default: llvm_unreachable("Unhandled case!");
654
0
    }
655
0
  else if (isBFloat16()) {
656
0
    assert(ElementBitwidth == 16 && "BFloat16 can only be 16 bits");
657
0
    S += "y";
658
0
  } else
659
0
    switch (ElementBitwidth) {
660
0
    case 16: S += "h"; break;
661
0
    case 32: S += "f"; break;
662
0
    case 64: S += "d"; break;
663
0
    default: llvm_unreachable("Unhandled case!");
664
0
    }
665
666
  // FIXME: NECESSARY???????????????????????????????????????????????????????????????????????
667
0
  if (isChar() && !isPointer() && isSigned())
668
    // Make chars explicitly signed.
669
0
    S = "S" + S;
670
0
  else if (isInteger() && !isSigned())
671
0
    S = "U" + S;
672
673
  // Constant indices are "int", but have the "constant expression" modifier.
674
0
  if (isImmediate()) {
675
0
    assert(isInteger() && isSigned());
676
0
    S = "I" + S;
677
0
  }
678
679
0
  if (isScalar())
680
0
    return S;
681
682
0
  std::string Ret;
683
0
  for (unsigned I = 0; I < NumVectors; ++I)
684
0
    Ret += "V" + utostr(getNumElements()) + S;
685
686
0
  return Ret;
687
0
}
688
689
0
unsigned Type::getNeonEnum() const {
690
0
  unsigned Addend;
691
0
  switch (ElementBitwidth) {
692
0
  case 8: Addend = 0; break;
693
0
  case 16: Addend = 1; break;
694
0
  case 32: Addend = 2; break;
695
0
  case 64: Addend = 3; break;
696
0
  case 128: Addend = 4; break;
697
0
  default: llvm_unreachable("Unhandled element bitwidth!");
698
0
  }
699
700
0
  unsigned Base = (unsigned)NeonTypeFlags::Int8 + Addend;
701
0
  if (isPoly()) {
702
    // Adjustment needed because Poly32 doesn't exist.
703
0
    if (Addend >= 2)
704
0
      --Addend;
705
0
    Base = (unsigned)NeonTypeFlags::Poly8 + Addend;
706
0
  }
707
0
  if (isFloating()) {
708
0
    assert(Addend != 0 && "Float8 doesn't exist!");
709
0
    Base = (unsigned)NeonTypeFlags::Float16 + (Addend - 1);
710
0
  }
711
712
0
  if (isBFloat16()) {
713
0
    assert(Addend == 1 && "BFloat16 is only 16 bit");
714
0
    Base = (unsigned)NeonTypeFlags::BFloat16;
715
0
  }
716
717
0
  if (Bitwidth == 128)
718
0
    Base |= (unsigned)NeonTypeFlags::QuadFlag;
719
0
  if (isInteger() && !isSigned())
720
0
    Base |= (unsigned)NeonTypeFlags::UnsignedFlag;
721
722
0
  return Base;
723
0
}
724
725
0
Type Type::fromTypedefName(StringRef Name) {
726
0
  Type T;
727
0
  T.Kind = SInt;
728
729
0
  if (Name.front() == 'u') {
730
0
    T.Kind = UInt;
731
0
    Name = Name.drop_front();
732
0
  }
733
734
0
  if (Name.startswith("float")) {
735
0
    T.Kind = Float;
736
0
    Name = Name.drop_front(5);
737
0
  } else if (Name.startswith("poly")) {
738
0
    T.Kind = Poly;
739
0
    Name = Name.drop_front(4);
740
0
  } else if (Name.startswith("bfloat")) {
741
0
    T.Kind = BFloat16;
742
0
    Name = Name.drop_front(6);
743
0
  } else {
744
0
    assert(Name.startswith("int"));
745
0
    Name = Name.drop_front(3);
746
0
  }
747
748
0
  unsigned I = 0;
749
0
  for (I = 0; I < Name.size(); ++I) {
750
0
    if (!isdigit(Name[I]))
751
0
      break;
752
0
  }
753
0
  Name.substr(0, I).getAsInteger(10, T.ElementBitwidth);
754
0
  Name = Name.drop_front(I);
755
756
0
  T.Bitwidth = T.ElementBitwidth;
757
0
  T.NumVectors = 1;
758
759
0
  if (Name.front() == 'x') {
760
0
    Name = Name.drop_front();
761
0
    unsigned I = 0;
762
0
    for (I = 0; I < Name.size(); ++I) {
763
0
      if (!isdigit(Name[I]))
764
0
        break;
765
0
    }
766
0
    unsigned NumLanes;
767
0
    Name.substr(0, I).getAsInteger(10, NumLanes);
768
0
    Name = Name.drop_front(I);
769
0
    T.Bitwidth = T.ElementBitwidth * NumLanes;
770
0
  } else {
771
    // Was scalar.
772
0
    T.NumVectors = 0;
773
0
  }
774
0
  if (Name.front() == 'x') {
775
0
    Name = Name.drop_front();
776
0
    unsigned I = 0;
777
0
    for (I = 0; I < Name.size(); ++I) {
778
0
      if (!isdigit(Name[I]))
779
0
        break;
780
0
    }
781
0
    Name.substr(0, I).getAsInteger(10, T.NumVectors);
782
0
    Name = Name.drop_front(I);
783
0
  }
784
785
0
  assert(Name.startswith("_t") && "Malformed typedef!");
786
0
  return T;
787
0
}
788
789
0
void Type::applyTypespec(bool &Quad) {
790
0
  std::string S = TS;
791
0
  ScalarForMangling = false;
792
0
  Kind = SInt;
793
0
  ElementBitwidth = ~0U;
794
0
  NumVectors = 1;
795
796
0
  for (char I : S) {
797
0
    switch (I) {
798
0
    case 'S':
799
0
      ScalarForMangling = true;
800
0
      break;
801
0
    case 'H':
802
0
      NoManglingQ = true;
803
0
      Quad = true;
804
0
      break;
805
0
    case 'Q':
806
0
      Quad = true;
807
0
      break;
808
0
    case 'P':
809
0
      Kind = Poly;
810
0
      break;
811
0
    case 'U':
812
0
      Kind = UInt;
813
0
      break;
814
0
    case 'c':
815
0
      ElementBitwidth = 8;
816
0
      break;
817
0
    case 'h':
818
0
      Kind = Float;
819
0
      LLVM_FALLTHROUGH;
820
0
    case 's':
821
0
      ElementBitwidth = 16;
822
0
      break;
823
0
    case 'f':
824
0
      Kind = Float;
825
0
      LLVM_FALLTHROUGH;
826
0
    case 'i':
827
0
      ElementBitwidth = 32;
828
0
      break;
829
0
    case 'd':
830
0
      Kind = Float;
831
0
      LLVM_FALLTHROUGH;
832
0
    case 'l':
833
0
      ElementBitwidth = 64;
834
0
      break;
835
0
    case 'k':
836
0
      ElementBitwidth = 128;
837
      // Poly doesn't have a 128x1 type.
838
0
      if (isPoly())
839
0
        NumVectors = 0;
840
0
      break;
841
0
    case 'b':
842
0
      Kind = BFloat16;
843
0
      ElementBitwidth = 16;
844
0
      break;
845
0
    default:
846
0
      llvm_unreachable("Unhandled type code!");
847
0
    }
848
0
  }
849
0
  assert(ElementBitwidth != ~0U && "Bad element bitwidth!");
850
851
0
  Bitwidth = Quad ? 128 : 64;
852
0
}
853
854
0
void Type::applyModifiers(StringRef Mods) {
855
0
  bool AppliedQuad = false;
856
0
  applyTypespec(AppliedQuad);
857
858
0
  for (char Mod : Mods) {
859
0
    switch (Mod) {
860
0
    case '.':
861
0
      break;
862
0
    case 'v':
863
0
      Kind = Void;
864
0
      break;
865
0
    case 'S':
866
0
      Kind = SInt;
867
0
      break;
868
0
    case 'U':
869
0
      Kind = UInt;
870
0
      break;
871
0
    case 'B':
872
0
      Kind = BFloat16;
873
0
      ElementBitwidth = 16;
874
0
      break;
875
0
    case 'F':
876
0
      Kind = Float;
877
0
      break;
878
0
    case 'P':
879
0
      Kind = Poly;
880
0
      break;
881
0
    case '>':
882
0
      assert(ElementBitwidth < 128);
883
0
      ElementBitwidth *= 2;
884
0
      break;
885
0
    case '<':
886
0
      assert(ElementBitwidth > 8);
887
0
      ElementBitwidth /= 2;
888
0
      break;
889
0
    case '1':
890
0
      NumVectors = 0;
891
0
      break;
892
0
    case '2':
893
0
      NumVectors = 2;
894
0
      break;
895
0
    case '3':
896
0
      NumVectors = 3;
897
0
      break;
898
0
    case '4':
899
0
      NumVectors = 4;
900
0
      break;
901
0
    case '*':
902
0
      Pointer = true;
903
0
      break;
904
0
    case 'c':
905
0
      Constant = true;
906
0
      break;
907
0
    case 'Q':
908
0
      Bitwidth = 128;
909
0
      break;
910
0
    case 'q':
911
0
      Bitwidth = 64;
912
0
      break;
913
0
    case 'I':
914
0
      Kind = SInt;
915
0
      ElementBitwidth = Bitwidth = 32;
916
0
      NumVectors = 0;
917
0
      Immediate = true;
918
0
      break;
919
0
    case 'p':
920
0
      if (isPoly())
921
0
        Kind = UInt;
922
0
      break;
923
0
    case '!':
924
      // Key type, handled elsewhere.
925
0
      break;
926
0
    default:
927
0
      llvm_unreachable("Unhandled character!");
928
0
    }
929
0
  }
930
0
}
931
932
//===----------------------------------------------------------------------===//
933
// Intrinsic implementation
934
//===----------------------------------------------------------------------===//
935
936
0
StringRef Intrinsic::getNextModifiers(StringRef Proto, unsigned &Pos) const {
937
0
  if (Proto.size() == Pos)
938
0
    return StringRef();
939
0
  else if (Proto[Pos] != '(')
940
0
    return Proto.substr(Pos++, 1);
941
942
0
  size_t Start = Pos + 1;
943
0
  size_t End = Proto.find(')', Start);
944
0
  assert_with_loc(End != StringRef::npos, "unmatched modifier group paren");
945
0
  Pos = End + 1;
946
0
  return Proto.slice(Start, End);
947
0
}
948
949
0
std::string Intrinsic::getInstTypeCode(Type T, ClassKind CK) const {
950
0
  char typeCode = '\0';
951
0
  bool printNumber = true;
952
953
0
  if (CK == ClassB)
954
0
    return "";
955
956
0
  if (T.isBFloat16())
957
0
    return "bf16";
958
959
0
  if (T.isPoly())
960
0
    typeCode = 'p';
961
0
  else if (T.isInteger())
962
0
    typeCode = T.isSigned() ? 's' : 'u';
963
0
  else
964
0
    typeCode = 'f';
965
966
0
  if (CK == ClassI) {
967
0
    switch (typeCode) {
968
0
    default:
969
0
      break;
970
0
    case 's':
971
0
    case 'u':
972
0
    case 'p':
973
0
      typeCode = 'i';
974
0
      break;
975
0
    }
976
0
  }
977
0
  if (CK == ClassB) {
978
0
    typeCode = '\0';
979
0
  }
980
981
0
  std::string S;
982
0
  if (typeCode != '\0')
983
0
    S.push_back(typeCode);
984
0
  if (printNumber)
985
0
    S += utostr(T.getElementSizeInBits());
986
987
0
  return S;
988
0
}
989
990
0
std::string Intrinsic::getBuiltinTypeStr() {
991
0
  ClassKind LocalCK = getClassKind(true);
992
0
  std::string S;
993
994
0
  Type RetT = getReturnType();
995
0
  if ((LocalCK == ClassI || LocalCK == ClassW) && RetT.isScalar() &&
996
0
      !RetT.isFloating() && !RetT.isBFloat16())
997
0
    RetT.makeInteger(RetT.getElementSizeInBits(), false);
998
999
  // Since the return value must be one type, return a vector type of the
1000
  // appropriate width which we will bitcast.  An exception is made for
1001
  // returning structs of 2, 3, or 4 vectors which are returned in a sret-like
1002
  // fashion, storing them to a pointer arg.
1003
0
  if (RetT.getNumVectors() > 1) {
1004
0
    S += "vv*"; // void result with void* first argument
1005
0
  } else {
1006
0
    if (RetT.isPoly())
1007
0
      RetT.makeInteger(RetT.getElementSizeInBits(), false);
1008
0
    if (!RetT.isScalar() && RetT.isInteger() && !RetT.isSigned())
1009
0
      RetT.makeSigned();
1010
1011
0
    if (LocalCK == ClassB && RetT.isValue() && !RetT.isScalar())
1012
      // Cast to vector of 8-bit elements.
1013
0
      RetT.makeInteger(8, true);
1014
1015
0
    S += RetT.builtin_str();
1016
0
  }
1017
1018
0
  for (unsigned I = 0; I < getNumParams(); ++I) {
1019
0
    Type T = getParamType(I);
1020
0
    if (T.isPoly())
1021
0
      T.makeInteger(T.getElementSizeInBits(), false);
1022
1023
0
    if (LocalCK == ClassB && !T.isScalar())
1024
0
      T.makeInteger(8, true);
1025
    // Halves always get converted to 8-bit elements.
1026
0
    if (T.isHalf() && T.isVector() && !T.isScalarForMangling())
1027
0
      T.makeInteger(8, true);
1028
1029
0
    if (LocalCK == ClassI && T.isInteger())
1030
0
      T.makeSigned();
1031
1032
0
    if (hasImmediate() && getImmediateIdx() == I)
1033
0
      T.makeImmediate(32);
1034
1035
0
    S += T.builtin_str();
1036
0
  }
1037
1038
  // Extra constant integer to hold type class enum for this function, e.g. s8
1039
0
  if (LocalCK == ClassB)
1040
0
    S += "i";
1041
1042
0
  return S;
1043
0
}
1044
1045
0
std::string Intrinsic::getMangledName(bool ForceClassS) const {
1046
  // Check if the prototype has a scalar operand with the type of the vector
1047
  // elements.  If not, bitcasting the args will take care of arg checking.
1048
  // The actual signedness etc. will be taken care of with special enums.
1049
0
  ClassKind LocalCK = CK;
1050
0
  if (!protoHasScalar())
1051
0
    LocalCK = ClassB;
1052
1053
0
  return mangleName(Name, ForceClassS ? ClassS : LocalCK);
1054
0
}
1055
1056
0
std::string Intrinsic::mangleName(std::string Name, ClassKind LocalCK) const {
1057
0
  std::string typeCode = getInstTypeCode(BaseType, LocalCK);
1058
0
  std::string S = Name;
1059
1060
0
  if (Name == "vcvt_f16_f32" || Name == "vcvt_f32_f16" ||
1061
0
      Name == "vcvt_f32_f64" || Name == "vcvt_f64_f32" ||
1062
0
      Name == "vcvt_f32_bf16")
1063
0
    return Name;
1064
1065
0
  if (!typeCode.empty()) {
1066
    // If the name ends with _xN (N = 2,3,4), insert the typeCode before _xN.
1067
0
    if (Name.size() >= 3 && isdigit(Name.back()) &&
1068
0
        Name[Name.length() - 2] == 'x' && Name[Name.length() - 3] == '_')
1069
0
      S.insert(S.length() - 3, "_" + typeCode);
1070
0
    else
1071
0
      S += "_" + typeCode;
1072
0
  }
1073
1074
0
  if (BaseType != InBaseType) {
1075
    // A reinterpret - out the input base type at the end.
1076
0
    S += "_" + getInstTypeCode(InBaseType, LocalCK);
1077
0
  }
1078
1079
0
  if (LocalCK == ClassB)
1080
0
    S += "_v";
1081
1082
  // Insert a 'q' before the first '_' character so that it ends up before
1083
  // _lane or _n on vector-scalar operations.
1084
0
  if (BaseType.getSizeInBits() == 128 && !BaseType.noManglingQ()) {
1085
0
    size_t Pos = S.find('_');
1086
0
    S.insert(Pos, "q");
1087
0
  }
1088
1089
0
  char Suffix = '\0';
1090
0
  if (BaseType.isScalarForMangling()) {
1091
0
    switch (BaseType.getElementSizeInBits()) {
1092
0
    case 8: Suffix = 'b'; break;
1093
0
    case 16: Suffix = 'h'; break;
1094
0
    case 32: Suffix = 's'; break;
1095
0
    case 64: Suffix = 'd'; break;
1096
0
    default: llvm_unreachable("Bad suffix!");
1097
0
    }
1098
0
  }
1099
0
  if (Suffix != '\0') {
1100
0
    size_t Pos = S.find('_');
1101
0
    S.insert(Pos, &Suffix, 1);
1102
0
  }
1103
1104
0
  return S;
1105
0
}
1106
1107
0
std::string Intrinsic::replaceParamsIn(std::string S) {
1108
0
  while (S.find('$') != std::string::npos) {
1109
0
    size_t Pos = S.find('$');
1110
0
    size_t End = Pos + 1;
1111
0
    while (isalpha(S[End]))
1112
0
      ++End;
1113
1114
0
    std::string VarName = S.substr(Pos + 1, End - Pos - 1);
1115
0
    assert_with_loc(Variables.find(VarName) != Variables.end(),
1116
0
                    "Variable not defined!");
1117
0
    S.replace(Pos, End - Pos, Variables.find(VarName)->second.getName());
1118
0
  }
1119
1120
0
  return S;
1121
0
}
1122
1123
0
void Intrinsic::initVariables() {
1124
0
  Variables.clear();
1125
1126
  // Modify the TypeSpec per-argument to get a concrete Type, and create
1127
  // known variables for each.
1128
0
  for (unsigned I = 1; I < Types.size(); ++I) {
1129
0
    char NameC = '0' + (I - 1);
1130
0
    std::string Name = "p";
1131
0
    Name.push_back(NameC);
1132
1133
0
    Variables[Name] = Variable(Types[I], Name + VariablePostfix);
1134
0
  }
1135
0
  RetVar = Variable(Types[0], "ret" + VariablePostfix);
1136
0
}
1137
1138
0
void Intrinsic::emitPrototype(StringRef NamePrefix) {
1139
0
  if (UseMacro)
1140
0
    OS << "#define ";
1141
0
  else
1142
0
    OS << "__ai " << Types[0].str() << " ";
1143
1144
0
  OS << NamePrefix.str() << mangleName(Name, ClassS) << "(";
1145
1146
0
  for (unsigned I = 0; I < getNumParams(); ++I) {
1147
0
    if (I != 0)
1148
0
      OS << ", ";
1149
1150
0
    char NameC = '0' + I;
1151
0
    std::string Name = "p";
1152
0
    Name.push_back(NameC);
1153
0
    assert(Variables.find(Name) != Variables.end());
1154
0
    Variable &V = Variables[Name];
1155
1156
0
    if (!UseMacro)
1157
0
      OS << V.getType().str() << " ";
1158
0
    OS << V.getName();
1159
0
  }
1160
1161
0
  OS << ")";
1162
0
}
1163
1164
0
void Intrinsic::emitOpeningBrace() {
1165
0
  if (UseMacro)
1166
0
    OS << " __extension__ ({";
1167
0
  else
1168
0
    OS << " {";
1169
0
  emitNewLine();
1170
0
}
1171
1172
0
void Intrinsic::emitClosingBrace() {
1173
0
  if (UseMacro)
1174
0
    OS << "})";
1175
0
  else
1176
0
    OS << "}";
1177
0
}
1178
1179
0
void Intrinsic::emitNewLine() {
1180
0
  if (UseMacro)
1181
0
    OS << " \\\n";
1182
0
  else
1183
0
    OS << "\n";
1184
0
}
1185
1186
0
void Intrinsic::emitReverseVariable(Variable &Dest, Variable &Src) {
1187
0
  if (Dest.getType().getNumVectors() > 1) {
1188
0
    emitNewLine();
1189
1190
0
    for (unsigned K = 0; K < Dest.getType().getNumVectors(); ++K) {
1191
0
      OS << "  " << Dest.getName() << ".val[" << K << "] = "
1192
0
         << "__builtin_shufflevector("
1193
0
         << Src.getName() << ".val[" << K << "], "
1194
0
         << Src.getName() << ".val[" << K << "]";
1195
0
      for (int J = Dest.getType().getNumElements() - 1; J >= 0; --J)
1196
0
        OS << ", " << J;
1197
0
      OS << ");";
1198
0
      emitNewLine();
1199
0
    }
1200
0
  } else {
1201
0
    OS << "  " << Dest.getName()
1202
0
       << " = __builtin_shufflevector(" << Src.getName() << ", " << Src.getName();
1203
0
    for (int J = Dest.getType().getNumElements() - 1; J >= 0; --J)
1204
0
      OS << ", " << J;
1205
0
    OS << ");";
1206
0
    emitNewLine();
1207
0
  }
1208
0
}
1209
1210
0
void Intrinsic::emitArgumentReversal() {
1211
0
  if (isBigEndianSafe())
1212
0
    return;
1213
1214
  // Reverse all vector arguments.
1215
0
  for (unsigned I = 0; I < getNumParams(); ++I) {
1216
0
    std::string Name = "p" + utostr(I);
1217
0
    std::string NewName = "rev" + utostr(I);
1218
1219
0
    Variable &V = Variables[Name];
1220
0
    Variable NewV(V.getType(), NewName + VariablePostfix);
1221
1222
0
    if (!NewV.getType().isVector() || NewV.getType().getNumElements() == 1)
1223
0
      continue;
1224
1225
0
    OS << "  " << NewV.getType().str() << " " << NewV.getName() << ";";
1226
0
    emitReverseVariable(NewV, V);
1227
0
    V = NewV;
1228
0
  }
1229
0
}
1230
1231
0
void Intrinsic::emitReturnReversal() {
1232
0
  if (isBigEndianSafe())
1233
0
    return;
1234
0
  if (!getReturnType().isVector() || getReturnType().isVoid() ||
1235
0
      getReturnType().getNumElements() == 1)
1236
0
    return;
1237
0
  emitReverseVariable(RetVar, RetVar);
1238
0
}
1239
1240
0
void Intrinsic::emitShadowedArgs() {
1241
  // Macro arguments are not type-checked like inline function arguments,
1242
  // so assign them to local temporaries to get the right type checking.
1243
0
  if (!UseMacro)
1244
0
    return;
1245
1246
0
  for (unsigned I = 0; I < getNumParams(); ++I) {
1247
    // Do not create a temporary for an immediate argument.
1248
    // That would defeat the whole point of using a macro!
1249
0
    if (getParamType(I).isImmediate())
1250
0
      continue;
1251
    // Do not create a temporary for pointer arguments. The input
1252
    // pointer may have an alignment hint.
1253
0
    if (getParamType(I).isPointer())
1254
0
      continue;
1255
1256
0
    std::string Name = "p" + utostr(I);
1257
1258
0
    assert(Variables.find(Name) != Variables.end());
1259
0
    Variable &V = Variables[Name];
1260
1261
0
    std::string NewName = "s" + utostr(I);
1262
0
    Variable V2(V.getType(), NewName + VariablePostfix);
1263
1264
0
    OS << "  " << V2.getType().str() << " " << V2.getName() << " = "
1265
0
       << V.getName() << ";";
1266
0
    emitNewLine();
1267
1268
0
    V = V2;
1269
0
  }
1270
0
}
1271
1272
0
bool Intrinsic::protoHasScalar() const {
1273
0
  return llvm::any_of(
1274
0
      Types, [](const Type &T) { return T.isScalar() && !T.isImmediate(); });
1275
0
}
1276
1277
0
void Intrinsic::emitBodyAsBuiltinCall() {
1278
0
  std::string S;
1279
1280
  // If this builtin returns a struct 2, 3, or 4 vectors, pass it as an implicit
1281
  // sret-like argument.
1282
0
  bool SRet = getReturnType().getNumVectors() >= 2;
1283
1284
0
  StringRef N = Name;
1285
0
  ClassKind LocalCK = CK;
1286
0
  if (!protoHasScalar())
1287
0
    LocalCK = ClassB;
1288
1289
0
  if (!getReturnType().isVoid() && !SRet)
1290
0
    S += "(" + RetVar.getType().str() + ") ";
1291
1292
0
  S += "__builtin_neon_" + mangleName(std::string(N), LocalCK) + "(";
1293
1294
0
  if (SRet)
1295
0
    S += "&" + RetVar.getName() + ", ";
1296
1297
0
  for (unsigned I = 0; I < getNumParams(); ++I) {
1298
0
    Variable &V = Variables["p" + utostr(I)];
1299
0
    Type T = V.getType();
1300
1301
    // Handle multiple-vector values specially, emitting each subvector as an
1302
    // argument to the builtin.
1303
0
    if (T.getNumVectors() > 1) {
1304
      // Check if an explicit cast is needed.
1305
0
      std::string Cast;
1306
0
      if (LocalCK == ClassB) {
1307
0
        Type T2 = T;
1308
0
        T2.makeOneVector();
1309
0
        T2.makeInteger(8, /*Sign=*/true);
1310
0
        Cast = "(" + T2.str() + ")";
1311
0
      }
1312
1313
0
      for (unsigned J = 0; J < T.getNumVectors(); ++J)
1314
0
        S += Cast + V.getName() + ".val[" + utostr(J) + "], ";
1315
0
      continue;
1316
0
    }
1317
1318
0
    std::string Arg = V.getName();
1319
0
    Type CastToType = T;
1320
1321
    // Check if an explicit cast is needed.
1322
0
    if (CastToType.isVector() &&
1323
0
        (LocalCK == ClassB || (T.isHalf() && !T.isScalarForMangling()))) {
1324
0
      CastToType.makeInteger(8, true);
1325
0
      Arg = "(" + CastToType.str() + ")" + Arg;
1326
0
    } else if (CastToType.isVector() && LocalCK == ClassI) {
1327
0
      if (CastToType.isInteger())
1328
0
        CastToType.makeSigned();
1329
0
      Arg = "(" + CastToType.str() + ")" + Arg;
1330
0
    }
1331
1332
0
    S += Arg + ", ";
1333
0
  }
1334
1335
  // Extra constant integer to hold type class enum for this function, e.g. s8
1336
0
  if (getClassKind(true) == ClassB) {
1337
0
    S += utostr(getPolymorphicKeyType().getNeonEnum());
1338
0
  } else {
1339
    // Remove extraneous ", ".
1340
0
    S.pop_back();
1341
0
    S.pop_back();
1342
0
  }
1343
0
  S += ");";
1344
1345
0
  std::string RetExpr;
1346
0
  if (!SRet && !RetVar.getType().isVoid())
1347
0
    RetExpr = RetVar.getName() + " = ";
1348
1349
0
  OS << "  " << RetExpr << S;
1350
0
  emitNewLine();
1351
0
}
1352
1353
0
void Intrinsic::emitBody(StringRef CallPrefix) {
1354
0
  std::vector<std::string> Lines;
1355
1356
0
  assert(RetVar.getType() == Types[0]);
1357
  // Create a return variable, if we're not void.
1358
0
  if (!RetVar.getType().isVoid()) {
1359
0
    OS << "  " << RetVar.getType().str() << " " << RetVar.getName() << ";";
1360
0
    emitNewLine();
1361
0
  }
1362
1363
0
  if (!Body || Body->getValues().empty()) {
1364
    // Nothing specific to output - must output a builtin.
1365
0
    emitBodyAsBuiltinCall();
1366
0
    return;
1367
0
  }
1368
1369
  // We have a list of "things to output". The last should be returned.
1370
0
  for (auto *I : Body->getValues()) {
1371
0
    if (StringInit *SI = dyn_cast<StringInit>(I)) {
1372
0
      Lines.push_back(replaceParamsIn(SI->getAsString()));
1373
0
    } else if (DagInit *DI = dyn_cast<DagInit>(I)) {
1374
0
      DagEmitter DE(*this, CallPrefix);
1375
0
      Lines.push_back(DE.emitDag(DI).second + ";");
1376
0
    }
1377
0
  }
1378
1379
0
  assert(!Lines.empty() && "Empty def?");
1380
0
  if (!RetVar.getType().isVoid())
1381
0
    Lines.back().insert(0, RetVar.getName() + " = ");
1382
1383
0
  for (auto &L : Lines) {
1384
0
    OS << "  " << L;
1385
0
    emitNewLine();
1386
0
  }
1387
0
}
1388
1389
0
void Intrinsic::emitReturn() {
1390
0
  if (RetVar.getType().isVoid())
1391
0
    return;
1392
0
  if (UseMacro)
1393
0
    OS << "  " << RetVar.getName() << ";";
1394
0
  else
1395
0
    OS << "  return " << RetVar.getName() << ";";
1396
0
  emitNewLine();
1397
0
}
1398
1399
0
std::pair<Type, std::string> Intrinsic::DagEmitter::emitDag(DagInit *DI) {
1400
  // At this point we should only be seeing a def.
1401
0
  DefInit *DefI = cast<DefInit>(DI->getOperator());
1402
0
  std::string Op = DefI->getAsString();
1403
1404
0
  if (Op == "cast" || Op == "bitcast")
1405
0
    return emitDagCast(DI, Op == "bitcast");
1406
0
  if (Op == "shuffle")
1407
0
    return emitDagShuffle(DI);
1408
0
  if (Op == "dup")
1409
0
    return emitDagDup(DI);
1410
0
  if (Op == "dup_typed")
1411
0
    return emitDagDupTyped(DI);
1412
0
  if (Op == "splat")
1413
0
    return emitDagSplat(DI);
1414
0
  if (Op == "save_temp")
1415
0
    return emitDagSaveTemp(DI);
1416
0
  if (Op == "op")
1417
0
    return emitDagOp(DI);
1418
0
  if (Op == "call" || Op == "call_mangled")
1419
0
    return emitDagCall(DI, Op == "call_mangled");
1420
0
  if (Op == "name_replace")
1421
0
    return emitDagNameReplace(DI);
1422
0
  if (Op == "literal")
1423
0
    return emitDagLiteral(DI);
1424
0
  assert_with_loc(false, "Unknown operation!");
1425
0
  return std::make_pair(Type::getVoid(), "");
1426
0
}
1427
1428
0
std::pair<Type, std::string> Intrinsic::DagEmitter::emitDagOp(DagInit *DI) {
1429
0
  std::string Op = cast<StringInit>(DI->getArg(0))->getAsUnquotedString();
1430
0
  if (DI->getNumArgs() == 2) {
1431
    // Unary op.
1432
0
    std::pair<Type, std::string> R =
1433
0
        emitDagArg(DI->getArg(1), std::string(DI->getArgNameStr(1)));
1434
0
    return std::make_pair(R.first, Op + R.second);
1435
0
  } else {
1436
0
    assert(DI->getNumArgs() == 3 && "Can only handle unary and binary ops!");
1437
0
    std::pair<Type, std::string> R1 =
1438
0
        emitDagArg(DI->getArg(1), std::string(DI->getArgNameStr(1)));
1439
0
    std::pair<Type, std::string> R2 =
1440
0
        emitDagArg(DI->getArg(2), std::string(DI->getArgNameStr(2)));
1441
0
    assert_with_loc(R1.first == R2.first, "Argument type mismatch!");
1442
0
    return std::make_pair(R1.first, R1.second + " " + Op + " " + R2.second);
1443
0
  }
1444
0
}
1445
1446
std::pair<Type, std::string>
1447
0
Intrinsic::DagEmitter::emitDagCall(DagInit *DI, bool MatchMangledName) {
1448
0
  std::vector<Type> Types;
1449
0
  std::vector<std::string> Values;
1450
0
  for (unsigned I = 0; I < DI->getNumArgs() - 1; ++I) {
1451
0
    std::pair<Type, std::string> R =
1452
0
        emitDagArg(DI->getArg(I + 1), std::string(DI->getArgNameStr(I + 1)));
1453
0
    Types.push_back(R.first);
1454
0
    Values.push_back(R.second);
1455
0
  }
1456
1457
  // Look up the called intrinsic.
1458
0
  std::string N;
1459
0
  if (StringInit *SI = dyn_cast<StringInit>(DI->getArg(0)))
1460
0
    N = SI->getAsUnquotedString();
1461
0
  else
1462
0
    N = emitDagArg(DI->getArg(0), "").second;
1463
0
  Optional<std::string> MangledName;
1464
0
  if (MatchMangledName) {
1465
0
    if (Intr.getRecord()->getValueAsBit("isLaneQ"))
1466
0
      N += "q";
1467
0
    MangledName = Intr.mangleName(N, ClassS);
1468
0
  }
1469
0
  Intrinsic &Callee = Intr.Emitter.getIntrinsic(N, Types, MangledName);
1470
1471
  // Make sure the callee is known as an early def.
1472
0
  Callee.setNeededEarly();
1473
0
  Intr.Dependencies.insert(&Callee);
1474
1475
  // Now create the call itself.
1476
0
  std::string S;
1477
0
  if (!Callee.isBigEndianSafe())
1478
0
    S += CallPrefix.str();
1479
0
  S += Callee.getMangledName(true) + "(";
1480
0
  for (unsigned I = 0; I < DI->getNumArgs() - 1; ++I) {
1481
0
    if (I != 0)
1482
0
      S += ", ";
1483
0
    S += Values[I];
1484
0
  }
1485
0
  S += ")";
1486
1487
0
  return std::make_pair(Callee.getReturnType(), S);
1488
0
}
1489
1490
std::pair<Type, std::string> Intrinsic::DagEmitter::emitDagCast(DagInit *DI,
1491
0
                                                                bool IsBitCast){
1492
  // (cast MOD* VAL) -> cast VAL to type given by MOD.
1493
0
  std::pair<Type, std::string> R =
1494
0
      emitDagArg(DI->getArg(DI->getNumArgs() - 1),
1495
0
                 std::string(DI->getArgNameStr(DI->getNumArgs() - 1)));
1496
0
  Type castToType = R.first;
1497
0
  for (unsigned ArgIdx = 0; ArgIdx < DI->getNumArgs() - 1; ++ArgIdx) {
1498
1499
    // MOD can take several forms:
1500
    //   1. $X - take the type of parameter / variable X.
1501
    //   2. The value "R" - take the type of the return type.
1502
    //   3. a type string
1503
    //   4. The value "U" or "S" to switch the signedness.
1504
    //   5. The value "H" or "D" to half or double the bitwidth.
1505
    //   6. The value "8" to convert to 8-bit (signed) integer lanes.
1506
0
    if (!DI->getArgNameStr(ArgIdx).empty()) {
1507
0
      assert_with_loc(Intr.Variables.find(std::string(
1508
0
                          DI->getArgNameStr(ArgIdx))) != Intr.Variables.end(),
1509
0
                      "Variable not found");
1510
0
      castToType =
1511
0
          Intr.Variables[std::string(DI->getArgNameStr(ArgIdx))].getType();
1512
0
    } else {
1513
0
      StringInit *SI = dyn_cast<StringInit>(DI->getArg(ArgIdx));
1514
0
      assert_with_loc(SI, "Expected string type or $Name for cast type");
1515
1516
0
      if (SI->getAsUnquotedString() == "R") {
1517
0
        castToType = Intr.getReturnType();
1518
0
      } else if (SI->getAsUnquotedString() == "U") {
1519
0
        castToType.makeUnsigned();
1520
0
      } else if (SI->getAsUnquotedString() == "S") {
1521
0
        castToType.makeSigned();
1522
0
      } else if (SI->getAsUnquotedString() == "H") {
1523
0
        castToType.halveLanes();
1524
0
      } else if (SI->getAsUnquotedString() == "D") {
1525
0
        castToType.doubleLanes();
1526
0
      } else if (SI->getAsUnquotedString() == "8") {
1527
0
        castToType.makeInteger(8, true);
1528
0
      } else if (SI->getAsUnquotedString() == "32") {
1529
0
        castToType.make32BitElement();
1530
0
      } else {
1531
0
        castToType = Type::fromTypedefName(SI->getAsUnquotedString());
1532
0
        assert_with_loc(!castToType.isVoid(), "Unknown typedef");
1533
0
      }
1534
0
    }
1535
0
  }
1536
1537
0
  std::string S;
1538
0
  if (IsBitCast) {
1539
    // Emit a reinterpret cast. The second operand must be an lvalue, so create
1540
    // a temporary.
1541
0
    std::string N = "reint";
1542
0
    unsigned I = 0;
1543
0
    while (Intr.Variables.find(N) != Intr.Variables.end())
1544
0
      N = "reint" + utostr(++I);
1545
0
    Intr.Variables[N] = Variable(R.first, N + Intr.VariablePostfix);
1546
1547
0
    Intr.OS << R.first.str() << " " << Intr.Variables[N].getName() << " = "
1548
0
            << R.second << ";";
1549
0
    Intr.emitNewLine();
1550
1551
0
    S = "*(" + castToType.str() + " *) &" + Intr.Variables[N].getName() + "";
1552
0
  } else {
1553
    // Emit a normal (static) cast.
1554
0
    S = "(" + castToType.str() + ")(" + R.second + ")";
1555
0
  }
1556
1557
0
  return std::make_pair(castToType, S);
1558
0
}
1559
1560
0
std::pair<Type, std::string> Intrinsic::DagEmitter::emitDagShuffle(DagInit *DI){
1561
  // See the documentation in arm_neon.td for a description of these operators.
1562
0
  class LowHalf : public SetTheory::Operator {
1563
0
  public:
1564
0
    void apply(SetTheory &ST, DagInit *Expr, SetTheory::RecSet &Elts,
1565
0
               ArrayRef<SMLoc> Loc) override {
1566
0
      SetTheory::RecSet Elts2;
1567
0
      ST.evaluate(Expr->arg_begin(), Expr->arg_end(), Elts2, Loc);
1568
0
      Elts.insert(Elts2.begin(), Elts2.begin() + (Elts2.size() / 2));
1569
0
    }
1570
0
  };
1571
1572
0
  class HighHalf : public SetTheory::Operator {
1573
0
  public:
1574
0
    void apply(SetTheory &ST, DagInit *Expr, SetTheory::RecSet &Elts,
1575
0
               ArrayRef<SMLoc> Loc) override {
1576
0
      SetTheory::RecSet Elts2;
1577
0
      ST.evaluate(Expr->arg_begin(), Expr->arg_end(), Elts2, Loc);
1578
0
      Elts.insert(Elts2.begin() + (Elts2.size() / 2), Elts2.end());
1579
0
    }
1580
0
  };
1581
1582
0
  class Rev : public SetTheory::Operator {
1583
0
    unsigned ElementSize;
1584
1585
0
  public:
1586
0
    Rev(unsigned ElementSize) : ElementSize(ElementSize) {}
1587
1588
0
    void apply(SetTheory &ST, DagInit *Expr, SetTheory::RecSet &Elts,
1589
0
               ArrayRef<SMLoc> Loc) override {
1590
0
      SetTheory::RecSet Elts2;
1591
0
      ST.evaluate(Expr->arg_begin() + 1, Expr->arg_end(), Elts2, Loc);
1592
1593
0
      int64_t VectorSize = cast<IntInit>(Expr->getArg(0))->getValue();
1594
0
      VectorSize /= ElementSize;
1595
1596
0
      std::vector<Record *> Revved;
1597
0
      for (unsigned VI = 0; VI < Elts2.size(); VI += VectorSize) {
1598
0
        for (int LI = VectorSize - 1; LI >= 0; --LI) {
1599
0
          Revved.push_back(Elts2[VI + LI]);
1600
0
        }
1601
0
      }
1602
1603
0
      Elts.insert(Revved.begin(), Revved.end());
1604
0
    }
1605
0
  };
1606
1607
0
  class MaskExpander : public SetTheory::Expander {
1608
0
    unsigned N;
1609
1610
0
  public:
1611
0
    MaskExpander(unsigned N) : N(N) {}
1612
1613
0
    void expand(SetTheory &ST, Record *R, SetTheory::RecSet &Elts) override {
1614
0
      unsigned Addend = 0;
1615
0
      if (R->getName() == "mask0")
1616
0
        Addend = 0;
1617
0
      else if (R->getName() == "mask1")
1618
0
        Addend = N;
1619
0
      else
1620
0
        return;
1621
0
      for (unsigned I = 0; I < N; ++I)
1622
0
        Elts.insert(R->getRecords().getDef("sv" + utostr(I + Addend)));
1623
0
    }
1624
0
  };
1625
1626
  // (shuffle arg1, arg2, sequence)
1627
0
  std::pair<Type, std::string> Arg1 =
1628
0
      emitDagArg(DI->getArg(0), std::string(DI->getArgNameStr(0)));
1629
0
  std::pair<Type, std::string> Arg2 =
1630
0
      emitDagArg(DI->getArg(1), std::string(DI->getArgNameStr(1)));
1631
0
  assert_with_loc(Arg1.first == Arg2.first,
1632
0
                  "Different types in arguments to shuffle!");
1633
1634
0
  SetTheory ST;
1635
0
  SetTheory::RecSet Elts;
1636
0
  ST.addOperator("lowhalf", std::make_unique<LowHalf>());
1637
0
  ST.addOperator("highhalf", std::make_unique<HighHalf>());
1638
0
  ST.addOperator("rev",
1639
0
                 std::make_unique<Rev>(Arg1.first.getElementSizeInBits()));
1640
0
  ST.addExpander("MaskExpand",
1641
0
                 std::make_unique<MaskExpander>(Arg1.first.getNumElements()));
1642
0
  ST.evaluate(DI->getArg(2), Elts, None);
1643
1644
0
  std::string S = "__builtin_shufflevector(" + Arg1.second + ", " + Arg2.second;
1645
0
  for (auto &E : Elts) {
1646
0
    StringRef Name = E->getName();
1647
0
    assert_with_loc(Name.startswith("sv"),
1648
0
                    "Incorrect element kind in shuffle mask!");
1649
0
    S += ", " + Name.drop_front(2).str();
1650
0
  }
1651
0
  S += ")";
1652
1653
  // Recalculate the return type - the shuffle may have halved or doubled it.
1654
0
  Type T(Arg1.first);
1655
0
  if (Elts.size() > T.getNumElements()) {
1656
0
    assert_with_loc(
1657
0
        Elts.size() == T.getNumElements() * 2,
1658
0
        "Can only double or half the number of elements in a shuffle!");
1659
0
    T.doubleLanes();
1660
0
  } else if (Elts.size() < T.getNumElements()) {
1661
0
    assert_with_loc(
1662
0
        Elts.size() == T.getNumElements() / 2,
1663
0
        "Can only double or half the number of elements in a shuffle!");
1664
0
    T.halveLanes();
1665
0
  }
1666
1667
0
  return std::make_pair(T, S);
1668
0
}
1669
1670
0
std::pair<Type, std::string> Intrinsic::DagEmitter::emitDagDup(DagInit *DI) {
1671
0
  assert_with_loc(DI->getNumArgs() == 1, "dup() expects one argument");
1672
0
  std::pair<Type, std::string> A =
1673
0
      emitDagArg(DI->getArg(0), std::string(DI->getArgNameStr(0)));
1674
0
  assert_with_loc(A.first.isScalar(), "dup() expects a scalar argument");
1675
1676
0
  Type T = Intr.getBaseType();
1677
0
  assert_with_loc(T.isVector(), "dup() used but default type is scalar!");
1678
0
  std::string S = "(" + T.str() + ") {";
1679
0
  for (unsigned I = 0; I < T.getNumElements(); ++I) {
1680
0
    if (I != 0)
1681
0
      S += ", ";
1682
0
    S += A.second;
1683
0
  }
1684
0
  S += "}";
1685
1686
0
  return std::make_pair(T, S);
1687
0
}
1688
1689
0
std::pair<Type, std::string> Intrinsic::DagEmitter::emitDagDupTyped(DagInit *DI) {
1690
0
  assert_with_loc(DI->getNumArgs() == 2, "dup_typed() expects two arguments");
1691
0
  std::pair<Type, std::string> B =
1692
0
      emitDagArg(DI->getArg(1), std::string(DI->getArgNameStr(1)));
1693
0
  assert_with_loc(B.first.isScalar(),
1694
0
                  "dup_typed() requires a scalar as the second argument");
1695
0
  Type T;
1696
  // If the type argument is a constant string, construct the type directly.
1697
0
  if (StringInit *SI = dyn_cast<StringInit>(DI->getArg(0))) {
1698
0
    T = Type::fromTypedefName(SI->getAsUnquotedString());
1699
0
    assert_with_loc(!T.isVoid(), "Unknown typedef");
1700
0
  } else
1701
0
    T = emitDagArg(DI->getArg(0), std::string(DI->getArgNameStr(0))).first;
1702
1703
0
  assert_with_loc(T.isVector(), "dup_typed() used but target type is scalar!");
1704
0
  std::string S = "(" + T.str() + ") {";
1705
0
  for (unsigned I = 0; I < T.getNumElements(); ++I) {
1706
0
    if (I != 0)
1707
0
      S += ", ";
1708
0
    S += B.second;
1709
0
  }
1710
0
  S += "}";
1711
1712
0
  return std::make_pair(T, S);
1713
0
}
1714
1715
0
std::pair<Type, std::string> Intrinsic::DagEmitter::emitDagSplat(DagInit *DI) {
1716
0
  assert_with_loc(DI->getNumArgs() == 2, "splat() expects two arguments");
1717
0
  std::pair<Type, std::string> A =
1718
0
      emitDagArg(DI->getArg(0), std::string(DI->getArgNameStr(0)));
1719
0
  std::pair<Type, std::string> B =
1720
0
      emitDagArg(DI->getArg(1), std::string(DI->getArgNameStr(1)));
1721
1722
0
  assert_with_loc(B.first.isScalar(),
1723
0
                  "splat() requires a scalar int as the second argument");
1724
1725
0
  std::string S = "__builtin_shufflevector(" + A.second + ", " + A.second;
1726
0
  for (unsigned I = 0; I < Intr.getBaseType().getNumElements(); ++I) {
1727
0
    S += ", " + B.second;
1728
0
  }
1729
0
  S += ")";
1730
1731
0
  return std::make_pair(Intr.getBaseType(), S);
1732
0
}
1733
1734
0
std::pair<Type, std::string> Intrinsic::DagEmitter::emitDagSaveTemp(DagInit *DI) {
1735
0
  assert_with_loc(DI->getNumArgs() == 2, "save_temp() expects two arguments");
1736
0
  std::pair<Type, std::string> A =
1737
0
      emitDagArg(DI->getArg(1), std::string(DI->getArgNameStr(1)));
1738
1739
0
  assert_with_loc(!A.first.isVoid(),
1740
0
                  "Argument to save_temp() must have non-void type!");
1741
1742
0
  std::string N = std::string(DI->getArgNameStr(0));
1743
0
  assert_with_loc(!N.empty(),
1744
0
                  "save_temp() expects a name as the first argument");
1745
1746
0
  assert_with_loc(Intr.Variables.find(N) == Intr.Variables.end(),
1747
0
                  "Variable already defined!");
1748
0
  Intr.Variables[N] = Variable(A.first, N + Intr.VariablePostfix);
1749
1750
0
  std::string S =
1751
0
      A.first.str() + " " + Intr.Variables[N].getName() + " = " + A.second;
1752
1753
0
  return std::make_pair(Type::getVoid(), S);
1754
0
}
1755
1756
std::pair<Type, std::string>
1757
0
Intrinsic::DagEmitter::emitDagNameReplace(DagInit *DI) {
1758
0
  std::string S = Intr.Name;
1759
1760
0
  assert_with_loc(DI->getNumArgs() == 2, "name_replace requires 2 arguments!");
1761
0
  std::string ToReplace = cast<StringInit>(DI->getArg(0))->getAsUnquotedString();
1762
0
  std::string ReplaceWith = cast<StringInit>(DI->getArg(1))->getAsUnquotedString();
1763
1764
0
  size_t Idx = S.find(ToReplace);
1765
1766
0
  assert_with_loc(Idx != std::string::npos, "name should contain '" + ToReplace + "'!");
1767
0
  S.replace(Idx, ToReplace.size(), ReplaceWith);
1768
1769
0
  return std::make_pair(Type::getVoid(), S);
1770
0
}
1771
1772
0
std::pair<Type, std::string> Intrinsic::DagEmitter::emitDagLiteral(DagInit *DI){
1773
0
  std::string Ty = cast<StringInit>(DI->getArg(0))->getAsUnquotedString();
1774
0
  std::string Value = cast<StringInit>(DI->getArg(1))->getAsUnquotedString();
1775
0
  return std::make_pair(Type::fromTypedefName(Ty), Value);
1776
0
}
1777
1778
std::pair<Type, std::string>
1779
0
Intrinsic::DagEmitter::emitDagArg(Init *Arg, std::string ArgName) {
1780
0
  if (!ArgName.empty()) {
1781
0
    assert_with_loc(!Arg->isComplete(),
1782
0
                    "Arguments must either be DAGs or names, not both!");
1783
0
    assert_with_loc(Intr.Variables.find(ArgName) != Intr.Variables.end(),
1784
0
                    "Variable not defined!");
1785
0
    Variable &V = Intr.Variables[ArgName];
1786
0
    return std::make_pair(V.getType(), V.getName());
1787
0
  }
1788
1789
0
  assert(Arg && "Neither ArgName nor Arg?!");
1790
0
  DagInit *DI = dyn_cast<DagInit>(Arg);
1791
0
  assert_with_loc(DI, "Arguments must either be DAGs or names!");
1792
1793
0
  return emitDag(DI);
1794
0
}
1795
1796
0
std::string Intrinsic::generate() {
1797
  // Avoid duplicated code for big and little endian
1798
0
  if (isBigEndianSafe()) {
1799
0
    generateImpl(false, "", "");
1800
0
    return OS.str();
1801
0
  }
1802
  // Little endian intrinsics are simple and don't require any argument
1803
  // swapping.
1804
0
  OS << "#ifdef __LITTLE_ENDIAN__\n";
1805
1806
0
  generateImpl(false, "", "");
1807
1808
0
  OS << "#else\n";
1809
1810
  // Big endian intrinsics are more complex. The user intended these
1811
  // intrinsics to operate on a vector "as-if" loaded by (V)LDR,
1812
  // but we load as-if (V)LD1. So we should swap all arguments and
1813
  // swap the return value too.
1814
  //
1815
  // If we call sub-intrinsics, we should call a version that does
1816
  // not re-swap the arguments!
1817
0
  generateImpl(true, "", "__noswap_");
1818
1819
  // If we're needed early, create a non-swapping variant for
1820
  // big-endian.
1821
0
  if (NeededEarly) {
1822
0
    generateImpl(false, "__noswap_", "__noswap_");
1823
0
  }
1824
0
  OS << "#endif\n\n";
1825
1826
0
  return OS.str();
1827
0
}
1828
1829
void Intrinsic::generateImpl(bool ReverseArguments,
1830
0
                             StringRef NamePrefix, StringRef CallPrefix) {
1831
0
  CurrentRecord = R;
1832
1833
  // If we call a macro, our local variables may be corrupted due to
1834
  // lack of proper lexical scoping. So, add a globally unique postfix
1835
  // to every variable.
1836
  //
1837
  // indexBody() should have set up the Dependencies set by now.
1838
0
  for (auto *I : Dependencies)
1839
0
    if (I->UseMacro) {
1840
0
      VariablePostfix = "_" + utostr(Emitter.getUniqueNumber());
1841
0
      break;
1842
0
    }
1843
1844
0
  initVariables();
1845
1846
0
  emitPrototype(NamePrefix);
1847
1848
0
  if (IsUnavailable) {
1849
0
    OS << " __attribute__((unavailable));";
1850
0
  } else {
1851
0
    emitOpeningBrace();
1852
0
    emitShadowedArgs();
1853
0
    if (ReverseArguments)
1854
0
      emitArgumentReversal();
1855
0
    emitBody(CallPrefix);
1856
0
    if (ReverseArguments)
1857
0
      emitReturnReversal();
1858
0
    emitReturn();
1859
0
    emitClosingBrace();
1860
0
  }
1861
0
  OS << "\n";
1862
1863
0
  CurrentRecord = nullptr;
1864
0
}
1865
1866
0
void Intrinsic::indexBody() {
1867
0
  CurrentRecord = R;
1868
1869
0
  initVariables();
1870
0
  emitBody("");
1871
0
  OS.str("");
1872
1873
0
  CurrentRecord = nullptr;
1874
0
}
1875
1876
//===----------------------------------------------------------------------===//
1877
// NeonEmitter implementation
1878
//===----------------------------------------------------------------------===//
1879
1880
Intrinsic &NeonEmitter::getIntrinsic(StringRef Name, ArrayRef<Type> Types,
1881
0
                                     Optional<std::string> MangledName) {
1882
  // First, look up the name in the intrinsic map.
1883
0
  assert_with_loc(IntrinsicMap.find(Name.str()) != IntrinsicMap.end(),
1884
0
                  ("Intrinsic '" + Name + "' not found!").str());
1885
0
  auto &V = IntrinsicMap.find(Name.str())->second;
1886
0
  std::vector<Intrinsic *> GoodVec;
1887
1888
  // Create a string to print if we end up failing.
1889
0
  std::string ErrMsg = "looking up intrinsic '" + Name.str() + "(";
1890
0
  for (unsigned I = 0; I < Types.size(); ++I) {
1891
0
    if (I != 0)
1892
0
      ErrMsg += ", ";
1893
0
    ErrMsg += Types[I].str();
1894
0
  }
1895
0
  ErrMsg += ")'\n";
1896
0
  ErrMsg += "Available overloads:\n";
1897
1898
  // Now, look through each intrinsic implementation and see if the types are
1899
  // compatible.
1900
0
  for (auto &I : V) {
1901
0
    ErrMsg += "  - " + I.getReturnType().str() + " " + I.getMangledName();
1902
0
    ErrMsg += "(";
1903
0
    for (unsigned A = 0; A < I.getNumParams(); ++A) {
1904
0
      if (A != 0)
1905
0
        ErrMsg += ", ";
1906
0
      ErrMsg += I.getParamType(A).str();
1907
0
    }
1908
0
    ErrMsg += ")\n";
1909
1910
0
    if (MangledName && MangledName != I.getMangledName(true))
1911
0
      continue;
1912
1913
0
    if (I.getNumParams() != Types.size())
1914
0
      continue;
1915
1916
0
    unsigned ArgNum = 0;
1917
0
    bool MatchingArgumentTypes = llvm::all_of(Types, [&](const auto &Type) {
1918
0
      return Type == I.getParamType(ArgNum++);
1919
0
    });
1920
1921
0
    if (MatchingArgumentTypes)
1922
0
      GoodVec.push_back(&I);
1923
0
  }
1924
1925
0
  assert_with_loc(!GoodVec.empty(),
1926
0
                  "No compatible intrinsic found - " + ErrMsg);
1927
0
  assert_with_loc(GoodVec.size() == 1, "Multiple overloads found - " + ErrMsg);
1928
1929
0
  return *GoodVec.front();
1930
0
}
1931
1932
void NeonEmitter::createIntrinsic(Record *R,
1933
0
                                  SmallVectorImpl<Intrinsic *> &Out) {
1934
0
  std::string Name = std::string(R->getValueAsString("Name"));
1935
0
  std::string Proto = std::string(R->getValueAsString("Prototype"));
1936
0
  std::string Types = std::string(R->getValueAsString("Types"));
1937
0
  Record *OperationRec = R->getValueAsDef("Operation");
1938
0
  bool BigEndianSafe  = R->getValueAsBit("BigEndianSafe");
1939
0
  std::string Guard = std::string(R->getValueAsString("ArchGuard"));
1940
0
  bool IsUnavailable = OperationRec->getValueAsBit("Unavailable");
1941
0
  std::string CartesianProductWith = std::string(R->getValueAsString("CartesianProductWith"));
1942
1943
  // Set the global current record. This allows assert_with_loc to produce
1944
  // decent location information even when highly nested.
1945
0
  CurrentRecord = R;
1946
1947
0
  ListInit *Body = OperationRec->getValueAsListInit("Ops");
1948
1949
0
  std::vector<TypeSpec> TypeSpecs = TypeSpec::fromTypeSpecs(Types);
1950
1951
0
  ClassKind CK = ClassNone;
1952
0
  if (R->getSuperClasses().size() >= 2)
1953
0
    CK = ClassMap[R->getSuperClasses()[1].first];
1954
1955
0
  std::vector<std::pair<TypeSpec, TypeSpec>> NewTypeSpecs;
1956
0
  if (!CartesianProductWith.empty()) {
1957
0
    std::vector<TypeSpec> ProductTypeSpecs = TypeSpec::fromTypeSpecs(CartesianProductWith);
1958
0
    for (auto TS : TypeSpecs) {
1959
0
      Type DefaultT(TS, ".");
1960
0
      for (auto SrcTS : ProductTypeSpecs) {
1961
0
        Type DefaultSrcT(SrcTS, ".");
1962
0
        if (TS == SrcTS ||
1963
0
            DefaultSrcT.getSizeInBits() != DefaultT.getSizeInBits())
1964
0
          continue;
1965
0
        NewTypeSpecs.push_back(std::make_pair(TS, SrcTS));
1966
0
      }
1967
0
    }
1968
0
  } else {
1969
0
    for (auto TS : TypeSpecs) {
1970
0
      NewTypeSpecs.push_back(std::make_pair(TS, TS));
1971
0
    }
1972
0
  }
1973
1974
0
  llvm::sort(NewTypeSpecs);
1975
0
  NewTypeSpecs.erase(std::unique(NewTypeSpecs.begin(), NewTypeSpecs.end()),
1976
0
         NewTypeSpecs.end());
1977
0
  auto &Entry = IntrinsicMap[Name];
1978
1979
0
  for (auto &I : NewTypeSpecs) {
1980
0
    Entry.emplace_back(R, Name, Proto, I.first, I.second, CK, Body, *this,
1981
0
                       Guard, IsUnavailable, BigEndianSafe);
1982
0
    Out.push_back(&Entry.back());
1983
0
  }
1984
1985
0
  CurrentRecord = nullptr;
1986
0
}
1987
1988
/// genBuiltinsDef: Generate the BuiltinsARM.def and  BuiltinsAArch64.def
1989
/// declaration of builtins, checking for unique builtin declarations.
1990
void NeonEmitter::genBuiltinsDef(raw_ostream &OS,
1991
0
                                 SmallVectorImpl<Intrinsic *> &Defs) {
1992
0
  OS << "#ifdef GET_NEON_BUILTINS\n";
1993
1994
  // We only want to emit a builtin once, and we want to emit them in
1995
  // alphabetical order, so use a std::set.
1996
0
  std::set<std::string> Builtins;
1997
1998
0
  for (auto *Def : Defs) {
1999
0
    if (Def->hasBody())
2000
0
      continue;
2001
2002
0
    std::string S = "BUILTIN(__builtin_neon_" + Def->getMangledName() + ", \"";
2003
2004
0
    S += Def->getBuiltinTypeStr();
2005
0
    S += "\", \"n\")";
2006
2007
0
    Builtins.insert(S);
2008
0
  }
2009
2010
0
  for (auto &S : Builtins)
2011
0
    OS << S << "\n";
2012
0
  OS << "#endif\n\n";
2013
0
}
2014
2015
/// Generate the ARM and AArch64 overloaded type checking code for
2016
/// SemaChecking.cpp, checking for unique builtin declarations.
2017
void NeonEmitter::genOverloadTypeCheckCode(raw_ostream &OS,
2018
0
                                           SmallVectorImpl<Intrinsic *> &Defs) {
2019
0
  OS << "#ifdef GET_NEON_OVERLOAD_CHECK\n";
2020
2021
  // We record each overload check line before emitting because subsequent Inst
2022
  // definitions may extend the number of permitted types (i.e. augment the
2023
  // Mask). Use std::map to avoid sorting the table by hash number.
2024
0
  struct OverloadInfo {
2025
0
    uint64_t Mask;
2026
0
    int PtrArgNum;
2027
0
    bool HasConstPtr;
2028
0
    OverloadInfo() : Mask(0ULL), PtrArgNum(0), HasConstPtr(false) {}
2029
0
  };
2030
0
  std::map<std::string, OverloadInfo> OverloadMap;
2031
2032
0
  for (auto *Def : Defs) {
2033
    // If the def has a body (that is, it has Operation DAGs), it won't call
2034
    // __builtin_neon_* so we don't need to generate a definition for it.
2035
0
    if (Def->hasBody())
2036
0
      continue;
2037
    // Functions which have a scalar argument cannot be overloaded, no need to
2038
    // check them if we are emitting the type checking code.
2039
0
    if (Def->protoHasScalar())
2040
0
      continue;
2041
2042
0
    uint64_t Mask = 0ULL;
2043
0
    Mask |= 1ULL << Def->getPolymorphicKeyType().getNeonEnum();
2044
2045
    // Check if the function has a pointer or const pointer argument.
2046
0
    int PtrArgNum = -1;
2047
0
    bool HasConstPtr = false;
2048
0
    for (unsigned I = 0; I < Def->getNumParams(); ++I) {
2049
0
      const auto &Type = Def->getParamType(I);
2050
0
      if (Type.isPointer()) {
2051
0
        PtrArgNum = I;
2052
0
        HasConstPtr = Type.isConstPointer();
2053
0
      }
2054
0
    }
2055
2056
    // For sret builtins, adjust the pointer argument index.
2057
0
    if (PtrArgNum >= 0 && Def->getReturnType().getNumVectors() > 1)
2058
0
      PtrArgNum += 1;
2059
2060
0
    std::string Name = Def->getName();
2061
    // Omit type checking for the pointer arguments of vld1_lane, vld1_dup,
2062
    // and vst1_lane intrinsics.  Using a pointer to the vector element
2063
    // type with one of those operations causes codegen to select an aligned
2064
    // load/store instruction.  If you want an unaligned operation,
2065
    // the pointer argument needs to have less alignment than element type,
2066
    // so just accept any pointer type.
2067
0
    if (Name == "vld1_lane" || Name == "vld1_dup" || Name == "vst1_lane") {
2068
0
      PtrArgNum = -1;
2069
0
      HasConstPtr = false;
2070
0
    }
2071
2072
0
    if (Mask) {
2073
0
      std::string Name = Def->getMangledName();
2074
0
      OverloadMap.insert(std::make_pair(Name, OverloadInfo()));
2075
0
      OverloadInfo &OI = OverloadMap[Name];
2076
0
      OI.Mask |= Mask;
2077
0
      OI.PtrArgNum |= PtrArgNum;
2078
0
      OI.HasConstPtr = HasConstPtr;
2079
0
    }
2080
0
  }
2081
2082
0
  for (auto &I : OverloadMap) {
2083
0
    OverloadInfo &OI = I.second;
2084
2085
0
    OS << "case NEON::BI__builtin_neon_" << I.first << ": ";
2086
0
    OS << "mask = 0x" << Twine::utohexstr(OI.Mask) << "ULL";
2087
0
    if (OI.PtrArgNum >= 0)
2088
0
      OS << "; PtrArgNum = " << OI.PtrArgNum;
2089
0
    if (OI.HasConstPtr)
2090
0
      OS << "; HasConstPtr = true";
2091
0
    OS << "; break;\n";
2092
0
  }
2093
0
  OS << "#endif\n\n";
2094
0
}
2095
2096
void NeonEmitter::genIntrinsicRangeCheckCode(raw_ostream &OS,
2097
0
                                        SmallVectorImpl<Intrinsic *> &Defs) {
2098
0
  OS << "#ifdef GET_NEON_IMMEDIATE_CHECK\n";
2099
2100
0
  std::set<std::string> Emitted;
2101
2102
0
  for (auto *Def : Defs) {
2103
0
    if (Def->hasBody())
2104
0
      continue;
2105
    // Functions which do not have an immediate do not need to have range
2106
    // checking code emitted.
2107
0
    if (!Def->hasImmediate())
2108
0
      continue;
2109
0
    if (Emitted.find(Def->getMangledName()) != Emitted.end())
2110
0
      continue;
2111
2112
0
    std::string LowerBound, UpperBound;
2113
2114
0
    Record *R = Def->getRecord();
2115
0
    if (R->getValueAsBit("isVXAR")) {
2116
      //VXAR takes an immediate in the range [0, 63]
2117
0
      LowerBound = "0";
2118
0
      UpperBound = "63";
2119
0
    } else if (R->getValueAsBit("isVCVT_N")) {
2120
      // VCVT between floating- and fixed-point values takes an immediate
2121
      // in the range [1, 32) for f32 or [1, 64) for f64 or [1, 16) for f16.
2122
0
      LowerBound = "1";
2123
0
    if (Def->getBaseType().getElementSizeInBits() == 16 ||
2124
0
      Def->getName().find('h') != std::string::npos)
2125
    // VCVTh operating on FP16 intrinsics in range [1, 16)
2126
0
    UpperBound = "15";
2127
0
    else if (Def->getBaseType().getElementSizeInBits() == 32)
2128
0
        UpperBound = "31";
2129
0
    else
2130
0
        UpperBound = "63";
2131
0
    } else if (R->getValueAsBit("isScalarShift")) {
2132
      // Right shifts have an 'r' in the name, left shifts do not. Convert
2133
      // instructions have the same bounds and right shifts.
2134
0
      if (Def->getName().find('r') != std::string::npos ||
2135
0
          Def->getName().find("cvt") != std::string::npos)
2136
0
        LowerBound = "1";
2137
2138
0
      UpperBound = utostr(Def->getReturnType().getElementSizeInBits() - 1);
2139
0
    } else if (R->getValueAsBit("isShift")) {
2140
      // Builtins which are overloaded by type will need to have their upper
2141
      // bound computed at Sema time based on the type constant.
2142
2143
      // Right shifts have an 'r' in the name, left shifts do not.
2144
0
      if (Def->getName().find('r') != std::string::npos)
2145
0
        LowerBound = "1";
2146
0
      UpperBound = "RFT(TV, true)";
2147
0
    } else if (Def->getClassKind(true) == ClassB) {
2148
      // ClassB intrinsics have a type (and hence lane number) that is only
2149
      // known at runtime.
2150
0
      if (R->getValueAsBit("isLaneQ"))
2151
0
        UpperBound = "RFT(TV, false, true)";
2152
0
      else
2153
0
        UpperBound = "RFT(TV, false, false)";
2154
0
    } else {
2155
      // The immediate generally refers to a lane in the preceding argument.
2156
0
      assert(Def->getImmediateIdx() > 0);
2157
0
      Type T = Def->getParamType(Def->getImmediateIdx() - 1);
2158
0
      UpperBound = utostr(T.getNumElements() - 1);
2159
0
    }
2160
2161
    // Calculate the index of the immediate that should be range checked.
2162
0
    unsigned Idx = Def->getNumParams();
2163
0
    if (Def->hasImmediate())
2164
0
      Idx = Def->getGeneratedParamIdx(Def->getImmediateIdx());
2165
2166
0
    OS << "case NEON::BI__builtin_neon_" << Def->getMangledName() << ": "
2167
0
       << "i = " << Idx << ";";
2168
0
    if (!LowerBound.empty())
2169
0
      OS << " l = " << LowerBound << ";";
2170
0
    if (!UpperBound.empty())
2171
0
      OS << " u = " << UpperBound << ";";
2172
0
    OS << " break;\n";
2173
2174
0
    Emitted.insert(Def->getMangledName());
2175
0
  }
2176
2177
0
  OS << "#endif\n\n";
2178
0
}
2179
2180
/// runHeader - Emit a file with sections defining:
2181
/// 1. the NEON section of BuiltinsARM.def and BuiltinsAArch64.def.
2182
/// 2. the SemaChecking code for the type overload checking.
2183
/// 3. the SemaChecking code for validation of intrinsic immediate arguments.
2184
0
void NeonEmitter::runHeader(raw_ostream &OS) {
2185
0
  std::vector<Record *> RV = Records.getAllDerivedDefinitions("Inst");
2186
2187
0
  SmallVector<Intrinsic *, 128> Defs;
2188
0
  for (auto *R : RV)
2189
0
    createIntrinsic(R, Defs);
2190
2191
  // Generate shared BuiltinsXXX.def
2192
0
  genBuiltinsDef(OS, Defs);
2193
2194
  // Generate ARM overloaded type checking code for SemaChecking.cpp
2195
0
  genOverloadTypeCheckCode(OS, Defs);
2196
2197
  // Generate ARM range checking code for shift/lane immediates.
2198
0
  genIntrinsicRangeCheckCode(OS, Defs);
2199
0
}
2200
2201
0
static void emitNeonTypeDefs(const std::string& types, raw_ostream &OS) {
2202
0
  std::string TypedefTypes(types);
2203
0
  std::vector<TypeSpec> TDTypeVec = TypeSpec::fromTypeSpecs(TypedefTypes);
2204
2205
  // Emit vector typedefs.
2206
0
  bool InIfdef = false;
2207
0
  for (auto &TS : TDTypeVec) {
2208
0
    bool IsA64 = false;
2209
0
    Type T(TS, ".");
2210
0
    if (T.isDouble())
2211
0
      IsA64 = true;
2212
2213
0
    if (InIfdef && !IsA64) {
2214
0
      OS << "#endif\n";
2215
0
      InIfdef = false;
2216
0
    }
2217
0
    if (!InIfdef && IsA64) {
2218
0
      OS << "#ifdef __aarch64__\n";
2219
0
      InIfdef = true;
2220
0
    }
2221
2222
0
    if (T.isPoly())
2223
0
      OS << "typedef __attribute__((neon_polyvector_type(";
2224
0
    else
2225
0
      OS << "typedef __attribute__((neon_vector_type(";
2226
2227
0
    Type T2 = T;
2228
0
    T2.makeScalar();
2229
0
    OS << T.getNumElements() << "))) ";
2230
0
    OS << T2.str();
2231
0
    OS << " " << T.str() << ";\n";
2232
0
  }
2233
0
  if (InIfdef)
2234
0
    OS << "#endif\n";
2235
0
  OS << "\n";
2236
2237
  // Emit struct typedefs.
2238
0
  InIfdef = false;
2239
0
  for (unsigned NumMembers = 2; NumMembers <= 4; ++NumMembers) {
2240
0
    for (auto &TS : TDTypeVec) {
2241
0
      bool IsA64 = false;
2242
0
      Type T(TS, ".");
2243
0
      if (T.isDouble())
2244
0
        IsA64 = true;
2245
2246
0
      if (InIfdef && !IsA64) {
2247
0
        OS << "#endif\n";
2248
0
        InIfdef = false;
2249
0
      }
2250
0
      if (!InIfdef && IsA64) {
2251
0
        OS << "#ifdef __aarch64__\n";
2252
0
        InIfdef = true;
2253
0
      }
2254
2255
0
      const char Mods[] = { static_cast<char>('2' + (NumMembers - 2)), 0};
2256
0
      Type VT(TS, Mods);
2257
0
      OS << "typedef struct " << VT.str() << " {\n";
2258
0
      OS << "  " << T.str() << " val";
2259
0
      OS << "[" << NumMembers << "]";
2260
0
      OS << ";\n} ";
2261
0
      OS << VT.str() << ";\n";
2262
0
      OS << "\n";
2263
0
    }
2264
0
  }
2265
0
  if (InIfdef)
2266
0
    OS << "#endif\n";
2267
0
}
2268
2269
/// run - Read the records in arm_neon.td and output arm_neon.h.  arm_neon.h
2270
/// is comprised of type definitions and function declarations.
2271
0
void NeonEmitter::run(raw_ostream &OS) {
2272
0
  OS << "/*===---- arm_neon.h - ARM Neon intrinsics "
2273
0
        "------------------------------"
2274
0
        "---===\n"
2275
0
        " *\n"
2276
0
        " * Permission is hereby granted, free of charge, to any person "
2277
0
        "obtaining "
2278
0
        "a copy\n"
2279
0
        " * of this software and associated documentation files (the "
2280
0
        "\"Software\"),"
2281
0
        " to deal\n"
2282
0
        " * in the Software without restriction, including without limitation "
2283
0
        "the "
2284
0
        "rights\n"
2285
0
        " * to use, copy, modify, merge, publish, distribute, sublicense, "
2286
0
        "and/or sell\n"
2287
0
        " * copies of the Software, and to permit persons to whom the Software "
2288
0
        "is\n"
2289
0
        " * furnished to do so, subject to the following conditions:\n"
2290
0
        " *\n"
2291
0
        " * The above copyright notice and this permission notice shall be "
2292
0
        "included in\n"
2293
0
        " * all copies or substantial portions of the Software.\n"
2294
0
        " *\n"
2295
0
        " * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, "
2296
0
        "EXPRESS OR\n"
2297
0
        " * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF "
2298
0
        "MERCHANTABILITY,\n"
2299
0
        " * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT "
2300
0
        "SHALL THE\n"
2301
0
        " * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR "
2302
0
        "OTHER\n"
2303
0
        " * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, "
2304
0
        "ARISING FROM,\n"
2305
0
        " * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER "
2306
0
        "DEALINGS IN\n"
2307
0
        " * THE SOFTWARE.\n"
2308
0
        " *\n"
2309
0
        " *===-----------------------------------------------------------------"
2310
0
        "---"
2311
0
        "---===\n"
2312
0
        " */\n\n";
2313
2314
0
  OS << "#ifndef __ARM_NEON_H\n";
2315
0
  OS << "#define __ARM_NEON_H\n\n";
2316
2317
0
  OS << "#ifndef __ARM_FP\n";
2318
0
  OS << "#error \"NEON intrinsics not available with the soft-float ABI. "
2319
0
        "Please use -mfloat-abi=softfp or -mfloat-abi=hard\"\n";
2320
0
  OS << "#else\n\n";
2321
2322
0
  OS << "#if !defined(__ARM_NEON)\n";
2323
0
  OS << "#error \"NEON support not enabled\"\n";
2324
0
  OS << "#else\n\n";
2325
2326
0
  OS << "#include <stdint.h>\n\n";
2327
2328
0
  OS << "#ifdef __ARM_FEATURE_BF16\n";
2329
0
  OS << "#include <arm_bf16.h>\n";
2330
0
  OS << "typedef __bf16 bfloat16_t;\n";
2331
0
  OS << "#endif\n\n";
2332
2333
  // Emit NEON-specific scalar typedefs.
2334
0
  OS << "typedef float float32_t;\n";
2335
0
  OS << "typedef __fp16 float16_t;\n";
2336
2337
0
  OS << "#ifdef __aarch64__\n";
2338
0
  OS << "typedef double float64_t;\n";
2339
0
  OS << "#endif\n\n";
2340
2341
  // For now, signedness of polynomial types depends on target
2342
0
  OS << "#ifdef __aarch64__\n";
2343
0
  OS << "typedef uint8_t poly8_t;\n";
2344
0
  OS << "typedef uint16_t poly16_t;\n";
2345
0
  OS << "typedef uint64_t poly64_t;\n";
2346
0
  OS << "typedef __uint128_t poly128_t;\n";
2347
0
  OS << "#else\n";
2348
0
  OS << "typedef int8_t poly8_t;\n";
2349
0
  OS << "typedef int16_t poly16_t;\n";
2350
0
  OS << "typedef int64_t poly64_t;\n";
2351
0
  OS << "#endif\n";
2352
2353
0
  emitNeonTypeDefs("cQcsQsiQilQlUcQUcUsQUsUiQUiUlQUlhQhfQfdQdPcQPcPsQPsPlQPl", OS);
2354
2355
0
  OS << "#ifdef __ARM_FEATURE_BF16\n";
2356
0
  emitNeonTypeDefs("bQb", OS);
2357
0
  OS << "#endif\n\n";
2358
2359
0
  OS << "#define __ai static __inline__ __attribute__((__always_inline__, "
2360
0
        "__nodebug__))\n\n";
2361
2362
0
  SmallVector<Intrinsic *, 128> Defs;
2363
0
  std::vector<Record *> RV = Records.getAllDerivedDefinitions("Inst");
2364
0
  for (auto *R : RV)
2365
0
    createIntrinsic(R, Defs);
2366
2367
0
  for (auto *I : Defs)
2368
0
    I->indexBody();
2369
2370
0
  llvm::stable_sort(Defs, llvm::deref<std::less<>>());
2371
2372
  // Only emit a def when its requirements have been met.
2373
  // FIXME: This loop could be made faster, but it's fast enough for now.
2374
0
  bool MadeProgress = true;
2375
0
  std::string InGuard;
2376
0
  while (!Defs.empty() && MadeProgress) {
2377
0
    MadeProgress = false;
2378
2379
0
    for (SmallVector<Intrinsic *, 128>::iterator I = Defs.begin();
2380
0
         I != Defs.end(); /*No step*/) {
2381
0
      bool DependenciesSatisfied = true;
2382
0
      for (auto *II : (*I)->getDependencies()) {
2383
0
        if (llvm::is_contained(Defs, II))
2384
0
          DependenciesSatisfied = false;
2385
0
      }
2386
0
      if (!DependenciesSatisfied) {
2387
        // Try the next one.
2388
0
        ++I;
2389
0
        continue;
2390
0
      }
2391
2392
      // Emit #endif/#if pair if needed.
2393
0
      if ((*I)->getGuard() != InGuard) {
2394
0
        if (!InGuard.empty())
2395
0
          OS << "#endif\n";
2396
0
        InGuard = (*I)->getGuard();
2397
0
        if (!InGuard.empty())
2398
0
          OS << "#if " << InGuard << "\n";
2399
0
      }
2400
2401
      // Actually generate the intrinsic code.
2402
0
      OS << (*I)->generate();
2403
2404
0
      MadeProgress = true;
2405
0
      I = Defs.erase(I);
2406
0
    }
2407
0
  }
2408
0
  assert(Defs.empty() && "Some requirements were not satisfied!");
2409
0
  if (!InGuard.empty())
2410
0
    OS << "#endif\n";
2411
2412
0
  OS << "\n";
2413
0
  OS << "#undef __ai\n\n";
2414
0
  OS << "#endif /* if !defined(__ARM_NEON) */\n";
2415
0
  OS << "#endif /* ifndef __ARM_FP */\n";
2416
0
  OS << "#endif /* __ARM_NEON_H */\n";
2417
0
}
2418
2419
/// run - Read the records in arm_fp16.td and output arm_fp16.h.  arm_fp16.h
2420
/// is comprised of type definitions and function declarations.
2421
0
void NeonEmitter::runFP16(raw_ostream &OS) {
2422
0
  OS << "/*===---- arm_fp16.h - ARM FP16 intrinsics "
2423
0
        "------------------------------"
2424
0
        "---===\n"
2425
0
        " *\n"
2426
0
        " * Permission is hereby granted, free of charge, to any person "
2427
0
        "obtaining a copy\n"
2428
0
        " * of this software and associated documentation files (the "
2429
0
        "\"Software\"), to deal\n"
2430
0
        " * in the Software without restriction, including without limitation "
2431
0
        "the rights\n"
2432
0
        " * to use, copy, modify, merge, publish, distribute, sublicense, "
2433
0
        "and/or sell\n"
2434
0
        " * copies of the Software, and to permit persons to whom the Software "
2435
0
        "is\n"
2436
0
        " * furnished to do so, subject to the following conditions:\n"
2437
0
        " *\n"
2438
0
        " * The above copyright notice and this permission notice shall be "
2439
0
        "included in\n"
2440
0
        " * all copies or substantial portions of the Software.\n"
2441
0
        " *\n"
2442
0
        " * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, "
2443
0
        "EXPRESS OR\n"
2444
0
        " * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF "
2445
0
        "MERCHANTABILITY,\n"
2446
0
        " * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT "
2447
0
        "SHALL THE\n"
2448
0
        " * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR "
2449
0
        "OTHER\n"
2450
0
        " * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, "
2451
0
        "ARISING FROM,\n"
2452
0
        " * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER "
2453
0
        "DEALINGS IN\n"
2454
0
        " * THE SOFTWARE.\n"
2455
0
        " *\n"
2456
0
        " *===-----------------------------------------------------------------"
2457
0
        "---"
2458
0
        "---===\n"
2459
0
        " */\n\n";
2460
2461
0
  OS << "#ifndef __ARM_FP16_H\n";
2462
0
  OS << "#define __ARM_FP16_H\n\n";
2463
2464
0
  OS << "#include <stdint.h>\n\n";
2465
2466
0
  OS << "typedef __fp16 float16_t;\n";
2467
2468
0
  OS << "#define __ai static __inline__ __attribute__((__always_inline__, "
2469
0
        "__nodebug__))\n\n";
2470
2471
0
  SmallVector<Intrinsic *, 128> Defs;
2472
0
  std::vector<Record *> RV = Records.getAllDerivedDefinitions("Inst");
2473
0
  for (auto *R : RV)
2474
0
    createIntrinsic(R, Defs);
2475
2476
0
  for (auto *I : Defs)
2477
0
    I->indexBody();
2478
2479
0
  llvm::stable_sort(Defs, llvm::deref<std::less<>>());
2480
2481
  // Only emit a def when its requirements have been met.
2482
  // FIXME: This loop could be made faster, but it's fast enough for now.
2483
0
  bool MadeProgress = true;
2484
0
  std::string InGuard;
2485
0
  while (!Defs.empty() && MadeProgress) {
2486
0
    MadeProgress = false;
2487
2488
0
    for (SmallVector<Intrinsic *, 128>::iterator I = Defs.begin();
2489
0
         I != Defs.end(); /*No step*/) {
2490
0
      bool DependenciesSatisfied = true;
2491
0
      for (auto *II : (*I)->getDependencies()) {
2492
0
        if (llvm::is_contained(Defs, II))
2493
0
          DependenciesSatisfied = false;
2494
0
      }
2495
0
      if (!DependenciesSatisfied) {
2496
        // Try the next one.
2497
0
        ++I;
2498
0
        continue;
2499
0
      }
2500
2501
      // Emit #endif/#if pair if needed.
2502
0
      if ((*I)->getGuard() != InGuard) {
2503
0
        if (!InGuard.empty())
2504
0
          OS << "#endif\n";
2505
0
        InGuard = (*I)->getGuard();
2506
0
        if (!InGuard.empty())
2507
0
          OS << "#if " << InGuard << "\n";
2508
0
      }
2509
2510
      // Actually generate the intrinsic code.
2511
0
      OS << (*I)->generate();
2512
2513
0
      MadeProgress = true;
2514
0
      I = Defs.erase(I);
2515
0
    }
2516
0
  }
2517
0
  assert(Defs.empty() && "Some requirements were not satisfied!");
2518
0
  if (!InGuard.empty())
2519
0
    OS << "#endif\n";
2520
2521
0
  OS << "\n";
2522
0
  OS << "#undef __ai\n\n";
2523
0
  OS << "#endif /* __ARM_FP16_H */\n";
2524
0
}
2525
2526
0
void NeonEmitter::runBF16(raw_ostream &OS) {
2527
0
  OS << "/*===---- arm_bf16.h - ARM BF16 intrinsics "
2528
0
        "-----------------------------------===\n"
2529
0
        " *\n"
2530
0
        " *\n"
2531
0
        " * Part of the LLVM Project, under the Apache License v2.0 with LLVM "
2532
0
        "Exceptions.\n"
2533
0
        " * See https://llvm.org/LICENSE.txt for license information.\n"
2534
0
        " * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n"
2535
0
        " *\n"
2536
0
        " *===-----------------------------------------------------------------"
2537
0
        "------===\n"
2538
0
        " */\n\n";
2539
2540
0
  OS << "#ifndef __ARM_BF16_H\n";
2541
0
  OS << "#define __ARM_BF16_H\n\n";
2542
2543
0
  OS << "typedef __bf16 bfloat16_t;\n";
2544
2545
0
  OS << "#define __ai static __inline__ __attribute__((__always_inline__, "
2546
0
        "__nodebug__))\n\n";
2547
2548
0
  SmallVector<Intrinsic *, 128> Defs;
2549
0
  std::vector<Record *> RV = Records.getAllDerivedDefinitions("Inst");
2550
0
  for (auto *R : RV)
2551
0
    createIntrinsic(R, Defs);
2552
2553
0
  for (auto *I : Defs)
2554
0
    I->indexBody();
2555
2556
0
  llvm::stable_sort(Defs, llvm::deref<std::less<>>());
2557
2558
  // Only emit a def when its requirements have been met.
2559
  // FIXME: This loop could be made faster, but it's fast enough for now.
2560
0
  bool MadeProgress = true;
2561
0
  std::string InGuard;
2562
0
  while (!Defs.empty() && MadeProgress) {
2563
0
    MadeProgress = false;
2564
2565
0
    for (SmallVector<Intrinsic *, 128>::iterator I = Defs.begin();
2566
0
         I != Defs.end(); /*No step*/) {
2567
0
      bool DependenciesSatisfied = true;
2568
0
      for (auto *II : (*I)->getDependencies()) {
2569
0
        if (llvm::is_contained(Defs, II))
2570
0
          DependenciesSatisfied = false;
2571
0
      }
2572
0
      if (!DependenciesSatisfied) {
2573
        // Try the next one.
2574
0
        ++I;
2575
0
        continue;
2576
0
      }
2577
2578
      // Emit #endif/#if pair if needed.
2579
0
      if ((*I)->getGuard() != InGuard) {
2580
0
        if (!InGuard.empty())
2581
0
          OS << "#endif\n";
2582
0
        InGuard = (*I)->getGuard();
2583
0
        if (!InGuard.empty())
2584
0
          OS << "#if " << InGuard << "\n";
2585
0
      }
2586
2587
      // Actually generate the intrinsic code.
2588
0
      OS << (*I)->generate();
2589
2590
0
      MadeProgress = true;
2591
0
      I = Defs.erase(I);
2592
0
    }
2593
0
  }
2594
0
  assert(Defs.empty() && "Some requirements were not satisfied!");
2595
0
  if (!InGuard.empty())
2596
0
    OS << "#endif\n";
2597
2598
0
  OS << "\n";
2599
0
  OS << "#undef __ai\n\n";
2600
2601
0
  OS << "#endif\n";
2602
0
}
2603
2604
0
void clang::EmitNeon(RecordKeeper &Records, raw_ostream &OS) {
2605
0
  NeonEmitter(Records).run(OS);
2606
0
}
2607
2608
0
void clang::EmitFP16(RecordKeeper &Records, raw_ostream &OS) {
2609
0
  NeonEmitter(Records).runFP16(OS);
2610
0
}
2611
2612
0
void clang::EmitBF16(RecordKeeper &Records, raw_ostream &OS) {
2613
0
  NeonEmitter(Records).runBF16(OS);
2614
0
}
2615
2616
0
void clang::EmitNeonSema(RecordKeeper &Records, raw_ostream &OS) {
2617
0
  NeonEmitter(Records).runHeader(OS);
2618
0
}
2619
2620
0
void clang::EmitNeonTest(RecordKeeper &Records, raw_ostream &OS) {
2621
0
  llvm_unreachable("Neon test generation no longer implemented!");
2622
0
}