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