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