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