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