1 //===---- llvm/IRBuilder.h - Builder for LLVM Instructions ------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the IRBuilder class, which is used as a convenient way
11 // to create LLVM instructions with a consistent and simplified interface.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #ifndef LLVM_IR_IRBUILDER_H
16 #define LLVM_IR_IRBUILDER_H
17 
18 #include "llvm/ADT/ArrayRef.h"
19 #include "llvm/ADT/StringRef.h"
20 #include "llvm/ADT/Twine.h"
21 #include "llvm/IR/BasicBlock.h"
22 #include "llvm/IR/ConstantFolder.h"
23 #include "llvm/IR/DataLayout.h"
24 #include "llvm/IR/Function.h"
25 #include "llvm/IR/GlobalVariable.h"
26 #include "llvm/IR/Instructions.h"
27 #include "llvm/IR/Intrinsics.h"
28 #include "llvm/IR/LLVMContext.h"
29 #include "llvm/IR/Operator.h"
30 #include "llvm/IR/ValueHandle.h"
31 #include "llvm/Support/CBindingWrapping.h"
32 
33 namespace llvm {
34 class MDNode;
35 
36 /// \brief This provides the default implementation of the IRBuilder
37 /// 'InsertHelper' method that is called whenever an instruction is created by
38 /// IRBuilder and needs to be inserted.
39 ///
40 /// By default, this inserts the instruction at the insertion point.
41 template <bool preserveNames = true>
42 class IRBuilderDefaultInserter {
43 protected:
InsertHelper(Instruction * I,const Twine & Name,BasicBlock * BB,BasicBlock::iterator InsertPt)44   void InsertHelper(Instruction *I, const Twine &Name,
45                     BasicBlock *BB, BasicBlock::iterator InsertPt) const {
46     if (BB) BB->getInstList().insert(InsertPt, I);
47     if (preserveNames)
48       I->setName(Name);
49   }
50 };
51 
52 /// \brief Common base class shared among various IRBuilders.
53 class IRBuilderBase {
54   DebugLoc CurDbgLocation;
55 
56 protected:
57   BasicBlock *BB;
58   BasicBlock::iterator InsertPt;
59   LLVMContext &Context;
60 
61   MDNode *DefaultFPMathTag;
62   FastMathFlags FMF;
63 
64 public:
65   IRBuilderBase(LLVMContext &context, MDNode *FPMathTag = nullptr)
Context(context)66     : Context(context), DefaultFPMathTag(FPMathTag), FMF() {
67     ClearInsertionPoint();
68   }
69 
70   //===--------------------------------------------------------------------===//
71   // Builder configuration methods
72   //===--------------------------------------------------------------------===//
73 
74   /// \brief Clear the insertion point: created instructions will not be
75   /// inserted into a block.
ClearInsertionPoint()76   void ClearInsertionPoint() {
77     BB = nullptr;
78     InsertPt.reset(nullptr);
79   }
80 
GetInsertBlock()81   BasicBlock *GetInsertBlock() const { return BB; }
GetInsertPoint()82   BasicBlock::iterator GetInsertPoint() const { return InsertPt; }
getContext()83   LLVMContext &getContext() const { return Context; }
84 
85   /// \brief This specifies that created instructions should be appended to the
86   /// end of the specified block.
SetInsertPoint(BasicBlock * TheBB)87   void SetInsertPoint(BasicBlock *TheBB) {
88     BB = TheBB;
89     InsertPt = BB->end();
90   }
91 
92   /// \brief This specifies that created instructions should be inserted before
93   /// the specified instruction.
SetInsertPoint(Instruction * I)94   void SetInsertPoint(Instruction *I) {
95     BB = I->getParent();
96     InsertPt = I->getIterator();
97     assert(InsertPt != BB->end() && "Can't read debug loc from end()");
98     SetCurrentDebugLocation(I->getDebugLoc());
99   }
100 
101   /// \brief This specifies that created instructions should be inserted at the
102   /// specified point.
SetInsertPoint(BasicBlock * TheBB,BasicBlock::iterator IP)103   void SetInsertPoint(BasicBlock *TheBB, BasicBlock::iterator IP) {
104     BB = TheBB;
105     InsertPt = IP;
106     if (IP != TheBB->end())
107       SetCurrentDebugLocation(IP->getDebugLoc());
108   }
109 
110   /// \brief Set location information used by debugging information.
SetCurrentDebugLocation(DebugLoc L)111   void SetCurrentDebugLocation(DebugLoc L) { CurDbgLocation = std::move(L); }
112 
113   /// \brief Get location information used by debugging information.
getCurrentDebugLocation()114   const DebugLoc &getCurrentDebugLocation() const { return CurDbgLocation; }
115 
116   /// \brief If this builder has a current debug location, set it on the
117   /// specified instruction.
SetInstDebugLocation(Instruction * I)118   void SetInstDebugLocation(Instruction *I) const {
119     if (CurDbgLocation)
120       I->setDebugLoc(CurDbgLocation);
121   }
122 
123   /// \brief Get the return type of the current function that we're emitting
124   /// into.
125   Type *getCurrentFunctionReturnType() const;
126 
127   /// InsertPoint - A saved insertion point.
128   class InsertPoint {
129     BasicBlock *Block;
130     BasicBlock::iterator Point;
131 
132   public:
133     /// \brief Creates a new insertion point which doesn't point to anything.
InsertPoint()134     InsertPoint() : Block(nullptr) {}
135 
136     /// \brief Creates a new insertion point at the given location.
InsertPoint(BasicBlock * InsertBlock,BasicBlock::iterator InsertPoint)137     InsertPoint(BasicBlock *InsertBlock, BasicBlock::iterator InsertPoint)
138       : Block(InsertBlock), Point(InsertPoint) {}
139 
140     /// \brief Returns true if this insert point is set.
isSet()141     bool isSet() const { return (Block != nullptr); }
142 
getBlock()143     llvm::BasicBlock *getBlock() const { return Block; }
getPoint()144     llvm::BasicBlock::iterator getPoint() const { return Point; }
145   };
146 
147   /// \brief Returns the current insert point.
saveIP()148   InsertPoint saveIP() const {
149     return InsertPoint(GetInsertBlock(), GetInsertPoint());
150   }
151 
152   /// \brief Returns the current insert point, clearing it in the process.
saveAndClearIP()153   InsertPoint saveAndClearIP() {
154     InsertPoint IP(GetInsertBlock(), GetInsertPoint());
155     ClearInsertionPoint();
156     return IP;
157   }
158 
159   /// \brief Sets the current insert point to a previously-saved location.
restoreIP(InsertPoint IP)160   void restoreIP(InsertPoint IP) {
161     if (IP.isSet())
162       SetInsertPoint(IP.getBlock(), IP.getPoint());
163     else
164       ClearInsertionPoint();
165   }
166 
167   /// \brief Get the floating point math metadata being used.
getDefaultFPMathTag()168   MDNode *getDefaultFPMathTag() const { return DefaultFPMathTag; }
169 
170   /// \brief Get the flags to be applied to created floating point ops
getFastMathFlags()171   FastMathFlags getFastMathFlags() const { return FMF; }
172 
173   /// \brief Clear the fast-math flags.
clearFastMathFlags()174   void clearFastMathFlags() { FMF.clear(); }
175 
176   /// \brief Set the floating point math metadata to be used.
SetDefaultFPMathTag(MDNode * FPMathTag)177   void SetDefaultFPMathTag(MDNode *FPMathTag) { DefaultFPMathTag = FPMathTag; }
178 
179   /// \brief Set the fast-math flags to be used with generated fp-math operators
SetFastMathFlags(FastMathFlags NewFMF)180   void SetFastMathFlags(FastMathFlags NewFMF) { FMF = NewFMF; }
181 
182   //===--------------------------------------------------------------------===//
183   // RAII helpers.
184   //===--------------------------------------------------------------------===//
185 
186   // \brief RAII object that stores the current insertion point and restores it
187   // when the object is destroyed. This includes the debug location.
188   class InsertPointGuard {
189     IRBuilderBase &Builder;
190     AssertingVH<BasicBlock> Block;
191     BasicBlock::iterator Point;
192     DebugLoc DbgLoc;
193 
194     InsertPointGuard(const InsertPointGuard &) = delete;
195     InsertPointGuard &operator=(const InsertPointGuard &) = delete;
196 
197   public:
InsertPointGuard(IRBuilderBase & B)198     InsertPointGuard(IRBuilderBase &B)
199         : Builder(B), Block(B.GetInsertBlock()), Point(B.GetInsertPoint()),
200           DbgLoc(B.getCurrentDebugLocation()) {}
201 
~InsertPointGuard()202     ~InsertPointGuard() {
203       Builder.restoreIP(InsertPoint(Block, Point));
204       Builder.SetCurrentDebugLocation(DbgLoc);
205     }
206   };
207 
208   // \brief RAII object that stores the current fast math settings and restores
209   // them when the object is destroyed.
210   class FastMathFlagGuard {
211     IRBuilderBase &Builder;
212     FastMathFlags FMF;
213     MDNode *FPMathTag;
214 
215     FastMathFlagGuard(const FastMathFlagGuard &) = delete;
216     FastMathFlagGuard &operator=(
217         const FastMathFlagGuard &) = delete;
218 
219   public:
FastMathFlagGuard(IRBuilderBase & B)220     FastMathFlagGuard(IRBuilderBase &B)
221         : Builder(B), FMF(B.FMF), FPMathTag(B.DefaultFPMathTag) {}
222 
~FastMathFlagGuard()223     ~FastMathFlagGuard() {
224       Builder.FMF = FMF;
225       Builder.DefaultFPMathTag = FPMathTag;
226     }
227   };
228 
229   //===--------------------------------------------------------------------===//
230   // Miscellaneous creation methods.
231   //===--------------------------------------------------------------------===//
232 
233   /// \brief Make a new global variable with initializer type i8*
234   ///
235   /// Make a new global variable with an initializer that has array of i8 type
236   /// filled in with the null terminated string value specified.  The new global
237   /// variable will be marked mergable with any others of the same contents.  If
238   /// Name is specified, it is the name of the global variable created.
239   GlobalVariable *CreateGlobalString(StringRef Str, const Twine &Name = "",
240                                      unsigned AddressSpace = 0);
241 
242   /// \brief Get a constant value representing either true or false.
getInt1(bool V)243   ConstantInt *getInt1(bool V) {
244     return ConstantInt::get(getInt1Ty(), V);
245   }
246 
247   /// \brief Get the constant value for i1 true.
getTrue()248   ConstantInt *getTrue() {
249     return ConstantInt::getTrue(Context);
250   }
251 
252   /// \brief Get the constant value for i1 false.
getFalse()253   ConstantInt *getFalse() {
254     return ConstantInt::getFalse(Context);
255   }
256 
257   /// \brief Get a constant 8-bit value.
getInt8(uint8_t C)258   ConstantInt *getInt8(uint8_t C) {
259     return ConstantInt::get(getInt8Ty(), C);
260   }
261 
262   /// \brief Get a constant 16-bit value.
getInt16(uint16_t C)263   ConstantInt *getInt16(uint16_t C) {
264     return ConstantInt::get(getInt16Ty(), C);
265   }
266 
267   /// \brief Get a constant 32-bit value.
getInt32(uint32_t C)268   ConstantInt *getInt32(uint32_t C) {
269     return ConstantInt::get(getInt32Ty(), C);
270   }
271 
272   /// \brief Get a constant 64-bit value.
getInt64(uint64_t C)273   ConstantInt *getInt64(uint64_t C) {
274     return ConstantInt::get(getInt64Ty(), C);
275   }
276 
277   /// \brief Get a constant N-bit value, zero extended or truncated from
278   /// a 64-bit value.
getIntN(unsigned N,uint64_t C)279   ConstantInt *getIntN(unsigned N, uint64_t C) {
280     return ConstantInt::get(getIntNTy(N), C);
281   }
282 
283   /// \brief Get a constant integer value.
getInt(const APInt & AI)284   ConstantInt *getInt(const APInt &AI) {
285     return ConstantInt::get(Context, AI);
286   }
287 
288   //===--------------------------------------------------------------------===//
289   // Type creation methods
290   //===--------------------------------------------------------------------===//
291 
292   /// \brief Fetch the type representing a single bit
getInt1Ty()293   IntegerType *getInt1Ty() {
294     return Type::getInt1Ty(Context);
295   }
296 
297   /// \brief Fetch the type representing an 8-bit integer.
getInt8Ty()298   IntegerType *getInt8Ty() {
299     return Type::getInt8Ty(Context);
300   }
301 
302   /// \brief Fetch the type representing a 16-bit integer.
getInt16Ty()303   IntegerType *getInt16Ty() {
304     return Type::getInt16Ty(Context);
305   }
306 
307   /// \brief Fetch the type representing a 32-bit integer.
getInt32Ty()308   IntegerType *getInt32Ty() {
309     return Type::getInt32Ty(Context);
310   }
311 
312   /// \brief Fetch the type representing a 64-bit integer.
getInt64Ty()313   IntegerType *getInt64Ty() {
314     return Type::getInt64Ty(Context);
315   }
316 
317   /// \brief Fetch the type representing a 128-bit integer.
getInt128Ty()318   IntegerType *getInt128Ty() { return Type::getInt128Ty(Context); }
319 
320   /// \brief Fetch the type representing an N-bit integer.
getIntNTy(unsigned N)321   IntegerType *getIntNTy(unsigned N) {
322     return Type::getIntNTy(Context, N);
323   }
324 
325   /// \brief Fetch the type representing a 16-bit floating point value.
getHalfTy()326   Type *getHalfTy() {
327     return Type::getHalfTy(Context);
328   }
329 
330   /// \brief Fetch the type representing a 32-bit floating point value.
getFloatTy()331   Type *getFloatTy() {
332     return Type::getFloatTy(Context);
333   }
334 
335   /// \brief Fetch the type representing a 64-bit floating point value.
getDoubleTy()336   Type *getDoubleTy() {
337     return Type::getDoubleTy(Context);
338   }
339 
340   /// \brief Fetch the type representing void.
getVoidTy()341   Type *getVoidTy() {
342     return Type::getVoidTy(Context);
343   }
344 
345   /// \brief Fetch the type representing a pointer to an 8-bit integer value.
346   PointerType *getInt8PtrTy(unsigned AddrSpace = 0) {
347     return Type::getInt8PtrTy(Context, AddrSpace);
348   }
349 
350   /// \brief Fetch the type representing a pointer to an integer value.
351   IntegerType *getIntPtrTy(const DataLayout &DL, unsigned AddrSpace = 0) {
352     return DL.getIntPtrType(Context, AddrSpace);
353   }
354 
355   //===--------------------------------------------------------------------===//
356   // Intrinsic creation methods
357   //===--------------------------------------------------------------------===//
358 
359   /// \brief Create and insert a memset to the specified pointer and the
360   /// specified value.
361   ///
362   /// If the pointer isn't an i8*, it will be converted. If a TBAA tag is
363   /// specified, it will be added to the instruction. Likewise with alias.scope
364   /// and noalias tags.
365   CallInst *CreateMemSet(Value *Ptr, Value *Val, uint64_t Size, unsigned Align,
366                          bool isVolatile = false, MDNode *TBAATag = nullptr,
367                          MDNode *ScopeTag = nullptr,
368                          MDNode *NoAliasTag = nullptr) {
369     return CreateMemSet(Ptr, Val, getInt64(Size), Align, isVolatile,
370                         TBAATag, ScopeTag, NoAliasTag);
371   }
372 
373   CallInst *CreateMemSet(Value *Ptr, Value *Val, Value *Size, unsigned Align,
374                          bool isVolatile = false, MDNode *TBAATag = nullptr,
375                          MDNode *ScopeTag = nullptr,
376                          MDNode *NoAliasTag = nullptr);
377 
378   /// \brief Create and insert a memcpy between the specified pointers.
379   ///
380   /// If the pointers aren't i8*, they will be converted.  If a TBAA tag is
381   /// specified, it will be added to the instruction. Likewise with alias.scope
382   /// and noalias tags.
383   CallInst *CreateMemCpy(Value *Dst, Value *Src, uint64_t Size, unsigned Align,
384                          bool isVolatile = false, MDNode *TBAATag = nullptr,
385                          MDNode *TBAAStructTag = nullptr,
386                          MDNode *ScopeTag = nullptr,
387                          MDNode *NoAliasTag = nullptr) {
388     return CreateMemCpy(Dst, Src, getInt64(Size), Align, isVolatile, TBAATag,
389                         TBAAStructTag, ScopeTag, NoAliasTag);
390   }
391 
392   CallInst *CreateMemCpy(Value *Dst, Value *Src, Value *Size, unsigned Align,
393                          bool isVolatile = false, MDNode *TBAATag = nullptr,
394                          MDNode *TBAAStructTag = nullptr,
395                          MDNode *ScopeTag = nullptr,
396                          MDNode *NoAliasTag = nullptr);
397 
398   /// \brief Create and insert a memmove between the specified
399   /// pointers.
400   ///
401   /// If the pointers aren't i8*, they will be converted.  If a TBAA tag is
402   /// specified, it will be added to the instruction. Likewise with alias.scope
403   /// and noalias tags.
404   CallInst *CreateMemMove(Value *Dst, Value *Src, uint64_t Size, unsigned Align,
405                           bool isVolatile = false, MDNode *TBAATag = nullptr,
406                           MDNode *ScopeTag = nullptr,
407                           MDNode *NoAliasTag = nullptr) {
408     return CreateMemMove(Dst, Src, getInt64(Size), Align, isVolatile,
409                          TBAATag, ScopeTag, NoAliasTag);
410   }
411 
412   CallInst *CreateMemMove(Value *Dst, Value *Src, Value *Size, unsigned Align,
413                           bool isVolatile = false, MDNode *TBAATag = nullptr,
414                           MDNode *ScopeTag = nullptr,
415                           MDNode *NoAliasTag = nullptr);
416 
417   /// \brief Create a lifetime.start intrinsic.
418   ///
419   /// If the pointer isn't i8* it will be converted.
420   CallInst *CreateLifetimeStart(Value *Ptr, ConstantInt *Size = nullptr);
421 
422   /// \brief Create a lifetime.end intrinsic.
423   ///
424   /// If the pointer isn't i8* it will be converted.
425   CallInst *CreateLifetimeEnd(Value *Ptr, ConstantInt *Size = nullptr);
426 
427   /// \brief Create a call to Masked Load intrinsic
428   CallInst *CreateMaskedLoad(Value *Ptr, unsigned Align, Value *Mask,
429                              Value *PassThru = nullptr, const Twine &Name = "");
430 
431   /// \brief Create a call to Masked Store intrinsic
432   CallInst *CreateMaskedStore(Value *Val, Value *Ptr, unsigned Align,
433                               Value *Mask);
434 
435   /// \brief Create an assume intrinsic call that allows the optimizer to
436   /// assume that the provided condition will be true.
437   CallInst *CreateAssumption(Value *Cond);
438 
439   /// \brief Create a call to the experimental.gc.statepoint intrinsic to
440   /// start a new statepoint sequence.
441   CallInst *CreateGCStatepointCall(uint64_t ID, uint32_t NumPatchBytes,
442                                    Value *ActualCallee,
443                                    ArrayRef<Value *> CallArgs,
444                                    ArrayRef<Value *> DeoptArgs,
445                                    ArrayRef<Value *> GCArgs,
446                                    const Twine &Name = "");
447 
448   /// \brief Create a call to the experimental.gc.statepoint intrinsic to
449   /// start a new statepoint sequence.
450   CallInst *CreateGCStatepointCall(uint64_t ID, uint32_t NumPatchBytes,
451                                    Value *ActualCallee, uint32_t Flags,
452                                    ArrayRef<Use> CallArgs,
453                                    ArrayRef<Use> TransitionArgs,
454                                    ArrayRef<Use> DeoptArgs,
455                                    ArrayRef<Value *> GCArgs,
456                                    const Twine &Name = "");
457 
458   // \brief Conveninence function for the common case when CallArgs are filled
459   // in using makeArrayRef(CS.arg_begin(), CS.arg_end()); Use needs to be
460   // .get()'ed to get the Value pointer.
461   CallInst *CreateGCStatepointCall(uint64_t ID, uint32_t NumPatchBytes,
462                                    Value *ActualCallee, ArrayRef<Use> CallArgs,
463                                    ArrayRef<Value *> DeoptArgs,
464                                    ArrayRef<Value *> GCArgs,
465                                    const Twine &Name = "");
466 
467   /// brief Create an invoke to the experimental.gc.statepoint intrinsic to
468   /// start a new statepoint sequence.
469   InvokeInst *
470   CreateGCStatepointInvoke(uint64_t ID, uint32_t NumPatchBytes,
471                            Value *ActualInvokee, BasicBlock *NormalDest,
472                            BasicBlock *UnwindDest, ArrayRef<Value *> InvokeArgs,
473                            ArrayRef<Value *> DeoptArgs,
474                            ArrayRef<Value *> GCArgs, const Twine &Name = "");
475 
476   /// brief Create an invoke to the experimental.gc.statepoint intrinsic to
477   /// start a new statepoint sequence.
478   InvokeInst *CreateGCStatepointInvoke(
479       uint64_t ID, uint32_t NumPatchBytes, Value *ActualInvokee,
480       BasicBlock *NormalDest, BasicBlock *UnwindDest, uint32_t Flags,
481       ArrayRef<Use> InvokeArgs, ArrayRef<Use> TransitionArgs,
482       ArrayRef<Use> DeoptArgs, ArrayRef<Value *> GCArgs,
483       const Twine &Name = "");
484 
485   // Conveninence function for the common case when CallArgs are filled in using
486   // makeArrayRef(CS.arg_begin(), CS.arg_end()); Use needs to be .get()'ed to
487   // get the Value *.
488   InvokeInst *
489   CreateGCStatepointInvoke(uint64_t ID, uint32_t NumPatchBytes,
490                            Value *ActualInvokee, BasicBlock *NormalDest,
491                            BasicBlock *UnwindDest, ArrayRef<Use> InvokeArgs,
492                            ArrayRef<Value *> DeoptArgs,
493                            ArrayRef<Value *> GCArgs, const Twine &Name = "");
494 
495   /// \brief Create a call to the experimental.gc.result intrinsic to extract
496   /// the result from a call wrapped in a statepoint.
497   CallInst *CreateGCResult(Instruction *Statepoint,
498                            Type *ResultType,
499                            const Twine &Name = "");
500 
501   /// \brief Create a call to the experimental.gc.relocate intrinsics to
502   /// project the relocated value of one pointer from the statepoint.
503   CallInst *CreateGCRelocate(Instruction *Statepoint,
504                              int BaseOffset,
505                              int DerivedOffset,
506                              Type *ResultType,
507                              const Twine &Name = "");
508 
509 private:
510   /// \brief Create a call to a masked intrinsic with given Id.
511   /// Masked intrinsic has only one overloaded type - data type.
512   CallInst *CreateMaskedIntrinsic(Intrinsic::ID Id, ArrayRef<Value *> Ops,
513                                   Type *DataTy, const Twine &Name = "");
514 
515   Value *getCastedInt8PtrValue(Value *Ptr);
516 };
517 
518 /// \brief This provides a uniform API for creating instructions and inserting
519 /// them into a basic block: either at the end of a BasicBlock, or at a specific
520 /// iterator location in a block.
521 ///
522 /// Note that the builder does not expose the full generality of LLVM
523 /// instructions.  For access to extra instruction properties, use the mutators
524 /// (e.g. setVolatile) on the instructions after they have been
525 /// created. Convenience state exists to specify fast-math flags and fp-math
526 /// tags.
527 ///
528 /// The first template argument handles whether or not to preserve names in the
529 /// final instruction output. This defaults to on.  The second template argument
530 /// specifies a class to use for creating constants.  This defaults to creating
531 /// minimally folded constants.  The third template argument allows clients to
532 /// specify custom insertion hooks that are called on every newly created
533 /// insertion.
534 template<bool preserveNames = true, typename T = ConstantFolder,
535          typename Inserter = IRBuilderDefaultInserter<preserveNames> >
536 class IRBuilder : public IRBuilderBase, public Inserter {
537   T Folder;
538 
539 public:
540   IRBuilder(LLVMContext &C, const T &F, Inserter I = Inserter(),
541             MDNode *FPMathTag = nullptr)
IRBuilderBase(C,FPMathTag)542       : IRBuilderBase(C, FPMathTag), Inserter(std::move(I)), Folder(F) {}
543 
544   explicit IRBuilder(LLVMContext &C, MDNode *FPMathTag = nullptr)
IRBuilderBase(C,FPMathTag)545     : IRBuilderBase(C, FPMathTag), Folder() {
546   }
547 
548   explicit IRBuilder(BasicBlock *TheBB, const T &F, MDNode *FPMathTag = nullptr)
549     : IRBuilderBase(TheBB->getContext(), FPMathTag), Folder(F) {
550     SetInsertPoint(TheBB);
551   }
552 
553   explicit IRBuilder(BasicBlock *TheBB, MDNode *FPMathTag = nullptr)
554     : IRBuilderBase(TheBB->getContext(), FPMathTag), Folder() {
555     SetInsertPoint(TheBB);
556   }
557 
558   explicit IRBuilder(Instruction *IP, MDNode *FPMathTag = nullptr)
559     : IRBuilderBase(IP->getContext(), FPMathTag), Folder() {
560     SetInsertPoint(IP);
561   }
562 
563   IRBuilder(BasicBlock *TheBB, BasicBlock::iterator IP, const T& F,
564             MDNode *FPMathTag = nullptr)
565     : IRBuilderBase(TheBB->getContext(), FPMathTag), Folder(F) {
566     SetInsertPoint(TheBB, IP);
567   }
568 
569   IRBuilder(BasicBlock *TheBB, BasicBlock::iterator IP,
570             MDNode *FPMathTag = nullptr)
571     : IRBuilderBase(TheBB->getContext(), FPMathTag), Folder() {
572     SetInsertPoint(TheBB, IP);
573   }
574 
575   /// \brief Get the constant folder being used.
getFolder()576   const T &getFolder() { return Folder; }
577 
578   /// \brief Return true if this builder is configured to actually add the
579   /// requested names to IR created through it.
isNamePreserving()580   bool isNamePreserving() const { return preserveNames; }
581 
582   /// \brief Insert and return the specified instruction.
583   template<typename InstTy>
584   InstTy *Insert(InstTy *I, const Twine &Name = "") const {
585     this->InsertHelper(I, Name, BB, InsertPt);
586     this->SetInstDebugLocation(I);
587     return I;
588   }
589 
590   /// \brief No-op overload to handle constants.
591   Constant *Insert(Constant *C, const Twine& = "") const {
592     return C;
593   }
594 
595   //===--------------------------------------------------------------------===//
596   // Instruction creation methods: Terminators
597   //===--------------------------------------------------------------------===//
598 
599 private:
600   /// \brief Helper to add branch weight and unpredictable metadata onto an
601   /// instruction.
602   /// \returns The annotated instruction.
603   template <typename InstTy>
addBranchMetadata(InstTy * I,MDNode * Weights,MDNode * Unpredictable)604   InstTy *addBranchMetadata(InstTy *I, MDNode *Weights, MDNode *Unpredictable) {
605     if (Weights)
606       I->setMetadata(LLVMContext::MD_prof, Weights);
607     if (Unpredictable)
608       I->setMetadata(LLVMContext::MD_unpredictable, Unpredictable);
609     return I;
610   }
611 
612 public:
613   /// \brief Create a 'ret void' instruction.
CreateRetVoid()614   ReturnInst *CreateRetVoid() {
615     return Insert(ReturnInst::Create(Context));
616   }
617 
618   /// \brief Create a 'ret <val>' instruction.
CreateRet(Value * V)619   ReturnInst *CreateRet(Value *V) {
620     return Insert(ReturnInst::Create(Context, V));
621   }
622 
623   /// \brief Create a sequence of N insertvalue instructions,
624   /// with one Value from the retVals array each, that build a aggregate
625   /// return value one value at a time, and a ret instruction to return
626   /// the resulting aggregate value.
627   ///
628   /// This is a convenience function for code that uses aggregate return values
629   /// as a vehicle for having multiple return values.
CreateAggregateRet(Value * const * retVals,unsigned N)630   ReturnInst *CreateAggregateRet(Value *const *retVals, unsigned N) {
631     Value *V = UndefValue::get(getCurrentFunctionReturnType());
632     for (unsigned i = 0; i != N; ++i)
633       V = CreateInsertValue(V, retVals[i], i, "mrv");
634     return Insert(ReturnInst::Create(Context, V));
635   }
636 
637   /// \brief Create an unconditional 'br label X' instruction.
CreateBr(BasicBlock * Dest)638   BranchInst *CreateBr(BasicBlock *Dest) {
639     return Insert(BranchInst::Create(Dest));
640   }
641 
642   /// \brief Create a conditional 'br Cond, TrueDest, FalseDest'
643   /// instruction.
644   BranchInst *CreateCondBr(Value *Cond, BasicBlock *True, BasicBlock *False,
645                            MDNode *BranchWeights = nullptr,
646                            MDNode *Unpredictable = nullptr) {
647     return Insert(addBranchMetadata(BranchInst::Create(True, False, Cond),
648                                     BranchWeights, Unpredictable));
649   }
650 
651   /// \brief Create a switch instruction with the specified value, default dest,
652   /// and with a hint for the number of cases that will be added (for efficient
653   /// allocation).
654   SwitchInst *CreateSwitch(Value *V, BasicBlock *Dest, unsigned NumCases = 10,
655                            MDNode *BranchWeights = nullptr,
656                            MDNode *Unpredictable = nullptr) {
657     return Insert(addBranchMetadata(SwitchInst::Create(V, Dest, NumCases),
658                                     BranchWeights, Unpredictable));
659   }
660 
661   /// \brief Create an indirect branch instruction with the specified address
662   /// operand, with an optional hint for the number of destinations that will be
663   /// added (for efficient allocation).
664   IndirectBrInst *CreateIndirectBr(Value *Addr, unsigned NumDests = 10) {
665     return Insert(IndirectBrInst::Create(Addr, NumDests));
666   }
667 
668   InvokeInst *CreateInvoke(Value *Callee, BasicBlock *NormalDest,
669                            BasicBlock *UnwindDest, const Twine &Name = "") {
670     return Insert(InvokeInst::Create(Callee, NormalDest, UnwindDest, None),
671                   Name);
672   }
673   InvokeInst *CreateInvoke(Value *Callee, BasicBlock *NormalDest,
674                            BasicBlock *UnwindDest, Value *Arg1,
675                            const Twine &Name = "") {
676     return Insert(InvokeInst::Create(Callee, NormalDest, UnwindDest, Arg1),
677                   Name);
678   }
679   InvokeInst *CreateInvoke3(Value *Callee, BasicBlock *NormalDest,
680                             BasicBlock *UnwindDest, Value *Arg1,
681                             Value *Arg2, Value *Arg3,
682                             const Twine &Name = "") {
683     Value *Args[] = { Arg1, Arg2, Arg3 };
684     return Insert(InvokeInst::Create(Callee, NormalDest, UnwindDest, Args),
685                   Name);
686   }
687   /// \brief Create an invoke instruction.
688   InvokeInst *CreateInvoke(Value *Callee, BasicBlock *NormalDest,
689                            BasicBlock *UnwindDest, ArrayRef<Value *> Args,
690                            const Twine &Name = "") {
691     return Insert(InvokeInst::Create(Callee, NormalDest, UnwindDest, Args),
692                   Name);
693   }
694   InvokeInst *CreateInvoke(Value *Callee, BasicBlock *NormalDest,
695                            BasicBlock *UnwindDest, ArrayRef<Value *> Args,
696                            ArrayRef<OperandBundleDef> OpBundles,
697                            const Twine &Name = "") {
698     return Insert(InvokeInst::Create(Callee, NormalDest, UnwindDest, Args,
699                                      OpBundles), Name);
700   }
701 
CreateResume(Value * Exn)702   ResumeInst *CreateResume(Value *Exn) {
703     return Insert(ResumeInst::Create(Exn));
704   }
705 
706   CleanupReturnInst *CreateCleanupRet(CleanupPadInst *CleanupPad,
707                                       BasicBlock *UnwindBB = nullptr) {
708     return Insert(CleanupReturnInst::Create(CleanupPad, UnwindBB));
709   }
710 
711   CatchSwitchInst *CreateCatchSwitch(Value *ParentPad, BasicBlock *UnwindBB,
712                                      unsigned NumHandlers,
713                                      const Twine &Name = "") {
714     return Insert(CatchSwitchInst::Create(ParentPad, UnwindBB, NumHandlers),
715                   Name);
716   }
717 
718   CatchPadInst *CreateCatchPad(Value *ParentPad, ArrayRef<Value *> Args,
719                                const Twine &Name = "") {
720     return Insert(CatchPadInst::Create(ParentPad, Args), Name);
721   }
722 
723   CleanupPadInst *CreateCleanupPad(Value *ParentPad,
724                                    ArrayRef<Value *> Args = None,
725                                    const Twine &Name = "") {
726     return Insert(CleanupPadInst::Create(ParentPad, Args), Name);
727   }
728 
CreateCatchRet(CatchPadInst * CatchPad,BasicBlock * BB)729   CatchReturnInst *CreateCatchRet(CatchPadInst *CatchPad, BasicBlock *BB) {
730     return Insert(CatchReturnInst::Create(CatchPad, BB));
731   }
732 
CreateUnreachable()733   UnreachableInst *CreateUnreachable() {
734     return Insert(new UnreachableInst(Context));
735   }
736 
737   //===--------------------------------------------------------------------===//
738   // Instruction creation methods: Binary Operators
739   //===--------------------------------------------------------------------===//
740 private:
CreateInsertNUWNSWBinOp(BinaryOperator::BinaryOps Opc,Value * LHS,Value * RHS,const Twine & Name,bool HasNUW,bool HasNSW)741   BinaryOperator *CreateInsertNUWNSWBinOp(BinaryOperator::BinaryOps Opc,
742                                           Value *LHS, Value *RHS,
743                                           const Twine &Name,
744                                           bool HasNUW, bool HasNSW) {
745     BinaryOperator *BO = Insert(BinaryOperator::Create(Opc, LHS, RHS), Name);
746     if (HasNUW) BO->setHasNoUnsignedWrap();
747     if (HasNSW) BO->setHasNoSignedWrap();
748     return BO;
749   }
750 
AddFPMathAttributes(Instruction * I,MDNode * FPMathTag,FastMathFlags FMF)751   Instruction *AddFPMathAttributes(Instruction *I,
752                                    MDNode *FPMathTag,
753                                    FastMathFlags FMF) const {
754     if (!FPMathTag)
755       FPMathTag = DefaultFPMathTag;
756     if (FPMathTag)
757       I->setMetadata(LLVMContext::MD_fpmath, FPMathTag);
758     I->setFastMathFlags(FMF);
759     return I;
760   }
761 
762 public:
763   Value *CreateAdd(Value *LHS, Value *RHS, const Twine &Name = "",
764                    bool HasNUW = false, bool HasNSW = false) {
765     if (Constant *LC = dyn_cast<Constant>(LHS))
766       if (Constant *RC = dyn_cast<Constant>(RHS))
767         return Insert(Folder.CreateAdd(LC, RC, HasNUW, HasNSW), Name);
768     return CreateInsertNUWNSWBinOp(Instruction::Add, LHS, RHS, Name,
769                                    HasNUW, HasNSW);
770   }
771   Value *CreateNSWAdd(Value *LHS, Value *RHS, const Twine &Name = "") {
772     return CreateAdd(LHS, RHS, Name, false, true);
773   }
774   Value *CreateNUWAdd(Value *LHS, Value *RHS, const Twine &Name = "") {
775     return CreateAdd(LHS, RHS, Name, true, false);
776   }
777   Value *CreateFAdd(Value *LHS, Value *RHS, const Twine &Name = "",
778                     MDNode *FPMathTag = nullptr) {
779     if (Constant *LC = dyn_cast<Constant>(LHS))
780       if (Constant *RC = dyn_cast<Constant>(RHS))
781         return Insert(Folder.CreateFAdd(LC, RC), Name);
782     return Insert(AddFPMathAttributes(BinaryOperator::CreateFAdd(LHS, RHS),
783                                       FPMathTag, FMF), Name);
784   }
785   Value *CreateSub(Value *LHS, Value *RHS, const Twine &Name = "",
786                    bool HasNUW = false, bool HasNSW = false) {
787     if (Constant *LC = dyn_cast<Constant>(LHS))
788       if (Constant *RC = dyn_cast<Constant>(RHS))
789         return Insert(Folder.CreateSub(LC, RC, HasNUW, HasNSW), Name);
790     return CreateInsertNUWNSWBinOp(Instruction::Sub, LHS, RHS, Name,
791                                    HasNUW, HasNSW);
792   }
793   Value *CreateNSWSub(Value *LHS, Value *RHS, const Twine &Name = "") {
794     return CreateSub(LHS, RHS, Name, false, true);
795   }
796   Value *CreateNUWSub(Value *LHS, Value *RHS, const Twine &Name = "") {
797     return CreateSub(LHS, RHS, Name, true, false);
798   }
799   Value *CreateFSub(Value *LHS, Value *RHS, const Twine &Name = "",
800                     MDNode *FPMathTag = nullptr) {
801     if (Constant *LC = dyn_cast<Constant>(LHS))
802       if (Constant *RC = dyn_cast<Constant>(RHS))
803         return Insert(Folder.CreateFSub(LC, RC), Name);
804     return Insert(AddFPMathAttributes(BinaryOperator::CreateFSub(LHS, RHS),
805                                       FPMathTag, FMF), Name);
806   }
807   Value *CreateMul(Value *LHS, Value *RHS, const Twine &Name = "",
808                    bool HasNUW = false, bool HasNSW = false) {
809     if (Constant *LC = dyn_cast<Constant>(LHS))
810       if (Constant *RC = dyn_cast<Constant>(RHS))
811         return Insert(Folder.CreateMul(LC, RC, HasNUW, HasNSW), Name);
812     return CreateInsertNUWNSWBinOp(Instruction::Mul, LHS, RHS, Name,
813                                    HasNUW, HasNSW);
814   }
815   Value *CreateNSWMul(Value *LHS, Value *RHS, const Twine &Name = "") {
816     return CreateMul(LHS, RHS, Name, false, true);
817   }
818   Value *CreateNUWMul(Value *LHS, Value *RHS, const Twine &Name = "") {
819     return CreateMul(LHS, RHS, Name, true, false);
820   }
821   Value *CreateFMul(Value *LHS, Value *RHS, const Twine &Name = "",
822                     MDNode *FPMathTag = nullptr) {
823     if (Constant *LC = dyn_cast<Constant>(LHS))
824       if (Constant *RC = dyn_cast<Constant>(RHS))
825         return Insert(Folder.CreateFMul(LC, RC), Name);
826     return Insert(AddFPMathAttributes(BinaryOperator::CreateFMul(LHS, RHS),
827                                       FPMathTag, FMF), Name);
828   }
829   Value *CreateUDiv(Value *LHS, Value *RHS, const Twine &Name = "",
830                     bool isExact = false) {
831     if (Constant *LC = dyn_cast<Constant>(LHS))
832       if (Constant *RC = dyn_cast<Constant>(RHS))
833         return Insert(Folder.CreateUDiv(LC, RC, isExact), Name);
834     if (!isExact)
835       return Insert(BinaryOperator::CreateUDiv(LHS, RHS), Name);
836     return Insert(BinaryOperator::CreateExactUDiv(LHS, RHS), Name);
837   }
838   Value *CreateExactUDiv(Value *LHS, Value *RHS, const Twine &Name = "") {
839     return CreateUDiv(LHS, RHS, Name, true);
840   }
841   Value *CreateSDiv(Value *LHS, Value *RHS, const Twine &Name = "",
842                     bool isExact = false) {
843     if (Constant *LC = dyn_cast<Constant>(LHS))
844       if (Constant *RC = dyn_cast<Constant>(RHS))
845         return Insert(Folder.CreateSDiv(LC, RC, isExact), Name);
846     if (!isExact)
847       return Insert(BinaryOperator::CreateSDiv(LHS, RHS), Name);
848     return Insert(BinaryOperator::CreateExactSDiv(LHS, RHS), Name);
849   }
850   Value *CreateExactSDiv(Value *LHS, Value *RHS, const Twine &Name = "") {
851     return CreateSDiv(LHS, RHS, Name, true);
852   }
853   Value *CreateFDiv(Value *LHS, Value *RHS, const Twine &Name = "",
854                     MDNode *FPMathTag = nullptr) {
855     if (Constant *LC = dyn_cast<Constant>(LHS))
856       if (Constant *RC = dyn_cast<Constant>(RHS))
857         return Insert(Folder.CreateFDiv(LC, RC), Name);
858     return Insert(AddFPMathAttributes(BinaryOperator::CreateFDiv(LHS, RHS),
859                                       FPMathTag, FMF), Name);
860   }
861   Value *CreateURem(Value *LHS, Value *RHS, const Twine &Name = "") {
862     if (Constant *LC = dyn_cast<Constant>(LHS))
863       if (Constant *RC = dyn_cast<Constant>(RHS))
864         return Insert(Folder.CreateURem(LC, RC), Name);
865     return Insert(BinaryOperator::CreateURem(LHS, RHS), Name);
866   }
867   Value *CreateSRem(Value *LHS, Value *RHS, const Twine &Name = "") {
868     if (Constant *LC = dyn_cast<Constant>(LHS))
869       if (Constant *RC = dyn_cast<Constant>(RHS))
870         return Insert(Folder.CreateSRem(LC, RC), Name);
871     return Insert(BinaryOperator::CreateSRem(LHS, RHS), Name);
872   }
873   Value *CreateFRem(Value *LHS, Value *RHS, const Twine &Name = "",
874                     MDNode *FPMathTag = nullptr) {
875     if (Constant *LC = dyn_cast<Constant>(LHS))
876       if (Constant *RC = dyn_cast<Constant>(RHS))
877         return Insert(Folder.CreateFRem(LC, RC), Name);
878     return Insert(AddFPMathAttributes(BinaryOperator::CreateFRem(LHS, RHS),
879                                       FPMathTag, FMF), Name);
880   }
881 
882   Value *CreateShl(Value *LHS, Value *RHS, const Twine &Name = "",
883                    bool HasNUW = false, bool HasNSW = false) {
884     if (Constant *LC = dyn_cast<Constant>(LHS))
885       if (Constant *RC = dyn_cast<Constant>(RHS))
886         return Insert(Folder.CreateShl(LC, RC, HasNUW, HasNSW), Name);
887     return CreateInsertNUWNSWBinOp(Instruction::Shl, LHS, RHS, Name,
888                                    HasNUW, HasNSW);
889   }
890   Value *CreateShl(Value *LHS, const APInt &RHS, const Twine &Name = "",
891                    bool HasNUW = false, bool HasNSW = false) {
892     return CreateShl(LHS, ConstantInt::get(LHS->getType(), RHS), Name,
893                      HasNUW, HasNSW);
894   }
895   Value *CreateShl(Value *LHS, uint64_t RHS, const Twine &Name = "",
896                    bool HasNUW = false, bool HasNSW = false) {
897     return CreateShl(LHS, ConstantInt::get(LHS->getType(), RHS), Name,
898                      HasNUW, HasNSW);
899   }
900 
901   Value *CreateLShr(Value *LHS, Value *RHS, const Twine &Name = "",
902                     bool isExact = false) {
903     if (Constant *LC = dyn_cast<Constant>(LHS))
904       if (Constant *RC = dyn_cast<Constant>(RHS))
905         return Insert(Folder.CreateLShr(LC, RC, isExact), Name);
906     if (!isExact)
907       return Insert(BinaryOperator::CreateLShr(LHS, RHS), Name);
908     return Insert(BinaryOperator::CreateExactLShr(LHS, RHS), Name);
909   }
910   Value *CreateLShr(Value *LHS, const APInt &RHS, const Twine &Name = "",
911                     bool isExact = false) {
912     return CreateLShr(LHS, ConstantInt::get(LHS->getType(), RHS), Name,isExact);
913   }
914   Value *CreateLShr(Value *LHS, uint64_t RHS, const Twine &Name = "",
915                     bool isExact = false) {
916     return CreateLShr(LHS, ConstantInt::get(LHS->getType(), RHS), Name,isExact);
917   }
918 
919   Value *CreateAShr(Value *LHS, Value *RHS, const Twine &Name = "",
920                     bool isExact = false) {
921     if (Constant *LC = dyn_cast<Constant>(LHS))
922       if (Constant *RC = dyn_cast<Constant>(RHS))
923         return Insert(Folder.CreateAShr(LC, RC, isExact), Name);
924     if (!isExact)
925       return Insert(BinaryOperator::CreateAShr(LHS, RHS), Name);
926     return Insert(BinaryOperator::CreateExactAShr(LHS, RHS), Name);
927   }
928   Value *CreateAShr(Value *LHS, const APInt &RHS, const Twine &Name = "",
929                     bool isExact = false) {
930     return CreateAShr(LHS, ConstantInt::get(LHS->getType(), RHS), Name,isExact);
931   }
932   Value *CreateAShr(Value *LHS, uint64_t RHS, const Twine &Name = "",
933                     bool isExact = false) {
934     return CreateAShr(LHS, ConstantInt::get(LHS->getType(), RHS), Name,isExact);
935   }
936 
937   Value *CreateAnd(Value *LHS, Value *RHS, const Twine &Name = "") {
938     if (Constant *RC = dyn_cast<Constant>(RHS)) {
939       if (isa<ConstantInt>(RC) && cast<ConstantInt>(RC)->isAllOnesValue())
940         return LHS;  // LHS & -1 -> LHS
941       if (Constant *LC = dyn_cast<Constant>(LHS))
942         return Insert(Folder.CreateAnd(LC, RC), Name);
943     }
944     return Insert(BinaryOperator::CreateAnd(LHS, RHS), Name);
945   }
946   Value *CreateAnd(Value *LHS, const APInt &RHS, const Twine &Name = "") {
947     return CreateAnd(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
948   }
949   Value *CreateAnd(Value *LHS, uint64_t RHS, const Twine &Name = "") {
950     return CreateAnd(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
951   }
952 
953   Value *CreateOr(Value *LHS, Value *RHS, const Twine &Name = "") {
954     if (Constant *RC = dyn_cast<Constant>(RHS)) {
955       if (RC->isNullValue())
956         return LHS;  // LHS | 0 -> LHS
957       if (Constant *LC = dyn_cast<Constant>(LHS))
958         return Insert(Folder.CreateOr(LC, RC), Name);
959     }
960     return Insert(BinaryOperator::CreateOr(LHS, RHS), Name);
961   }
962   Value *CreateOr(Value *LHS, const APInt &RHS, const Twine &Name = "") {
963     return CreateOr(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
964   }
965   Value *CreateOr(Value *LHS, uint64_t RHS, const Twine &Name = "") {
966     return CreateOr(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
967   }
968 
969   Value *CreateXor(Value *LHS, Value *RHS, const Twine &Name = "") {
970     if (Constant *LC = dyn_cast<Constant>(LHS))
971       if (Constant *RC = dyn_cast<Constant>(RHS))
972         return Insert(Folder.CreateXor(LC, RC), Name);
973     return Insert(BinaryOperator::CreateXor(LHS, RHS), Name);
974   }
975   Value *CreateXor(Value *LHS, const APInt &RHS, const Twine &Name = "") {
976     return CreateXor(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
977   }
978   Value *CreateXor(Value *LHS, uint64_t RHS, const Twine &Name = "") {
979     return CreateXor(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
980   }
981 
982   Value *CreateBinOp(Instruction::BinaryOps Opc,
983                      Value *LHS, Value *RHS, const Twine &Name = "",
984                      MDNode *FPMathTag = nullptr) {
985     if (Constant *LC = dyn_cast<Constant>(LHS))
986       if (Constant *RC = dyn_cast<Constant>(RHS))
987         return Insert(Folder.CreateBinOp(Opc, LC, RC), Name);
988     llvm::Instruction *BinOp = BinaryOperator::Create(Opc, LHS, RHS);
989     if (isa<FPMathOperator>(BinOp))
990       BinOp = AddFPMathAttributes(BinOp, FPMathTag, FMF);
991     return Insert(BinOp, Name);
992   }
993 
994   Value *CreateNeg(Value *V, const Twine &Name = "",
995                    bool HasNUW = false, bool HasNSW = false) {
996     if (Constant *VC = dyn_cast<Constant>(V))
997       return Insert(Folder.CreateNeg(VC, HasNUW, HasNSW), Name);
998     BinaryOperator *BO = Insert(BinaryOperator::CreateNeg(V), Name);
999     if (HasNUW) BO->setHasNoUnsignedWrap();
1000     if (HasNSW) BO->setHasNoSignedWrap();
1001     return BO;
1002   }
1003   Value *CreateNSWNeg(Value *V, const Twine &Name = "") {
1004     return CreateNeg(V, Name, false, true);
1005   }
1006   Value *CreateNUWNeg(Value *V, const Twine &Name = "") {
1007     return CreateNeg(V, Name, true, false);
1008   }
1009   Value *CreateFNeg(Value *V, const Twine &Name = "",
1010                     MDNode *FPMathTag = nullptr) {
1011     if (Constant *VC = dyn_cast<Constant>(V))
1012       return Insert(Folder.CreateFNeg(VC), Name);
1013     return Insert(AddFPMathAttributes(BinaryOperator::CreateFNeg(V),
1014                                       FPMathTag, FMF), Name);
1015   }
1016   Value *CreateNot(Value *V, const Twine &Name = "") {
1017     if (Constant *VC = dyn_cast<Constant>(V))
1018       return Insert(Folder.CreateNot(VC), Name);
1019     return Insert(BinaryOperator::CreateNot(V), Name);
1020   }
1021 
1022   //===--------------------------------------------------------------------===//
1023   // Instruction creation methods: Memory Instructions
1024   //===--------------------------------------------------------------------===//
1025 
1026   AllocaInst *CreateAlloca(Type *Ty, Value *ArraySize = nullptr,
1027                            const Twine &Name = "") {
1028     return Insert(new AllocaInst(Ty, ArraySize), Name);
1029   }
1030   // \brief Provided to resolve 'CreateLoad(Ptr, "...")' correctly, instead of
1031   // converting the string to 'bool' for the isVolatile parameter.
CreateLoad(Value * Ptr,const char * Name)1032   LoadInst *CreateLoad(Value *Ptr, const char *Name) {
1033     return Insert(new LoadInst(Ptr), Name);
1034   }
1035   LoadInst *CreateLoad(Value *Ptr, const Twine &Name = "") {
1036     return Insert(new LoadInst(Ptr), Name);
1037   }
1038   LoadInst *CreateLoad(Type *Ty, Value *Ptr, const Twine &Name = "") {
1039     return Insert(new LoadInst(Ty, Ptr), Name);
1040   }
1041   LoadInst *CreateLoad(Value *Ptr, bool isVolatile, const Twine &Name = "") {
1042     return Insert(new LoadInst(Ptr, nullptr, isVolatile), Name);
1043   }
1044   StoreInst *CreateStore(Value *Val, Value *Ptr, bool isVolatile = false) {
1045     return Insert(new StoreInst(Val, Ptr, isVolatile));
1046   }
1047   // \brief Provided to resolve 'CreateAlignedLoad(Ptr, Align, "...")'
1048   // correctly, instead of converting the string to 'bool' for the isVolatile
1049   // parameter.
CreateAlignedLoad(Value * Ptr,unsigned Align,const char * Name)1050   LoadInst *CreateAlignedLoad(Value *Ptr, unsigned Align, const char *Name) {
1051     LoadInst *LI = CreateLoad(Ptr, Name);
1052     LI->setAlignment(Align);
1053     return LI;
1054   }
1055   LoadInst *CreateAlignedLoad(Value *Ptr, unsigned Align,
1056                               const Twine &Name = "") {
1057     LoadInst *LI = CreateLoad(Ptr, Name);
1058     LI->setAlignment(Align);
1059     return LI;
1060   }
1061   LoadInst *CreateAlignedLoad(Value *Ptr, unsigned Align, bool isVolatile,
1062                               const Twine &Name = "") {
1063     LoadInst *LI = CreateLoad(Ptr, isVolatile, Name);
1064     LI->setAlignment(Align);
1065     return LI;
1066   }
1067   StoreInst *CreateAlignedStore(Value *Val, Value *Ptr, unsigned Align,
1068                                 bool isVolatile = false) {
1069     StoreInst *SI = CreateStore(Val, Ptr, isVolatile);
1070     SI->setAlignment(Align);
1071     return SI;
1072   }
1073   FenceInst *CreateFence(AtomicOrdering Ordering,
1074                          SynchronizationScope SynchScope = CrossThread,
1075                          const Twine &Name = "") {
1076     return Insert(new FenceInst(Context, Ordering, SynchScope), Name);
1077   }
1078   AtomicCmpXchgInst *
1079   CreateAtomicCmpXchg(Value *Ptr, Value *Cmp, Value *New,
1080                       AtomicOrdering SuccessOrdering,
1081                       AtomicOrdering FailureOrdering,
1082                       SynchronizationScope SynchScope = CrossThread) {
1083     return Insert(new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering,
1084                                         FailureOrdering, SynchScope));
1085   }
1086   AtomicRMWInst *CreateAtomicRMW(AtomicRMWInst::BinOp Op, Value *Ptr, Value *Val,
1087                                  AtomicOrdering Ordering,
1088                                SynchronizationScope SynchScope = CrossThread) {
1089     return Insert(new AtomicRMWInst(Op, Ptr, Val, Ordering, SynchScope));
1090   }
1091   Value *CreateGEP(Value *Ptr, ArrayRef<Value *> IdxList,
1092                    const Twine &Name = "") {
1093     return CreateGEP(nullptr, Ptr, IdxList, Name);
1094   }
1095   Value *CreateGEP(Type *Ty, Value *Ptr, ArrayRef<Value *> IdxList,
1096                    const Twine &Name = "") {
1097     if (Constant *PC = dyn_cast<Constant>(Ptr)) {
1098       // Every index must be constant.
1099       size_t i, e;
1100       for (i = 0, e = IdxList.size(); i != e; ++i)
1101         if (!isa<Constant>(IdxList[i]))
1102           break;
1103       if (i == e)
1104         return Insert(Folder.CreateGetElementPtr(Ty, PC, IdxList), Name);
1105     }
1106     return Insert(GetElementPtrInst::Create(Ty, Ptr, IdxList), Name);
1107   }
1108   Value *CreateInBoundsGEP(Value *Ptr, ArrayRef<Value *> IdxList,
1109                            const Twine &Name = "") {
1110     return CreateInBoundsGEP(nullptr, Ptr, IdxList, Name);
1111   }
1112   Value *CreateInBoundsGEP(Type *Ty, Value *Ptr, ArrayRef<Value *> IdxList,
1113                            const Twine &Name = "") {
1114     if (Constant *PC = dyn_cast<Constant>(Ptr)) {
1115       // Every index must be constant.
1116       size_t i, e;
1117       for (i = 0, e = IdxList.size(); i != e; ++i)
1118         if (!isa<Constant>(IdxList[i]))
1119           break;
1120       if (i == e)
1121         return Insert(Folder.CreateInBoundsGetElementPtr(Ty, PC, IdxList),
1122                       Name);
1123     }
1124     return Insert(GetElementPtrInst::CreateInBounds(Ty, Ptr, IdxList), Name);
1125   }
1126   Value *CreateGEP(Value *Ptr, Value *Idx, const Twine &Name = "") {
1127     return CreateGEP(nullptr, Ptr, Idx, Name);
1128   }
1129   Value *CreateGEP(Type *Ty, Value *Ptr, Value *Idx, const Twine &Name = "") {
1130     if (Constant *PC = dyn_cast<Constant>(Ptr))
1131       if (Constant *IC = dyn_cast<Constant>(Idx))
1132         return Insert(Folder.CreateGetElementPtr(Ty, PC, IC), Name);
1133     return Insert(GetElementPtrInst::Create(Ty, Ptr, Idx), Name);
1134   }
1135   Value *CreateInBoundsGEP(Type *Ty, Value *Ptr, Value *Idx,
1136                            const Twine &Name = "") {
1137     if (Constant *PC = dyn_cast<Constant>(Ptr))
1138       if (Constant *IC = dyn_cast<Constant>(Idx))
1139         return Insert(Folder.CreateInBoundsGetElementPtr(Ty, PC, IC), Name);
1140     return Insert(GetElementPtrInst::CreateInBounds(Ty, Ptr, Idx), Name);
1141   }
1142   Value *CreateConstGEP1_32(Value *Ptr, unsigned Idx0, const Twine &Name = "") {
1143     return CreateConstGEP1_32(nullptr, Ptr, Idx0, Name);
1144   }
1145   Value *CreateConstGEP1_32(Type *Ty, Value *Ptr, unsigned Idx0,
1146                             const Twine &Name = "") {
1147     Value *Idx = ConstantInt::get(Type::getInt32Ty(Context), Idx0);
1148 
1149     if (Constant *PC = dyn_cast<Constant>(Ptr))
1150       return Insert(Folder.CreateGetElementPtr(Ty, PC, Idx), Name);
1151 
1152     return Insert(GetElementPtrInst::Create(Ty, Ptr, Idx), Name);
1153   }
1154   Value *CreateConstInBoundsGEP1_32(Type *Ty, Value *Ptr, unsigned Idx0,
1155                                     const Twine &Name = "") {
1156     Value *Idx = ConstantInt::get(Type::getInt32Ty(Context), Idx0);
1157 
1158     if (Constant *PC = dyn_cast<Constant>(Ptr))
1159       return Insert(Folder.CreateInBoundsGetElementPtr(Ty, PC, Idx), Name);
1160 
1161     return Insert(GetElementPtrInst::CreateInBounds(Ty, Ptr, Idx), Name);
1162   }
1163   Value *CreateConstGEP2_32(Type *Ty, Value *Ptr, unsigned Idx0, unsigned Idx1,
1164                             const Twine &Name = "") {
1165     Value *Idxs[] = {
1166       ConstantInt::get(Type::getInt32Ty(Context), Idx0),
1167       ConstantInt::get(Type::getInt32Ty(Context), Idx1)
1168     };
1169 
1170     if (Constant *PC = dyn_cast<Constant>(Ptr))
1171       return Insert(Folder.CreateGetElementPtr(Ty, PC, Idxs), Name);
1172 
1173     return Insert(GetElementPtrInst::Create(Ty, Ptr, Idxs), Name);
1174   }
1175   Value *CreateConstInBoundsGEP2_32(Type *Ty, Value *Ptr, unsigned Idx0,
1176                                     unsigned Idx1, const Twine &Name = "") {
1177     Value *Idxs[] = {
1178       ConstantInt::get(Type::getInt32Ty(Context), Idx0),
1179       ConstantInt::get(Type::getInt32Ty(Context), Idx1)
1180     };
1181 
1182     if (Constant *PC = dyn_cast<Constant>(Ptr))
1183       return Insert(Folder.CreateInBoundsGetElementPtr(Ty, PC, Idxs), Name);
1184 
1185     return Insert(GetElementPtrInst::CreateInBounds(Ty, Ptr, Idxs), Name);
1186   }
1187   Value *CreateConstGEP1_64(Value *Ptr, uint64_t Idx0, const Twine &Name = "") {
1188     Value *Idx = ConstantInt::get(Type::getInt64Ty(Context), Idx0);
1189 
1190     if (Constant *PC = dyn_cast<Constant>(Ptr))
1191       return Insert(Folder.CreateGetElementPtr(nullptr, PC, Idx), Name);
1192 
1193     return Insert(GetElementPtrInst::Create(nullptr, Ptr, Idx), Name);
1194   }
1195   Value *CreateConstInBoundsGEP1_64(Value *Ptr, uint64_t Idx0,
1196                                     const Twine &Name = "") {
1197     Value *Idx = ConstantInt::get(Type::getInt64Ty(Context), Idx0);
1198 
1199     if (Constant *PC = dyn_cast<Constant>(Ptr))
1200       return Insert(Folder.CreateInBoundsGetElementPtr(nullptr, PC, Idx), Name);
1201 
1202     return Insert(GetElementPtrInst::CreateInBounds(nullptr, Ptr, Idx), Name);
1203   }
1204   Value *CreateConstGEP2_64(Value *Ptr, uint64_t Idx0, uint64_t Idx1,
1205                     const Twine &Name = "") {
1206     Value *Idxs[] = {
1207       ConstantInt::get(Type::getInt64Ty(Context), Idx0),
1208       ConstantInt::get(Type::getInt64Ty(Context), Idx1)
1209     };
1210 
1211     if (Constant *PC = dyn_cast<Constant>(Ptr))
1212       return Insert(Folder.CreateGetElementPtr(nullptr, PC, Idxs), Name);
1213 
1214     return Insert(GetElementPtrInst::Create(nullptr, Ptr, Idxs), Name);
1215   }
1216   Value *CreateConstInBoundsGEP2_64(Value *Ptr, uint64_t Idx0, uint64_t Idx1,
1217                                     const Twine &Name = "") {
1218     Value *Idxs[] = {
1219       ConstantInt::get(Type::getInt64Ty(Context), Idx0),
1220       ConstantInt::get(Type::getInt64Ty(Context), Idx1)
1221     };
1222 
1223     if (Constant *PC = dyn_cast<Constant>(Ptr))
1224       return Insert(Folder.CreateInBoundsGetElementPtr(nullptr, PC, Idxs),
1225                     Name);
1226 
1227     return Insert(GetElementPtrInst::CreateInBounds(nullptr, Ptr, Idxs), Name);
1228   }
1229   Value *CreateStructGEP(Type *Ty, Value *Ptr, unsigned Idx,
1230                          const Twine &Name = "") {
1231     return CreateConstInBoundsGEP2_32(Ty, Ptr, 0, Idx, Name);
1232   }
1233 
1234   /// \brief Same as CreateGlobalString, but return a pointer with "i8*" type
1235   /// instead of a pointer to array of i8.
1236   Value *CreateGlobalStringPtr(StringRef Str, const Twine &Name = "",
1237                                unsigned AddressSpace = 0) {
1238     GlobalVariable *gv = CreateGlobalString(Str, Name, AddressSpace);
1239     Value *zero = ConstantInt::get(Type::getInt32Ty(Context), 0);
1240     Value *Args[] = { zero, zero };
1241     return CreateInBoundsGEP(gv->getValueType(), gv, Args, Name);
1242   }
1243 
1244   //===--------------------------------------------------------------------===//
1245   // Instruction creation methods: Cast/Conversion Operators
1246   //===--------------------------------------------------------------------===//
1247 
1248   Value *CreateTrunc(Value *V, Type *DestTy, const Twine &Name = "") {
1249     return CreateCast(Instruction::Trunc, V, DestTy, Name);
1250   }
1251   Value *CreateZExt(Value *V, Type *DestTy, const Twine &Name = "") {
1252     return CreateCast(Instruction::ZExt, V, DestTy, Name);
1253   }
1254   Value *CreateSExt(Value *V, Type *DestTy, const Twine &Name = "") {
1255     return CreateCast(Instruction::SExt, V, DestTy, Name);
1256   }
1257   /// \brief Create a ZExt or Trunc from the integer value V to DestTy. Return
1258   /// the value untouched if the type of V is already DestTy.
1259   Value *CreateZExtOrTrunc(Value *V, Type *DestTy,
1260                            const Twine &Name = "") {
1261     assert(V->getType()->isIntOrIntVectorTy() &&
1262            DestTy->isIntOrIntVectorTy() &&
1263            "Can only zero extend/truncate integers!");
1264     Type *VTy = V->getType();
1265     if (VTy->getScalarSizeInBits() < DestTy->getScalarSizeInBits())
1266       return CreateZExt(V, DestTy, Name);
1267     if (VTy->getScalarSizeInBits() > DestTy->getScalarSizeInBits())
1268       return CreateTrunc(V, DestTy, Name);
1269     return V;
1270   }
1271   /// \brief Create a SExt or Trunc from the integer value V to DestTy. Return
1272   /// the value untouched if the type of V is already DestTy.
1273   Value *CreateSExtOrTrunc(Value *V, Type *DestTy,
1274                            const Twine &Name = "") {
1275     assert(V->getType()->isIntOrIntVectorTy() &&
1276            DestTy->isIntOrIntVectorTy() &&
1277            "Can only sign extend/truncate integers!");
1278     Type *VTy = V->getType();
1279     if (VTy->getScalarSizeInBits() < DestTy->getScalarSizeInBits())
1280       return CreateSExt(V, DestTy, Name);
1281     if (VTy->getScalarSizeInBits() > DestTy->getScalarSizeInBits())
1282       return CreateTrunc(V, DestTy, Name);
1283     return V;
1284   }
1285   Value *CreateFPToUI(Value *V, Type *DestTy, const Twine &Name = ""){
1286     return CreateCast(Instruction::FPToUI, V, DestTy, Name);
1287   }
1288   Value *CreateFPToSI(Value *V, Type *DestTy, const Twine &Name = ""){
1289     return CreateCast(Instruction::FPToSI, V, DestTy, Name);
1290   }
1291   Value *CreateUIToFP(Value *V, Type *DestTy, const Twine &Name = ""){
1292     return CreateCast(Instruction::UIToFP, V, DestTy, Name);
1293   }
1294   Value *CreateSIToFP(Value *V, Type *DestTy, const Twine &Name = ""){
1295     return CreateCast(Instruction::SIToFP, V, DestTy, Name);
1296   }
1297   Value *CreateFPTrunc(Value *V, Type *DestTy,
1298                        const Twine &Name = "") {
1299     return CreateCast(Instruction::FPTrunc, V, DestTy, Name);
1300   }
1301   Value *CreateFPExt(Value *V, Type *DestTy, const Twine &Name = "") {
1302     return CreateCast(Instruction::FPExt, V, DestTy, Name);
1303   }
1304   Value *CreatePtrToInt(Value *V, Type *DestTy,
1305                         const Twine &Name = "") {
1306     return CreateCast(Instruction::PtrToInt, V, DestTy, Name);
1307   }
1308   Value *CreateIntToPtr(Value *V, Type *DestTy,
1309                         const Twine &Name = "") {
1310     return CreateCast(Instruction::IntToPtr, V, DestTy, Name);
1311   }
1312   Value *CreateBitCast(Value *V, Type *DestTy,
1313                        const Twine &Name = "") {
1314     return CreateCast(Instruction::BitCast, V, DestTy, Name);
1315   }
1316   Value *CreateAddrSpaceCast(Value *V, Type *DestTy,
1317                              const Twine &Name = "") {
1318     return CreateCast(Instruction::AddrSpaceCast, V, DestTy, Name);
1319   }
1320   Value *CreateZExtOrBitCast(Value *V, Type *DestTy,
1321                              const Twine &Name = "") {
1322     if (V->getType() == DestTy)
1323       return V;
1324     if (Constant *VC = dyn_cast<Constant>(V))
1325       return Insert(Folder.CreateZExtOrBitCast(VC, DestTy), Name);
1326     return Insert(CastInst::CreateZExtOrBitCast(V, DestTy), Name);
1327   }
1328   Value *CreateSExtOrBitCast(Value *V, Type *DestTy,
1329                              const Twine &Name = "") {
1330     if (V->getType() == DestTy)
1331       return V;
1332     if (Constant *VC = dyn_cast<Constant>(V))
1333       return Insert(Folder.CreateSExtOrBitCast(VC, DestTy), Name);
1334     return Insert(CastInst::CreateSExtOrBitCast(V, DestTy), Name);
1335   }
1336   Value *CreateTruncOrBitCast(Value *V, Type *DestTy,
1337                               const Twine &Name = "") {
1338     if (V->getType() == DestTy)
1339       return V;
1340     if (Constant *VC = dyn_cast<Constant>(V))
1341       return Insert(Folder.CreateTruncOrBitCast(VC, DestTy), Name);
1342     return Insert(CastInst::CreateTruncOrBitCast(V, DestTy), Name);
1343   }
1344   Value *CreateCast(Instruction::CastOps Op, Value *V, Type *DestTy,
1345                     const Twine &Name = "") {
1346     if (V->getType() == DestTy)
1347       return V;
1348     if (Constant *VC = dyn_cast<Constant>(V))
1349       return Insert(Folder.CreateCast(Op, VC, DestTy), Name);
1350     return Insert(CastInst::Create(Op, V, DestTy), Name);
1351   }
1352   Value *CreatePointerCast(Value *V, Type *DestTy,
1353                            const Twine &Name = "") {
1354     if (V->getType() == DestTy)
1355       return V;
1356     if (Constant *VC = dyn_cast<Constant>(V))
1357       return Insert(Folder.CreatePointerCast(VC, DestTy), Name);
1358     return Insert(CastInst::CreatePointerCast(V, DestTy), Name);
1359   }
1360 
1361   Value *CreatePointerBitCastOrAddrSpaceCast(Value *V, Type *DestTy,
1362                                              const Twine &Name = "") {
1363     if (V->getType() == DestTy)
1364       return V;
1365 
1366     if (Constant *VC = dyn_cast<Constant>(V)) {
1367       return Insert(Folder.CreatePointerBitCastOrAddrSpaceCast(VC, DestTy),
1368                     Name);
1369     }
1370 
1371     return Insert(CastInst::CreatePointerBitCastOrAddrSpaceCast(V, DestTy),
1372                   Name);
1373   }
1374 
1375   Value *CreateIntCast(Value *V, Type *DestTy, bool isSigned,
1376                        const Twine &Name = "") {
1377     if (V->getType() == DestTy)
1378       return V;
1379     if (Constant *VC = dyn_cast<Constant>(V))
1380       return Insert(Folder.CreateIntCast(VC, DestTy, isSigned), Name);
1381     return Insert(CastInst::CreateIntegerCast(V, DestTy, isSigned), Name);
1382   }
1383 
1384   Value *CreateBitOrPointerCast(Value *V, Type *DestTy,
1385                                 const Twine &Name = "") {
1386     if (V->getType() == DestTy)
1387       return V;
1388     if (V->getType()->getScalarType()->isPointerTy() &&
1389         DestTy->getScalarType()->isIntegerTy())
1390       return CreatePtrToInt(V, DestTy, Name);
1391     if (V->getType()->getScalarType()->isIntegerTy() &&
1392         DestTy->getScalarType()->isPointerTy())
1393       return CreateIntToPtr(V, DestTy, Name);
1394 
1395     return CreateBitCast(V, DestTy, Name);
1396   }
1397 
1398 private:
1399   // \brief Provided to resolve 'CreateIntCast(Ptr, Ptr, "...")', giving a
1400   // compile time error, instead of converting the string to bool for the
1401   // isSigned parameter.
1402   Value *CreateIntCast(Value *, Type *, const char *) = delete;
1403 
1404 public:
1405   Value *CreateFPCast(Value *V, Type *DestTy, const Twine &Name = "") {
1406     if (V->getType() == DestTy)
1407       return V;
1408     if (Constant *VC = dyn_cast<Constant>(V))
1409       return Insert(Folder.CreateFPCast(VC, DestTy), Name);
1410     return Insert(CastInst::CreateFPCast(V, DestTy), Name);
1411   }
1412 
1413   //===--------------------------------------------------------------------===//
1414   // Instruction creation methods: Compare Instructions
1415   //===--------------------------------------------------------------------===//
1416 
1417   Value *CreateICmpEQ(Value *LHS, Value *RHS, const Twine &Name = "") {
1418     return CreateICmp(ICmpInst::ICMP_EQ, LHS, RHS, Name);
1419   }
1420   Value *CreateICmpNE(Value *LHS, Value *RHS, const Twine &Name = "") {
1421     return CreateICmp(ICmpInst::ICMP_NE, LHS, RHS, Name);
1422   }
1423   Value *CreateICmpUGT(Value *LHS, Value *RHS, const Twine &Name = "") {
1424     return CreateICmp(ICmpInst::ICMP_UGT, LHS, RHS, Name);
1425   }
1426   Value *CreateICmpUGE(Value *LHS, Value *RHS, const Twine &Name = "") {
1427     return CreateICmp(ICmpInst::ICMP_UGE, LHS, RHS, Name);
1428   }
1429   Value *CreateICmpULT(Value *LHS, Value *RHS, const Twine &Name = "") {
1430     return CreateICmp(ICmpInst::ICMP_ULT, LHS, RHS, Name);
1431   }
1432   Value *CreateICmpULE(Value *LHS, Value *RHS, const Twine &Name = "") {
1433     return CreateICmp(ICmpInst::ICMP_ULE, LHS, RHS, Name);
1434   }
1435   Value *CreateICmpSGT(Value *LHS, Value *RHS, const Twine &Name = "") {
1436     return CreateICmp(ICmpInst::ICMP_SGT, LHS, RHS, Name);
1437   }
1438   Value *CreateICmpSGE(Value *LHS, Value *RHS, const Twine &Name = "") {
1439     return CreateICmp(ICmpInst::ICMP_SGE, LHS, RHS, Name);
1440   }
1441   Value *CreateICmpSLT(Value *LHS, Value *RHS, const Twine &Name = "") {
1442     return CreateICmp(ICmpInst::ICMP_SLT, LHS, RHS, Name);
1443   }
1444   Value *CreateICmpSLE(Value *LHS, Value *RHS, const Twine &Name = "") {
1445     return CreateICmp(ICmpInst::ICMP_SLE, LHS, RHS, Name);
1446   }
1447 
1448   Value *CreateFCmpOEQ(Value *LHS, Value *RHS, const Twine &Name = "",
1449                        MDNode *FPMathTag = nullptr) {
1450     return CreateFCmp(FCmpInst::FCMP_OEQ, LHS, RHS, Name, FPMathTag);
1451   }
1452   Value *CreateFCmpOGT(Value *LHS, Value *RHS, const Twine &Name = "",
1453                        MDNode *FPMathTag = nullptr) {
1454     return CreateFCmp(FCmpInst::FCMP_OGT, LHS, RHS, Name, FPMathTag);
1455   }
1456   Value *CreateFCmpOGE(Value *LHS, Value *RHS, const Twine &Name = "",
1457                        MDNode *FPMathTag = nullptr) {
1458     return CreateFCmp(FCmpInst::FCMP_OGE, LHS, RHS, Name, FPMathTag);
1459   }
1460   Value *CreateFCmpOLT(Value *LHS, Value *RHS, const Twine &Name = "",
1461                        MDNode *FPMathTag = nullptr) {
1462     return CreateFCmp(FCmpInst::FCMP_OLT, LHS, RHS, Name, FPMathTag);
1463   }
1464   Value *CreateFCmpOLE(Value *LHS, Value *RHS, const Twine &Name = "",
1465                        MDNode *FPMathTag = nullptr) {
1466     return CreateFCmp(FCmpInst::FCMP_OLE, LHS, RHS, Name, FPMathTag);
1467   }
1468   Value *CreateFCmpONE(Value *LHS, Value *RHS, const Twine &Name = "",
1469                        MDNode *FPMathTag = nullptr) {
1470     return CreateFCmp(FCmpInst::FCMP_ONE, LHS, RHS, Name, FPMathTag);
1471   }
1472   Value *CreateFCmpORD(Value *LHS, Value *RHS, const Twine &Name = "",
1473                        MDNode *FPMathTag = nullptr) {
1474     return CreateFCmp(FCmpInst::FCMP_ORD, LHS, RHS, Name, FPMathTag);
1475   }
1476   Value *CreateFCmpUNO(Value *LHS, Value *RHS, const Twine &Name = "",
1477                        MDNode *FPMathTag = nullptr) {
1478     return CreateFCmp(FCmpInst::FCMP_UNO, LHS, RHS, Name, FPMathTag);
1479   }
1480   Value *CreateFCmpUEQ(Value *LHS, Value *RHS, const Twine &Name = "",
1481                        MDNode *FPMathTag = nullptr) {
1482     return CreateFCmp(FCmpInst::FCMP_UEQ, LHS, RHS, Name, FPMathTag);
1483   }
1484   Value *CreateFCmpUGT(Value *LHS, Value *RHS, const Twine &Name = "",
1485                        MDNode *FPMathTag = nullptr) {
1486     return CreateFCmp(FCmpInst::FCMP_UGT, LHS, RHS, Name, FPMathTag);
1487   }
1488   Value *CreateFCmpUGE(Value *LHS, Value *RHS, const Twine &Name = "",
1489                        MDNode *FPMathTag = nullptr) {
1490     return CreateFCmp(FCmpInst::FCMP_UGE, LHS, RHS, Name, FPMathTag);
1491   }
1492   Value *CreateFCmpULT(Value *LHS, Value *RHS, const Twine &Name = "",
1493                        MDNode *FPMathTag = nullptr) {
1494     return CreateFCmp(FCmpInst::FCMP_ULT, LHS, RHS, Name, FPMathTag);
1495   }
1496   Value *CreateFCmpULE(Value *LHS, Value *RHS, const Twine &Name = "",
1497                        MDNode *FPMathTag = nullptr) {
1498     return CreateFCmp(FCmpInst::FCMP_ULE, LHS, RHS, Name, FPMathTag);
1499   }
1500   Value *CreateFCmpUNE(Value *LHS, Value *RHS, const Twine &Name = "",
1501                        MDNode *FPMathTag = nullptr) {
1502     return CreateFCmp(FCmpInst::FCMP_UNE, LHS, RHS, Name, FPMathTag);
1503   }
1504 
1505   Value *CreateICmp(CmpInst::Predicate P, Value *LHS, Value *RHS,
1506                     const Twine &Name = "") {
1507     if (Constant *LC = dyn_cast<Constant>(LHS))
1508       if (Constant *RC = dyn_cast<Constant>(RHS))
1509         return Insert(Folder.CreateICmp(P, LC, RC), Name);
1510     return Insert(new ICmpInst(P, LHS, RHS), Name);
1511   }
1512   Value *CreateFCmp(CmpInst::Predicate P, Value *LHS, Value *RHS,
1513                     const Twine &Name = "", MDNode *FPMathTag = nullptr) {
1514     if (Constant *LC = dyn_cast<Constant>(LHS))
1515       if (Constant *RC = dyn_cast<Constant>(RHS))
1516         return Insert(Folder.CreateFCmp(P, LC, RC), Name);
1517     return Insert(AddFPMathAttributes(new FCmpInst(P, LHS, RHS),
1518                                       FPMathTag, FMF), Name);
1519   }
1520 
1521   //===--------------------------------------------------------------------===//
1522   // Instruction creation methods: Other Instructions
1523   //===--------------------------------------------------------------------===//
1524 
1525   PHINode *CreatePHI(Type *Ty, unsigned NumReservedValues,
1526                      const Twine &Name = "") {
1527     return Insert(PHINode::Create(Ty, NumReservedValues), Name);
1528   }
1529 
1530   CallInst *CreateCall(Value *Callee, ArrayRef<Value *> Args = None,
1531                        ArrayRef<OperandBundleDef> OpBundles = None,
1532                        const Twine &Name = "") {
1533     return Insert(CallInst::Create(Callee, Args, OpBundles), Name);
1534   }
1535 
1536   CallInst *CreateCall(Value *Callee, ArrayRef<Value *> Args,
1537                        const Twine &Name, MDNode *FPMathTag = nullptr) {
1538     PointerType *PTy = cast<PointerType>(Callee->getType());
1539     FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1540     return CreateCall(FTy, Callee, Args, Name, FPMathTag);
1541   }
1542 
1543   CallInst *CreateCall(llvm::FunctionType *FTy, Value *Callee,
1544                        ArrayRef<Value *> Args, const Twine &Name = "",
1545                        MDNode *FPMathTag = nullptr) {
1546     CallInst *CI = CallInst::Create(FTy, Callee, Args);
1547     if (isa<FPMathOperator>(CI))
1548       CI = cast<CallInst>(AddFPMathAttributes(CI, FPMathTag, FMF));
1549     return Insert(CI, Name);
1550   }
1551 
1552   CallInst *CreateCall(Function *Callee, ArrayRef<Value *> Args,
1553                        const Twine &Name = "", MDNode *FPMathTag = nullptr) {
1554     return CreateCall(Callee->getFunctionType(), Callee, Args, Name, FPMathTag);
1555   }
1556 
1557   Value *CreateSelect(Value *C, Value *True, Value *False,
1558                       const Twine &Name = "") {
1559     if (Constant *CC = dyn_cast<Constant>(C))
1560       if (Constant *TC = dyn_cast<Constant>(True))
1561         if (Constant *FC = dyn_cast<Constant>(False))
1562           return Insert(Folder.CreateSelect(CC, TC, FC), Name);
1563     return Insert(SelectInst::Create(C, True, False), Name);
1564   }
1565 
1566   VAArgInst *CreateVAArg(Value *List, Type *Ty, const Twine &Name = "") {
1567     return Insert(new VAArgInst(List, Ty), Name);
1568   }
1569 
1570   Value *CreateExtractElement(Value *Vec, Value *Idx,
1571                               const Twine &Name = "") {
1572     if (Constant *VC = dyn_cast<Constant>(Vec))
1573       if (Constant *IC = dyn_cast<Constant>(Idx))
1574         return Insert(Folder.CreateExtractElement(VC, IC), Name);
1575     return Insert(ExtractElementInst::Create(Vec, Idx), Name);
1576   }
1577 
1578   Value *CreateExtractElement(Value *Vec, uint64_t Idx,
1579                               const Twine &Name = "") {
1580     return CreateExtractElement(Vec, getInt64(Idx), Name);
1581   }
1582 
1583   Value *CreateInsertElement(Value *Vec, Value *NewElt, Value *Idx,
1584                              const Twine &Name = "") {
1585     if (Constant *VC = dyn_cast<Constant>(Vec))
1586       if (Constant *NC = dyn_cast<Constant>(NewElt))
1587         if (Constant *IC = dyn_cast<Constant>(Idx))
1588           return Insert(Folder.CreateInsertElement(VC, NC, IC), Name);
1589     return Insert(InsertElementInst::Create(Vec, NewElt, Idx), Name);
1590   }
1591 
1592   Value *CreateInsertElement(Value *Vec, Value *NewElt, uint64_t Idx,
1593                              const Twine &Name = "") {
1594     return CreateInsertElement(Vec, NewElt, getInt64(Idx), Name);
1595   }
1596 
1597   Value *CreateShuffleVector(Value *V1, Value *V2, Value *Mask,
1598                              const Twine &Name = "") {
1599     if (Constant *V1C = dyn_cast<Constant>(V1))
1600       if (Constant *V2C = dyn_cast<Constant>(V2))
1601         if (Constant *MC = dyn_cast<Constant>(Mask))
1602           return Insert(Folder.CreateShuffleVector(V1C, V2C, MC), Name);
1603     return Insert(new ShuffleVectorInst(V1, V2, Mask), Name);
1604   }
1605 
1606   Value *CreateShuffleVector(Value *V1, Value *V2, ArrayRef<int> IntMask,
1607                              const Twine &Name = "") {
1608     size_t MaskSize = IntMask.size();
1609     SmallVector<Constant*, 8> MaskVec(MaskSize);
1610     for (size_t i = 0; i != MaskSize; ++i)
1611       MaskVec[i] = getInt32(IntMask[i]);
1612     Value *Mask = ConstantVector::get(MaskVec);
1613     return CreateShuffleVector(V1, V2, Mask, Name);
1614   }
1615 
1616   Value *CreateExtractValue(Value *Agg,
1617                             ArrayRef<unsigned> Idxs,
1618                             const Twine &Name = "") {
1619     if (Constant *AggC = dyn_cast<Constant>(Agg))
1620       return Insert(Folder.CreateExtractValue(AggC, Idxs), Name);
1621     return Insert(ExtractValueInst::Create(Agg, Idxs), Name);
1622   }
1623 
1624   Value *CreateInsertValue(Value *Agg, Value *Val,
1625                            ArrayRef<unsigned> Idxs,
1626                            const Twine &Name = "") {
1627     if (Constant *AggC = dyn_cast<Constant>(Agg))
1628       if (Constant *ValC = dyn_cast<Constant>(Val))
1629         return Insert(Folder.CreateInsertValue(AggC, ValC, Idxs), Name);
1630     return Insert(InsertValueInst::Create(Agg, Val, Idxs), Name);
1631   }
1632 
1633   LandingPadInst *CreateLandingPad(Type *Ty, unsigned NumClauses,
1634                                    const Twine &Name = "") {
1635     return Insert(LandingPadInst::Create(Ty, NumClauses), Name);
1636   }
1637 
1638   //===--------------------------------------------------------------------===//
1639   // Utility creation methods
1640   //===--------------------------------------------------------------------===//
1641 
1642   /// \brief Return an i1 value testing if \p Arg is null.
1643   Value *CreateIsNull(Value *Arg, const Twine &Name = "") {
1644     return CreateICmpEQ(Arg, Constant::getNullValue(Arg->getType()),
1645                         Name);
1646   }
1647 
1648   /// \brief Return an i1 value testing if \p Arg is not null.
1649   Value *CreateIsNotNull(Value *Arg, const Twine &Name = "") {
1650     return CreateICmpNE(Arg, Constant::getNullValue(Arg->getType()),
1651                         Name);
1652   }
1653 
1654   /// \brief Return the i64 difference between two pointer values, dividing out
1655   /// the size of the pointed-to objects.
1656   ///
1657   /// This is intended to implement C-style pointer subtraction. As such, the
1658   /// pointers must be appropriately aligned for their element types and
1659   /// pointing into the same object.
1660   Value *CreatePtrDiff(Value *LHS, Value *RHS, const Twine &Name = "") {
1661     assert(LHS->getType() == RHS->getType() &&
1662            "Pointer subtraction operand types must match!");
1663     PointerType *ArgType = cast<PointerType>(LHS->getType());
1664     Value *LHS_int = CreatePtrToInt(LHS, Type::getInt64Ty(Context));
1665     Value *RHS_int = CreatePtrToInt(RHS, Type::getInt64Ty(Context));
1666     Value *Difference = CreateSub(LHS_int, RHS_int);
1667     return CreateExactSDiv(Difference,
1668                            ConstantExpr::getSizeOf(ArgType->getElementType()),
1669                            Name);
1670   }
1671 
1672   /// \brief Create an invariant.group.barrier intrinsic call, that stops
1673   /// optimizer to propagate equality using invariant.group metadata.
1674   /// If Ptr type is different from i8*, it's casted to i8* before call
1675   /// and casted back to Ptr type after call.
CreateInvariantGroupBarrier(Value * Ptr)1676   Value *CreateInvariantGroupBarrier(Value *Ptr) {
1677     Module *M = BB->getParent()->getParent();
1678     Function *FnInvariantGroupBarrier = Intrinsic::getDeclaration(M,
1679             Intrinsic::invariant_group_barrier);
1680 
1681     Type *ArgumentAndReturnType = FnInvariantGroupBarrier->getReturnType();
1682     assert(ArgumentAndReturnType ==
1683         FnInvariantGroupBarrier->getFunctionType()->getParamType(0) &&
1684         "InvariantGroupBarrier should take and return the same type");
1685     Type *PtrType = Ptr->getType();
1686 
1687     bool PtrTypeConversionNeeded = PtrType != ArgumentAndReturnType;
1688     if (PtrTypeConversionNeeded)
1689       Ptr = CreateBitCast(Ptr, ArgumentAndReturnType);
1690 
1691     CallInst *Fn = CreateCall(FnInvariantGroupBarrier, {Ptr});
1692 
1693     if (PtrTypeConversionNeeded)
1694       return CreateBitCast(Fn, PtrType);
1695     return Fn;
1696   }
1697 
1698   /// \brief Return a vector value that contains \arg V broadcasted to \p
1699   /// NumElts elements.
1700   Value *CreateVectorSplat(unsigned NumElts, Value *V, const Twine &Name = "") {
1701     assert(NumElts > 0 && "Cannot splat to an empty vector!");
1702 
1703     // First insert it into an undef vector so we can shuffle it.
1704     Type *I32Ty = getInt32Ty();
1705     Value *Undef = UndefValue::get(VectorType::get(V->getType(), NumElts));
1706     V = CreateInsertElement(Undef, V, ConstantInt::get(I32Ty, 0),
1707                             Name + ".splatinsert");
1708 
1709     // Shuffle the value across the desired number of elements.
1710     Value *Zeros = ConstantAggregateZero::get(VectorType::get(I32Ty, NumElts));
1711     return CreateShuffleVector(V, Undef, Zeros, Name + ".splat");
1712   }
1713 
1714   /// \brief Return a value that has been extracted from a larger integer type.
CreateExtractInteger(const DataLayout & DL,Value * From,IntegerType * ExtractedTy,uint64_t Offset,const Twine & Name)1715   Value *CreateExtractInteger(const DataLayout &DL, Value *From,
1716                               IntegerType *ExtractedTy, uint64_t Offset,
1717                               const Twine &Name) {
1718     IntegerType *IntTy = cast<IntegerType>(From->getType());
1719     assert(DL.getTypeStoreSize(ExtractedTy) + Offset <=
1720                DL.getTypeStoreSize(IntTy) &&
1721            "Element extends past full value");
1722     uint64_t ShAmt = 8 * Offset;
1723     Value *V = From;
1724     if (DL.isBigEndian())
1725       ShAmt = 8 * (DL.getTypeStoreSize(IntTy) -
1726                    DL.getTypeStoreSize(ExtractedTy) - Offset);
1727     if (ShAmt) {
1728       V = CreateLShr(V, ShAmt, Name + ".shift");
1729     }
1730     assert(ExtractedTy->getBitWidth() <= IntTy->getBitWidth() &&
1731            "Cannot extract to a larger integer!");
1732     if (ExtractedTy != IntTy) {
1733       V = CreateTrunc(V, ExtractedTy, Name + ".trunc");
1734     }
1735     return V;
1736   }
1737 
1738   /// \brief Create an assume intrinsic call that represents an alignment
1739   /// assumption on the provided pointer.
1740   ///
1741   /// An optional offset can be provided, and if it is provided, the offset
1742   /// must be subtracted from the provided pointer to get the pointer with the
1743   /// specified alignment.
1744   CallInst *CreateAlignmentAssumption(const DataLayout &DL, Value *PtrValue,
1745                                       unsigned Alignment,
1746                                       Value *OffsetValue = nullptr) {
1747     assert(isa<PointerType>(PtrValue->getType()) &&
1748            "trying to create an alignment assumption on a non-pointer?");
1749 
1750     PointerType *PtrTy = cast<PointerType>(PtrValue->getType());
1751     Type *IntPtrTy = getIntPtrTy(DL, PtrTy->getAddressSpace());
1752     Value *PtrIntValue = CreatePtrToInt(PtrValue, IntPtrTy, "ptrint");
1753 
1754     Value *Mask = ConstantInt::get(IntPtrTy,
1755       Alignment > 0 ? Alignment - 1 : 0);
1756     if (OffsetValue) {
1757       bool IsOffsetZero = false;
1758       if (ConstantInt *CI = dyn_cast<ConstantInt>(OffsetValue))
1759         IsOffsetZero = CI->isZero();
1760 
1761       if (!IsOffsetZero) {
1762         if (OffsetValue->getType() != IntPtrTy)
1763           OffsetValue = CreateIntCast(OffsetValue, IntPtrTy, /*isSigned*/ true,
1764                                       "offsetcast");
1765         PtrIntValue = CreateSub(PtrIntValue, OffsetValue, "offsetptr");
1766       }
1767     }
1768 
1769     Value *Zero = ConstantInt::get(IntPtrTy, 0);
1770     Value *MaskedPtr = CreateAnd(PtrIntValue, Mask, "maskedptr");
1771     Value *InvCond = CreateICmpEQ(MaskedPtr, Zero, "maskcond");
1772 
1773     return CreateAssumption(InvCond);
1774   }
1775 };
1776 
1777 // Create wrappers for C Binding types (see CBindingWrapping.h).
1778 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(IRBuilder<>, LLVMBuilderRef)
1779 
1780 } // end namespace llvm
1781 
1782 #endif // LLVM_IR_IRBUILDER_H
1783