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