[Statepoints] Support for "patchable" statepoints.
[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 *CreateGCStatepointCall(uint64_t ID, uint32_t NumPatchBytes,
451                                    Value *ActualCallee,
452                                    ArrayRef<Value *> CallArgs,
453                                    ArrayRef<Value *> DeoptArgs,
454                                    ArrayRef<Value *> GCArgs,
455                                    const Twine &Name = "");
456
457   // \brief Conveninence function for the common case when CallArgs are filled
458   // in using makeArrayRef(CS.arg_begin(), CS.arg_end()); Use needs to be
459   // .get()'ed to get the Value pointer.
460   CallInst *CreateGCStatepointCall(uint64_t ID, uint32_t NumPatchBytes,
461                                    Value *ActualCallee, ArrayRef<Use> CallArgs,
462                                    ArrayRef<Value *> DeoptArgs,
463                                    ArrayRef<Value *> GCArgs,
464                                    const Twine &Name = "");
465
466   /// brief Create an invoke to the experimental.gc.statepoint intrinsic to
467   /// start a new statepoint sequence.
468   InvokeInst *
469   CreateGCStatepointInvoke(uint64_t ID, uint32_t NumPatchBytes,
470                            Value *ActualInvokee, BasicBlock *NormalDest,
471                            BasicBlock *UnwindDest, ArrayRef<Value *> InvokeArgs,
472                            ArrayRef<Value *> DeoptArgs,
473                            ArrayRef<Value *> GCArgs, const Twine &Name = "");
474
475   // Conveninence function for the common case when CallArgs are filled in using
476   // makeArrayRef(CS.arg_begin(), CS.arg_end()); Use needs to be .get()'ed to
477   // get the Value *.
478   InvokeInst *
479   CreateGCStatepointInvoke(uint64_t ID, uint32_t NumPatchBytes,
480                            Value *ActualInvokee, BasicBlock *NormalDest,
481                            BasicBlock *UnwindDest, ArrayRef<Use> InvokeArgs,
482                            ArrayRef<Value *> DeoptArgs,
483                            ArrayRef<Value *> GCArgs, const Twine &Name = "");
484
485   /// \brief Create a call to the experimental.gc.result intrinsic to extract
486   /// the result from a call wrapped in a statepoint.
487   CallInst *CreateGCResult(Instruction *Statepoint,
488                            Type *ResultType,
489                            const Twine &Name = "");
490
491   /// \brief Create a call to the experimental.gc.relocate intrinsics to
492   /// project the relocated value of one pointer from the statepoint.
493   CallInst *CreateGCRelocate(Instruction *Statepoint,
494                              int BaseOffset,
495                              int DerivedOffset,
496                              Type *ResultType,
497                              const Twine &Name = "");
498
499 private:
500   /// \brief Create a call to a masked intrinsic with given Id.
501   /// Masked intrinsic has only one overloaded type - data type.
502   CallInst *CreateMaskedIntrinsic(unsigned Id, ArrayRef<Value *> Ops,
503                                   Type *DataTy, const Twine &Name = "");
504
505   Value *getCastedInt8PtrValue(Value *Ptr);
506 };
507
508 /// \brief This provides a uniform API for creating instructions and inserting
509 /// them into a basic block: either at the end of a BasicBlock, or at a specific
510 /// iterator location in a block.
511 ///
512 /// Note that the builder does not expose the full generality of LLVM
513 /// instructions.  For access to extra instruction properties, use the mutators
514 /// (e.g. setVolatile) on the instructions after they have been
515 /// created. Convenience state exists to specify fast-math flags and fp-math
516 /// tags.
517 ///
518 /// The first template argument handles whether or not to preserve names in the
519 /// final instruction output. This defaults to on.  The second template argument
520 /// specifies a class to use for creating constants.  This defaults to creating
521 /// minimally folded constants.  The third template argument allows clients to
522 /// specify custom insertion hooks that are called on every newly created
523 /// insertion.
524 template<bool preserveNames = true, typename T = ConstantFolder,
525          typename Inserter = IRBuilderDefaultInserter<preserveNames> >
526 class IRBuilder : public IRBuilderBase, public Inserter {
527   T Folder;
528 public:
529   IRBuilder(LLVMContext &C, const T &F, const Inserter &I = Inserter(),
530             MDNode *FPMathTag = nullptr)
531     : IRBuilderBase(C, FPMathTag), Inserter(I), Folder(F) {
532   }
533
534   explicit IRBuilder(LLVMContext &C, MDNode *FPMathTag = nullptr)
535     : IRBuilderBase(C, FPMathTag), Folder() {
536   }
537
538   explicit IRBuilder(BasicBlock *TheBB, const T &F, MDNode *FPMathTag = nullptr)
539     : IRBuilderBase(TheBB->getContext(), FPMathTag), Folder(F) {
540     SetInsertPoint(TheBB);
541   }
542
543   explicit IRBuilder(BasicBlock *TheBB, MDNode *FPMathTag = nullptr)
544     : IRBuilderBase(TheBB->getContext(), FPMathTag), Folder() {
545     SetInsertPoint(TheBB);
546   }
547
548   explicit IRBuilder(Instruction *IP, MDNode *FPMathTag = nullptr)
549     : IRBuilderBase(IP->getContext(), FPMathTag), Folder() {
550     SetInsertPoint(IP);
551     SetCurrentDebugLocation(IP->getDebugLoc());
552   }
553
554   explicit IRBuilder(Use &U, MDNode *FPMathTag = nullptr)
555     : IRBuilderBase(U->getContext(), FPMathTag), Folder() {
556     SetInsertPoint(U);
557     SetCurrentDebugLocation(cast<Instruction>(U.getUser())->getDebugLoc());
558   }
559
560   IRBuilder(BasicBlock *TheBB, BasicBlock::iterator IP, const T& F,
561             MDNode *FPMathTag = nullptr)
562     : IRBuilderBase(TheBB->getContext(), FPMathTag), Folder(F) {
563     SetInsertPoint(TheBB, IP);
564   }
565
566   IRBuilder(BasicBlock *TheBB, BasicBlock::iterator IP,
567             MDNode *FPMathTag = nullptr)
568     : IRBuilderBase(TheBB->getContext(), FPMathTag), Folder() {
569     SetInsertPoint(TheBB, IP);
570   }
571
572   /// \brief Get the constant folder being used.
573   const T &getFolder() { return Folder; }
574
575   /// \brief Return true if this builder is configured to actually add the
576   /// requested names to IR created through it.
577   bool isNamePreserving() const { return preserveNames; }
578
579   /// \brief Insert and return the specified instruction.
580   template<typename InstTy>
581   InstTy *Insert(InstTy *I, const Twine &Name = "") const {
582     this->InsertHelper(I, Name, BB, InsertPt);
583     this->SetInstDebugLocation(I);
584     return I;
585   }
586
587   /// \brief No-op overload to handle constants.
588   Constant *Insert(Constant *C, const Twine& = "") const {
589     return C;
590   }
591
592   //===--------------------------------------------------------------------===//
593   // Instruction creation methods: Terminators
594   //===--------------------------------------------------------------------===//
595
596 private:
597   /// \brief Helper to add branch weight metadata onto an instruction.
598   /// \returns The annotated instruction.
599   template <typename InstTy>
600   InstTy *addBranchWeights(InstTy *I, MDNode *Weights) {
601     if (Weights)
602       I->setMetadata(LLVMContext::MD_prof, Weights);
603     return I;
604   }
605
606 public:
607   /// \brief Create a 'ret void' instruction.
608   ReturnInst *CreateRetVoid() {
609     return Insert(ReturnInst::Create(Context));
610   }
611
612   /// \brief Create a 'ret <val>' instruction.
613   ReturnInst *CreateRet(Value *V) {
614     return Insert(ReturnInst::Create(Context, V));
615   }
616
617   /// \brief Create a sequence of N insertvalue instructions,
618   /// with one Value from the retVals array each, that build a aggregate
619   /// return value one value at a time, and a ret instruction to return
620   /// the resulting aggregate value.
621   ///
622   /// This is a convenience function for code that uses aggregate return values
623   /// as a vehicle for having multiple return values.
624   ReturnInst *CreateAggregateRet(Value *const *retVals, unsigned N) {
625     Value *V = UndefValue::get(getCurrentFunctionReturnType());
626     for (unsigned i = 0; i != N; ++i)
627       V = CreateInsertValue(V, retVals[i], i, "mrv");
628     return Insert(ReturnInst::Create(Context, V));
629   }
630
631   /// \brief Create an unconditional 'br label X' instruction.
632   BranchInst *CreateBr(BasicBlock *Dest) {
633     return Insert(BranchInst::Create(Dest));
634   }
635
636   /// \brief Create a conditional 'br Cond, TrueDest, FalseDest'
637   /// instruction.
638   BranchInst *CreateCondBr(Value *Cond, BasicBlock *True, BasicBlock *False,
639                            MDNode *BranchWeights = nullptr) {
640     return Insert(addBranchWeights(BranchInst::Create(True, False, Cond),
641                                    BranchWeights));
642   }
643
644   /// \brief Create a switch instruction with the specified value, default dest,
645   /// and with a hint for the number of cases that will be added (for efficient
646   /// allocation).
647   SwitchInst *CreateSwitch(Value *V, BasicBlock *Dest, unsigned NumCases = 10,
648                            MDNode *BranchWeights = nullptr) {
649     return Insert(addBranchWeights(SwitchInst::Create(V, Dest, NumCases),
650                                    BranchWeights));
651   }
652
653   /// \brief Create an indirect branch instruction with the specified address
654   /// operand, with an optional hint for the number of destinations that will be
655   /// added (for efficient allocation).
656   IndirectBrInst *CreateIndirectBr(Value *Addr, unsigned NumDests = 10) {
657     return Insert(IndirectBrInst::Create(Addr, NumDests));
658   }
659
660   InvokeInst *CreateInvoke(Value *Callee, BasicBlock *NormalDest,
661                            BasicBlock *UnwindDest, const Twine &Name = "") {
662     return Insert(InvokeInst::Create(Callee, NormalDest, UnwindDest, None),
663                   Name);
664   }
665   InvokeInst *CreateInvoke(Value *Callee, BasicBlock *NormalDest,
666                            BasicBlock *UnwindDest, Value *Arg1,
667                            const Twine &Name = "") {
668     return Insert(InvokeInst::Create(Callee, NormalDest, UnwindDest, Arg1),
669                   Name);
670   }
671   InvokeInst *CreateInvoke3(Value *Callee, BasicBlock *NormalDest,
672                             BasicBlock *UnwindDest, Value *Arg1,
673                             Value *Arg2, Value *Arg3,
674                             const Twine &Name = "") {
675     Value *Args[] = { Arg1, Arg2, Arg3 };
676     return Insert(InvokeInst::Create(Callee, NormalDest, UnwindDest, Args),
677                   Name);
678   }
679   /// \brief Create an invoke instruction.
680   InvokeInst *CreateInvoke(Value *Callee, BasicBlock *NormalDest,
681                            BasicBlock *UnwindDest, ArrayRef<Value *> Args,
682                            const Twine &Name = "") {
683     return Insert(InvokeInst::Create(Callee, NormalDest, UnwindDest, Args),
684                   Name);
685   }
686
687   ResumeInst *CreateResume(Value *Exn) {
688     return Insert(ResumeInst::Create(Exn));
689   }
690
691   UnreachableInst *CreateUnreachable() {
692     return Insert(new UnreachableInst(Context));
693   }
694
695   //===--------------------------------------------------------------------===//
696   // Instruction creation methods: Binary Operators
697   //===--------------------------------------------------------------------===//
698 private:
699   BinaryOperator *CreateInsertNUWNSWBinOp(BinaryOperator::BinaryOps Opc,
700                                           Value *LHS, Value *RHS,
701                                           const Twine &Name,
702                                           bool HasNUW, bool HasNSW) {
703     BinaryOperator *BO = Insert(BinaryOperator::Create(Opc, LHS, RHS), Name);
704     if (HasNUW) BO->setHasNoUnsignedWrap();
705     if (HasNSW) BO->setHasNoSignedWrap();
706     return BO;
707   }
708
709   Instruction *AddFPMathAttributes(Instruction *I,
710                                    MDNode *FPMathTag,
711                                    FastMathFlags FMF) const {
712     if (!FPMathTag)
713       FPMathTag = DefaultFPMathTag;
714     if (FPMathTag)
715       I->setMetadata(LLVMContext::MD_fpmath, FPMathTag);
716     I->setFastMathFlags(FMF);
717     return I;
718   }
719 public:
720   Value *CreateAdd(Value *LHS, Value *RHS, const Twine &Name = "",
721                    bool HasNUW = false, bool HasNSW = false) {
722     if (Constant *LC = dyn_cast<Constant>(LHS))
723       if (Constant *RC = dyn_cast<Constant>(RHS))
724         return Insert(Folder.CreateAdd(LC, RC, HasNUW, HasNSW), Name);
725     return CreateInsertNUWNSWBinOp(Instruction::Add, LHS, RHS, Name,
726                                    HasNUW, HasNSW);
727   }
728   Value *CreateNSWAdd(Value *LHS, Value *RHS, const Twine &Name = "") {
729     return CreateAdd(LHS, RHS, Name, false, true);
730   }
731   Value *CreateNUWAdd(Value *LHS, Value *RHS, const Twine &Name = "") {
732     return CreateAdd(LHS, RHS, Name, true, false);
733   }
734   Value *CreateFAdd(Value *LHS, Value *RHS, const Twine &Name = "",
735                     MDNode *FPMathTag = nullptr) {
736     if (Constant *LC = dyn_cast<Constant>(LHS))
737       if (Constant *RC = dyn_cast<Constant>(RHS))
738         return Insert(Folder.CreateFAdd(LC, RC), Name);
739     return Insert(AddFPMathAttributes(BinaryOperator::CreateFAdd(LHS, RHS),
740                                       FPMathTag, FMF), Name);
741   }
742   Value *CreateSub(Value *LHS, Value *RHS, const Twine &Name = "",
743                    bool HasNUW = false, bool HasNSW = false) {
744     if (Constant *LC = dyn_cast<Constant>(LHS))
745       if (Constant *RC = dyn_cast<Constant>(RHS))
746         return Insert(Folder.CreateSub(LC, RC, HasNUW, HasNSW), Name);
747     return CreateInsertNUWNSWBinOp(Instruction::Sub, LHS, RHS, Name,
748                                    HasNUW, HasNSW);
749   }
750   Value *CreateNSWSub(Value *LHS, Value *RHS, const Twine &Name = "") {
751     return CreateSub(LHS, RHS, Name, false, true);
752   }
753   Value *CreateNUWSub(Value *LHS, Value *RHS, const Twine &Name = "") {
754     return CreateSub(LHS, RHS, Name, true, false);
755   }
756   Value *CreateFSub(Value *LHS, Value *RHS, const Twine &Name = "",
757                     MDNode *FPMathTag = nullptr) {
758     if (Constant *LC = dyn_cast<Constant>(LHS))
759       if (Constant *RC = dyn_cast<Constant>(RHS))
760         return Insert(Folder.CreateFSub(LC, RC), Name);
761     return Insert(AddFPMathAttributes(BinaryOperator::CreateFSub(LHS, RHS),
762                                       FPMathTag, FMF), Name);
763   }
764   Value *CreateMul(Value *LHS, Value *RHS, const Twine &Name = "",
765                    bool HasNUW = false, bool HasNSW = false) {
766     if (Constant *LC = dyn_cast<Constant>(LHS))
767       if (Constant *RC = dyn_cast<Constant>(RHS))
768         return Insert(Folder.CreateMul(LC, RC, HasNUW, HasNSW), Name);
769     return CreateInsertNUWNSWBinOp(Instruction::Mul, LHS, RHS, Name,
770                                    HasNUW, HasNSW);
771   }
772   Value *CreateNSWMul(Value *LHS, Value *RHS, const Twine &Name = "") {
773     return CreateMul(LHS, RHS, Name, false, true);
774   }
775   Value *CreateNUWMul(Value *LHS, Value *RHS, const Twine &Name = "") {
776     return CreateMul(LHS, RHS, Name, true, false);
777   }
778   Value *CreateFMul(Value *LHS, Value *RHS, const Twine &Name = "",
779                     MDNode *FPMathTag = nullptr) {
780     if (Constant *LC = dyn_cast<Constant>(LHS))
781       if (Constant *RC = dyn_cast<Constant>(RHS))
782         return Insert(Folder.CreateFMul(LC, RC), Name);
783     return Insert(AddFPMathAttributes(BinaryOperator::CreateFMul(LHS, RHS),
784                                       FPMathTag, FMF), Name);
785   }
786   Value *CreateUDiv(Value *LHS, Value *RHS, const Twine &Name = "",
787                     bool isExact = false) {
788     if (Constant *LC = dyn_cast<Constant>(LHS))
789       if (Constant *RC = dyn_cast<Constant>(RHS))
790         return Insert(Folder.CreateUDiv(LC, RC, isExact), Name);
791     if (!isExact)
792       return Insert(BinaryOperator::CreateUDiv(LHS, RHS), Name);
793     return Insert(BinaryOperator::CreateExactUDiv(LHS, RHS), Name);
794   }
795   Value *CreateExactUDiv(Value *LHS, Value *RHS, const Twine &Name = "") {
796     return CreateUDiv(LHS, RHS, Name, true);
797   }
798   Value *CreateSDiv(Value *LHS, Value *RHS, const Twine &Name = "",
799                     bool isExact = false) {
800     if (Constant *LC = dyn_cast<Constant>(LHS))
801       if (Constant *RC = dyn_cast<Constant>(RHS))
802         return Insert(Folder.CreateSDiv(LC, RC, isExact), Name);
803     if (!isExact)
804       return Insert(BinaryOperator::CreateSDiv(LHS, RHS), Name);
805     return Insert(BinaryOperator::CreateExactSDiv(LHS, RHS), Name);
806   }
807   Value *CreateExactSDiv(Value *LHS, Value *RHS, const Twine &Name = "") {
808     return CreateSDiv(LHS, RHS, Name, true);
809   }
810   Value *CreateFDiv(Value *LHS, Value *RHS, const Twine &Name = "",
811                     MDNode *FPMathTag = nullptr) {
812     if (Constant *LC = dyn_cast<Constant>(LHS))
813       if (Constant *RC = dyn_cast<Constant>(RHS))
814         return Insert(Folder.CreateFDiv(LC, RC), Name);
815     return Insert(AddFPMathAttributes(BinaryOperator::CreateFDiv(LHS, RHS),
816                                       FPMathTag, FMF), Name);
817   }
818   Value *CreateURem(Value *LHS, Value *RHS, const Twine &Name = "") {
819     if (Constant *LC = dyn_cast<Constant>(LHS))
820       if (Constant *RC = dyn_cast<Constant>(RHS))
821         return Insert(Folder.CreateURem(LC, RC), Name);
822     return Insert(BinaryOperator::CreateURem(LHS, RHS), Name);
823   }
824   Value *CreateSRem(Value *LHS, Value *RHS, const Twine &Name = "") {
825     if (Constant *LC = dyn_cast<Constant>(LHS))
826       if (Constant *RC = dyn_cast<Constant>(RHS))
827         return Insert(Folder.CreateSRem(LC, RC), Name);
828     return Insert(BinaryOperator::CreateSRem(LHS, RHS), Name);
829   }
830   Value *CreateFRem(Value *LHS, Value *RHS, const Twine &Name = "",
831                     MDNode *FPMathTag = nullptr) {
832     if (Constant *LC = dyn_cast<Constant>(LHS))
833       if (Constant *RC = dyn_cast<Constant>(RHS))
834         return Insert(Folder.CreateFRem(LC, RC), Name);
835     return Insert(AddFPMathAttributes(BinaryOperator::CreateFRem(LHS, RHS),
836                                       FPMathTag, FMF), Name);
837   }
838
839   Value *CreateShl(Value *LHS, Value *RHS, const Twine &Name = "",
840                    bool HasNUW = false, bool HasNSW = false) {
841     if (Constant *LC = dyn_cast<Constant>(LHS))
842       if (Constant *RC = dyn_cast<Constant>(RHS))
843         return Insert(Folder.CreateShl(LC, RC, HasNUW, HasNSW), Name);
844     return CreateInsertNUWNSWBinOp(Instruction::Shl, LHS, RHS, Name,
845                                    HasNUW, HasNSW);
846   }
847   Value *CreateShl(Value *LHS, const APInt &RHS, const Twine &Name = "",
848                    bool HasNUW = false, bool HasNSW = false) {
849     return CreateShl(LHS, ConstantInt::get(LHS->getType(), RHS), Name,
850                      HasNUW, HasNSW);
851   }
852   Value *CreateShl(Value *LHS, uint64_t RHS, const Twine &Name = "",
853                    bool HasNUW = false, bool HasNSW = false) {
854     return CreateShl(LHS, ConstantInt::get(LHS->getType(), RHS), Name,
855                      HasNUW, HasNSW);
856   }
857
858   Value *CreateLShr(Value *LHS, Value *RHS, const Twine &Name = "",
859                     bool isExact = false) {
860     if (Constant *LC = dyn_cast<Constant>(LHS))
861       if (Constant *RC = dyn_cast<Constant>(RHS))
862         return Insert(Folder.CreateLShr(LC, RC, isExact), Name);
863     if (!isExact)
864       return Insert(BinaryOperator::CreateLShr(LHS, RHS), Name);
865     return Insert(BinaryOperator::CreateExactLShr(LHS, RHS), Name);
866   }
867   Value *CreateLShr(Value *LHS, const APInt &RHS, const Twine &Name = "",
868                     bool isExact = false) {
869     return CreateLShr(LHS, ConstantInt::get(LHS->getType(), RHS), Name,isExact);
870   }
871   Value *CreateLShr(Value *LHS, uint64_t RHS, const Twine &Name = "",
872                     bool isExact = false) {
873     return CreateLShr(LHS, ConstantInt::get(LHS->getType(), RHS), Name,isExact);
874   }
875
876   Value *CreateAShr(Value *LHS, Value *RHS, const Twine &Name = "",
877                     bool isExact = false) {
878     if (Constant *LC = dyn_cast<Constant>(LHS))
879       if (Constant *RC = dyn_cast<Constant>(RHS))
880         return Insert(Folder.CreateAShr(LC, RC, isExact), Name);
881     if (!isExact)
882       return Insert(BinaryOperator::CreateAShr(LHS, RHS), Name);
883     return Insert(BinaryOperator::CreateExactAShr(LHS, RHS), Name);
884   }
885   Value *CreateAShr(Value *LHS, const APInt &RHS, const Twine &Name = "",
886                     bool isExact = false) {
887     return CreateAShr(LHS, ConstantInt::get(LHS->getType(), RHS), Name,isExact);
888   }
889   Value *CreateAShr(Value *LHS, uint64_t RHS, const Twine &Name = "",
890                     bool isExact = false) {
891     return CreateAShr(LHS, ConstantInt::get(LHS->getType(), RHS), Name,isExact);
892   }
893
894   Value *CreateAnd(Value *LHS, Value *RHS, const Twine &Name = "") {
895     if (Constant *RC = dyn_cast<Constant>(RHS)) {
896       if (isa<ConstantInt>(RC) && cast<ConstantInt>(RC)->isAllOnesValue())
897         return LHS;  // LHS & -1 -> LHS
898       if (Constant *LC = dyn_cast<Constant>(LHS))
899         return Insert(Folder.CreateAnd(LC, RC), Name);
900     }
901     return Insert(BinaryOperator::CreateAnd(LHS, RHS), Name);
902   }
903   Value *CreateAnd(Value *LHS, const APInt &RHS, const Twine &Name = "") {
904     return CreateAnd(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
905   }
906   Value *CreateAnd(Value *LHS, uint64_t RHS, const Twine &Name = "") {
907     return CreateAnd(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
908   }
909
910   Value *CreateOr(Value *LHS, Value *RHS, const Twine &Name = "") {
911     if (Constant *RC = dyn_cast<Constant>(RHS)) {
912       if (RC->isNullValue())
913         return LHS;  // LHS | 0 -> LHS
914       if (Constant *LC = dyn_cast<Constant>(LHS))
915         return Insert(Folder.CreateOr(LC, RC), Name);
916     }
917     return Insert(BinaryOperator::CreateOr(LHS, RHS), Name);
918   }
919   Value *CreateOr(Value *LHS, const APInt &RHS, const Twine &Name = "") {
920     return CreateOr(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
921   }
922   Value *CreateOr(Value *LHS, uint64_t RHS, const Twine &Name = "") {
923     return CreateOr(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
924   }
925
926   Value *CreateXor(Value *LHS, Value *RHS, const Twine &Name = "") {
927     if (Constant *LC = dyn_cast<Constant>(LHS))
928       if (Constant *RC = dyn_cast<Constant>(RHS))
929         return Insert(Folder.CreateXor(LC, RC), Name);
930     return Insert(BinaryOperator::CreateXor(LHS, RHS), Name);
931   }
932   Value *CreateXor(Value *LHS, const APInt &RHS, const Twine &Name = "") {
933     return CreateXor(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
934   }
935   Value *CreateXor(Value *LHS, uint64_t RHS, const Twine &Name = "") {
936     return CreateXor(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
937   }
938
939   Value *CreateBinOp(Instruction::BinaryOps Opc,
940                      Value *LHS, Value *RHS, const Twine &Name = "",
941                      MDNode *FPMathTag = nullptr) {
942     if (Constant *LC = dyn_cast<Constant>(LHS))
943       if (Constant *RC = dyn_cast<Constant>(RHS))
944         return Insert(Folder.CreateBinOp(Opc, LC, RC), Name);
945     llvm::Instruction *BinOp = BinaryOperator::Create(Opc, LHS, RHS);
946     if (isa<FPMathOperator>(BinOp))
947       BinOp = AddFPMathAttributes(BinOp, FPMathTag, FMF);
948     return Insert(BinOp, Name);
949   }
950
951   Value *CreateNeg(Value *V, const Twine &Name = "",
952                    bool HasNUW = false, bool HasNSW = false) {
953     if (Constant *VC = dyn_cast<Constant>(V))
954       return Insert(Folder.CreateNeg(VC, HasNUW, HasNSW), Name);
955     BinaryOperator *BO = Insert(BinaryOperator::CreateNeg(V), Name);
956     if (HasNUW) BO->setHasNoUnsignedWrap();
957     if (HasNSW) BO->setHasNoSignedWrap();
958     return BO;
959   }
960   Value *CreateNSWNeg(Value *V, const Twine &Name = "") {
961     return CreateNeg(V, Name, false, true);
962   }
963   Value *CreateNUWNeg(Value *V, const Twine &Name = "") {
964     return CreateNeg(V, Name, true, false);
965   }
966   Value *CreateFNeg(Value *V, const Twine &Name = "",
967                     MDNode *FPMathTag = nullptr) {
968     if (Constant *VC = dyn_cast<Constant>(V))
969       return Insert(Folder.CreateFNeg(VC), Name);
970     return Insert(AddFPMathAttributes(BinaryOperator::CreateFNeg(V),
971                                       FPMathTag, FMF), Name);
972   }
973   Value *CreateNot(Value *V, const Twine &Name = "") {
974     if (Constant *VC = dyn_cast<Constant>(V))
975       return Insert(Folder.CreateNot(VC), Name);
976     return Insert(BinaryOperator::CreateNot(V), Name);
977   }
978
979   //===--------------------------------------------------------------------===//
980   // Instruction creation methods: Memory Instructions
981   //===--------------------------------------------------------------------===//
982
983   AllocaInst *CreateAlloca(Type *Ty, Value *ArraySize = nullptr,
984                            const Twine &Name = "") {
985     return Insert(new AllocaInst(Ty, ArraySize), Name);
986   }
987   // \brief Provided to resolve 'CreateLoad(Ptr, "...")' correctly, instead of
988   // converting the string to 'bool' for the isVolatile parameter.
989   LoadInst *CreateLoad(Value *Ptr, const char *Name) {
990     return Insert(new LoadInst(Ptr), Name);
991   }
992   LoadInst *CreateLoad(Value *Ptr, const Twine &Name = "") {
993     return Insert(new LoadInst(Ptr), Name);
994   }
995   LoadInst *CreateLoad(Value *Ptr, bool isVolatile, const Twine &Name = "") {
996     return Insert(new LoadInst(Ptr, nullptr, isVolatile), Name);
997   }
998   StoreInst *CreateStore(Value *Val, Value *Ptr, bool isVolatile = false) {
999     return Insert(new StoreInst(Val, Ptr, isVolatile));
1000   }
1001   // \brief Provided to resolve 'CreateAlignedLoad(Ptr, Align, "...")'
1002   // correctly, instead of converting the string to 'bool' for the isVolatile
1003   // parameter.
1004   LoadInst *CreateAlignedLoad(Value *Ptr, unsigned Align, const char *Name) {
1005     LoadInst *LI = CreateLoad(Ptr, Name);
1006     LI->setAlignment(Align);
1007     return LI;
1008   }
1009   LoadInst *CreateAlignedLoad(Value *Ptr, unsigned Align,
1010                               const Twine &Name = "") {
1011     LoadInst *LI = CreateLoad(Ptr, Name);
1012     LI->setAlignment(Align);
1013     return LI;
1014   }
1015   LoadInst *CreateAlignedLoad(Value *Ptr, unsigned Align, bool isVolatile,
1016                               const Twine &Name = "") {
1017     LoadInst *LI = CreateLoad(Ptr, isVolatile, Name);
1018     LI->setAlignment(Align);
1019     return LI;
1020   }
1021   StoreInst *CreateAlignedStore(Value *Val, Value *Ptr, unsigned Align,
1022                                 bool isVolatile = false) {
1023     StoreInst *SI = CreateStore(Val, Ptr, isVolatile);
1024     SI->setAlignment(Align);
1025     return SI;
1026   }
1027   FenceInst *CreateFence(AtomicOrdering Ordering,
1028                          SynchronizationScope SynchScope = CrossThread,
1029                          const Twine &Name = "") {
1030     return Insert(new FenceInst(Context, Ordering, SynchScope), Name);
1031   }
1032   AtomicCmpXchgInst *
1033   CreateAtomicCmpXchg(Value *Ptr, Value *Cmp, Value *New,
1034                       AtomicOrdering SuccessOrdering,
1035                       AtomicOrdering FailureOrdering,
1036                       SynchronizationScope SynchScope = CrossThread) {
1037     return Insert(new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering,
1038                                         FailureOrdering, SynchScope));
1039   }
1040   AtomicRMWInst *CreateAtomicRMW(AtomicRMWInst::BinOp Op, Value *Ptr, Value *Val,
1041                                  AtomicOrdering Ordering,
1042                                SynchronizationScope SynchScope = CrossThread) {
1043     return Insert(new AtomicRMWInst(Op, Ptr, Val, Ordering, SynchScope));
1044   }
1045   Value *CreateGEP(Value *Ptr, ArrayRef<Value *> IdxList,
1046                    const Twine &Name = "") {
1047     return CreateGEP(nullptr, Ptr, IdxList, Name);
1048   }
1049   Value *CreateGEP(Type *Ty, Value *Ptr, ArrayRef<Value *> IdxList,
1050                    const Twine &Name = "") {
1051     if (Constant *PC = dyn_cast<Constant>(Ptr)) {
1052       // Every index must be constant.
1053       size_t i, e;
1054       for (i = 0, e = IdxList.size(); i != e; ++i)
1055         if (!isa<Constant>(IdxList[i]))
1056           break;
1057       if (i == e)
1058         return Insert(Folder.CreateGetElementPtr(Ty, PC, IdxList), Name);
1059     }
1060     return Insert(GetElementPtrInst::Create(Ty, Ptr, IdxList), Name);
1061   }
1062   Value *CreateInBoundsGEP(Value *Ptr, ArrayRef<Value *> IdxList,
1063                            const Twine &Name = "") {
1064     return CreateInBoundsGEP(nullptr, Ptr, IdxList, Name);
1065   }
1066   Value *CreateInBoundsGEP(Type *Ty, Value *Ptr, ArrayRef<Value *> IdxList,
1067                            const Twine &Name = "") {
1068     if (Constant *PC = dyn_cast<Constant>(Ptr)) {
1069       // Every index must be constant.
1070       size_t i, e;
1071       for (i = 0, e = IdxList.size(); i != e; ++i)
1072         if (!isa<Constant>(IdxList[i]))
1073           break;
1074       if (i == e)
1075         return Insert(Folder.CreateInBoundsGetElementPtr(Ty, PC, IdxList),
1076                       Name);
1077     }
1078     return Insert(GetElementPtrInst::CreateInBounds(Ty, Ptr, IdxList), Name);
1079   }
1080   Value *CreateGEP(Value *Ptr, Value *Idx, const Twine &Name = "") {
1081     return CreateGEP(nullptr, Ptr, Idx, Name);
1082   }
1083   Value *CreateGEP(Type *Ty, Value *Ptr, Value *Idx, const Twine &Name = "") {
1084     if (Constant *PC = dyn_cast<Constant>(Ptr))
1085       if (Constant *IC = dyn_cast<Constant>(Idx))
1086         return Insert(Folder.CreateGetElementPtr(Ty, PC, IC), Name);
1087     return Insert(GetElementPtrInst::Create(Ty, Ptr, Idx), Name);
1088   }
1089   Value *CreateInBoundsGEP(Type *Ty, Value *Ptr, Value *Idx,
1090                            const Twine &Name = "") {
1091     if (Constant *PC = dyn_cast<Constant>(Ptr))
1092       if (Constant *IC = dyn_cast<Constant>(Idx))
1093         return Insert(Folder.CreateInBoundsGetElementPtr(Ty, PC, IC), Name);
1094     return Insert(GetElementPtrInst::CreateInBounds(Ty, Ptr, Idx), Name);
1095   }
1096   Value *CreateConstGEP1_32(Value *Ptr, unsigned Idx0, const Twine &Name = "") {
1097     return CreateConstGEP1_32(nullptr, Ptr, Idx0, Name);
1098   }
1099   Value *CreateConstGEP1_32(Type *Ty, Value *Ptr, unsigned Idx0,
1100                             const Twine &Name = "") {
1101     Value *Idx = ConstantInt::get(Type::getInt32Ty(Context), Idx0);
1102
1103     if (Constant *PC = dyn_cast<Constant>(Ptr))
1104       return Insert(Folder.CreateGetElementPtr(Ty, PC, Idx), Name);
1105
1106     return Insert(GetElementPtrInst::Create(Ty, Ptr, Idx), Name);
1107   }
1108   Value *CreateConstInBoundsGEP1_32(Type *Ty, Value *Ptr, unsigned Idx0,
1109                                     const Twine &Name = "") {
1110     Value *Idx = ConstantInt::get(Type::getInt32Ty(Context), Idx0);
1111
1112     if (Constant *PC = dyn_cast<Constant>(Ptr))
1113       return Insert(Folder.CreateInBoundsGetElementPtr(Ty, PC, Idx), Name);
1114
1115     return Insert(GetElementPtrInst::CreateInBounds(Ty, Ptr, Idx), Name);
1116   }
1117   Value *CreateConstGEP2_32(Type *Ty, Value *Ptr, unsigned Idx0, unsigned Idx1,
1118                             const Twine &Name = "") {
1119     Value *Idxs[] = {
1120       ConstantInt::get(Type::getInt32Ty(Context), Idx0),
1121       ConstantInt::get(Type::getInt32Ty(Context), Idx1)
1122     };
1123
1124     if (Constant *PC = dyn_cast<Constant>(Ptr))
1125       return Insert(Folder.CreateGetElementPtr(Ty, PC, Idxs), Name);
1126
1127     return Insert(GetElementPtrInst::Create(Ty, Ptr, Idxs), Name);
1128   }
1129   Value *CreateConstInBoundsGEP2_32(Type *Ty, Value *Ptr, unsigned Idx0,
1130                                     unsigned Idx1, const Twine &Name = "") {
1131     Value *Idxs[] = {
1132       ConstantInt::get(Type::getInt32Ty(Context), Idx0),
1133       ConstantInt::get(Type::getInt32Ty(Context), Idx1)
1134     };
1135
1136     if (Constant *PC = dyn_cast<Constant>(Ptr))
1137       return Insert(Folder.CreateInBoundsGetElementPtr(Ty, PC, Idxs), Name);
1138
1139     return Insert(GetElementPtrInst::CreateInBounds(Ty, Ptr, Idxs), Name);
1140   }
1141   Value *CreateConstGEP1_64(Value *Ptr, uint64_t Idx0, const Twine &Name = "") {
1142     Value *Idx = ConstantInt::get(Type::getInt64Ty(Context), Idx0);
1143
1144     if (Constant *PC = dyn_cast<Constant>(Ptr))
1145       return Insert(Folder.CreateGetElementPtr(nullptr, PC, Idx), Name);
1146
1147     return Insert(GetElementPtrInst::Create(nullptr, Ptr, Idx), Name);
1148   }
1149   Value *CreateConstInBoundsGEP1_64(Value *Ptr, uint64_t Idx0,
1150                                     const Twine &Name = "") {
1151     Value *Idx = ConstantInt::get(Type::getInt64Ty(Context), Idx0);
1152
1153     if (Constant *PC = dyn_cast<Constant>(Ptr))
1154       return Insert(Folder.CreateInBoundsGetElementPtr(nullptr, PC, Idx), Name);
1155
1156     return Insert(GetElementPtrInst::CreateInBounds(nullptr, Ptr, Idx), Name);
1157   }
1158   Value *CreateConstGEP2_64(Value *Ptr, uint64_t Idx0, uint64_t Idx1,
1159                     const Twine &Name = "") {
1160     Value *Idxs[] = {
1161       ConstantInt::get(Type::getInt64Ty(Context), Idx0),
1162       ConstantInt::get(Type::getInt64Ty(Context), Idx1)
1163     };
1164
1165     if (Constant *PC = dyn_cast<Constant>(Ptr))
1166       return Insert(Folder.CreateGetElementPtr(nullptr, PC, Idxs), Name);
1167
1168     return Insert(GetElementPtrInst::Create(nullptr, Ptr, Idxs), Name);
1169   }
1170   Value *CreateConstInBoundsGEP2_64(Value *Ptr, uint64_t Idx0, uint64_t Idx1,
1171                                     const Twine &Name = "") {
1172     Value *Idxs[] = {
1173       ConstantInt::get(Type::getInt64Ty(Context), Idx0),
1174       ConstantInt::get(Type::getInt64Ty(Context), Idx1)
1175     };
1176
1177     if (Constant *PC = dyn_cast<Constant>(Ptr))
1178       return Insert(Folder.CreateInBoundsGetElementPtr(nullptr, PC, Idxs),
1179                     Name);
1180
1181     return Insert(GetElementPtrInst::CreateInBounds(nullptr, Ptr, Idxs), Name);
1182   }
1183   Value *CreateStructGEP(Type *Ty, Value *Ptr, unsigned Idx,
1184                          const Twine &Name = "") {
1185     return CreateConstInBoundsGEP2_32(Ty, Ptr, 0, Idx, Name);
1186   }
1187
1188   /// \brief Same as CreateGlobalString, but return a pointer with "i8*" type
1189   /// instead of a pointer to array of i8.
1190   Value *CreateGlobalStringPtr(StringRef Str, const Twine &Name = "") {
1191     GlobalVariable *gv = CreateGlobalString(Str, Name);
1192     Value *zero = ConstantInt::get(Type::getInt32Ty(Context), 0);
1193     Value *Args[] = { zero, zero };
1194     return CreateInBoundsGEP(gv->getValueType(), gv, Args, Name);
1195   }
1196
1197   //===--------------------------------------------------------------------===//
1198   // Instruction creation methods: Cast/Conversion Operators
1199   //===--------------------------------------------------------------------===//
1200
1201   Value *CreateTrunc(Value *V, Type *DestTy, const Twine &Name = "") {
1202     return CreateCast(Instruction::Trunc, V, DestTy, Name);
1203   }
1204   Value *CreateZExt(Value *V, Type *DestTy, const Twine &Name = "") {
1205     return CreateCast(Instruction::ZExt, V, DestTy, Name);
1206   }
1207   Value *CreateSExt(Value *V, Type *DestTy, const Twine &Name = "") {
1208     return CreateCast(Instruction::SExt, V, DestTy, Name);
1209   }
1210   /// \brief Create a ZExt or Trunc from the integer value V to DestTy. Return
1211   /// the value untouched if the type of V is already DestTy.
1212   Value *CreateZExtOrTrunc(Value *V, Type *DestTy,
1213                            const Twine &Name = "") {
1214     assert(V->getType()->isIntOrIntVectorTy() &&
1215            DestTy->isIntOrIntVectorTy() &&
1216            "Can only zero extend/truncate integers!");
1217     Type *VTy = V->getType();
1218     if (VTy->getScalarSizeInBits() < DestTy->getScalarSizeInBits())
1219       return CreateZExt(V, DestTy, Name);
1220     if (VTy->getScalarSizeInBits() > DestTy->getScalarSizeInBits())
1221       return CreateTrunc(V, DestTy, Name);
1222     return V;
1223   }
1224   /// \brief Create a SExt or Trunc from the integer value V to DestTy. Return
1225   /// the value untouched if the type of V is already DestTy.
1226   Value *CreateSExtOrTrunc(Value *V, Type *DestTy,
1227                            const Twine &Name = "") {
1228     assert(V->getType()->isIntOrIntVectorTy() &&
1229            DestTy->isIntOrIntVectorTy() &&
1230            "Can only sign extend/truncate integers!");
1231     Type *VTy = V->getType();
1232     if (VTy->getScalarSizeInBits() < DestTy->getScalarSizeInBits())
1233       return CreateSExt(V, DestTy, Name);
1234     if (VTy->getScalarSizeInBits() > DestTy->getScalarSizeInBits())
1235       return CreateTrunc(V, DestTy, Name);
1236     return V;
1237   }
1238   Value *CreateFPToUI(Value *V, Type *DestTy, const Twine &Name = ""){
1239     return CreateCast(Instruction::FPToUI, V, DestTy, Name);
1240   }
1241   Value *CreateFPToSI(Value *V, Type *DestTy, const Twine &Name = ""){
1242     return CreateCast(Instruction::FPToSI, V, DestTy, Name);
1243   }
1244   Value *CreateUIToFP(Value *V, Type *DestTy, const Twine &Name = ""){
1245     return CreateCast(Instruction::UIToFP, V, DestTy, Name);
1246   }
1247   Value *CreateSIToFP(Value *V, Type *DestTy, const Twine &Name = ""){
1248     return CreateCast(Instruction::SIToFP, V, DestTy, Name);
1249   }
1250   Value *CreateFPTrunc(Value *V, Type *DestTy,
1251                        const Twine &Name = "") {
1252     return CreateCast(Instruction::FPTrunc, V, DestTy, Name);
1253   }
1254   Value *CreateFPExt(Value *V, Type *DestTy, const Twine &Name = "") {
1255     return CreateCast(Instruction::FPExt, V, DestTy, Name);
1256   }
1257   Value *CreatePtrToInt(Value *V, Type *DestTy,
1258                         const Twine &Name = "") {
1259     return CreateCast(Instruction::PtrToInt, V, DestTy, Name);
1260   }
1261   Value *CreateIntToPtr(Value *V, Type *DestTy,
1262                         const Twine &Name = "") {
1263     return CreateCast(Instruction::IntToPtr, V, DestTy, Name);
1264   }
1265   Value *CreateBitCast(Value *V, Type *DestTy,
1266                        const Twine &Name = "") {
1267     return CreateCast(Instruction::BitCast, V, DestTy, Name);
1268   }
1269   Value *CreateAddrSpaceCast(Value *V, Type *DestTy,
1270                              const Twine &Name = "") {
1271     return CreateCast(Instruction::AddrSpaceCast, V, DestTy, Name);
1272   }
1273   Value *CreateZExtOrBitCast(Value *V, Type *DestTy,
1274                              const Twine &Name = "") {
1275     if (V->getType() == DestTy)
1276       return V;
1277     if (Constant *VC = dyn_cast<Constant>(V))
1278       return Insert(Folder.CreateZExtOrBitCast(VC, DestTy), Name);
1279     return Insert(CastInst::CreateZExtOrBitCast(V, DestTy), Name);
1280   }
1281   Value *CreateSExtOrBitCast(Value *V, Type *DestTy,
1282                              const Twine &Name = "") {
1283     if (V->getType() == DestTy)
1284       return V;
1285     if (Constant *VC = dyn_cast<Constant>(V))
1286       return Insert(Folder.CreateSExtOrBitCast(VC, DestTy), Name);
1287     return Insert(CastInst::CreateSExtOrBitCast(V, DestTy), Name);
1288   }
1289   Value *CreateTruncOrBitCast(Value *V, Type *DestTy,
1290                               const Twine &Name = "") {
1291     if (V->getType() == DestTy)
1292       return V;
1293     if (Constant *VC = dyn_cast<Constant>(V))
1294       return Insert(Folder.CreateTruncOrBitCast(VC, DestTy), Name);
1295     return Insert(CastInst::CreateTruncOrBitCast(V, DestTy), Name);
1296   }
1297   Value *CreateCast(Instruction::CastOps Op, Value *V, Type *DestTy,
1298                     const Twine &Name = "") {
1299     if (V->getType() == DestTy)
1300       return V;
1301     if (Constant *VC = dyn_cast<Constant>(V))
1302       return Insert(Folder.CreateCast(Op, VC, DestTy), Name);
1303     return Insert(CastInst::Create(Op, V, DestTy), Name);
1304   }
1305   Value *CreatePointerCast(Value *V, Type *DestTy,
1306                            const Twine &Name = "") {
1307     if (V->getType() == DestTy)
1308       return V;
1309     if (Constant *VC = dyn_cast<Constant>(V))
1310       return Insert(Folder.CreatePointerCast(VC, DestTy), Name);
1311     return Insert(CastInst::CreatePointerCast(V, DestTy), Name);
1312   }
1313
1314   Value *CreatePointerBitCastOrAddrSpaceCast(Value *V, Type *DestTy,
1315                                              const Twine &Name = "") {
1316     if (V->getType() == DestTy)
1317       return V;
1318
1319     if (Constant *VC = dyn_cast<Constant>(V)) {
1320       return Insert(Folder.CreatePointerBitCastOrAddrSpaceCast(VC, DestTy),
1321                     Name);
1322     }
1323
1324     return Insert(CastInst::CreatePointerBitCastOrAddrSpaceCast(V, DestTy),
1325                   Name);
1326   }
1327
1328   Value *CreateIntCast(Value *V, Type *DestTy, bool isSigned,
1329                        const Twine &Name = "") {
1330     if (V->getType() == DestTy)
1331       return V;
1332     if (Constant *VC = dyn_cast<Constant>(V))
1333       return Insert(Folder.CreateIntCast(VC, DestTy, isSigned), Name);
1334     return Insert(CastInst::CreateIntegerCast(V, DestTy, isSigned), Name);
1335   }
1336
1337   Value *CreateBitOrPointerCast(Value *V, Type *DestTy,
1338                                 const Twine &Name = "") {
1339     if (V->getType() == DestTy)
1340       return V;
1341     if (V->getType()->isPointerTy() && DestTy->isIntegerTy())
1342       return CreatePtrToInt(V, DestTy, Name);
1343     if (V->getType()->isIntegerTy() && DestTy->isPointerTy())
1344       return CreateIntToPtr(V, DestTy, Name);
1345
1346     return CreateBitCast(V, DestTy, Name);
1347   }
1348 private:
1349   // \brief Provided to resolve 'CreateIntCast(Ptr, Ptr, "...")', giving a
1350   // compile time error, instead of converting the string to bool for the
1351   // isSigned parameter.
1352   Value *CreateIntCast(Value *, Type *, const char *) = delete;
1353 public:
1354   Value *CreateFPCast(Value *V, Type *DestTy, const Twine &Name = "") {
1355     if (V->getType() == DestTy)
1356       return V;
1357     if (Constant *VC = dyn_cast<Constant>(V))
1358       return Insert(Folder.CreateFPCast(VC, DestTy), Name);
1359     return Insert(CastInst::CreateFPCast(V, DestTy), Name);
1360   }
1361
1362   //===--------------------------------------------------------------------===//
1363   // Instruction creation methods: Compare Instructions
1364   //===--------------------------------------------------------------------===//
1365
1366   Value *CreateICmpEQ(Value *LHS, Value *RHS, const Twine &Name = "") {
1367     return CreateICmp(ICmpInst::ICMP_EQ, LHS, RHS, Name);
1368   }
1369   Value *CreateICmpNE(Value *LHS, Value *RHS, const Twine &Name = "") {
1370     return CreateICmp(ICmpInst::ICMP_NE, LHS, RHS, Name);
1371   }
1372   Value *CreateICmpUGT(Value *LHS, Value *RHS, const Twine &Name = "") {
1373     return CreateICmp(ICmpInst::ICMP_UGT, LHS, RHS, Name);
1374   }
1375   Value *CreateICmpUGE(Value *LHS, Value *RHS, const Twine &Name = "") {
1376     return CreateICmp(ICmpInst::ICMP_UGE, LHS, RHS, Name);
1377   }
1378   Value *CreateICmpULT(Value *LHS, Value *RHS, const Twine &Name = "") {
1379     return CreateICmp(ICmpInst::ICMP_ULT, LHS, RHS, Name);
1380   }
1381   Value *CreateICmpULE(Value *LHS, Value *RHS, const Twine &Name = "") {
1382     return CreateICmp(ICmpInst::ICMP_ULE, LHS, RHS, Name);
1383   }
1384   Value *CreateICmpSGT(Value *LHS, Value *RHS, const Twine &Name = "") {
1385     return CreateICmp(ICmpInst::ICMP_SGT, LHS, RHS, Name);
1386   }
1387   Value *CreateICmpSGE(Value *LHS, Value *RHS, const Twine &Name = "") {
1388     return CreateICmp(ICmpInst::ICMP_SGE, LHS, RHS, Name);
1389   }
1390   Value *CreateICmpSLT(Value *LHS, Value *RHS, const Twine &Name = "") {
1391     return CreateICmp(ICmpInst::ICMP_SLT, LHS, RHS, Name);
1392   }
1393   Value *CreateICmpSLE(Value *LHS, Value *RHS, const Twine &Name = "") {
1394     return CreateICmp(ICmpInst::ICMP_SLE, LHS, RHS, Name);
1395   }
1396
1397   Value *CreateFCmpOEQ(Value *LHS, Value *RHS, const Twine &Name = "") {
1398     return CreateFCmp(FCmpInst::FCMP_OEQ, LHS, RHS, Name);
1399   }
1400   Value *CreateFCmpOGT(Value *LHS, Value *RHS, const Twine &Name = "") {
1401     return CreateFCmp(FCmpInst::FCMP_OGT, LHS, RHS, Name);
1402   }
1403   Value *CreateFCmpOGE(Value *LHS, Value *RHS, const Twine &Name = "") {
1404     return CreateFCmp(FCmpInst::FCMP_OGE, LHS, RHS, Name);
1405   }
1406   Value *CreateFCmpOLT(Value *LHS, Value *RHS, const Twine &Name = "") {
1407     return CreateFCmp(FCmpInst::FCMP_OLT, LHS, RHS, Name);
1408   }
1409   Value *CreateFCmpOLE(Value *LHS, Value *RHS, const Twine &Name = "") {
1410     return CreateFCmp(FCmpInst::FCMP_OLE, LHS, RHS, Name);
1411   }
1412   Value *CreateFCmpONE(Value *LHS, Value *RHS, const Twine &Name = "") {
1413     return CreateFCmp(FCmpInst::FCMP_ONE, LHS, RHS, Name);
1414   }
1415   Value *CreateFCmpORD(Value *LHS, Value *RHS, const Twine &Name = "") {
1416     return CreateFCmp(FCmpInst::FCMP_ORD, LHS, RHS, Name);
1417   }
1418   Value *CreateFCmpUNO(Value *LHS, Value *RHS, const Twine &Name = "") {
1419     return CreateFCmp(FCmpInst::FCMP_UNO, LHS, RHS, Name);
1420   }
1421   Value *CreateFCmpUEQ(Value *LHS, Value *RHS, const Twine &Name = "") {
1422     return CreateFCmp(FCmpInst::FCMP_UEQ, LHS, RHS, Name);
1423   }
1424   Value *CreateFCmpUGT(Value *LHS, Value *RHS, const Twine &Name = "") {
1425     return CreateFCmp(FCmpInst::FCMP_UGT, LHS, RHS, Name);
1426   }
1427   Value *CreateFCmpUGE(Value *LHS, Value *RHS, const Twine &Name = "") {
1428     return CreateFCmp(FCmpInst::FCMP_UGE, LHS, RHS, Name);
1429   }
1430   Value *CreateFCmpULT(Value *LHS, Value *RHS, const Twine &Name = "") {
1431     return CreateFCmp(FCmpInst::FCMP_ULT, LHS, RHS, Name);
1432   }
1433   Value *CreateFCmpULE(Value *LHS, Value *RHS, const Twine &Name = "") {
1434     return CreateFCmp(FCmpInst::FCMP_ULE, LHS, RHS, Name);
1435   }
1436   Value *CreateFCmpUNE(Value *LHS, Value *RHS, const Twine &Name = "") {
1437     return CreateFCmp(FCmpInst::FCMP_UNE, LHS, RHS, Name);
1438   }
1439
1440   Value *CreateICmp(CmpInst::Predicate P, Value *LHS, Value *RHS,
1441                     const Twine &Name = "") {
1442     if (Constant *LC = dyn_cast<Constant>(LHS))
1443       if (Constant *RC = dyn_cast<Constant>(RHS))
1444         return Insert(Folder.CreateICmp(P, LC, RC), Name);
1445     return Insert(new ICmpInst(P, LHS, RHS), Name);
1446   }
1447   Value *CreateFCmp(CmpInst::Predicate P, Value *LHS, Value *RHS,
1448                     const Twine &Name = "") {
1449     if (Constant *LC = dyn_cast<Constant>(LHS))
1450       if (Constant *RC = dyn_cast<Constant>(RHS))
1451         return Insert(Folder.CreateFCmp(P, LC, RC), Name);
1452     return Insert(new FCmpInst(P, LHS, RHS), Name);
1453   }
1454
1455   //===--------------------------------------------------------------------===//
1456   // Instruction creation methods: Other Instructions
1457   //===--------------------------------------------------------------------===//
1458
1459   PHINode *CreatePHI(Type *Ty, unsigned NumReservedValues,
1460                      const Twine &Name = "") {
1461     return Insert(PHINode::Create(Ty, NumReservedValues), Name);
1462   }
1463
1464   CallInst *CreateCall(Value *Callee, const Twine &Name = "") {
1465     return Insert(CallInst::Create(Callee), Name);
1466   }
1467   CallInst *CreateCall(Value *Callee, Value *Arg, const Twine &Name = "") {
1468     return Insert(CallInst::Create(Callee, Arg), Name);
1469   }
1470   CallInst *CreateCall2(Value *Callee, Value *Arg1, Value *Arg2,
1471                         const Twine &Name = "") {
1472     return CreateCall2(cast<FunctionType>(cast<PointerType>(Callee->getType())
1473                                               ->getElementType()),
1474                        Callee, Arg1, Arg2, Name);
1475   }
1476   CallInst *CreateCall2(FunctionType *Ty, Value *Callee, Value *Arg1,
1477                         Value *Arg2, const Twine &Name = "") {
1478     Value *Args[] = { Arg1, Arg2 };
1479     return Insert(CallInst::Create(Ty, Callee, Args), Name);
1480   }
1481   CallInst *CreateCall3(Value *Callee, Value *Arg1, Value *Arg2, Value *Arg3,
1482                         const Twine &Name = "") {
1483     Value *Args[] = { Arg1, Arg2, Arg3 };
1484     return Insert(CallInst::Create(Callee, Args), Name);
1485   }
1486   CallInst *CreateCall4(Value *Callee, Value *Arg1, Value *Arg2, Value *Arg3,
1487                         Value *Arg4, const Twine &Name = "") {
1488     Value *Args[] = { Arg1, Arg2, Arg3, Arg4 };
1489     return Insert(CallInst::Create(Callee, Args), Name);
1490   }
1491   CallInst *CreateCall5(Value *Callee, Value *Arg1, Value *Arg2, Value *Arg3,
1492                         Value *Arg4, Value *Arg5, const Twine &Name = "") {
1493     Value *Args[] = { Arg1, Arg2, Arg3, Arg4, Arg5 };
1494     return Insert(CallInst::Create(Callee, Args), Name);
1495   }
1496
1497   CallInst *CreateCall(Value *Callee, ArrayRef<Value *> Args,
1498                        const Twine &Name = "") {
1499     return Insert(CallInst::Create(Callee, Args), Name);
1500   }
1501
1502   Value *CreateSelect(Value *C, Value *True, Value *False,
1503                       const Twine &Name = "") {
1504     if (Constant *CC = dyn_cast<Constant>(C))
1505       if (Constant *TC = dyn_cast<Constant>(True))
1506         if (Constant *FC = dyn_cast<Constant>(False))
1507           return Insert(Folder.CreateSelect(CC, TC, FC), Name);
1508     return Insert(SelectInst::Create(C, True, False), Name);
1509   }
1510
1511   VAArgInst *CreateVAArg(Value *List, Type *Ty, const Twine &Name = "") {
1512     return Insert(new VAArgInst(List, Ty), Name);
1513   }
1514
1515   Value *CreateExtractElement(Value *Vec, Value *Idx,
1516                               const Twine &Name = "") {
1517     if (Constant *VC = dyn_cast<Constant>(Vec))
1518       if (Constant *IC = dyn_cast<Constant>(Idx))
1519         return Insert(Folder.CreateExtractElement(VC, IC), Name);
1520     return Insert(ExtractElementInst::Create(Vec, Idx), Name);
1521   }
1522
1523   Value *CreateExtractElement(Value *Vec, uint64_t Idx,
1524                               const Twine &Name = "") {
1525     return CreateExtractElement(Vec, getInt64(Idx), Name);
1526   }
1527
1528   Value *CreateInsertElement(Value *Vec, Value *NewElt, Value *Idx,
1529                              const Twine &Name = "") {
1530     if (Constant *VC = dyn_cast<Constant>(Vec))
1531       if (Constant *NC = dyn_cast<Constant>(NewElt))
1532         if (Constant *IC = dyn_cast<Constant>(Idx))
1533           return Insert(Folder.CreateInsertElement(VC, NC, IC), Name);
1534     return Insert(InsertElementInst::Create(Vec, NewElt, Idx), Name);
1535   }
1536
1537   Value *CreateInsertElement(Value *Vec, Value *NewElt, uint64_t Idx,
1538                              const Twine &Name = "") {
1539     return CreateInsertElement(Vec, NewElt, getInt64(Idx), Name);
1540   }
1541
1542   Value *CreateShuffleVector(Value *V1, Value *V2, Value *Mask,
1543                              const Twine &Name = "") {
1544     if (Constant *V1C = dyn_cast<Constant>(V1))
1545       if (Constant *V2C = dyn_cast<Constant>(V2))
1546         if (Constant *MC = dyn_cast<Constant>(Mask))
1547           return Insert(Folder.CreateShuffleVector(V1C, V2C, MC), Name);
1548     return Insert(new ShuffleVectorInst(V1, V2, Mask), Name);
1549   }
1550
1551   Value *CreateShuffleVector(Value *V1, Value *V2, ArrayRef<int> IntMask,
1552                              const Twine &Name = "") {
1553     size_t MaskSize = IntMask.size();
1554     SmallVector<Constant*, 8> MaskVec(MaskSize);
1555     for (size_t i = 0; i != MaskSize; ++i)
1556       MaskVec[i] = getInt32(IntMask[i]);
1557     Value *Mask = ConstantVector::get(MaskVec);
1558     return CreateShuffleVector(V1, V2, Mask, Name);
1559   }
1560
1561   Value *CreateExtractValue(Value *Agg,
1562                             ArrayRef<unsigned> Idxs,
1563                             const Twine &Name = "") {
1564     if (Constant *AggC = dyn_cast<Constant>(Agg))
1565       return Insert(Folder.CreateExtractValue(AggC, Idxs), Name);
1566     return Insert(ExtractValueInst::Create(Agg, Idxs), Name);
1567   }
1568
1569   Value *CreateInsertValue(Value *Agg, Value *Val,
1570                            ArrayRef<unsigned> Idxs,
1571                            const Twine &Name = "") {
1572     if (Constant *AggC = dyn_cast<Constant>(Agg))
1573       if (Constant *ValC = dyn_cast<Constant>(Val))
1574         return Insert(Folder.CreateInsertValue(AggC, ValC, Idxs), Name);
1575     return Insert(InsertValueInst::Create(Agg, Val, Idxs), Name);
1576   }
1577
1578   LandingPadInst *CreateLandingPad(Type *Ty, Value *PersFn, unsigned NumClauses,
1579                                    const Twine &Name = "") {
1580     return Insert(LandingPadInst::Create(Ty, PersFn, NumClauses), Name);
1581   }
1582
1583   //===--------------------------------------------------------------------===//
1584   // Utility creation methods
1585   //===--------------------------------------------------------------------===//
1586
1587   /// \brief Return an i1 value testing if \p Arg is null.
1588   Value *CreateIsNull(Value *Arg, const Twine &Name = "") {
1589     return CreateICmpEQ(Arg, Constant::getNullValue(Arg->getType()),
1590                         Name);
1591   }
1592
1593   /// \brief Return an i1 value testing if \p Arg is not null.
1594   Value *CreateIsNotNull(Value *Arg, const Twine &Name = "") {
1595     return CreateICmpNE(Arg, Constant::getNullValue(Arg->getType()),
1596                         Name);
1597   }
1598
1599   /// \brief Return the i64 difference between two pointer values, dividing out
1600   /// the size of the pointed-to objects.
1601   ///
1602   /// This is intended to implement C-style pointer subtraction. As such, the
1603   /// pointers must be appropriately aligned for their element types and
1604   /// pointing into the same object.
1605   Value *CreatePtrDiff(Value *LHS, Value *RHS, const Twine &Name = "") {
1606     assert(LHS->getType() == RHS->getType() &&
1607            "Pointer subtraction operand types must match!");
1608     PointerType *ArgType = cast<PointerType>(LHS->getType());
1609     Value *LHS_int = CreatePtrToInt(LHS, Type::getInt64Ty(Context));
1610     Value *RHS_int = CreatePtrToInt(RHS, Type::getInt64Ty(Context));
1611     Value *Difference = CreateSub(LHS_int, RHS_int);
1612     return CreateExactSDiv(Difference,
1613                            ConstantExpr::getSizeOf(ArgType->getElementType()),
1614                            Name);
1615   }
1616
1617   /// \brief Return a vector value that contains \arg V broadcasted to \p
1618   /// NumElts elements.
1619   Value *CreateVectorSplat(unsigned NumElts, Value *V, const Twine &Name = "") {
1620     assert(NumElts > 0 && "Cannot splat to an empty vector!");
1621
1622     // First insert it into an undef vector so we can shuffle it.
1623     Type *I32Ty = getInt32Ty();
1624     Value *Undef = UndefValue::get(VectorType::get(V->getType(), NumElts));
1625     V = CreateInsertElement(Undef, V, ConstantInt::get(I32Ty, 0),
1626                             Name + ".splatinsert");
1627
1628     // Shuffle the value across the desired number of elements.
1629     Value *Zeros = ConstantAggregateZero::get(VectorType::get(I32Ty, NumElts));
1630     return CreateShuffleVector(V, Undef, Zeros, Name + ".splat");
1631   }
1632
1633   /// \brief Return a value that has been extracted from a larger integer type.
1634   Value *CreateExtractInteger(const DataLayout &DL, Value *From,
1635                               IntegerType *ExtractedTy, uint64_t Offset,
1636                               const Twine &Name) {
1637     IntegerType *IntTy = cast<IntegerType>(From->getType());
1638     assert(DL.getTypeStoreSize(ExtractedTy) + Offset <=
1639                DL.getTypeStoreSize(IntTy) &&
1640            "Element extends past full value");
1641     uint64_t ShAmt = 8 * Offset;
1642     Value *V = From;
1643     if (DL.isBigEndian())
1644       ShAmt = 8 * (DL.getTypeStoreSize(IntTy) -
1645                    DL.getTypeStoreSize(ExtractedTy) - Offset);
1646     if (ShAmt) {
1647       V = CreateLShr(V, ShAmt, Name + ".shift");
1648     }
1649     assert(ExtractedTy->getBitWidth() <= IntTy->getBitWidth() &&
1650            "Cannot extract to a larger integer!");
1651     if (ExtractedTy != IntTy) {
1652       V = CreateTrunc(V, ExtractedTy, Name + ".trunc");
1653     }
1654     return V;
1655   }
1656
1657   /// \brief Create an assume intrinsic call that represents an alignment
1658   /// assumption on the provided pointer.
1659   ///
1660   /// An optional offset can be provided, and if it is provided, the offset
1661   /// must be subtracted from the provided pointer to get the pointer with the
1662   /// specified alignment.
1663   CallInst *CreateAlignmentAssumption(const DataLayout &DL, Value *PtrValue,
1664                                       unsigned Alignment,
1665                                       Value *OffsetValue = nullptr) {
1666     assert(isa<PointerType>(PtrValue->getType()) &&
1667            "trying to create an alignment assumption on a non-pointer?");
1668
1669     PointerType *PtrTy = cast<PointerType>(PtrValue->getType());
1670     Type *IntPtrTy = getIntPtrTy(DL, PtrTy->getAddressSpace());
1671     Value *PtrIntValue = CreatePtrToInt(PtrValue, IntPtrTy, "ptrint");
1672
1673     Value *Mask = ConstantInt::get(IntPtrTy,
1674       Alignment > 0 ? Alignment - 1 : 0);
1675     if (OffsetValue) {
1676       bool IsOffsetZero = false;
1677       if (ConstantInt *CI = dyn_cast<ConstantInt>(OffsetValue))
1678         IsOffsetZero = CI->isZero();
1679
1680       if (!IsOffsetZero) {
1681         if (OffsetValue->getType() != IntPtrTy)
1682           OffsetValue = CreateIntCast(OffsetValue, IntPtrTy, /*isSigned*/ true,
1683                                       "offsetcast");
1684         PtrIntValue = CreateSub(PtrIntValue, OffsetValue, "offsetptr");
1685       }
1686     }
1687
1688     Value *Zero = ConstantInt::get(IntPtrTy, 0);
1689     Value *MaskedPtr = CreateAnd(PtrIntValue, Mask, "maskedptr");
1690     Value *InvCond = CreateICmpEQ(MaskedPtr, Zero, "maskcond");
1691
1692     return CreateAssumption(InvCond);
1693   }
1694 };
1695
1696 // Create wrappers for C Binding types (see CBindingWrapping.h).
1697 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(IRBuilder<>, LLVMBuilderRef)
1698
1699 }
1700
1701 #endif