NeonEmitter.cpp 80 KB

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