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