IRBuilder.h 103 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- llvm/IRBuilder.h - Builder for LLVM Instructions ---------*- C++ -*-===//
  7. //
  8. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  9. // See https://llvm.org/LICENSE.txt for license information.
  10. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  11. //
  12. //===----------------------------------------------------------------------===//
  13. //
  14. // This file defines the IRBuilder class, which is used as a convenient way
  15. // to create LLVM instructions with a consistent and simplified interface.
  16. //
  17. //===----------------------------------------------------------------------===//
  18. #ifndef LLVM_IR_IRBUILDER_H
  19. #define LLVM_IR_IRBUILDER_H
  20. #include "llvm-c/Types.h"
  21. #include "llvm/ADT/ArrayRef.h"
  22. #include "llvm/ADT/STLExtras.h"
  23. #include "llvm/ADT/StringRef.h"
  24. #include "llvm/ADT/Twine.h"
  25. #include "llvm/IR/BasicBlock.h"
  26. #include "llvm/IR/Constant.h"
  27. #include "llvm/IR/ConstantFolder.h"
  28. #include "llvm/IR/Constants.h"
  29. #include "llvm/IR/DataLayout.h"
  30. #include "llvm/IR/DebugLoc.h"
  31. #include "llvm/IR/DerivedTypes.h"
  32. #include "llvm/IR/FPEnv.h"
  33. #include "llvm/IR/Function.h"
  34. #include "llvm/IR/GlobalVariable.h"
  35. #include "llvm/IR/InstrTypes.h"
  36. #include "llvm/IR/Instruction.h"
  37. #include "llvm/IR/Instructions.h"
  38. #include "llvm/IR/Intrinsics.h"
  39. #include "llvm/IR/LLVMContext.h"
  40. #include "llvm/IR/Module.h"
  41. #include "llvm/IR/Operator.h"
  42. #include "llvm/IR/Type.h"
  43. #include "llvm/IR/Value.h"
  44. #include "llvm/IR/ValueHandle.h"
  45. #include "llvm/Support/AtomicOrdering.h"
  46. #include "llvm/Support/CBindingWrapping.h"
  47. #include "llvm/Support/Casting.h"
  48. #include <cassert>
  49. #include <cstdint>
  50. #include <functional>
  51. #include <optional>
  52. #include <utility>
  53. namespace llvm {
  54. class APInt;
  55. class Use;
  56. /// This provides the default implementation of the IRBuilder
  57. /// 'InsertHelper' method that is called whenever an instruction is created by
  58. /// IRBuilder and needs to be inserted.
  59. ///
  60. /// By default, this inserts the instruction at the insertion point.
  61. class IRBuilderDefaultInserter {
  62. public:
  63. virtual ~IRBuilderDefaultInserter();
  64. virtual void InsertHelper(Instruction *I, const Twine &Name,
  65. BasicBlock *BB,
  66. BasicBlock::iterator InsertPt) const {
  67. if (BB)
  68. I->insertInto(BB, InsertPt);
  69. I->setName(Name);
  70. }
  71. };
  72. /// Provides an 'InsertHelper' that calls a user-provided callback after
  73. /// performing the default insertion.
  74. class IRBuilderCallbackInserter : public IRBuilderDefaultInserter {
  75. std::function<void(Instruction *)> Callback;
  76. public:
  77. ~IRBuilderCallbackInserter() override;
  78. IRBuilderCallbackInserter(std::function<void(Instruction *)> Callback)
  79. : Callback(std::move(Callback)) {}
  80. void InsertHelper(Instruction *I, const Twine &Name,
  81. BasicBlock *BB,
  82. BasicBlock::iterator InsertPt) const override {
  83. IRBuilderDefaultInserter::InsertHelper(I, Name, BB, InsertPt);
  84. Callback(I);
  85. }
  86. };
  87. /// Common base class shared among various IRBuilders.
  88. class IRBuilderBase {
  89. /// Pairs of (metadata kind, MDNode *) that should be added to all newly
  90. /// created instructions, like !dbg metadata.
  91. SmallVector<std::pair<unsigned, MDNode *>, 2> MetadataToCopy;
  92. /// Add or update the an entry (Kind, MD) to MetadataToCopy, if \p MD is not
  93. /// null. If \p MD is null, remove the entry with \p Kind.
  94. void AddOrRemoveMetadataToCopy(unsigned Kind, MDNode *MD) {
  95. if (!MD) {
  96. erase_if(MetadataToCopy, [Kind](const std::pair<unsigned, MDNode *> &KV) {
  97. return KV.first == Kind;
  98. });
  99. return;
  100. }
  101. for (auto &KV : MetadataToCopy)
  102. if (KV.first == Kind) {
  103. KV.second = MD;
  104. return;
  105. }
  106. MetadataToCopy.emplace_back(Kind, MD);
  107. }
  108. protected:
  109. BasicBlock *BB;
  110. BasicBlock::iterator InsertPt;
  111. LLVMContext &Context;
  112. const IRBuilderFolder &Folder;
  113. const IRBuilderDefaultInserter &Inserter;
  114. MDNode *DefaultFPMathTag;
  115. FastMathFlags FMF;
  116. bool IsFPConstrained = false;
  117. fp::ExceptionBehavior DefaultConstrainedExcept = fp::ebStrict;
  118. RoundingMode DefaultConstrainedRounding = RoundingMode::Dynamic;
  119. ArrayRef<OperandBundleDef> DefaultOperandBundles;
  120. public:
  121. IRBuilderBase(LLVMContext &context, const IRBuilderFolder &Folder,
  122. const IRBuilderDefaultInserter &Inserter, MDNode *FPMathTag,
  123. ArrayRef<OperandBundleDef> OpBundles)
  124. : Context(context), Folder(Folder), Inserter(Inserter),
  125. DefaultFPMathTag(FPMathTag), DefaultOperandBundles(OpBundles) {
  126. ClearInsertionPoint();
  127. }
  128. /// Insert and return the specified instruction.
  129. template<typename InstTy>
  130. InstTy *Insert(InstTy *I, const Twine &Name = "") const {
  131. Inserter.InsertHelper(I, Name, BB, InsertPt);
  132. AddMetadataToInst(I);
  133. return I;
  134. }
  135. /// No-op overload to handle constants.
  136. Constant *Insert(Constant *C, const Twine& = "") const {
  137. return C;
  138. }
  139. Value *Insert(Value *V, const Twine &Name = "") const {
  140. if (Instruction *I = dyn_cast<Instruction>(V))
  141. return Insert(I, Name);
  142. assert(isa<Constant>(V));
  143. return V;
  144. }
  145. //===--------------------------------------------------------------------===//
  146. // Builder configuration methods
  147. //===--------------------------------------------------------------------===//
  148. /// Clear the insertion point: created instructions will not be
  149. /// inserted into a block.
  150. void ClearInsertionPoint() {
  151. BB = nullptr;
  152. InsertPt = BasicBlock::iterator();
  153. }
  154. BasicBlock *GetInsertBlock() const { return BB; }
  155. BasicBlock::iterator GetInsertPoint() const { return InsertPt; }
  156. LLVMContext &getContext() const { return Context; }
  157. /// This specifies that created instructions should be appended to the
  158. /// end of the specified block.
  159. void SetInsertPoint(BasicBlock *TheBB) {
  160. BB = TheBB;
  161. InsertPt = BB->end();
  162. }
  163. /// This specifies that created instructions should be inserted before
  164. /// the specified instruction.
  165. void SetInsertPoint(Instruction *I) {
  166. BB = I->getParent();
  167. InsertPt = I->getIterator();
  168. assert(InsertPt != BB->end() && "Can't read debug loc from end()");
  169. SetCurrentDebugLocation(I->getDebugLoc());
  170. }
  171. /// This specifies that created instructions should be inserted at the
  172. /// specified point.
  173. void SetInsertPoint(BasicBlock *TheBB, BasicBlock::iterator IP) {
  174. BB = TheBB;
  175. InsertPt = IP;
  176. if (IP != TheBB->end())
  177. SetCurrentDebugLocation(IP->getDebugLoc());
  178. }
  179. /// This specifies that created instructions should inserted at the beginning
  180. /// end of the specified function, but after already existing static alloca
  181. /// instructions that are at the start.
  182. void SetInsertPointPastAllocas(Function *F) {
  183. BB = &F->getEntryBlock();
  184. InsertPt = BB->getFirstNonPHIOrDbgOrAlloca();
  185. }
  186. /// Set location information used by debugging information.
  187. void SetCurrentDebugLocation(DebugLoc L) {
  188. AddOrRemoveMetadataToCopy(LLVMContext::MD_dbg, L.getAsMDNode());
  189. }
  190. /// Collect metadata with IDs \p MetadataKinds from \p Src which should be
  191. /// added to all created instructions. Entries present in MedataDataToCopy but
  192. /// not on \p Src will be dropped from MetadataToCopy.
  193. void CollectMetadataToCopy(Instruction *Src,
  194. ArrayRef<unsigned> MetadataKinds) {
  195. for (unsigned K : MetadataKinds)
  196. AddOrRemoveMetadataToCopy(K, Src->getMetadata(K));
  197. }
  198. /// Get location information used by debugging information.
  199. DebugLoc getCurrentDebugLocation() const;
  200. /// If this builder has a current debug location, set it on the
  201. /// specified instruction.
  202. void SetInstDebugLocation(Instruction *I) const;
  203. /// Add all entries in MetadataToCopy to \p I.
  204. void AddMetadataToInst(Instruction *I) const {
  205. for (const auto &KV : MetadataToCopy)
  206. I->setMetadata(KV.first, KV.second);
  207. }
  208. /// Get the return type of the current function that we're emitting
  209. /// into.
  210. Type *getCurrentFunctionReturnType() const;
  211. /// InsertPoint - A saved insertion point.
  212. class InsertPoint {
  213. BasicBlock *Block = nullptr;
  214. BasicBlock::iterator Point;
  215. public:
  216. /// Creates a new insertion point which doesn't point to anything.
  217. InsertPoint() = default;
  218. /// Creates a new insertion point at the given location.
  219. InsertPoint(BasicBlock *InsertBlock, BasicBlock::iterator InsertPoint)
  220. : Block(InsertBlock), Point(InsertPoint) {}
  221. /// Returns true if this insert point is set.
  222. bool isSet() const { return (Block != nullptr); }
  223. BasicBlock *getBlock() const { return Block; }
  224. BasicBlock::iterator getPoint() const { return Point; }
  225. };
  226. /// Returns the current insert point.
  227. InsertPoint saveIP() const {
  228. return InsertPoint(GetInsertBlock(), GetInsertPoint());
  229. }
  230. /// Returns the current insert point, clearing it in the process.
  231. InsertPoint saveAndClearIP() {
  232. InsertPoint IP(GetInsertBlock(), GetInsertPoint());
  233. ClearInsertionPoint();
  234. return IP;
  235. }
  236. /// Sets the current insert point to a previously-saved location.
  237. void restoreIP(InsertPoint IP) {
  238. if (IP.isSet())
  239. SetInsertPoint(IP.getBlock(), IP.getPoint());
  240. else
  241. ClearInsertionPoint();
  242. }
  243. /// Get the floating point math metadata being used.
  244. MDNode *getDefaultFPMathTag() const { return DefaultFPMathTag; }
  245. /// Get the flags to be applied to created floating point ops
  246. FastMathFlags getFastMathFlags() const { return FMF; }
  247. FastMathFlags &getFastMathFlags() { return FMF; }
  248. /// Clear the fast-math flags.
  249. void clearFastMathFlags() { FMF.clear(); }
  250. /// Set the floating point math metadata to be used.
  251. void setDefaultFPMathTag(MDNode *FPMathTag) { DefaultFPMathTag = FPMathTag; }
  252. /// Set the fast-math flags to be used with generated fp-math operators
  253. void setFastMathFlags(FastMathFlags NewFMF) { FMF = NewFMF; }
  254. /// Enable/Disable use of constrained floating point math. When
  255. /// enabled the CreateF<op>() calls instead create constrained
  256. /// floating point intrinsic calls. Fast math flags are unaffected
  257. /// by this setting.
  258. void setIsFPConstrained(bool IsCon) { IsFPConstrained = IsCon; }
  259. /// Query for the use of constrained floating point math
  260. bool getIsFPConstrained() { return IsFPConstrained; }
  261. /// Set the exception handling to be used with constrained floating point
  262. void setDefaultConstrainedExcept(fp::ExceptionBehavior NewExcept) {
  263. #ifndef NDEBUG
  264. std::optional<StringRef> ExceptStr =
  265. convertExceptionBehaviorToStr(NewExcept);
  266. assert(ExceptStr && "Garbage strict exception behavior!");
  267. #endif
  268. DefaultConstrainedExcept = NewExcept;
  269. }
  270. /// Set the rounding mode handling to be used with constrained floating point
  271. void setDefaultConstrainedRounding(RoundingMode NewRounding) {
  272. #ifndef NDEBUG
  273. std::optional<StringRef> RoundingStr =
  274. convertRoundingModeToStr(NewRounding);
  275. assert(RoundingStr && "Garbage strict rounding mode!");
  276. #endif
  277. DefaultConstrainedRounding = NewRounding;
  278. }
  279. /// Get the exception handling used with constrained floating point
  280. fp::ExceptionBehavior getDefaultConstrainedExcept() {
  281. return DefaultConstrainedExcept;
  282. }
  283. /// Get the rounding mode handling used with constrained floating point
  284. RoundingMode getDefaultConstrainedRounding() {
  285. return DefaultConstrainedRounding;
  286. }
  287. void setConstrainedFPFunctionAttr() {
  288. assert(BB && "Must have a basic block to set any function attributes!");
  289. Function *F = BB->getParent();
  290. if (!F->hasFnAttribute(Attribute::StrictFP)) {
  291. F->addFnAttr(Attribute::StrictFP);
  292. }
  293. }
  294. void setConstrainedFPCallAttr(CallBase *I) {
  295. I->addFnAttr(Attribute::StrictFP);
  296. }
  297. void setDefaultOperandBundles(ArrayRef<OperandBundleDef> OpBundles) {
  298. DefaultOperandBundles = OpBundles;
  299. }
  300. //===--------------------------------------------------------------------===//
  301. // RAII helpers.
  302. //===--------------------------------------------------------------------===//
  303. // RAII object that stores the current insertion point and restores it
  304. // when the object is destroyed. This includes the debug location.
  305. class InsertPointGuard {
  306. IRBuilderBase &Builder;
  307. AssertingVH<BasicBlock> Block;
  308. BasicBlock::iterator Point;
  309. DebugLoc DbgLoc;
  310. public:
  311. InsertPointGuard(IRBuilderBase &B)
  312. : Builder(B), Block(B.GetInsertBlock()), Point(B.GetInsertPoint()),
  313. DbgLoc(B.getCurrentDebugLocation()) {}
  314. InsertPointGuard(const InsertPointGuard &) = delete;
  315. InsertPointGuard &operator=(const InsertPointGuard &) = delete;
  316. ~InsertPointGuard() {
  317. Builder.restoreIP(InsertPoint(Block, Point));
  318. Builder.SetCurrentDebugLocation(DbgLoc);
  319. }
  320. };
  321. // RAII object that stores the current fast math settings and restores
  322. // them when the object is destroyed.
  323. class FastMathFlagGuard {
  324. IRBuilderBase &Builder;
  325. FastMathFlags FMF;
  326. MDNode *FPMathTag;
  327. bool IsFPConstrained;
  328. fp::ExceptionBehavior DefaultConstrainedExcept;
  329. RoundingMode DefaultConstrainedRounding;
  330. public:
  331. FastMathFlagGuard(IRBuilderBase &B)
  332. : Builder(B), FMF(B.FMF), FPMathTag(B.DefaultFPMathTag),
  333. IsFPConstrained(B.IsFPConstrained),
  334. DefaultConstrainedExcept(B.DefaultConstrainedExcept),
  335. DefaultConstrainedRounding(B.DefaultConstrainedRounding) {}
  336. FastMathFlagGuard(const FastMathFlagGuard &) = delete;
  337. FastMathFlagGuard &operator=(const FastMathFlagGuard &) = delete;
  338. ~FastMathFlagGuard() {
  339. Builder.FMF = FMF;
  340. Builder.DefaultFPMathTag = FPMathTag;
  341. Builder.IsFPConstrained = IsFPConstrained;
  342. Builder.DefaultConstrainedExcept = DefaultConstrainedExcept;
  343. Builder.DefaultConstrainedRounding = DefaultConstrainedRounding;
  344. }
  345. };
  346. // RAII object that stores the current default operand bundles and restores
  347. // them when the object is destroyed.
  348. class OperandBundlesGuard {
  349. IRBuilderBase &Builder;
  350. ArrayRef<OperandBundleDef> DefaultOperandBundles;
  351. public:
  352. OperandBundlesGuard(IRBuilderBase &B)
  353. : Builder(B), DefaultOperandBundles(B.DefaultOperandBundles) {}
  354. OperandBundlesGuard(const OperandBundlesGuard &) = delete;
  355. OperandBundlesGuard &operator=(const OperandBundlesGuard &) = delete;
  356. ~OperandBundlesGuard() {
  357. Builder.DefaultOperandBundles = DefaultOperandBundles;
  358. }
  359. };
  360. //===--------------------------------------------------------------------===//
  361. // Miscellaneous creation methods.
  362. //===--------------------------------------------------------------------===//
  363. /// Make a new global variable with initializer type i8*
  364. ///
  365. /// Make a new global variable with an initializer that has array of i8 type
  366. /// filled in with the null terminated string value specified. The new global
  367. /// variable will be marked mergable with any others of the same contents. If
  368. /// Name is specified, it is the name of the global variable created.
  369. ///
  370. /// If no module is given via \p M, it is take from the insertion point basic
  371. /// block.
  372. GlobalVariable *CreateGlobalString(StringRef Str, const Twine &Name = "",
  373. unsigned AddressSpace = 0,
  374. Module *M = nullptr);
  375. /// Get a constant value representing either true or false.
  376. ConstantInt *getInt1(bool V) {
  377. return ConstantInt::get(getInt1Ty(), V);
  378. }
  379. /// Get the constant value for i1 true.
  380. ConstantInt *getTrue() {
  381. return ConstantInt::getTrue(Context);
  382. }
  383. /// Get the constant value for i1 false.
  384. ConstantInt *getFalse() {
  385. return ConstantInt::getFalse(Context);
  386. }
  387. /// Get a constant 8-bit value.
  388. ConstantInt *getInt8(uint8_t C) {
  389. return ConstantInt::get(getInt8Ty(), C);
  390. }
  391. /// Get a constant 16-bit value.
  392. ConstantInt *getInt16(uint16_t C) {
  393. return ConstantInt::get(getInt16Ty(), C);
  394. }
  395. /// Get a constant 32-bit value.
  396. ConstantInt *getInt32(uint32_t C) {
  397. return ConstantInt::get(getInt32Ty(), C);
  398. }
  399. /// Get a constant 64-bit value.
  400. ConstantInt *getInt64(uint64_t C) {
  401. return ConstantInt::get(getInt64Ty(), C);
  402. }
  403. /// Get a constant N-bit value, zero extended or truncated from
  404. /// a 64-bit value.
  405. ConstantInt *getIntN(unsigned N, uint64_t C) {
  406. return ConstantInt::get(getIntNTy(N), C);
  407. }
  408. /// Get a constant integer value.
  409. ConstantInt *getInt(const APInt &AI) {
  410. return ConstantInt::get(Context, AI);
  411. }
  412. //===--------------------------------------------------------------------===//
  413. // Type creation methods
  414. //===--------------------------------------------------------------------===//
  415. /// Fetch the type representing a single bit
  416. IntegerType *getInt1Ty() {
  417. return Type::getInt1Ty(Context);
  418. }
  419. /// Fetch the type representing an 8-bit integer.
  420. IntegerType *getInt8Ty() {
  421. return Type::getInt8Ty(Context);
  422. }
  423. /// Fetch the type representing a 16-bit integer.
  424. IntegerType *getInt16Ty() {
  425. return Type::getInt16Ty(Context);
  426. }
  427. /// Fetch the type representing a 32-bit integer.
  428. IntegerType *getInt32Ty() {
  429. return Type::getInt32Ty(Context);
  430. }
  431. /// Fetch the type representing a 64-bit integer.
  432. IntegerType *getInt64Ty() {
  433. return Type::getInt64Ty(Context);
  434. }
  435. /// Fetch the type representing a 128-bit integer.
  436. IntegerType *getInt128Ty() { return Type::getInt128Ty(Context); }
  437. /// Fetch the type representing an N-bit integer.
  438. IntegerType *getIntNTy(unsigned N) {
  439. return Type::getIntNTy(Context, N);
  440. }
  441. /// Fetch the type representing a 16-bit floating point value.
  442. Type *getHalfTy() {
  443. return Type::getHalfTy(Context);
  444. }
  445. /// Fetch the type representing a 16-bit brain floating point value.
  446. Type *getBFloatTy() {
  447. return Type::getBFloatTy(Context);
  448. }
  449. /// Fetch the type representing a 32-bit floating point value.
  450. Type *getFloatTy() {
  451. return Type::getFloatTy(Context);
  452. }
  453. /// Fetch the type representing a 64-bit floating point value.
  454. Type *getDoubleTy() {
  455. return Type::getDoubleTy(Context);
  456. }
  457. /// Fetch the type representing void.
  458. Type *getVoidTy() {
  459. return Type::getVoidTy(Context);
  460. }
  461. /// Fetch the type representing a pointer.
  462. PointerType *getPtrTy(unsigned AddrSpace = 0) {
  463. return PointerType::get(Context, AddrSpace);
  464. }
  465. /// Fetch the type representing a pointer to an 8-bit integer value.
  466. PointerType *getInt8PtrTy(unsigned AddrSpace = 0) {
  467. return Type::getInt8PtrTy(Context, AddrSpace);
  468. }
  469. /// Fetch the type of an integer with size at least as big as that of a
  470. /// pointer in the given address space.
  471. IntegerType *getIntPtrTy(const DataLayout &DL, unsigned AddrSpace = 0) {
  472. return DL.getIntPtrType(Context, AddrSpace);
  473. }
  474. //===--------------------------------------------------------------------===//
  475. // Intrinsic creation methods
  476. //===--------------------------------------------------------------------===//
  477. /// Create and insert a memset to the specified pointer and the
  478. /// specified value.
  479. ///
  480. /// If the pointer isn't an i8*, it will be converted. If a TBAA tag is
  481. /// specified, it will be added to the instruction. Likewise with alias.scope
  482. /// and noalias tags.
  483. CallInst *CreateMemSet(Value *Ptr, Value *Val, uint64_t Size,
  484. MaybeAlign Align, bool isVolatile = false,
  485. MDNode *TBAATag = nullptr, MDNode *ScopeTag = nullptr,
  486. MDNode *NoAliasTag = nullptr) {
  487. return CreateMemSet(Ptr, Val, getInt64(Size), Align, isVolatile,
  488. TBAATag, ScopeTag, NoAliasTag);
  489. }
  490. CallInst *CreateMemSet(Value *Ptr, Value *Val, Value *Size, MaybeAlign Align,
  491. bool isVolatile = false, MDNode *TBAATag = nullptr,
  492. MDNode *ScopeTag = nullptr,
  493. MDNode *NoAliasTag = nullptr);
  494. CallInst *CreateMemSetInline(Value *Dst, MaybeAlign DstAlign, Value *Val,
  495. Value *Size, bool IsVolatile = false,
  496. MDNode *TBAATag = nullptr,
  497. MDNode *ScopeTag = nullptr,
  498. MDNode *NoAliasTag = nullptr);
  499. /// Create and insert an element unordered-atomic memset of the region of
  500. /// memory starting at the given pointer to the given value.
  501. ///
  502. /// If the pointer isn't an i8*, it will be converted. If a TBAA tag is
  503. /// specified, it will be added to the instruction. Likewise with alias.scope
  504. /// and noalias tags.
  505. CallInst *CreateElementUnorderedAtomicMemSet(Value *Ptr, Value *Val,
  506. uint64_t Size, Align Alignment,
  507. uint32_t ElementSize,
  508. MDNode *TBAATag = nullptr,
  509. MDNode *ScopeTag = nullptr,
  510. MDNode *NoAliasTag = nullptr) {
  511. return CreateElementUnorderedAtomicMemSet(Ptr, Val, getInt64(Size),
  512. Align(Alignment), ElementSize,
  513. TBAATag, ScopeTag, NoAliasTag);
  514. }
  515. CallInst *CreateElementUnorderedAtomicMemSet(Value *Ptr, Value *Val,
  516. Value *Size, Align Alignment,
  517. uint32_t ElementSize,
  518. MDNode *TBAATag = nullptr,
  519. MDNode *ScopeTag = nullptr,
  520. MDNode *NoAliasTag = nullptr);
  521. /// Create and insert a memcpy between the specified pointers.
  522. ///
  523. /// If the pointers aren't i8*, they will be converted. If a TBAA tag is
  524. /// specified, it will be added to the instruction. Likewise with alias.scope
  525. /// and noalias tags.
  526. CallInst *CreateMemCpy(Value *Dst, MaybeAlign DstAlign, Value *Src,
  527. MaybeAlign SrcAlign, uint64_t Size,
  528. bool isVolatile = false, MDNode *TBAATag = nullptr,
  529. MDNode *TBAAStructTag = nullptr,
  530. MDNode *ScopeTag = nullptr,
  531. MDNode *NoAliasTag = nullptr) {
  532. return CreateMemCpy(Dst, DstAlign, Src, SrcAlign, getInt64(Size),
  533. isVolatile, TBAATag, TBAAStructTag, ScopeTag,
  534. NoAliasTag);
  535. }
  536. CallInst *CreateMemTransferInst(
  537. Intrinsic::ID IntrID, Value *Dst, MaybeAlign DstAlign, Value *Src,
  538. MaybeAlign SrcAlign, Value *Size, bool isVolatile = false,
  539. MDNode *TBAATag = nullptr, MDNode *TBAAStructTag = nullptr,
  540. MDNode *ScopeTag = nullptr, MDNode *NoAliasTag = nullptr);
  541. CallInst *CreateMemCpy(Value *Dst, MaybeAlign DstAlign, Value *Src,
  542. MaybeAlign SrcAlign, Value *Size,
  543. bool isVolatile = false, MDNode *TBAATag = nullptr,
  544. MDNode *TBAAStructTag = nullptr,
  545. MDNode *ScopeTag = nullptr,
  546. MDNode *NoAliasTag = nullptr) {
  547. return CreateMemTransferInst(Intrinsic::memcpy, Dst, DstAlign, Src,
  548. SrcAlign, Size, isVolatile, TBAATag,
  549. TBAAStructTag, ScopeTag, NoAliasTag);
  550. }
  551. CallInst *
  552. CreateMemCpyInline(Value *Dst, MaybeAlign DstAlign, Value *Src,
  553. MaybeAlign SrcAlign, Value *Size, bool IsVolatile = false,
  554. MDNode *TBAATag = nullptr, MDNode *TBAAStructTag = nullptr,
  555. MDNode *ScopeTag = nullptr, MDNode *NoAliasTag = nullptr);
  556. /// Create and insert an element unordered-atomic memcpy between the
  557. /// specified pointers.
  558. ///
  559. /// DstAlign/SrcAlign are the alignments of the Dst/Src pointers, respectively.
  560. ///
  561. /// If the pointers aren't i8*, they will be converted. If a TBAA tag is
  562. /// specified, it will be added to the instruction. Likewise with alias.scope
  563. /// and noalias tags.
  564. CallInst *CreateElementUnorderedAtomicMemCpy(
  565. Value *Dst, Align DstAlign, Value *Src, Align SrcAlign, Value *Size,
  566. uint32_t ElementSize, MDNode *TBAATag = nullptr,
  567. MDNode *TBAAStructTag = nullptr, MDNode *ScopeTag = nullptr,
  568. MDNode *NoAliasTag = nullptr);
  569. CallInst *CreateMemMove(Value *Dst, MaybeAlign DstAlign, Value *Src,
  570. MaybeAlign SrcAlign, uint64_t Size,
  571. bool isVolatile = false, MDNode *TBAATag = nullptr,
  572. MDNode *ScopeTag = nullptr,
  573. MDNode *NoAliasTag = nullptr) {
  574. return CreateMemMove(Dst, DstAlign, Src, SrcAlign, getInt64(Size),
  575. isVolatile, TBAATag, ScopeTag, NoAliasTag);
  576. }
  577. CallInst *CreateMemMove(Value *Dst, MaybeAlign DstAlign, Value *Src,
  578. MaybeAlign SrcAlign, Value *Size,
  579. bool isVolatile = false, MDNode *TBAATag = nullptr,
  580. MDNode *ScopeTag = nullptr,
  581. MDNode *NoAliasTag = nullptr);
  582. /// \brief Create and insert an element unordered-atomic memmove between the
  583. /// specified pointers.
  584. ///
  585. /// DstAlign/SrcAlign are the alignments of the Dst/Src pointers,
  586. /// respectively.
  587. ///
  588. /// If the pointers aren't i8*, they will be converted. If a TBAA tag is
  589. /// specified, it will be added to the instruction. Likewise with alias.scope
  590. /// and noalias tags.
  591. CallInst *CreateElementUnorderedAtomicMemMove(
  592. Value *Dst, Align DstAlign, Value *Src, Align SrcAlign, Value *Size,
  593. uint32_t ElementSize, MDNode *TBAATag = nullptr,
  594. MDNode *TBAAStructTag = nullptr, MDNode *ScopeTag = nullptr,
  595. MDNode *NoAliasTag = nullptr);
  596. private:
  597. CallInst *getReductionIntrinsic(Intrinsic::ID ID, Value *Src);
  598. public:
  599. /// Create a sequential vector fadd reduction intrinsic of the source vector.
  600. /// The first parameter is a scalar accumulator value. An unordered reduction
  601. /// can be created by adding the reassoc fast-math flag to the resulting
  602. /// sequential reduction.
  603. CallInst *CreateFAddReduce(Value *Acc, Value *Src);
  604. /// Create a sequential vector fmul reduction intrinsic of the source vector.
  605. /// The first parameter is a scalar accumulator value. An unordered reduction
  606. /// can be created by adding the reassoc fast-math flag to the resulting
  607. /// sequential reduction.
  608. CallInst *CreateFMulReduce(Value *Acc, Value *Src);
  609. /// Create a vector int add reduction intrinsic of the source vector.
  610. CallInst *CreateAddReduce(Value *Src);
  611. /// Create a vector int mul reduction intrinsic of the source vector.
  612. CallInst *CreateMulReduce(Value *Src);
  613. /// Create a vector int AND reduction intrinsic of the source vector.
  614. CallInst *CreateAndReduce(Value *Src);
  615. /// Create a vector int OR reduction intrinsic of the source vector.
  616. CallInst *CreateOrReduce(Value *Src);
  617. /// Create a vector int XOR reduction intrinsic of the source vector.
  618. CallInst *CreateXorReduce(Value *Src);
  619. /// Create a vector integer max reduction intrinsic of the source
  620. /// vector.
  621. CallInst *CreateIntMaxReduce(Value *Src, bool IsSigned = false);
  622. /// Create a vector integer min reduction intrinsic of the source
  623. /// vector.
  624. CallInst *CreateIntMinReduce(Value *Src, bool IsSigned = false);
  625. /// Create a vector float max reduction intrinsic of the source
  626. /// vector.
  627. CallInst *CreateFPMaxReduce(Value *Src);
  628. /// Create a vector float min reduction intrinsic of the source
  629. /// vector.
  630. CallInst *CreateFPMinReduce(Value *Src);
  631. /// Create a lifetime.start intrinsic.
  632. ///
  633. /// If the pointer isn't i8* it will be converted.
  634. CallInst *CreateLifetimeStart(Value *Ptr, ConstantInt *Size = nullptr);
  635. /// Create a lifetime.end intrinsic.
  636. ///
  637. /// If the pointer isn't i8* it will be converted.
  638. CallInst *CreateLifetimeEnd(Value *Ptr, ConstantInt *Size = nullptr);
  639. /// Create a call to invariant.start intrinsic.
  640. ///
  641. /// If the pointer isn't i8* it will be converted.
  642. CallInst *CreateInvariantStart(Value *Ptr, ConstantInt *Size = nullptr);
  643. /// Create a call to llvm.threadlocal.address intrinsic.
  644. CallInst *CreateThreadLocalAddress(Value *Ptr);
  645. /// Create a call to Masked Load intrinsic
  646. CallInst *CreateMaskedLoad(Type *Ty, Value *Ptr, Align Alignment, Value *Mask,
  647. Value *PassThru = nullptr, const Twine &Name = "");
  648. /// Create a call to Masked Store intrinsic
  649. CallInst *CreateMaskedStore(Value *Val, Value *Ptr, Align Alignment,
  650. Value *Mask);
  651. /// Create a call to Masked Gather intrinsic
  652. CallInst *CreateMaskedGather(Type *Ty, Value *Ptrs, Align Alignment,
  653. Value *Mask = nullptr, Value *PassThru = nullptr,
  654. const Twine &Name = "");
  655. /// Create a call to Masked Scatter intrinsic
  656. CallInst *CreateMaskedScatter(Value *Val, Value *Ptrs, Align Alignment,
  657. Value *Mask = nullptr);
  658. /// Create a call to Masked Expand Load intrinsic
  659. CallInst *CreateMaskedExpandLoad(Type *Ty, Value *Ptr, Value *Mask = nullptr,
  660. Value *PassThru = nullptr,
  661. const Twine &Name = "");
  662. /// Create a call to Masked Compress Store intrinsic
  663. CallInst *CreateMaskedCompressStore(Value *Val, Value *Ptr,
  664. Value *Mask = nullptr);
  665. /// Create an assume intrinsic call that allows the optimizer to
  666. /// assume that the provided condition will be true.
  667. ///
  668. /// The optional argument \p OpBundles specifies operand bundles that are
  669. /// added to the call instruction.
  670. CallInst *
  671. CreateAssumption(Value *Cond,
  672. ArrayRef<OperandBundleDef> OpBundles = std::nullopt);
  673. /// Create a llvm.experimental.noalias.scope.decl intrinsic call.
  674. Instruction *CreateNoAliasScopeDeclaration(Value *Scope);
  675. Instruction *CreateNoAliasScopeDeclaration(MDNode *ScopeTag) {
  676. return CreateNoAliasScopeDeclaration(
  677. MetadataAsValue::get(Context, ScopeTag));
  678. }
  679. /// Create a call to the experimental.gc.statepoint intrinsic to
  680. /// start a new statepoint sequence.
  681. CallInst *CreateGCStatepointCall(uint64_t ID, uint32_t NumPatchBytes,
  682. FunctionCallee ActualCallee,
  683. ArrayRef<Value *> CallArgs,
  684. std::optional<ArrayRef<Value *>> DeoptArgs,
  685. ArrayRef<Value *> GCArgs,
  686. const Twine &Name = "");
  687. /// Create a call to the experimental.gc.statepoint intrinsic to
  688. /// start a new statepoint sequence.
  689. CallInst *CreateGCStatepointCall(uint64_t ID, uint32_t NumPatchBytes,
  690. FunctionCallee ActualCallee, uint32_t Flags,
  691. ArrayRef<Value *> CallArgs,
  692. std::optional<ArrayRef<Use>> TransitionArgs,
  693. std::optional<ArrayRef<Use>> DeoptArgs,
  694. ArrayRef<Value *> GCArgs,
  695. const Twine &Name = "");
  696. /// Conveninence function for the common case when CallArgs are filled
  697. /// in using ArrayRef(CS.arg_begin(), CS.arg_end()); Use needs to be
  698. /// .get()'ed to get the Value pointer.
  699. CallInst *CreateGCStatepointCall(uint64_t ID, uint32_t NumPatchBytes,
  700. FunctionCallee ActualCallee,
  701. ArrayRef<Use> CallArgs,
  702. std::optional<ArrayRef<Value *>> DeoptArgs,
  703. ArrayRef<Value *> GCArgs,
  704. const Twine &Name = "");
  705. /// Create an invoke to the experimental.gc.statepoint intrinsic to
  706. /// start a new statepoint sequence.
  707. InvokeInst *
  708. CreateGCStatepointInvoke(uint64_t ID, uint32_t NumPatchBytes,
  709. FunctionCallee ActualInvokee, BasicBlock *NormalDest,
  710. BasicBlock *UnwindDest, ArrayRef<Value *> InvokeArgs,
  711. std::optional<ArrayRef<Value *>> DeoptArgs,
  712. ArrayRef<Value *> GCArgs, const Twine &Name = "");
  713. /// Create an invoke to the experimental.gc.statepoint intrinsic to
  714. /// start a new statepoint sequence.
  715. InvokeInst *CreateGCStatepointInvoke(
  716. uint64_t ID, uint32_t NumPatchBytes, FunctionCallee ActualInvokee,
  717. BasicBlock *NormalDest, BasicBlock *UnwindDest, uint32_t Flags,
  718. ArrayRef<Value *> InvokeArgs, std::optional<ArrayRef<Use>> TransitionArgs,
  719. std::optional<ArrayRef<Use>> DeoptArgs, ArrayRef<Value *> GCArgs,
  720. const Twine &Name = "");
  721. // Convenience function for the common case when CallArgs are filled in using
  722. // ArrayRef(CS.arg_begin(), CS.arg_end()); Use needs to be .get()'ed to
  723. // get the Value *.
  724. InvokeInst *
  725. CreateGCStatepointInvoke(uint64_t ID, uint32_t NumPatchBytes,
  726. FunctionCallee ActualInvokee, BasicBlock *NormalDest,
  727. BasicBlock *UnwindDest, ArrayRef<Use> InvokeArgs,
  728. std::optional<ArrayRef<Value *>> DeoptArgs,
  729. ArrayRef<Value *> GCArgs, const Twine &Name = "");
  730. /// Create a call to the experimental.gc.result intrinsic to extract
  731. /// the result from a call wrapped in a statepoint.
  732. CallInst *CreateGCResult(Instruction *Statepoint,
  733. Type *ResultType,
  734. const Twine &Name = "");
  735. /// Create a call to the experimental.gc.relocate intrinsics to
  736. /// project the relocated value of one pointer from the statepoint.
  737. CallInst *CreateGCRelocate(Instruction *Statepoint,
  738. int BaseOffset,
  739. int DerivedOffset,
  740. Type *ResultType,
  741. const Twine &Name = "");
  742. /// Create a call to the experimental.gc.pointer.base intrinsic to get the
  743. /// base pointer for the specified derived pointer.
  744. CallInst *CreateGCGetPointerBase(Value *DerivedPtr, const Twine &Name = "");
  745. /// Create a call to the experimental.gc.get.pointer.offset intrinsic to get
  746. /// the offset of the specified derived pointer from its base.
  747. CallInst *CreateGCGetPointerOffset(Value *DerivedPtr, const Twine &Name = "");
  748. /// Create a call to llvm.vscale, multiplied by \p Scaling. The type of VScale
  749. /// will be the same type as that of \p Scaling.
  750. Value *CreateVScale(Constant *Scaling, const Twine &Name = "");
  751. /// Creates a vector of type \p DstType with the linear sequence <0, 1, ...>
  752. Value *CreateStepVector(Type *DstType, const Twine &Name = "");
  753. /// Create a call to intrinsic \p ID with 1 operand which is mangled on its
  754. /// type.
  755. CallInst *CreateUnaryIntrinsic(Intrinsic::ID ID, Value *V,
  756. Instruction *FMFSource = nullptr,
  757. const Twine &Name = "");
  758. /// Create a call to intrinsic \p ID with 2 operands which is mangled on the
  759. /// first type.
  760. CallInst *CreateBinaryIntrinsic(Intrinsic::ID ID, Value *LHS, Value *RHS,
  761. Instruction *FMFSource = nullptr,
  762. const Twine &Name = "");
  763. /// Create a call to intrinsic \p ID with \p Args, mangled using \p Types. If
  764. /// \p FMFSource is provided, copy fast-math-flags from that instruction to
  765. /// the intrinsic.
  766. CallInst *CreateIntrinsic(Intrinsic::ID ID, ArrayRef<Type *> Types,
  767. ArrayRef<Value *> Args,
  768. Instruction *FMFSource = nullptr,
  769. const Twine &Name = "");
  770. /// Create a call to intrinsic \p ID with \p RetTy and \p Args. If
  771. /// \p FMFSource is provided, copy fast-math-flags from that instruction to
  772. /// the intrinsic.
  773. CallInst *CreateIntrinsic(Type *RetTy, Intrinsic::ID ID,
  774. ArrayRef<Value *> Args,
  775. Instruction *FMFSource = nullptr,
  776. const Twine &Name = "");
  777. /// Create call to the minnum intrinsic.
  778. CallInst *CreateMinNum(Value *LHS, Value *RHS, const Twine &Name = "") {
  779. return CreateBinaryIntrinsic(Intrinsic::minnum, LHS, RHS, nullptr, Name);
  780. }
  781. /// Create call to the maxnum intrinsic.
  782. CallInst *CreateMaxNum(Value *LHS, Value *RHS, const Twine &Name = "") {
  783. return CreateBinaryIntrinsic(Intrinsic::maxnum, LHS, RHS, nullptr, Name);
  784. }
  785. /// Create call to the minimum intrinsic.
  786. CallInst *CreateMinimum(Value *LHS, Value *RHS, const Twine &Name = "") {
  787. return CreateBinaryIntrinsic(Intrinsic::minimum, LHS, RHS, nullptr, Name);
  788. }
  789. /// Create call to the maximum intrinsic.
  790. CallInst *CreateMaximum(Value *LHS, Value *RHS, const Twine &Name = "") {
  791. return CreateBinaryIntrinsic(Intrinsic::maximum, LHS, RHS, nullptr, Name);
  792. }
  793. /// Create call to the copysign intrinsic.
  794. CallInst *CreateCopySign(Value *LHS, Value *RHS,
  795. Instruction *FMFSource = nullptr,
  796. const Twine &Name = "") {
  797. return CreateBinaryIntrinsic(Intrinsic::copysign, LHS, RHS, FMFSource,
  798. Name);
  799. }
  800. /// Create a call to the arithmetic_fence intrinsic.
  801. CallInst *CreateArithmeticFence(Value *Val, Type *DstType,
  802. const Twine &Name = "") {
  803. return CreateIntrinsic(Intrinsic::arithmetic_fence, DstType, Val, nullptr,
  804. Name);
  805. }
  806. /// Create a call to the vector.extract intrinsic.
  807. CallInst *CreateExtractVector(Type *DstType, Value *SrcVec, Value *Idx,
  808. const Twine &Name = "") {
  809. return CreateIntrinsic(Intrinsic::vector_extract,
  810. {DstType, SrcVec->getType()}, {SrcVec, Idx}, nullptr,
  811. Name);
  812. }
  813. /// Create a call to the vector.insert intrinsic.
  814. CallInst *CreateInsertVector(Type *DstType, Value *SrcVec, Value *SubVec,
  815. Value *Idx, const Twine &Name = "") {
  816. return CreateIntrinsic(Intrinsic::vector_insert,
  817. {DstType, SubVec->getType()}, {SrcVec, SubVec, Idx},
  818. nullptr, Name);
  819. }
  820. private:
  821. /// Create a call to a masked intrinsic with given Id.
  822. CallInst *CreateMaskedIntrinsic(Intrinsic::ID Id, ArrayRef<Value *> Ops,
  823. ArrayRef<Type *> OverloadedTypes,
  824. const Twine &Name = "");
  825. Value *getCastedInt8PtrValue(Value *Ptr);
  826. //===--------------------------------------------------------------------===//
  827. // Instruction creation methods: Terminators
  828. //===--------------------------------------------------------------------===//
  829. private:
  830. /// Helper to add branch weight and unpredictable metadata onto an
  831. /// instruction.
  832. /// \returns The annotated instruction.
  833. template <typename InstTy>
  834. InstTy *addBranchMetadata(InstTy *I, MDNode *Weights, MDNode *Unpredictable) {
  835. if (Weights)
  836. I->setMetadata(LLVMContext::MD_prof, Weights);
  837. if (Unpredictable)
  838. I->setMetadata(LLVMContext::MD_unpredictable, Unpredictable);
  839. return I;
  840. }
  841. public:
  842. /// Create a 'ret void' instruction.
  843. ReturnInst *CreateRetVoid() {
  844. return Insert(ReturnInst::Create(Context));
  845. }
  846. /// Create a 'ret <val>' instruction.
  847. ReturnInst *CreateRet(Value *V) {
  848. return Insert(ReturnInst::Create(Context, V));
  849. }
  850. /// Create a sequence of N insertvalue instructions,
  851. /// with one Value from the retVals array each, that build a aggregate
  852. /// return value one value at a time, and a ret instruction to return
  853. /// the resulting aggregate value.
  854. ///
  855. /// This is a convenience function for code that uses aggregate return values
  856. /// as a vehicle for having multiple return values.
  857. ReturnInst *CreateAggregateRet(Value *const *retVals, unsigned N) {
  858. Value *V = PoisonValue::get(getCurrentFunctionReturnType());
  859. for (unsigned i = 0; i != N; ++i)
  860. V = CreateInsertValue(V, retVals[i], i, "mrv");
  861. return Insert(ReturnInst::Create(Context, V));
  862. }
  863. /// Create an unconditional 'br label X' instruction.
  864. BranchInst *CreateBr(BasicBlock *Dest) {
  865. return Insert(BranchInst::Create(Dest));
  866. }
  867. /// Create a conditional 'br Cond, TrueDest, FalseDest'
  868. /// instruction.
  869. BranchInst *CreateCondBr(Value *Cond, BasicBlock *True, BasicBlock *False,
  870. MDNode *BranchWeights = nullptr,
  871. MDNode *Unpredictable = nullptr) {
  872. return Insert(addBranchMetadata(BranchInst::Create(True, False, Cond),
  873. BranchWeights, Unpredictable));
  874. }
  875. /// Create a conditional 'br Cond, TrueDest, FalseDest'
  876. /// instruction. Copy branch meta data if available.
  877. BranchInst *CreateCondBr(Value *Cond, BasicBlock *True, BasicBlock *False,
  878. Instruction *MDSrc) {
  879. BranchInst *Br = BranchInst::Create(True, False, Cond);
  880. if (MDSrc) {
  881. unsigned WL[4] = {LLVMContext::MD_prof, LLVMContext::MD_unpredictable,
  882. LLVMContext::MD_make_implicit, LLVMContext::MD_dbg};
  883. Br->copyMetadata(*MDSrc, WL);
  884. }
  885. return Insert(Br);
  886. }
  887. /// Create a switch instruction with the specified value, default dest,
  888. /// and with a hint for the number of cases that will be added (for efficient
  889. /// allocation).
  890. SwitchInst *CreateSwitch(Value *V, BasicBlock *Dest, unsigned NumCases = 10,
  891. MDNode *BranchWeights = nullptr,
  892. MDNode *Unpredictable = nullptr) {
  893. return Insert(addBranchMetadata(SwitchInst::Create(V, Dest, NumCases),
  894. BranchWeights, Unpredictable));
  895. }
  896. /// Create an indirect branch instruction with the specified address
  897. /// operand, with an optional hint for the number of destinations that will be
  898. /// added (for efficient allocation).
  899. IndirectBrInst *CreateIndirectBr(Value *Addr, unsigned NumDests = 10) {
  900. return Insert(IndirectBrInst::Create(Addr, NumDests));
  901. }
  902. /// Create an invoke instruction.
  903. InvokeInst *CreateInvoke(FunctionType *Ty, Value *Callee,
  904. BasicBlock *NormalDest, BasicBlock *UnwindDest,
  905. ArrayRef<Value *> Args,
  906. ArrayRef<OperandBundleDef> OpBundles,
  907. const Twine &Name = "") {
  908. InvokeInst *II =
  909. InvokeInst::Create(Ty, Callee, NormalDest, UnwindDest, Args, OpBundles);
  910. if (IsFPConstrained)
  911. setConstrainedFPCallAttr(II);
  912. return Insert(II, Name);
  913. }
  914. InvokeInst *CreateInvoke(FunctionType *Ty, Value *Callee,
  915. BasicBlock *NormalDest, BasicBlock *UnwindDest,
  916. ArrayRef<Value *> Args = std::nullopt,
  917. const Twine &Name = "") {
  918. InvokeInst *II =
  919. InvokeInst::Create(Ty, Callee, NormalDest, UnwindDest, Args);
  920. if (IsFPConstrained)
  921. setConstrainedFPCallAttr(II);
  922. return Insert(II, Name);
  923. }
  924. InvokeInst *CreateInvoke(FunctionCallee Callee, BasicBlock *NormalDest,
  925. BasicBlock *UnwindDest, ArrayRef<Value *> Args,
  926. ArrayRef<OperandBundleDef> OpBundles,
  927. const Twine &Name = "") {
  928. return CreateInvoke(Callee.getFunctionType(), Callee.getCallee(),
  929. NormalDest, UnwindDest, Args, OpBundles, Name);
  930. }
  931. InvokeInst *CreateInvoke(FunctionCallee Callee, BasicBlock *NormalDest,
  932. BasicBlock *UnwindDest,
  933. ArrayRef<Value *> Args = std::nullopt,
  934. const Twine &Name = "") {
  935. return CreateInvoke(Callee.getFunctionType(), Callee.getCallee(),
  936. NormalDest, UnwindDest, Args, Name);
  937. }
  938. /// \brief Create a callbr instruction.
  939. CallBrInst *CreateCallBr(FunctionType *Ty, Value *Callee,
  940. BasicBlock *DefaultDest,
  941. ArrayRef<BasicBlock *> IndirectDests,
  942. ArrayRef<Value *> Args = std::nullopt,
  943. const Twine &Name = "") {
  944. return Insert(CallBrInst::Create(Ty, Callee, DefaultDest, IndirectDests,
  945. Args), Name);
  946. }
  947. CallBrInst *CreateCallBr(FunctionType *Ty, Value *Callee,
  948. BasicBlock *DefaultDest,
  949. ArrayRef<BasicBlock *> IndirectDests,
  950. ArrayRef<Value *> Args,
  951. ArrayRef<OperandBundleDef> OpBundles,
  952. const Twine &Name = "") {
  953. return Insert(
  954. CallBrInst::Create(Ty, Callee, DefaultDest, IndirectDests, Args,
  955. OpBundles), Name);
  956. }
  957. CallBrInst *CreateCallBr(FunctionCallee Callee, BasicBlock *DefaultDest,
  958. ArrayRef<BasicBlock *> IndirectDests,
  959. ArrayRef<Value *> Args = std::nullopt,
  960. const Twine &Name = "") {
  961. return CreateCallBr(Callee.getFunctionType(), Callee.getCallee(),
  962. DefaultDest, IndirectDests, Args, Name);
  963. }
  964. CallBrInst *CreateCallBr(FunctionCallee Callee, BasicBlock *DefaultDest,
  965. ArrayRef<BasicBlock *> IndirectDests,
  966. ArrayRef<Value *> Args,
  967. ArrayRef<OperandBundleDef> OpBundles,
  968. const Twine &Name = "") {
  969. return CreateCallBr(Callee.getFunctionType(), Callee.getCallee(),
  970. DefaultDest, IndirectDests, Args, Name);
  971. }
  972. ResumeInst *CreateResume(Value *Exn) {
  973. return Insert(ResumeInst::Create(Exn));
  974. }
  975. CleanupReturnInst *CreateCleanupRet(CleanupPadInst *CleanupPad,
  976. BasicBlock *UnwindBB = nullptr) {
  977. return Insert(CleanupReturnInst::Create(CleanupPad, UnwindBB));
  978. }
  979. CatchSwitchInst *CreateCatchSwitch(Value *ParentPad, BasicBlock *UnwindBB,
  980. unsigned NumHandlers,
  981. const Twine &Name = "") {
  982. return Insert(CatchSwitchInst::Create(ParentPad, UnwindBB, NumHandlers),
  983. Name);
  984. }
  985. CatchPadInst *CreateCatchPad(Value *ParentPad, ArrayRef<Value *> Args,
  986. const Twine &Name = "") {
  987. return Insert(CatchPadInst::Create(ParentPad, Args), Name);
  988. }
  989. CleanupPadInst *CreateCleanupPad(Value *ParentPad,
  990. ArrayRef<Value *> Args = std::nullopt,
  991. const Twine &Name = "") {
  992. return Insert(CleanupPadInst::Create(ParentPad, Args), Name);
  993. }
  994. CatchReturnInst *CreateCatchRet(CatchPadInst *CatchPad, BasicBlock *BB) {
  995. return Insert(CatchReturnInst::Create(CatchPad, BB));
  996. }
  997. UnreachableInst *CreateUnreachable() {
  998. return Insert(new UnreachableInst(Context));
  999. }
  1000. //===--------------------------------------------------------------------===//
  1001. // Instruction creation methods: Binary Operators
  1002. //===--------------------------------------------------------------------===//
  1003. private:
  1004. BinaryOperator *CreateInsertNUWNSWBinOp(BinaryOperator::BinaryOps Opc,
  1005. Value *LHS, Value *RHS,
  1006. const Twine &Name,
  1007. bool HasNUW, bool HasNSW) {
  1008. BinaryOperator *BO = Insert(BinaryOperator::Create(Opc, LHS, RHS), Name);
  1009. if (HasNUW) BO->setHasNoUnsignedWrap();
  1010. if (HasNSW) BO->setHasNoSignedWrap();
  1011. return BO;
  1012. }
  1013. Instruction *setFPAttrs(Instruction *I, MDNode *FPMD,
  1014. FastMathFlags FMF) const {
  1015. if (!FPMD)
  1016. FPMD = DefaultFPMathTag;
  1017. if (FPMD)
  1018. I->setMetadata(LLVMContext::MD_fpmath, FPMD);
  1019. I->setFastMathFlags(FMF);
  1020. return I;
  1021. }
  1022. Value *getConstrainedFPRounding(std::optional<RoundingMode> Rounding) {
  1023. RoundingMode UseRounding = DefaultConstrainedRounding;
  1024. if (Rounding)
  1025. UseRounding = *Rounding;
  1026. std::optional<StringRef> RoundingStr =
  1027. convertRoundingModeToStr(UseRounding);
  1028. assert(RoundingStr && "Garbage strict rounding mode!");
  1029. auto *RoundingMDS = MDString::get(Context, *RoundingStr);
  1030. return MetadataAsValue::get(Context, RoundingMDS);
  1031. }
  1032. Value *getConstrainedFPExcept(std::optional<fp::ExceptionBehavior> Except) {
  1033. std::optional<StringRef> ExceptStr = convertExceptionBehaviorToStr(
  1034. Except.value_or(DefaultConstrainedExcept));
  1035. assert(ExceptStr && "Garbage strict exception behavior!");
  1036. auto *ExceptMDS = MDString::get(Context, *ExceptStr);
  1037. return MetadataAsValue::get(Context, ExceptMDS);
  1038. }
  1039. Value *getConstrainedFPPredicate(CmpInst::Predicate Predicate) {
  1040. assert(CmpInst::isFPPredicate(Predicate) &&
  1041. Predicate != CmpInst::FCMP_FALSE &&
  1042. Predicate != CmpInst::FCMP_TRUE &&
  1043. "Invalid constrained FP comparison predicate!");
  1044. StringRef PredicateStr = CmpInst::getPredicateName(Predicate);
  1045. auto *PredicateMDS = MDString::get(Context, PredicateStr);
  1046. return MetadataAsValue::get(Context, PredicateMDS);
  1047. }
  1048. public:
  1049. Value *CreateAdd(Value *LHS, Value *RHS, const Twine &Name = "",
  1050. bool HasNUW = false, bool HasNSW = false) {
  1051. if (Value *V =
  1052. Folder.FoldNoWrapBinOp(Instruction::Add, LHS, RHS, HasNUW, HasNSW))
  1053. return V;
  1054. return CreateInsertNUWNSWBinOp(Instruction::Add, LHS, RHS, Name, HasNUW,
  1055. HasNSW);
  1056. }
  1057. Value *CreateNSWAdd(Value *LHS, Value *RHS, const Twine &Name = "") {
  1058. return CreateAdd(LHS, RHS, Name, false, true);
  1059. }
  1060. Value *CreateNUWAdd(Value *LHS, Value *RHS, const Twine &Name = "") {
  1061. return CreateAdd(LHS, RHS, Name, true, false);
  1062. }
  1063. Value *CreateSub(Value *LHS, Value *RHS, const Twine &Name = "",
  1064. bool HasNUW = false, bool HasNSW = false) {
  1065. if (Value *V =
  1066. Folder.FoldNoWrapBinOp(Instruction::Sub, LHS, RHS, HasNUW, HasNSW))
  1067. return V;
  1068. return CreateInsertNUWNSWBinOp(Instruction::Sub, LHS, RHS, Name, HasNUW,
  1069. HasNSW);
  1070. }
  1071. Value *CreateNSWSub(Value *LHS, Value *RHS, const Twine &Name = "") {
  1072. return CreateSub(LHS, RHS, Name, false, true);
  1073. }
  1074. Value *CreateNUWSub(Value *LHS, Value *RHS, const Twine &Name = "") {
  1075. return CreateSub(LHS, RHS, Name, true, false);
  1076. }
  1077. Value *CreateMul(Value *LHS, Value *RHS, const Twine &Name = "",
  1078. bool HasNUW = false, bool HasNSW = false) {
  1079. if (Value *V =
  1080. Folder.FoldNoWrapBinOp(Instruction::Mul, LHS, RHS, HasNUW, HasNSW))
  1081. return V;
  1082. return CreateInsertNUWNSWBinOp(Instruction::Mul, LHS, RHS, Name, HasNUW,
  1083. HasNSW);
  1084. }
  1085. Value *CreateNSWMul(Value *LHS, Value *RHS, const Twine &Name = "") {
  1086. return CreateMul(LHS, RHS, Name, false, true);
  1087. }
  1088. Value *CreateNUWMul(Value *LHS, Value *RHS, const Twine &Name = "") {
  1089. return CreateMul(LHS, RHS, Name, true, false);
  1090. }
  1091. Value *CreateUDiv(Value *LHS, Value *RHS, const Twine &Name = "",
  1092. bool isExact = false) {
  1093. if (Value *V = Folder.FoldExactBinOp(Instruction::UDiv, LHS, RHS, isExact))
  1094. return V;
  1095. if (!isExact)
  1096. return Insert(BinaryOperator::CreateUDiv(LHS, RHS), Name);
  1097. return Insert(BinaryOperator::CreateExactUDiv(LHS, RHS), Name);
  1098. }
  1099. Value *CreateExactUDiv(Value *LHS, Value *RHS, const Twine &Name = "") {
  1100. return CreateUDiv(LHS, RHS, Name, true);
  1101. }
  1102. Value *CreateSDiv(Value *LHS, Value *RHS, const Twine &Name = "",
  1103. bool isExact = false) {
  1104. if (Value *V = Folder.FoldExactBinOp(Instruction::SDiv, LHS, RHS, isExact))
  1105. return V;
  1106. if (!isExact)
  1107. return Insert(BinaryOperator::CreateSDiv(LHS, RHS), Name);
  1108. return Insert(BinaryOperator::CreateExactSDiv(LHS, RHS), Name);
  1109. }
  1110. Value *CreateExactSDiv(Value *LHS, Value *RHS, const Twine &Name = "") {
  1111. return CreateSDiv(LHS, RHS, Name, true);
  1112. }
  1113. Value *CreateURem(Value *LHS, Value *RHS, const Twine &Name = "") {
  1114. if (Value *V = Folder.FoldBinOp(Instruction::URem, LHS, RHS))
  1115. return V;
  1116. return Insert(BinaryOperator::CreateURem(LHS, RHS), Name);
  1117. }
  1118. Value *CreateSRem(Value *LHS, Value *RHS, const Twine &Name = "") {
  1119. if (Value *V = Folder.FoldBinOp(Instruction::SRem, LHS, RHS))
  1120. return V;
  1121. return Insert(BinaryOperator::CreateSRem(LHS, RHS), Name);
  1122. }
  1123. Value *CreateShl(Value *LHS, Value *RHS, const Twine &Name = "",
  1124. bool HasNUW = false, bool HasNSW = false) {
  1125. if (Value *V =
  1126. Folder.FoldNoWrapBinOp(Instruction::Shl, LHS, RHS, HasNUW, HasNSW))
  1127. return V;
  1128. return CreateInsertNUWNSWBinOp(Instruction::Shl, LHS, RHS, Name,
  1129. HasNUW, HasNSW);
  1130. }
  1131. Value *CreateShl(Value *LHS, const APInt &RHS, const Twine &Name = "",
  1132. bool HasNUW = false, bool HasNSW = false) {
  1133. return CreateShl(LHS, ConstantInt::get(LHS->getType(), RHS), Name,
  1134. HasNUW, HasNSW);
  1135. }
  1136. Value *CreateShl(Value *LHS, uint64_t RHS, const Twine &Name = "",
  1137. bool HasNUW = false, bool HasNSW = false) {
  1138. return CreateShl(LHS, ConstantInt::get(LHS->getType(), RHS), Name,
  1139. HasNUW, HasNSW);
  1140. }
  1141. Value *CreateLShr(Value *LHS, Value *RHS, const Twine &Name = "",
  1142. bool isExact = false) {
  1143. if (Value *V = Folder.FoldExactBinOp(Instruction::LShr, LHS, RHS, isExact))
  1144. return V;
  1145. if (!isExact)
  1146. return Insert(BinaryOperator::CreateLShr(LHS, RHS), Name);
  1147. return Insert(BinaryOperator::CreateExactLShr(LHS, RHS), Name);
  1148. }
  1149. Value *CreateLShr(Value *LHS, const APInt &RHS, const Twine &Name = "",
  1150. bool isExact = false) {
  1151. return CreateLShr(LHS, ConstantInt::get(LHS->getType(), RHS), Name,isExact);
  1152. }
  1153. Value *CreateLShr(Value *LHS, uint64_t RHS, const Twine &Name = "",
  1154. bool isExact = false) {
  1155. return CreateLShr(LHS, ConstantInt::get(LHS->getType(), RHS), Name,isExact);
  1156. }
  1157. Value *CreateAShr(Value *LHS, Value *RHS, const Twine &Name = "",
  1158. bool isExact = false) {
  1159. if (Value *V = Folder.FoldExactBinOp(Instruction::AShr, LHS, RHS, isExact))
  1160. return V;
  1161. if (!isExact)
  1162. return Insert(BinaryOperator::CreateAShr(LHS, RHS), Name);
  1163. return Insert(BinaryOperator::CreateExactAShr(LHS, RHS), Name);
  1164. }
  1165. Value *CreateAShr(Value *LHS, const APInt &RHS, const Twine &Name = "",
  1166. bool isExact = false) {
  1167. return CreateAShr(LHS, ConstantInt::get(LHS->getType(), RHS), Name,isExact);
  1168. }
  1169. Value *CreateAShr(Value *LHS, uint64_t RHS, const Twine &Name = "",
  1170. bool isExact = false) {
  1171. return CreateAShr(LHS, ConstantInt::get(LHS->getType(), RHS), Name,isExact);
  1172. }
  1173. Value *CreateAnd(Value *LHS, Value *RHS, const Twine &Name = "") {
  1174. if (auto *V = Folder.FoldBinOp(Instruction::And, LHS, RHS))
  1175. return V;
  1176. return Insert(BinaryOperator::CreateAnd(LHS, RHS), Name);
  1177. }
  1178. Value *CreateAnd(Value *LHS, const APInt &RHS, const Twine &Name = "") {
  1179. return CreateAnd(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
  1180. }
  1181. Value *CreateAnd(Value *LHS, uint64_t RHS, const Twine &Name = "") {
  1182. return CreateAnd(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
  1183. }
  1184. Value *CreateAnd(ArrayRef<Value*> Ops) {
  1185. assert(!Ops.empty());
  1186. Value *Accum = Ops[0];
  1187. for (unsigned i = 1; i < Ops.size(); i++)
  1188. Accum = CreateAnd(Accum, Ops[i]);
  1189. return Accum;
  1190. }
  1191. Value *CreateOr(Value *LHS, Value *RHS, const Twine &Name = "") {
  1192. if (auto *V = Folder.FoldBinOp(Instruction::Or, LHS, RHS))
  1193. return V;
  1194. return Insert(BinaryOperator::CreateOr(LHS, RHS), Name);
  1195. }
  1196. Value *CreateOr(Value *LHS, const APInt &RHS, const Twine &Name = "") {
  1197. return CreateOr(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
  1198. }
  1199. Value *CreateOr(Value *LHS, uint64_t RHS, const Twine &Name = "") {
  1200. return CreateOr(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
  1201. }
  1202. Value *CreateOr(ArrayRef<Value*> Ops) {
  1203. assert(!Ops.empty());
  1204. Value *Accum = Ops[0];
  1205. for (unsigned i = 1; i < Ops.size(); i++)
  1206. Accum = CreateOr(Accum, Ops[i]);
  1207. return Accum;
  1208. }
  1209. Value *CreateXor(Value *LHS, Value *RHS, const Twine &Name = "") {
  1210. if (Value *V = Folder.FoldBinOp(Instruction::Xor, LHS, RHS))
  1211. return V;
  1212. return Insert(BinaryOperator::CreateXor(LHS, RHS), Name);
  1213. }
  1214. Value *CreateXor(Value *LHS, const APInt &RHS, const Twine &Name = "") {
  1215. return CreateXor(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
  1216. }
  1217. Value *CreateXor(Value *LHS, uint64_t RHS, const Twine &Name = "") {
  1218. return CreateXor(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
  1219. }
  1220. Value *CreateFAdd(Value *L, Value *R, const Twine &Name = "",
  1221. MDNode *FPMD = nullptr) {
  1222. if (IsFPConstrained)
  1223. return CreateConstrainedFPBinOp(Intrinsic::experimental_constrained_fadd,
  1224. L, R, nullptr, Name, FPMD);
  1225. if (Value *V = Folder.FoldBinOpFMF(Instruction::FAdd, L, R, FMF))
  1226. return V;
  1227. Instruction *I = setFPAttrs(BinaryOperator::CreateFAdd(L, R), FPMD, FMF);
  1228. return Insert(I, Name);
  1229. }
  1230. /// Copy fast-math-flags from an instruction rather than using the builder's
  1231. /// default FMF.
  1232. Value *CreateFAddFMF(Value *L, Value *R, Instruction *FMFSource,
  1233. const Twine &Name = "") {
  1234. if (IsFPConstrained)
  1235. return CreateConstrainedFPBinOp(Intrinsic::experimental_constrained_fadd,
  1236. L, R, FMFSource, Name);
  1237. FastMathFlags FMF = FMFSource->getFastMathFlags();
  1238. if (Value *V = Folder.FoldBinOpFMF(Instruction::FAdd, L, R, FMF))
  1239. return V;
  1240. Instruction *I = setFPAttrs(BinaryOperator::CreateFAdd(L, R), nullptr, FMF);
  1241. return Insert(I, Name);
  1242. }
  1243. Value *CreateFSub(Value *L, Value *R, const Twine &Name = "",
  1244. MDNode *FPMD = nullptr) {
  1245. if (IsFPConstrained)
  1246. return CreateConstrainedFPBinOp(Intrinsic::experimental_constrained_fsub,
  1247. L, R, nullptr, Name, FPMD);
  1248. if (Value *V = Folder.FoldBinOpFMF(Instruction::FSub, L, R, FMF))
  1249. return V;
  1250. Instruction *I = setFPAttrs(BinaryOperator::CreateFSub(L, R), FPMD, FMF);
  1251. return Insert(I, Name);
  1252. }
  1253. /// Copy fast-math-flags from an instruction rather than using the builder's
  1254. /// default FMF.
  1255. Value *CreateFSubFMF(Value *L, Value *R, Instruction *FMFSource,
  1256. const Twine &Name = "") {
  1257. if (IsFPConstrained)
  1258. return CreateConstrainedFPBinOp(Intrinsic::experimental_constrained_fsub,
  1259. L, R, FMFSource, Name);
  1260. FastMathFlags FMF = FMFSource->getFastMathFlags();
  1261. if (Value *V = Folder.FoldBinOpFMF(Instruction::FSub, L, R, FMF))
  1262. return V;
  1263. Instruction *I = setFPAttrs(BinaryOperator::CreateFSub(L, R), nullptr, FMF);
  1264. return Insert(I, Name);
  1265. }
  1266. Value *CreateFMul(Value *L, Value *R, const Twine &Name = "",
  1267. MDNode *FPMD = nullptr) {
  1268. if (IsFPConstrained)
  1269. return CreateConstrainedFPBinOp(Intrinsic::experimental_constrained_fmul,
  1270. L, R, nullptr, Name, FPMD);
  1271. if (Value *V = Folder.FoldBinOpFMF(Instruction::FMul, L, R, FMF))
  1272. return V;
  1273. Instruction *I = setFPAttrs(BinaryOperator::CreateFMul(L, R), FPMD, FMF);
  1274. return Insert(I, Name);
  1275. }
  1276. /// Copy fast-math-flags from an instruction rather than using the builder's
  1277. /// default FMF.
  1278. Value *CreateFMulFMF(Value *L, Value *R, Instruction *FMFSource,
  1279. const Twine &Name = "") {
  1280. if (IsFPConstrained)
  1281. return CreateConstrainedFPBinOp(Intrinsic::experimental_constrained_fmul,
  1282. L, R, FMFSource, Name);
  1283. FastMathFlags FMF = FMFSource->getFastMathFlags();
  1284. if (Value *V = Folder.FoldBinOpFMF(Instruction::FMul, L, R, FMF))
  1285. return V;
  1286. Instruction *I = setFPAttrs(BinaryOperator::CreateFMul(L, R), nullptr, FMF);
  1287. return Insert(I, Name);
  1288. }
  1289. Value *CreateFDiv(Value *L, Value *R, const Twine &Name = "",
  1290. MDNode *FPMD = nullptr) {
  1291. if (IsFPConstrained)
  1292. return CreateConstrainedFPBinOp(Intrinsic::experimental_constrained_fdiv,
  1293. L, R, nullptr, Name, FPMD);
  1294. if (Value *V = Folder.FoldBinOpFMF(Instruction::FDiv, L, R, FMF))
  1295. return V;
  1296. Instruction *I = setFPAttrs(BinaryOperator::CreateFDiv(L, R), FPMD, FMF);
  1297. return Insert(I, Name);
  1298. }
  1299. /// Copy fast-math-flags from an instruction rather than using the builder's
  1300. /// default FMF.
  1301. Value *CreateFDivFMF(Value *L, Value *R, Instruction *FMFSource,
  1302. const Twine &Name = "") {
  1303. if (IsFPConstrained)
  1304. return CreateConstrainedFPBinOp(Intrinsic::experimental_constrained_fdiv,
  1305. L, R, FMFSource, Name);
  1306. FastMathFlags FMF = FMFSource->getFastMathFlags();
  1307. if (Value *V = Folder.FoldBinOpFMF(Instruction::FDiv, L, R, FMF))
  1308. return V;
  1309. Instruction *I = setFPAttrs(BinaryOperator::CreateFDiv(L, R), nullptr, FMF);
  1310. return Insert(I, Name);
  1311. }
  1312. Value *CreateFRem(Value *L, Value *R, const Twine &Name = "",
  1313. MDNode *FPMD = nullptr) {
  1314. if (IsFPConstrained)
  1315. return CreateConstrainedFPBinOp(Intrinsic::experimental_constrained_frem,
  1316. L, R, nullptr, Name, FPMD);
  1317. if (Value *V = Folder.FoldBinOpFMF(Instruction::FRem, L, R, FMF)) return V;
  1318. Instruction *I = setFPAttrs(BinaryOperator::CreateFRem(L, R), FPMD, FMF);
  1319. return Insert(I, Name);
  1320. }
  1321. /// Copy fast-math-flags from an instruction rather than using the builder's
  1322. /// default FMF.
  1323. Value *CreateFRemFMF(Value *L, Value *R, Instruction *FMFSource,
  1324. const Twine &Name = "") {
  1325. if (IsFPConstrained)
  1326. return CreateConstrainedFPBinOp(Intrinsic::experimental_constrained_frem,
  1327. L, R, FMFSource, Name);
  1328. FastMathFlags FMF = FMFSource->getFastMathFlags();
  1329. if (Value *V = Folder.FoldBinOpFMF(Instruction::FRem, L, R, FMF)) return V;
  1330. Instruction *I = setFPAttrs(BinaryOperator::CreateFRem(L, R), nullptr, FMF);
  1331. return Insert(I, Name);
  1332. }
  1333. Value *CreateBinOp(Instruction::BinaryOps Opc,
  1334. Value *LHS, Value *RHS, const Twine &Name = "",
  1335. MDNode *FPMathTag = nullptr) {
  1336. if (Value *V = Folder.FoldBinOp(Opc, LHS, RHS)) return V;
  1337. Instruction *BinOp = BinaryOperator::Create(Opc, LHS, RHS);
  1338. if (isa<FPMathOperator>(BinOp))
  1339. setFPAttrs(BinOp, FPMathTag, FMF);
  1340. return Insert(BinOp, Name);
  1341. }
  1342. Value *CreateLogicalAnd(Value *Cond1, Value *Cond2, const Twine &Name = "") {
  1343. assert(Cond2->getType()->isIntOrIntVectorTy(1));
  1344. return CreateSelect(Cond1, Cond2,
  1345. ConstantInt::getNullValue(Cond2->getType()), Name);
  1346. }
  1347. Value *CreateLogicalOr(Value *Cond1, Value *Cond2, const Twine &Name = "") {
  1348. assert(Cond2->getType()->isIntOrIntVectorTy(1));
  1349. return CreateSelect(Cond1, ConstantInt::getAllOnesValue(Cond2->getType()),
  1350. Cond2, Name);
  1351. }
  1352. Value *CreateLogicalOp(Instruction::BinaryOps Opc, Value *Cond1, Value *Cond2,
  1353. const Twine &Name = "") {
  1354. switch (Opc) {
  1355. case Instruction::And:
  1356. return CreateLogicalAnd(Cond1, Cond2, Name);
  1357. case Instruction::Or:
  1358. return CreateLogicalOr(Cond1, Cond2, Name);
  1359. default:
  1360. break;
  1361. }
  1362. llvm_unreachable("Not a logical operation.");
  1363. }
  1364. // NOTE: this is sequential, non-commutative, ordered reduction!
  1365. Value *CreateLogicalOr(ArrayRef<Value *> Ops) {
  1366. assert(!Ops.empty());
  1367. Value *Accum = Ops[0];
  1368. for (unsigned i = 1; i < Ops.size(); i++)
  1369. Accum = CreateLogicalOr(Accum, Ops[i]);
  1370. return Accum;
  1371. }
  1372. CallInst *CreateConstrainedFPBinOp(
  1373. Intrinsic::ID ID, Value *L, Value *R, Instruction *FMFSource = nullptr,
  1374. const Twine &Name = "", MDNode *FPMathTag = nullptr,
  1375. std::optional<RoundingMode> Rounding = std::nullopt,
  1376. std::optional<fp::ExceptionBehavior> Except = std::nullopt);
  1377. Value *CreateNeg(Value *V, const Twine &Name = "", bool HasNUW = false,
  1378. bool HasNSW = false) {
  1379. return CreateSub(Constant::getNullValue(V->getType()), V, Name, HasNUW,
  1380. HasNSW);
  1381. }
  1382. Value *CreateNSWNeg(Value *V, const Twine &Name = "") {
  1383. return CreateNeg(V, Name, false, true);
  1384. }
  1385. Value *CreateNUWNeg(Value *V, const Twine &Name = "") {
  1386. return CreateNeg(V, Name, true, false);
  1387. }
  1388. Value *CreateFNeg(Value *V, const Twine &Name = "",
  1389. MDNode *FPMathTag = nullptr) {
  1390. if (Value *Res = Folder.FoldUnOpFMF(Instruction::FNeg, V, FMF))
  1391. return Res;
  1392. return Insert(setFPAttrs(UnaryOperator::CreateFNeg(V), FPMathTag, FMF),
  1393. Name);
  1394. }
  1395. /// Copy fast-math-flags from an instruction rather than using the builder's
  1396. /// default FMF.
  1397. Value *CreateFNegFMF(Value *V, Instruction *FMFSource,
  1398. const Twine &Name = "") {
  1399. FastMathFlags FMF = FMFSource->getFastMathFlags();
  1400. if (Value *Res = Folder.FoldUnOpFMF(Instruction::FNeg, V, FMF))
  1401. return Res;
  1402. return Insert(setFPAttrs(UnaryOperator::CreateFNeg(V), nullptr, FMF),
  1403. Name);
  1404. }
  1405. Value *CreateNot(Value *V, const Twine &Name = "") {
  1406. return CreateXor(V, Constant::getAllOnesValue(V->getType()), Name);
  1407. }
  1408. Value *CreateUnOp(Instruction::UnaryOps Opc,
  1409. Value *V, const Twine &Name = "",
  1410. MDNode *FPMathTag = nullptr) {
  1411. if (Value *Res = Folder.FoldUnOpFMF(Opc, V, FMF))
  1412. return Res;
  1413. Instruction *UnOp = UnaryOperator::Create(Opc, V);
  1414. if (isa<FPMathOperator>(UnOp))
  1415. setFPAttrs(UnOp, FPMathTag, FMF);
  1416. return Insert(UnOp, Name);
  1417. }
  1418. /// Create either a UnaryOperator or BinaryOperator depending on \p Opc.
  1419. /// Correct number of operands must be passed accordingly.
  1420. Value *CreateNAryOp(unsigned Opc, ArrayRef<Value *> Ops,
  1421. const Twine &Name = "", MDNode *FPMathTag = nullptr);
  1422. //===--------------------------------------------------------------------===//
  1423. // Instruction creation methods: Memory Instructions
  1424. //===--------------------------------------------------------------------===//
  1425. AllocaInst *CreateAlloca(Type *Ty, unsigned AddrSpace,
  1426. Value *ArraySize = nullptr, const Twine &Name = "") {
  1427. const DataLayout &DL = BB->getModule()->getDataLayout();
  1428. Align AllocaAlign = DL.getPrefTypeAlign(Ty);
  1429. return Insert(new AllocaInst(Ty, AddrSpace, ArraySize, AllocaAlign), Name);
  1430. }
  1431. AllocaInst *CreateAlloca(Type *Ty, Value *ArraySize = nullptr,
  1432. const Twine &Name = "") {
  1433. const DataLayout &DL = BB->getModule()->getDataLayout();
  1434. Align AllocaAlign = DL.getPrefTypeAlign(Ty);
  1435. unsigned AddrSpace = DL.getAllocaAddrSpace();
  1436. return Insert(new AllocaInst(Ty, AddrSpace, ArraySize, AllocaAlign), Name);
  1437. }
  1438. /// Provided to resolve 'CreateLoad(Ty, Ptr, "...")' correctly, instead of
  1439. /// converting the string to 'bool' for the isVolatile parameter.
  1440. LoadInst *CreateLoad(Type *Ty, Value *Ptr, const char *Name) {
  1441. return CreateAlignedLoad(Ty, Ptr, MaybeAlign(), Name);
  1442. }
  1443. LoadInst *CreateLoad(Type *Ty, Value *Ptr, const Twine &Name = "") {
  1444. return CreateAlignedLoad(Ty, Ptr, MaybeAlign(), Name);
  1445. }
  1446. LoadInst *CreateLoad(Type *Ty, Value *Ptr, bool isVolatile,
  1447. const Twine &Name = "") {
  1448. return CreateAlignedLoad(Ty, Ptr, MaybeAlign(), isVolatile, Name);
  1449. }
  1450. StoreInst *CreateStore(Value *Val, Value *Ptr, bool isVolatile = false) {
  1451. return CreateAlignedStore(Val, Ptr, MaybeAlign(), isVolatile);
  1452. }
  1453. LoadInst *CreateAlignedLoad(Type *Ty, Value *Ptr, MaybeAlign Align,
  1454. const char *Name) {
  1455. return CreateAlignedLoad(Ty, Ptr, Align, /*isVolatile*/false, Name);
  1456. }
  1457. LoadInst *CreateAlignedLoad(Type *Ty, Value *Ptr, MaybeAlign Align,
  1458. const Twine &Name = "") {
  1459. return CreateAlignedLoad(Ty, Ptr, Align, /*isVolatile*/false, Name);
  1460. }
  1461. LoadInst *CreateAlignedLoad(Type *Ty, Value *Ptr, MaybeAlign Align,
  1462. bool isVolatile, const Twine &Name = "") {
  1463. if (!Align) {
  1464. const DataLayout &DL = BB->getModule()->getDataLayout();
  1465. Align = DL.getABITypeAlign(Ty);
  1466. }
  1467. return Insert(new LoadInst(Ty, Ptr, Twine(), isVolatile, *Align), Name);
  1468. }
  1469. StoreInst *CreateAlignedStore(Value *Val, Value *Ptr, MaybeAlign Align,
  1470. bool isVolatile = false) {
  1471. if (!Align) {
  1472. const DataLayout &DL = BB->getModule()->getDataLayout();
  1473. Align = DL.getABITypeAlign(Val->getType());
  1474. }
  1475. return Insert(new StoreInst(Val, Ptr, isVolatile, *Align));
  1476. }
  1477. FenceInst *CreateFence(AtomicOrdering Ordering,
  1478. SyncScope::ID SSID = SyncScope::System,
  1479. const Twine &Name = "") {
  1480. return Insert(new FenceInst(Context, Ordering, SSID), Name);
  1481. }
  1482. AtomicCmpXchgInst *
  1483. CreateAtomicCmpXchg(Value *Ptr, Value *Cmp, Value *New, MaybeAlign Align,
  1484. AtomicOrdering SuccessOrdering,
  1485. AtomicOrdering FailureOrdering,
  1486. SyncScope::ID SSID = SyncScope::System) {
  1487. if (!Align) {
  1488. const DataLayout &DL = BB->getModule()->getDataLayout();
  1489. Align = llvm::Align(DL.getTypeStoreSize(New->getType()));
  1490. }
  1491. return Insert(new AtomicCmpXchgInst(Ptr, Cmp, New, *Align, SuccessOrdering,
  1492. FailureOrdering, SSID));
  1493. }
  1494. AtomicRMWInst *CreateAtomicRMW(AtomicRMWInst::BinOp Op, Value *Ptr,
  1495. Value *Val, MaybeAlign Align,
  1496. AtomicOrdering Ordering,
  1497. SyncScope::ID SSID = SyncScope::System) {
  1498. if (!Align) {
  1499. const DataLayout &DL = BB->getModule()->getDataLayout();
  1500. Align = llvm::Align(DL.getTypeStoreSize(Val->getType()));
  1501. }
  1502. return Insert(new AtomicRMWInst(Op, Ptr, Val, *Align, Ordering, SSID));
  1503. }
  1504. Value *CreateGEP(Type *Ty, Value *Ptr, ArrayRef<Value *> IdxList,
  1505. const Twine &Name = "", bool IsInBounds = false) {
  1506. if (auto *V = Folder.FoldGEP(Ty, Ptr, IdxList, IsInBounds))
  1507. return V;
  1508. return Insert(IsInBounds
  1509. ? GetElementPtrInst::CreateInBounds(Ty, Ptr, IdxList)
  1510. : GetElementPtrInst::Create(Ty, Ptr, IdxList),
  1511. Name);
  1512. }
  1513. Value *CreateInBoundsGEP(Type *Ty, Value *Ptr, ArrayRef<Value *> IdxList,
  1514. const Twine &Name = "") {
  1515. return CreateGEP(Ty, Ptr, IdxList, Name, /* IsInBounds */ true);
  1516. }
  1517. Value *CreateConstGEP1_32(Type *Ty, Value *Ptr, unsigned Idx0,
  1518. const Twine &Name = "") {
  1519. Value *Idx = ConstantInt::get(Type::getInt32Ty(Context), Idx0);
  1520. if (auto *V = Folder.FoldGEP(Ty, Ptr, Idx, /*IsInBounds=*/false))
  1521. return V;
  1522. return Insert(GetElementPtrInst::Create(Ty, Ptr, Idx), Name);
  1523. }
  1524. Value *CreateConstInBoundsGEP1_32(Type *Ty, Value *Ptr, unsigned Idx0,
  1525. const Twine &Name = "") {
  1526. Value *Idx = ConstantInt::get(Type::getInt32Ty(Context), Idx0);
  1527. if (auto *V = Folder.FoldGEP(Ty, Ptr, Idx, /*IsInBounds=*/true))
  1528. return V;
  1529. return Insert(GetElementPtrInst::CreateInBounds(Ty, Ptr, Idx), Name);
  1530. }
  1531. Value *CreateConstGEP2_32(Type *Ty, Value *Ptr, unsigned Idx0, unsigned Idx1,
  1532. const Twine &Name = "") {
  1533. Value *Idxs[] = {
  1534. ConstantInt::get(Type::getInt32Ty(Context), Idx0),
  1535. ConstantInt::get(Type::getInt32Ty(Context), Idx1)
  1536. };
  1537. if (auto *V = Folder.FoldGEP(Ty, Ptr, Idxs, /*IsInBounds=*/false))
  1538. return V;
  1539. return Insert(GetElementPtrInst::Create(Ty, Ptr, Idxs), Name);
  1540. }
  1541. Value *CreateConstInBoundsGEP2_32(Type *Ty, Value *Ptr, unsigned Idx0,
  1542. unsigned Idx1, const Twine &Name = "") {
  1543. Value *Idxs[] = {
  1544. ConstantInt::get(Type::getInt32Ty(Context), Idx0),
  1545. ConstantInt::get(Type::getInt32Ty(Context), Idx1)
  1546. };
  1547. if (auto *V = Folder.FoldGEP(Ty, Ptr, Idxs, /*IsInBounds=*/true))
  1548. return V;
  1549. return Insert(GetElementPtrInst::CreateInBounds(Ty, Ptr, Idxs), Name);
  1550. }
  1551. Value *CreateConstGEP1_64(Type *Ty, Value *Ptr, uint64_t Idx0,
  1552. const Twine &Name = "") {
  1553. Value *Idx = ConstantInt::get(Type::getInt64Ty(Context), Idx0);
  1554. if (auto *V = Folder.FoldGEP(Ty, Ptr, Idx, /*IsInBounds=*/false))
  1555. return V;
  1556. return Insert(GetElementPtrInst::Create(Ty, Ptr, Idx), Name);
  1557. }
  1558. Value *CreateConstInBoundsGEP1_64(Type *Ty, Value *Ptr, uint64_t Idx0,
  1559. const Twine &Name = "") {
  1560. Value *Idx = ConstantInt::get(Type::getInt64Ty(Context), Idx0);
  1561. if (auto *V = Folder.FoldGEP(Ty, Ptr, Idx, /*IsInBounds=*/true))
  1562. return V;
  1563. return Insert(GetElementPtrInst::CreateInBounds(Ty, Ptr, Idx), Name);
  1564. }
  1565. Value *CreateConstGEP2_64(Type *Ty, Value *Ptr, uint64_t Idx0, uint64_t Idx1,
  1566. const Twine &Name = "") {
  1567. Value *Idxs[] = {
  1568. ConstantInt::get(Type::getInt64Ty(Context), Idx0),
  1569. ConstantInt::get(Type::getInt64Ty(Context), Idx1)
  1570. };
  1571. if (auto *V = Folder.FoldGEP(Ty, Ptr, Idxs, /*IsInBounds=*/false))
  1572. return V;
  1573. return Insert(GetElementPtrInst::Create(Ty, Ptr, Idxs), Name);
  1574. }
  1575. Value *CreateConstInBoundsGEP2_64(Type *Ty, Value *Ptr, uint64_t Idx0,
  1576. uint64_t Idx1, const Twine &Name = "") {
  1577. Value *Idxs[] = {
  1578. ConstantInt::get(Type::getInt64Ty(Context), Idx0),
  1579. ConstantInt::get(Type::getInt64Ty(Context), Idx1)
  1580. };
  1581. if (auto *V = Folder.FoldGEP(Ty, Ptr, Idxs, /*IsInBounds=*/true))
  1582. return V;
  1583. return Insert(GetElementPtrInst::CreateInBounds(Ty, Ptr, Idxs), Name);
  1584. }
  1585. Value *CreateStructGEP(Type *Ty, Value *Ptr, unsigned Idx,
  1586. const Twine &Name = "") {
  1587. return CreateConstInBoundsGEP2_32(Ty, Ptr, 0, Idx, Name);
  1588. }
  1589. /// Same as CreateGlobalString, but return a pointer with "i8*" type
  1590. /// instead of a pointer to array of i8.
  1591. ///
  1592. /// If no module is given via \p M, it is take from the insertion point basic
  1593. /// block.
  1594. Constant *CreateGlobalStringPtr(StringRef Str, const Twine &Name = "",
  1595. unsigned AddressSpace = 0,
  1596. Module *M = nullptr) {
  1597. GlobalVariable *GV = CreateGlobalString(Str, Name, AddressSpace, M);
  1598. Constant *Zero = ConstantInt::get(Type::getInt32Ty(Context), 0);
  1599. Constant *Indices[] = {Zero, Zero};
  1600. return ConstantExpr::getInBoundsGetElementPtr(GV->getValueType(), GV,
  1601. Indices);
  1602. }
  1603. //===--------------------------------------------------------------------===//
  1604. // Instruction creation methods: Cast/Conversion Operators
  1605. //===--------------------------------------------------------------------===//
  1606. Value *CreateTrunc(Value *V, Type *DestTy, const Twine &Name = "") {
  1607. return CreateCast(Instruction::Trunc, V, DestTy, Name);
  1608. }
  1609. Value *CreateZExt(Value *V, Type *DestTy, const Twine &Name = "") {
  1610. return CreateCast(Instruction::ZExt, V, DestTy, Name);
  1611. }
  1612. Value *CreateSExt(Value *V, Type *DestTy, const Twine &Name = "") {
  1613. return CreateCast(Instruction::SExt, V, DestTy, Name);
  1614. }
  1615. /// Create a ZExt or Trunc from the integer value V to DestTy. Return
  1616. /// the value untouched if the type of V is already DestTy.
  1617. Value *CreateZExtOrTrunc(Value *V, Type *DestTy,
  1618. const Twine &Name = "") {
  1619. assert(V->getType()->isIntOrIntVectorTy() &&
  1620. DestTy->isIntOrIntVectorTy() &&
  1621. "Can only zero extend/truncate integers!");
  1622. Type *VTy = V->getType();
  1623. if (VTy->getScalarSizeInBits() < DestTy->getScalarSizeInBits())
  1624. return CreateZExt(V, DestTy, Name);
  1625. if (VTy->getScalarSizeInBits() > DestTy->getScalarSizeInBits())
  1626. return CreateTrunc(V, DestTy, Name);
  1627. return V;
  1628. }
  1629. /// Create a SExt or Trunc from the integer value V to DestTy. Return
  1630. /// the value untouched if the type of V is already DestTy.
  1631. Value *CreateSExtOrTrunc(Value *V, Type *DestTy,
  1632. const Twine &Name = "") {
  1633. assert(V->getType()->isIntOrIntVectorTy() &&
  1634. DestTy->isIntOrIntVectorTy() &&
  1635. "Can only sign extend/truncate integers!");
  1636. Type *VTy = V->getType();
  1637. if (VTy->getScalarSizeInBits() < DestTy->getScalarSizeInBits())
  1638. return CreateSExt(V, DestTy, Name);
  1639. if (VTy->getScalarSizeInBits() > DestTy->getScalarSizeInBits())
  1640. return CreateTrunc(V, DestTy, Name);
  1641. return V;
  1642. }
  1643. Value *CreateFPToUI(Value *V, Type *DestTy, const Twine &Name = "") {
  1644. if (IsFPConstrained)
  1645. return CreateConstrainedFPCast(Intrinsic::experimental_constrained_fptoui,
  1646. V, DestTy, nullptr, Name);
  1647. return CreateCast(Instruction::FPToUI, V, DestTy, Name);
  1648. }
  1649. Value *CreateFPToSI(Value *V, Type *DestTy, const Twine &Name = "") {
  1650. if (IsFPConstrained)
  1651. return CreateConstrainedFPCast(Intrinsic::experimental_constrained_fptosi,
  1652. V, DestTy, nullptr, Name);
  1653. return CreateCast(Instruction::FPToSI, V, DestTy, Name);
  1654. }
  1655. Value *CreateUIToFP(Value *V, Type *DestTy, const Twine &Name = ""){
  1656. if (IsFPConstrained)
  1657. return CreateConstrainedFPCast(Intrinsic::experimental_constrained_uitofp,
  1658. V, DestTy, nullptr, Name);
  1659. return CreateCast(Instruction::UIToFP, V, DestTy, Name);
  1660. }
  1661. Value *CreateSIToFP(Value *V, Type *DestTy, const Twine &Name = ""){
  1662. if (IsFPConstrained)
  1663. return CreateConstrainedFPCast(Intrinsic::experimental_constrained_sitofp,
  1664. V, DestTy, nullptr, Name);
  1665. return CreateCast(Instruction::SIToFP, V, DestTy, Name);
  1666. }
  1667. Value *CreateFPTrunc(Value *V, Type *DestTy,
  1668. const Twine &Name = "") {
  1669. if (IsFPConstrained)
  1670. return CreateConstrainedFPCast(
  1671. Intrinsic::experimental_constrained_fptrunc, V, DestTy, nullptr,
  1672. Name);
  1673. return CreateCast(Instruction::FPTrunc, V, DestTy, Name);
  1674. }
  1675. Value *CreateFPExt(Value *V, Type *DestTy, const Twine &Name = "") {
  1676. if (IsFPConstrained)
  1677. return CreateConstrainedFPCast(Intrinsic::experimental_constrained_fpext,
  1678. V, DestTy, nullptr, Name);
  1679. return CreateCast(Instruction::FPExt, V, DestTy, Name);
  1680. }
  1681. Value *CreatePtrToInt(Value *V, Type *DestTy,
  1682. const Twine &Name = "") {
  1683. return CreateCast(Instruction::PtrToInt, V, DestTy, Name);
  1684. }
  1685. Value *CreateIntToPtr(Value *V, Type *DestTy,
  1686. const Twine &Name = "") {
  1687. return CreateCast(Instruction::IntToPtr, V, DestTy, Name);
  1688. }
  1689. Value *CreateBitCast(Value *V, Type *DestTy,
  1690. const Twine &Name = "") {
  1691. return CreateCast(Instruction::BitCast, V, DestTy, Name);
  1692. }
  1693. Value *CreateAddrSpaceCast(Value *V, Type *DestTy,
  1694. const Twine &Name = "") {
  1695. return CreateCast(Instruction::AddrSpaceCast, V, DestTy, Name);
  1696. }
  1697. Value *CreateZExtOrBitCast(Value *V, Type *DestTy,
  1698. const Twine &Name = "") {
  1699. if (V->getType() == DestTy)
  1700. return V;
  1701. if (auto *VC = dyn_cast<Constant>(V))
  1702. return Insert(Folder.CreateZExtOrBitCast(VC, DestTy), Name);
  1703. return Insert(CastInst::CreateZExtOrBitCast(V, DestTy), Name);
  1704. }
  1705. Value *CreateSExtOrBitCast(Value *V, Type *DestTy,
  1706. const Twine &Name = "") {
  1707. if (V->getType() == DestTy)
  1708. return V;
  1709. if (auto *VC = dyn_cast<Constant>(V))
  1710. return Insert(Folder.CreateSExtOrBitCast(VC, DestTy), Name);
  1711. return Insert(CastInst::CreateSExtOrBitCast(V, DestTy), Name);
  1712. }
  1713. Value *CreateTruncOrBitCast(Value *V, Type *DestTy,
  1714. const Twine &Name = "") {
  1715. if (V->getType() == DestTy)
  1716. return V;
  1717. if (auto *VC = dyn_cast<Constant>(V))
  1718. return Insert(Folder.CreateTruncOrBitCast(VC, DestTy), Name);
  1719. return Insert(CastInst::CreateTruncOrBitCast(V, DestTy), Name);
  1720. }
  1721. Value *CreateCast(Instruction::CastOps Op, Value *V, Type *DestTy,
  1722. const Twine &Name = "") {
  1723. if (V->getType() == DestTy)
  1724. return V;
  1725. if (auto *VC = dyn_cast<Constant>(V))
  1726. return Insert(Folder.CreateCast(Op, VC, DestTy), Name);
  1727. return Insert(CastInst::Create(Op, V, DestTy), Name);
  1728. }
  1729. Value *CreatePointerCast(Value *V, Type *DestTy,
  1730. const Twine &Name = "") {
  1731. if (V->getType() == DestTy)
  1732. return V;
  1733. if (auto *VC = dyn_cast<Constant>(V))
  1734. return Insert(Folder.CreatePointerCast(VC, DestTy), Name);
  1735. return Insert(CastInst::CreatePointerCast(V, DestTy), Name);
  1736. }
  1737. Value *CreatePointerBitCastOrAddrSpaceCast(Value *V, Type *DestTy,
  1738. const Twine &Name = "") {
  1739. if (V->getType() == DestTy)
  1740. return V;
  1741. if (auto *VC = dyn_cast<Constant>(V)) {
  1742. return Insert(Folder.CreatePointerBitCastOrAddrSpaceCast(VC, DestTy),
  1743. Name);
  1744. }
  1745. return Insert(CastInst::CreatePointerBitCastOrAddrSpaceCast(V, DestTy),
  1746. Name);
  1747. }
  1748. Value *CreateIntCast(Value *V, Type *DestTy, bool isSigned,
  1749. const Twine &Name = "") {
  1750. if (V->getType() == DestTy)
  1751. return V;
  1752. if (auto *VC = dyn_cast<Constant>(V))
  1753. return Insert(Folder.CreateIntCast(VC, DestTy, isSigned), Name);
  1754. return Insert(CastInst::CreateIntegerCast(V, DestTy, isSigned), Name);
  1755. }
  1756. Value *CreateBitOrPointerCast(Value *V, Type *DestTy,
  1757. const Twine &Name = "") {
  1758. if (V->getType() == DestTy)
  1759. return V;
  1760. if (V->getType()->isPtrOrPtrVectorTy() && DestTy->isIntOrIntVectorTy())
  1761. return CreatePtrToInt(V, DestTy, Name);
  1762. if (V->getType()->isIntOrIntVectorTy() && DestTy->isPtrOrPtrVectorTy())
  1763. return CreateIntToPtr(V, DestTy, Name);
  1764. return CreateBitCast(V, DestTy, Name);
  1765. }
  1766. Value *CreateFPCast(Value *V, Type *DestTy, const Twine &Name = "") {
  1767. if (V->getType() == DestTy)
  1768. return V;
  1769. if (auto *VC = dyn_cast<Constant>(V))
  1770. return Insert(Folder.CreateFPCast(VC, DestTy), Name);
  1771. return Insert(CastInst::CreateFPCast(V, DestTy), Name);
  1772. }
  1773. CallInst *CreateConstrainedFPCast(
  1774. Intrinsic::ID ID, Value *V, Type *DestTy,
  1775. Instruction *FMFSource = nullptr, const Twine &Name = "",
  1776. MDNode *FPMathTag = nullptr,
  1777. std::optional<RoundingMode> Rounding = std::nullopt,
  1778. std::optional<fp::ExceptionBehavior> Except = std::nullopt);
  1779. // Provided to resolve 'CreateIntCast(Ptr, Ptr, "...")', giving a
  1780. // compile time error, instead of converting the string to bool for the
  1781. // isSigned parameter.
  1782. Value *CreateIntCast(Value *, Type *, const char *) = delete;
  1783. //===--------------------------------------------------------------------===//
  1784. // Instruction creation methods: Compare Instructions
  1785. //===--------------------------------------------------------------------===//
  1786. Value *CreateICmpEQ(Value *LHS, Value *RHS, const Twine &Name = "") {
  1787. return CreateICmp(ICmpInst::ICMP_EQ, LHS, RHS, Name);
  1788. }
  1789. Value *CreateICmpNE(Value *LHS, Value *RHS, const Twine &Name = "") {
  1790. return CreateICmp(ICmpInst::ICMP_NE, LHS, RHS, Name);
  1791. }
  1792. Value *CreateICmpUGT(Value *LHS, Value *RHS, const Twine &Name = "") {
  1793. return CreateICmp(ICmpInst::ICMP_UGT, LHS, RHS, Name);
  1794. }
  1795. Value *CreateICmpUGE(Value *LHS, Value *RHS, const Twine &Name = "") {
  1796. return CreateICmp(ICmpInst::ICMP_UGE, LHS, RHS, Name);
  1797. }
  1798. Value *CreateICmpULT(Value *LHS, Value *RHS, const Twine &Name = "") {
  1799. return CreateICmp(ICmpInst::ICMP_ULT, LHS, RHS, Name);
  1800. }
  1801. Value *CreateICmpULE(Value *LHS, Value *RHS, const Twine &Name = "") {
  1802. return CreateICmp(ICmpInst::ICMP_ULE, LHS, RHS, Name);
  1803. }
  1804. Value *CreateICmpSGT(Value *LHS, Value *RHS, const Twine &Name = "") {
  1805. return CreateICmp(ICmpInst::ICMP_SGT, LHS, RHS, Name);
  1806. }
  1807. Value *CreateICmpSGE(Value *LHS, Value *RHS, const Twine &Name = "") {
  1808. return CreateICmp(ICmpInst::ICMP_SGE, LHS, RHS, Name);
  1809. }
  1810. Value *CreateICmpSLT(Value *LHS, Value *RHS, const Twine &Name = "") {
  1811. return CreateICmp(ICmpInst::ICMP_SLT, LHS, RHS, Name);
  1812. }
  1813. Value *CreateICmpSLE(Value *LHS, Value *RHS, const Twine &Name = "") {
  1814. return CreateICmp(ICmpInst::ICMP_SLE, LHS, RHS, Name);
  1815. }
  1816. Value *CreateFCmpOEQ(Value *LHS, Value *RHS, const Twine &Name = "",
  1817. MDNode *FPMathTag = nullptr) {
  1818. return CreateFCmp(FCmpInst::FCMP_OEQ, LHS, RHS, Name, FPMathTag);
  1819. }
  1820. Value *CreateFCmpOGT(Value *LHS, Value *RHS, const Twine &Name = "",
  1821. MDNode *FPMathTag = nullptr) {
  1822. return CreateFCmp(FCmpInst::FCMP_OGT, LHS, RHS, Name, FPMathTag);
  1823. }
  1824. Value *CreateFCmpOGE(Value *LHS, Value *RHS, const Twine &Name = "",
  1825. MDNode *FPMathTag = nullptr) {
  1826. return CreateFCmp(FCmpInst::FCMP_OGE, LHS, RHS, Name, FPMathTag);
  1827. }
  1828. Value *CreateFCmpOLT(Value *LHS, Value *RHS, const Twine &Name = "",
  1829. MDNode *FPMathTag = nullptr) {
  1830. return CreateFCmp(FCmpInst::FCMP_OLT, LHS, RHS, Name, FPMathTag);
  1831. }
  1832. Value *CreateFCmpOLE(Value *LHS, Value *RHS, const Twine &Name = "",
  1833. MDNode *FPMathTag = nullptr) {
  1834. return CreateFCmp(FCmpInst::FCMP_OLE, LHS, RHS, Name, FPMathTag);
  1835. }
  1836. Value *CreateFCmpONE(Value *LHS, Value *RHS, const Twine &Name = "",
  1837. MDNode *FPMathTag = nullptr) {
  1838. return CreateFCmp(FCmpInst::FCMP_ONE, LHS, RHS, Name, FPMathTag);
  1839. }
  1840. Value *CreateFCmpORD(Value *LHS, Value *RHS, const Twine &Name = "",
  1841. MDNode *FPMathTag = nullptr) {
  1842. return CreateFCmp(FCmpInst::FCMP_ORD, LHS, RHS, Name, FPMathTag);
  1843. }
  1844. Value *CreateFCmpUNO(Value *LHS, Value *RHS, const Twine &Name = "",
  1845. MDNode *FPMathTag = nullptr) {
  1846. return CreateFCmp(FCmpInst::FCMP_UNO, LHS, RHS, Name, FPMathTag);
  1847. }
  1848. Value *CreateFCmpUEQ(Value *LHS, Value *RHS, const Twine &Name = "",
  1849. MDNode *FPMathTag = nullptr) {
  1850. return CreateFCmp(FCmpInst::FCMP_UEQ, LHS, RHS, Name, FPMathTag);
  1851. }
  1852. Value *CreateFCmpUGT(Value *LHS, Value *RHS, const Twine &Name = "",
  1853. MDNode *FPMathTag = nullptr) {
  1854. return CreateFCmp(FCmpInst::FCMP_UGT, LHS, RHS, Name, FPMathTag);
  1855. }
  1856. Value *CreateFCmpUGE(Value *LHS, Value *RHS, const Twine &Name = "",
  1857. MDNode *FPMathTag = nullptr) {
  1858. return CreateFCmp(FCmpInst::FCMP_UGE, LHS, RHS, Name, FPMathTag);
  1859. }
  1860. Value *CreateFCmpULT(Value *LHS, Value *RHS, const Twine &Name = "",
  1861. MDNode *FPMathTag = nullptr) {
  1862. return CreateFCmp(FCmpInst::FCMP_ULT, LHS, RHS, Name, FPMathTag);
  1863. }
  1864. Value *CreateFCmpULE(Value *LHS, Value *RHS, const Twine &Name = "",
  1865. MDNode *FPMathTag = nullptr) {
  1866. return CreateFCmp(FCmpInst::FCMP_ULE, LHS, RHS, Name, FPMathTag);
  1867. }
  1868. Value *CreateFCmpUNE(Value *LHS, Value *RHS, const Twine &Name = "",
  1869. MDNode *FPMathTag = nullptr) {
  1870. return CreateFCmp(FCmpInst::FCMP_UNE, LHS, RHS, Name, FPMathTag);
  1871. }
  1872. Value *CreateICmp(CmpInst::Predicate P, Value *LHS, Value *RHS,
  1873. const Twine &Name = "") {
  1874. if (auto *V = Folder.FoldICmp(P, LHS, RHS))
  1875. return V;
  1876. return Insert(new ICmpInst(P, LHS, RHS), Name);
  1877. }
  1878. // Create a quiet floating-point comparison (i.e. one that raises an FP
  1879. // exception only in the case where an input is a signaling NaN).
  1880. // Note that this differs from CreateFCmpS only if IsFPConstrained is true.
  1881. Value *CreateFCmp(CmpInst::Predicate P, Value *LHS, Value *RHS,
  1882. const Twine &Name = "", MDNode *FPMathTag = nullptr) {
  1883. return CreateFCmpHelper(P, LHS, RHS, Name, FPMathTag, false);
  1884. }
  1885. Value *CreateCmp(CmpInst::Predicate Pred, Value *LHS, Value *RHS,
  1886. const Twine &Name = "", MDNode *FPMathTag = nullptr) {
  1887. return CmpInst::isFPPredicate(Pred)
  1888. ? CreateFCmp(Pred, LHS, RHS, Name, FPMathTag)
  1889. : CreateICmp(Pred, LHS, RHS, Name);
  1890. }
  1891. // Create a signaling floating-point comparison (i.e. one that raises an FP
  1892. // exception whenever an input is any NaN, signaling or quiet).
  1893. // Note that this differs from CreateFCmp only if IsFPConstrained is true.
  1894. Value *CreateFCmpS(CmpInst::Predicate P, Value *LHS, Value *RHS,
  1895. const Twine &Name = "", MDNode *FPMathTag = nullptr) {
  1896. return CreateFCmpHelper(P, LHS, RHS, Name, FPMathTag, true);
  1897. }
  1898. private:
  1899. // Helper routine to create either a signaling or a quiet FP comparison.
  1900. Value *CreateFCmpHelper(CmpInst::Predicate P, Value *LHS, Value *RHS,
  1901. const Twine &Name, MDNode *FPMathTag,
  1902. bool IsSignaling);
  1903. public:
  1904. CallInst *CreateConstrainedFPCmp(
  1905. Intrinsic::ID ID, CmpInst::Predicate P, Value *L, Value *R,
  1906. const Twine &Name = "",
  1907. std::optional<fp::ExceptionBehavior> Except = std::nullopt);
  1908. //===--------------------------------------------------------------------===//
  1909. // Instruction creation methods: Other Instructions
  1910. //===--------------------------------------------------------------------===//
  1911. PHINode *CreatePHI(Type *Ty, unsigned NumReservedValues,
  1912. const Twine &Name = "") {
  1913. PHINode *Phi = PHINode::Create(Ty, NumReservedValues);
  1914. if (isa<FPMathOperator>(Phi))
  1915. setFPAttrs(Phi, nullptr /* MDNode* */, FMF);
  1916. return Insert(Phi, Name);
  1917. }
  1918. private:
  1919. CallInst *createCallHelper(Function *Callee, ArrayRef<Value *> Ops,
  1920. const Twine &Name = "",
  1921. Instruction *FMFSource = nullptr,
  1922. ArrayRef<OperandBundleDef> OpBundles = {});
  1923. public:
  1924. CallInst *CreateCall(FunctionType *FTy, Value *Callee,
  1925. ArrayRef<Value *> Args = std::nullopt,
  1926. const Twine &Name = "", MDNode *FPMathTag = nullptr) {
  1927. CallInst *CI = CallInst::Create(FTy, Callee, Args, DefaultOperandBundles);
  1928. if (IsFPConstrained)
  1929. setConstrainedFPCallAttr(CI);
  1930. if (isa<FPMathOperator>(CI))
  1931. setFPAttrs(CI, FPMathTag, FMF);
  1932. return Insert(CI, Name);
  1933. }
  1934. CallInst *CreateCall(FunctionType *FTy, Value *Callee, ArrayRef<Value *> Args,
  1935. ArrayRef<OperandBundleDef> OpBundles,
  1936. const Twine &Name = "", MDNode *FPMathTag = nullptr) {
  1937. CallInst *CI = CallInst::Create(FTy, Callee, Args, OpBundles);
  1938. if (IsFPConstrained)
  1939. setConstrainedFPCallAttr(CI);
  1940. if (isa<FPMathOperator>(CI))
  1941. setFPAttrs(CI, FPMathTag, FMF);
  1942. return Insert(CI, Name);
  1943. }
  1944. CallInst *CreateCall(FunctionCallee Callee,
  1945. ArrayRef<Value *> Args = std::nullopt,
  1946. const Twine &Name = "", MDNode *FPMathTag = nullptr) {
  1947. return CreateCall(Callee.getFunctionType(), Callee.getCallee(), Args, Name,
  1948. FPMathTag);
  1949. }
  1950. CallInst *CreateCall(FunctionCallee Callee, ArrayRef<Value *> Args,
  1951. ArrayRef<OperandBundleDef> OpBundles,
  1952. const Twine &Name = "", MDNode *FPMathTag = nullptr) {
  1953. return CreateCall(Callee.getFunctionType(), Callee.getCallee(), Args,
  1954. OpBundles, Name, FPMathTag);
  1955. }
  1956. CallInst *CreateConstrainedFPCall(
  1957. Function *Callee, ArrayRef<Value *> Args, const Twine &Name = "",
  1958. std::optional<RoundingMode> Rounding = std::nullopt,
  1959. std::optional<fp::ExceptionBehavior> Except = std::nullopt);
  1960. Value *CreateSelect(Value *C, Value *True, Value *False,
  1961. const Twine &Name = "", Instruction *MDFrom = nullptr);
  1962. VAArgInst *CreateVAArg(Value *List, Type *Ty, const Twine &Name = "") {
  1963. return Insert(new VAArgInst(List, Ty), Name);
  1964. }
  1965. Value *CreateExtractElement(Value *Vec, Value *Idx,
  1966. const Twine &Name = "") {
  1967. if (Value *V = Folder.FoldExtractElement(Vec, Idx))
  1968. return V;
  1969. return Insert(ExtractElementInst::Create(Vec, Idx), Name);
  1970. }
  1971. Value *CreateExtractElement(Value *Vec, uint64_t Idx,
  1972. const Twine &Name = "") {
  1973. return CreateExtractElement(Vec, getInt64(Idx), Name);
  1974. }
  1975. Value *CreateInsertElement(Type *VecTy, Value *NewElt, Value *Idx,
  1976. const Twine &Name = "") {
  1977. return CreateInsertElement(PoisonValue::get(VecTy), NewElt, Idx, Name);
  1978. }
  1979. Value *CreateInsertElement(Type *VecTy, Value *NewElt, uint64_t Idx,
  1980. const Twine &Name = "") {
  1981. return CreateInsertElement(PoisonValue::get(VecTy), NewElt, Idx, Name);
  1982. }
  1983. Value *CreateInsertElement(Value *Vec, Value *NewElt, Value *Idx,
  1984. const Twine &Name = "") {
  1985. if (Value *V = Folder.FoldInsertElement(Vec, NewElt, Idx))
  1986. return V;
  1987. return Insert(InsertElementInst::Create(Vec, NewElt, Idx), Name);
  1988. }
  1989. Value *CreateInsertElement(Value *Vec, Value *NewElt, uint64_t Idx,
  1990. const Twine &Name = "") {
  1991. return CreateInsertElement(Vec, NewElt, getInt64(Idx), Name);
  1992. }
  1993. Value *CreateShuffleVector(Value *V1, Value *V2, Value *Mask,
  1994. const Twine &Name = "") {
  1995. SmallVector<int, 16> IntMask;
  1996. ShuffleVectorInst::getShuffleMask(cast<Constant>(Mask), IntMask);
  1997. return CreateShuffleVector(V1, V2, IntMask, Name);
  1998. }
  1999. /// See class ShuffleVectorInst for a description of the mask representation.
  2000. Value *CreateShuffleVector(Value *V1, Value *V2, ArrayRef<int> Mask,
  2001. const Twine &Name = "") {
  2002. if (Value *V = Folder.FoldShuffleVector(V1, V2, Mask))
  2003. return V;
  2004. return Insert(new ShuffleVectorInst(V1, V2, Mask), Name);
  2005. }
  2006. /// Create a unary shuffle. The second vector operand of the IR instruction
  2007. /// is poison.
  2008. Value *CreateShuffleVector(Value *V, ArrayRef<int> Mask,
  2009. const Twine &Name = "") {
  2010. return CreateShuffleVector(V, PoisonValue::get(V->getType()), Mask, Name);
  2011. }
  2012. Value *CreateExtractValue(Value *Agg, ArrayRef<unsigned> Idxs,
  2013. const Twine &Name = "") {
  2014. if (auto *V = Folder.FoldExtractValue(Agg, Idxs))
  2015. return V;
  2016. return Insert(ExtractValueInst::Create(Agg, Idxs), Name);
  2017. }
  2018. Value *CreateInsertValue(Value *Agg, Value *Val, ArrayRef<unsigned> Idxs,
  2019. const Twine &Name = "") {
  2020. if (auto *V = Folder.FoldInsertValue(Agg, Val, Idxs))
  2021. return V;
  2022. return Insert(InsertValueInst::Create(Agg, Val, Idxs), Name);
  2023. }
  2024. LandingPadInst *CreateLandingPad(Type *Ty, unsigned NumClauses,
  2025. const Twine &Name = "") {
  2026. return Insert(LandingPadInst::Create(Ty, NumClauses), Name);
  2027. }
  2028. Value *CreateFreeze(Value *V, const Twine &Name = "") {
  2029. return Insert(new FreezeInst(V), Name);
  2030. }
  2031. //===--------------------------------------------------------------------===//
  2032. // Utility creation methods
  2033. //===--------------------------------------------------------------------===//
  2034. /// Return a boolean value testing if \p Arg == 0.
  2035. Value *CreateIsNull(Value *Arg, const Twine &Name = "") {
  2036. return CreateICmpEQ(Arg, ConstantInt::getNullValue(Arg->getType()), Name);
  2037. }
  2038. /// Return a boolean value testing if \p Arg != 0.
  2039. Value *CreateIsNotNull(Value *Arg, const Twine &Name = "") {
  2040. return CreateICmpNE(Arg, ConstantInt::getNullValue(Arg->getType()), Name);
  2041. }
  2042. /// Return a boolean value testing if \p Arg < 0.
  2043. Value *CreateIsNeg(Value *Arg, const Twine &Name = "") {
  2044. return CreateICmpSLT(Arg, ConstantInt::getNullValue(Arg->getType()), Name);
  2045. }
  2046. /// Return a boolean value testing if \p Arg > -1.
  2047. Value *CreateIsNotNeg(Value *Arg, const Twine &Name = "") {
  2048. return CreateICmpSGT(Arg, ConstantInt::getAllOnesValue(Arg->getType()),
  2049. Name);
  2050. }
  2051. /// Return the i64 difference between two pointer values, dividing out
  2052. /// the size of the pointed-to objects.
  2053. ///
  2054. /// This is intended to implement C-style pointer subtraction. As such, the
  2055. /// pointers must be appropriately aligned for their element types and
  2056. /// pointing into the same object.
  2057. Value *CreatePtrDiff(Type *ElemTy, Value *LHS, Value *RHS,
  2058. const Twine &Name = "");
  2059. /// Create a launder.invariant.group intrinsic call. If Ptr type is
  2060. /// different from pointer to i8, it's casted to pointer to i8 in the same
  2061. /// address space before call and casted back to Ptr type after call.
  2062. Value *CreateLaunderInvariantGroup(Value *Ptr);
  2063. /// \brief Create a strip.invariant.group intrinsic call. If Ptr type is
  2064. /// different from pointer to i8, it's casted to pointer to i8 in the same
  2065. /// address space before call and casted back to Ptr type after call.
  2066. Value *CreateStripInvariantGroup(Value *Ptr);
  2067. /// Return a vector value that contains the vector V reversed
  2068. Value *CreateVectorReverse(Value *V, const Twine &Name = "");
  2069. /// Return a vector splice intrinsic if using scalable vectors, otherwise
  2070. /// return a shufflevector. If the immediate is positive, a vector is
  2071. /// extracted from concat(V1, V2), starting at Imm. If the immediate
  2072. /// is negative, we extract -Imm elements from V1 and the remaining
  2073. /// elements from V2. Imm is a signed integer in the range
  2074. /// -VL <= Imm < VL (where VL is the runtime vector length of the
  2075. /// source/result vector)
  2076. Value *CreateVectorSplice(Value *V1, Value *V2, int64_t Imm,
  2077. const Twine &Name = "");
  2078. /// Return a vector value that contains \arg V broadcasted to \p
  2079. /// NumElts elements.
  2080. Value *CreateVectorSplat(unsigned NumElts, Value *V, const Twine &Name = "");
  2081. /// Return a vector value that contains \arg V broadcasted to \p
  2082. /// EC elements.
  2083. Value *CreateVectorSplat(ElementCount EC, Value *V, const Twine &Name = "");
  2084. /// Return a value that has been extracted from a larger integer type.
  2085. Value *CreateExtractInteger(const DataLayout &DL, Value *From,
  2086. IntegerType *ExtractedTy, uint64_t Offset,
  2087. const Twine &Name);
  2088. Value *CreatePreserveArrayAccessIndex(Type *ElTy, Value *Base,
  2089. unsigned Dimension, unsigned LastIndex,
  2090. MDNode *DbgInfo);
  2091. Value *CreatePreserveUnionAccessIndex(Value *Base, unsigned FieldIndex,
  2092. MDNode *DbgInfo);
  2093. Value *CreatePreserveStructAccessIndex(Type *ElTy, Value *Base,
  2094. unsigned Index, unsigned FieldIndex,
  2095. MDNode *DbgInfo);
  2096. private:
  2097. /// Helper function that creates an assume intrinsic call that
  2098. /// represents an alignment assumption on the provided pointer \p PtrValue
  2099. /// with offset \p OffsetValue and alignment value \p AlignValue.
  2100. CallInst *CreateAlignmentAssumptionHelper(const DataLayout &DL,
  2101. Value *PtrValue, Value *AlignValue,
  2102. Value *OffsetValue);
  2103. public:
  2104. /// Create an assume intrinsic call that represents an alignment
  2105. /// assumption on the provided pointer.
  2106. ///
  2107. /// An optional offset can be provided, and if it is provided, the offset
  2108. /// must be subtracted from the provided pointer to get the pointer with the
  2109. /// specified alignment.
  2110. CallInst *CreateAlignmentAssumption(const DataLayout &DL, Value *PtrValue,
  2111. unsigned Alignment,
  2112. Value *OffsetValue = nullptr);
  2113. /// Create an assume intrinsic call that represents an alignment
  2114. /// assumption on the provided pointer.
  2115. ///
  2116. /// An optional offset can be provided, and if it is provided, the offset
  2117. /// must be subtracted from the provided pointer to get the pointer with the
  2118. /// specified alignment.
  2119. ///
  2120. /// This overload handles the condition where the Alignment is dependent
  2121. /// on an existing value rather than a static value.
  2122. CallInst *CreateAlignmentAssumption(const DataLayout &DL, Value *PtrValue,
  2123. Value *Alignment,
  2124. Value *OffsetValue = nullptr);
  2125. };
  2126. /// This provides a uniform API for creating instructions and inserting
  2127. /// them into a basic block: either at the end of a BasicBlock, or at a specific
  2128. /// iterator location in a block.
  2129. ///
  2130. /// Note that the builder does not expose the full generality of LLVM
  2131. /// instructions. For access to extra instruction properties, use the mutators
  2132. /// (e.g. setVolatile) on the instructions after they have been
  2133. /// created. Convenience state exists to specify fast-math flags and fp-math
  2134. /// tags.
  2135. ///
  2136. /// The first template argument specifies a class to use for creating constants.
  2137. /// This defaults to creating minimally folded constants. The second template
  2138. /// argument allows clients to specify custom insertion hooks that are called on
  2139. /// every newly created insertion.
  2140. template <typename FolderTy = ConstantFolder,
  2141. typename InserterTy = IRBuilderDefaultInserter>
  2142. class IRBuilder : public IRBuilderBase {
  2143. private:
  2144. FolderTy Folder;
  2145. InserterTy Inserter;
  2146. public:
  2147. IRBuilder(LLVMContext &C, FolderTy Folder, InserterTy Inserter = InserterTy(),
  2148. MDNode *FPMathTag = nullptr,
  2149. ArrayRef<OperandBundleDef> OpBundles = std::nullopt)
  2150. : IRBuilderBase(C, this->Folder, this->Inserter, FPMathTag, OpBundles),
  2151. Folder(Folder), Inserter(Inserter) {}
  2152. explicit IRBuilder(LLVMContext &C, MDNode *FPMathTag = nullptr,
  2153. ArrayRef<OperandBundleDef> OpBundles = std::nullopt)
  2154. : IRBuilderBase(C, this->Folder, this->Inserter, FPMathTag, OpBundles) {}
  2155. explicit IRBuilder(BasicBlock *TheBB, FolderTy Folder,
  2156. MDNode *FPMathTag = nullptr,
  2157. ArrayRef<OperandBundleDef> OpBundles = std::nullopt)
  2158. : IRBuilderBase(TheBB->getContext(), this->Folder, this->Inserter,
  2159. FPMathTag, OpBundles),
  2160. Folder(Folder) {
  2161. SetInsertPoint(TheBB);
  2162. }
  2163. explicit IRBuilder(BasicBlock *TheBB, MDNode *FPMathTag = nullptr,
  2164. ArrayRef<OperandBundleDef> OpBundles = std::nullopt)
  2165. : IRBuilderBase(TheBB->getContext(), this->Folder, this->Inserter,
  2166. FPMathTag, OpBundles) {
  2167. SetInsertPoint(TheBB);
  2168. }
  2169. explicit IRBuilder(Instruction *IP, MDNode *FPMathTag = nullptr,
  2170. ArrayRef<OperandBundleDef> OpBundles = std::nullopt)
  2171. : IRBuilderBase(IP->getContext(), this->Folder, this->Inserter, FPMathTag,
  2172. OpBundles) {
  2173. SetInsertPoint(IP);
  2174. }
  2175. IRBuilder(BasicBlock *TheBB, BasicBlock::iterator IP, FolderTy Folder,
  2176. MDNode *FPMathTag = nullptr,
  2177. ArrayRef<OperandBundleDef> OpBundles = std::nullopt)
  2178. : IRBuilderBase(TheBB->getContext(), this->Folder, this->Inserter,
  2179. FPMathTag, OpBundles),
  2180. Folder(Folder) {
  2181. SetInsertPoint(TheBB, IP);
  2182. }
  2183. IRBuilder(BasicBlock *TheBB, BasicBlock::iterator IP,
  2184. MDNode *FPMathTag = nullptr,
  2185. ArrayRef<OperandBundleDef> OpBundles = std::nullopt)
  2186. : IRBuilderBase(TheBB->getContext(), this->Folder, this->Inserter,
  2187. FPMathTag, OpBundles) {
  2188. SetInsertPoint(TheBB, IP);
  2189. }
  2190. /// Avoid copying the full IRBuilder. Prefer using InsertPointGuard
  2191. /// or FastMathFlagGuard instead.
  2192. IRBuilder(const IRBuilder &) = delete;
  2193. InserterTy &getInserter() { return Inserter; }
  2194. };
  2195. template <typename FolderTy, typename InserterTy>
  2196. IRBuilder(LLVMContext &, FolderTy, InserterTy, MDNode *,
  2197. ArrayRef<OperandBundleDef>) -> IRBuilder<FolderTy, InserterTy>;
  2198. IRBuilder(LLVMContext &, MDNode *, ArrayRef<OperandBundleDef>) -> IRBuilder<>;
  2199. template <typename FolderTy>
  2200. IRBuilder(BasicBlock *, FolderTy, MDNode *, ArrayRef<OperandBundleDef>)
  2201. -> IRBuilder<FolderTy>;
  2202. IRBuilder(BasicBlock *, MDNode *, ArrayRef<OperandBundleDef>) -> IRBuilder<>;
  2203. IRBuilder(Instruction *, MDNode *, ArrayRef<OperandBundleDef>) -> IRBuilder<>;
  2204. template <typename FolderTy>
  2205. IRBuilder(BasicBlock *, BasicBlock::iterator, FolderTy, MDNode *,
  2206. ArrayRef<OperandBundleDef>) -> IRBuilder<FolderTy>;
  2207. IRBuilder(BasicBlock *, BasicBlock::iterator, MDNode *,
  2208. ArrayRef<OperandBundleDef>) -> IRBuilder<>;
  2209. // Create wrappers for C Binding types (see CBindingWrapping.h).
  2210. DEFINE_SIMPLE_CONVERSION_FUNCTIONS(IRBuilder<>, LLVMBuilderRef)
  2211. } // end namespace llvm
  2212. #endif // LLVM_IR_IRBUILDER_H
  2213. #ifdef __GNUC__
  2214. #pragma GCC diagnostic pop
  2215. #endif