Move the personality function from LandingPadInst to Function
[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(Type *Ty, Value *Ptr, const Twine &Name = "") {
997     return Insert(new LoadInst(Ty, Ptr), Name);
998   }
999   LoadInst *CreateLoad(Value *Ptr, bool isVolatile, const Twine &Name = "") {
1000     return Insert(new LoadInst(Ptr, nullptr, isVolatile), Name);
1001   }
1002   StoreInst *CreateStore(Value *Val, Value *Ptr, bool isVolatile = false) {
1003     return Insert(new StoreInst(Val, Ptr, isVolatile));
1004   }
1005   // \brief Provided to resolve 'CreateAlignedLoad(Ptr, Align, "...")'
1006   // correctly, instead of converting the string to 'bool' for the isVolatile
1007   // parameter.
1008   LoadInst *CreateAlignedLoad(Value *Ptr, unsigned Align, const char *Name) {
1009     LoadInst *LI = CreateLoad(Ptr, Name);
1010     LI->setAlignment(Align);
1011     return LI;
1012   }
1013   LoadInst *CreateAlignedLoad(Value *Ptr, unsigned Align,
1014                               const Twine &Name = "") {
1015     LoadInst *LI = CreateLoad(Ptr, Name);
1016     LI->setAlignment(Align);
1017     return LI;
1018   }
1019   LoadInst *CreateAlignedLoad(Value *Ptr, unsigned Align, bool isVolatile,
1020                               const Twine &Name = "") {
1021     LoadInst *LI = CreateLoad(Ptr, isVolatile, Name);
1022     LI->setAlignment(Align);
1023     return LI;
1024   }
1025   StoreInst *CreateAlignedStore(Value *Val, Value *Ptr, unsigned Align,
1026                                 bool isVolatile = false) {
1027     StoreInst *SI = CreateStore(Val, Ptr, isVolatile);
1028     SI->setAlignment(Align);
1029     return SI;
1030   }
1031   FenceInst *CreateFence(AtomicOrdering Ordering,
1032                          SynchronizationScope SynchScope = CrossThread,
1033                          const Twine &Name = "") {
1034     return Insert(new FenceInst(Context, Ordering, SynchScope), Name);
1035   }
1036   AtomicCmpXchgInst *
1037   CreateAtomicCmpXchg(Value *Ptr, Value *Cmp, Value *New,
1038                       AtomicOrdering SuccessOrdering,
1039                       AtomicOrdering FailureOrdering,
1040                       SynchronizationScope SynchScope = CrossThread) {
1041     return Insert(new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering,
1042                                         FailureOrdering, SynchScope));
1043   }
1044   AtomicRMWInst *CreateAtomicRMW(AtomicRMWInst::BinOp Op, Value *Ptr, Value *Val,
1045                                  AtomicOrdering Ordering,
1046                                SynchronizationScope SynchScope = CrossThread) {
1047     return Insert(new AtomicRMWInst(Op, Ptr, Val, Ordering, SynchScope));
1048   }
1049   Value *CreateGEP(Value *Ptr, ArrayRef<Value *> IdxList,
1050                    const Twine &Name = "") {
1051     return CreateGEP(nullptr, Ptr, IdxList, Name);
1052   }
1053   Value *CreateGEP(Type *Ty, Value *Ptr, ArrayRef<Value *> IdxList,
1054                    const Twine &Name = "") {
1055     if (Constant *PC = dyn_cast<Constant>(Ptr)) {
1056       // Every index must be constant.
1057       size_t i, e;
1058       for (i = 0, e = IdxList.size(); i != e; ++i)
1059         if (!isa<Constant>(IdxList[i]))
1060           break;
1061       if (i == e)
1062         return Insert(Folder.CreateGetElementPtr(Ty, PC, IdxList), Name);
1063     }
1064     return Insert(GetElementPtrInst::Create(Ty, Ptr, IdxList), Name);
1065   }
1066   Value *CreateInBoundsGEP(Value *Ptr, ArrayRef<Value *> IdxList,
1067                            const Twine &Name = "") {
1068     return CreateInBoundsGEP(nullptr, Ptr, IdxList, Name);
1069   }
1070   Value *CreateInBoundsGEP(Type *Ty, Value *Ptr, ArrayRef<Value *> IdxList,
1071                            const Twine &Name = "") {
1072     if (Constant *PC = dyn_cast<Constant>(Ptr)) {
1073       // Every index must be constant.
1074       size_t i, e;
1075       for (i = 0, e = IdxList.size(); i != e; ++i)
1076         if (!isa<Constant>(IdxList[i]))
1077           break;
1078       if (i == e)
1079         return Insert(Folder.CreateInBoundsGetElementPtr(Ty, PC, IdxList),
1080                       Name);
1081     }
1082     return Insert(GetElementPtrInst::CreateInBounds(Ty, Ptr, IdxList), Name);
1083   }
1084   Value *CreateGEP(Value *Ptr, Value *Idx, const Twine &Name = "") {
1085     return CreateGEP(nullptr, Ptr, Idx, Name);
1086   }
1087   Value *CreateGEP(Type *Ty, Value *Ptr, Value *Idx, const Twine &Name = "") {
1088     if (Constant *PC = dyn_cast<Constant>(Ptr))
1089       if (Constant *IC = dyn_cast<Constant>(Idx))
1090         return Insert(Folder.CreateGetElementPtr(Ty, PC, IC), Name);
1091     return Insert(GetElementPtrInst::Create(Ty, Ptr, Idx), Name);
1092   }
1093   Value *CreateInBoundsGEP(Type *Ty, Value *Ptr, Value *Idx,
1094                            const Twine &Name = "") {
1095     if (Constant *PC = dyn_cast<Constant>(Ptr))
1096       if (Constant *IC = dyn_cast<Constant>(Idx))
1097         return Insert(Folder.CreateInBoundsGetElementPtr(Ty, PC, IC), Name);
1098     return Insert(GetElementPtrInst::CreateInBounds(Ty, Ptr, Idx), Name);
1099   }
1100   Value *CreateConstGEP1_32(Value *Ptr, unsigned Idx0, const Twine &Name = "") {
1101     return CreateConstGEP1_32(nullptr, Ptr, Idx0, Name);
1102   }
1103   Value *CreateConstGEP1_32(Type *Ty, Value *Ptr, unsigned Idx0,
1104                             const Twine &Name = "") {
1105     Value *Idx = ConstantInt::get(Type::getInt32Ty(Context), Idx0);
1106
1107     if (Constant *PC = dyn_cast<Constant>(Ptr))
1108       return Insert(Folder.CreateGetElementPtr(Ty, PC, Idx), Name);
1109
1110     return Insert(GetElementPtrInst::Create(Ty, Ptr, Idx), Name);
1111   }
1112   Value *CreateConstInBoundsGEP1_32(Type *Ty, Value *Ptr, unsigned Idx0,
1113                                     const Twine &Name = "") {
1114     Value *Idx = ConstantInt::get(Type::getInt32Ty(Context), Idx0);
1115
1116     if (Constant *PC = dyn_cast<Constant>(Ptr))
1117       return Insert(Folder.CreateInBoundsGetElementPtr(Ty, PC, Idx), Name);
1118
1119     return Insert(GetElementPtrInst::CreateInBounds(Ty, Ptr, Idx), Name);
1120   }
1121   Value *CreateConstGEP2_32(Type *Ty, Value *Ptr, unsigned Idx0, unsigned Idx1,
1122                             const Twine &Name = "") {
1123     Value *Idxs[] = {
1124       ConstantInt::get(Type::getInt32Ty(Context), Idx0),
1125       ConstantInt::get(Type::getInt32Ty(Context), Idx1)
1126     };
1127
1128     if (Constant *PC = dyn_cast<Constant>(Ptr))
1129       return Insert(Folder.CreateGetElementPtr(Ty, PC, Idxs), Name);
1130
1131     return Insert(GetElementPtrInst::Create(Ty, Ptr, Idxs), Name);
1132   }
1133   Value *CreateConstInBoundsGEP2_32(Type *Ty, Value *Ptr, unsigned Idx0,
1134                                     unsigned Idx1, const Twine &Name = "") {
1135     Value *Idxs[] = {
1136       ConstantInt::get(Type::getInt32Ty(Context), Idx0),
1137       ConstantInt::get(Type::getInt32Ty(Context), Idx1)
1138     };
1139
1140     if (Constant *PC = dyn_cast<Constant>(Ptr))
1141       return Insert(Folder.CreateInBoundsGetElementPtr(Ty, PC, Idxs), Name);
1142
1143     return Insert(GetElementPtrInst::CreateInBounds(Ty, Ptr, Idxs), Name);
1144   }
1145   Value *CreateConstGEP1_64(Value *Ptr, uint64_t Idx0, const Twine &Name = "") {
1146     Value *Idx = ConstantInt::get(Type::getInt64Ty(Context), Idx0);
1147
1148     if (Constant *PC = dyn_cast<Constant>(Ptr))
1149       return Insert(Folder.CreateGetElementPtr(nullptr, PC, Idx), Name);
1150
1151     return Insert(GetElementPtrInst::Create(nullptr, Ptr, Idx), Name);
1152   }
1153   Value *CreateConstInBoundsGEP1_64(Value *Ptr, uint64_t Idx0,
1154                                     const Twine &Name = "") {
1155     Value *Idx = ConstantInt::get(Type::getInt64Ty(Context), Idx0);
1156
1157     if (Constant *PC = dyn_cast<Constant>(Ptr))
1158       return Insert(Folder.CreateInBoundsGetElementPtr(nullptr, PC, Idx), Name);
1159
1160     return Insert(GetElementPtrInst::CreateInBounds(nullptr, Ptr, Idx), Name);
1161   }
1162   Value *CreateConstGEP2_64(Value *Ptr, uint64_t Idx0, uint64_t Idx1,
1163                     const Twine &Name = "") {
1164     Value *Idxs[] = {
1165       ConstantInt::get(Type::getInt64Ty(Context), Idx0),
1166       ConstantInt::get(Type::getInt64Ty(Context), Idx1)
1167     };
1168
1169     if (Constant *PC = dyn_cast<Constant>(Ptr))
1170       return Insert(Folder.CreateGetElementPtr(nullptr, PC, Idxs), Name);
1171
1172     return Insert(GetElementPtrInst::Create(nullptr, Ptr, Idxs), Name);
1173   }
1174   Value *CreateConstInBoundsGEP2_64(Value *Ptr, uint64_t Idx0, uint64_t Idx1,
1175                                     const Twine &Name = "") {
1176     Value *Idxs[] = {
1177       ConstantInt::get(Type::getInt64Ty(Context), Idx0),
1178       ConstantInt::get(Type::getInt64Ty(Context), Idx1)
1179     };
1180
1181     if (Constant *PC = dyn_cast<Constant>(Ptr))
1182       return Insert(Folder.CreateInBoundsGetElementPtr(nullptr, PC, Idxs),
1183                     Name);
1184
1185     return Insert(GetElementPtrInst::CreateInBounds(nullptr, Ptr, Idxs), Name);
1186   }
1187   Value *CreateStructGEP(Type *Ty, Value *Ptr, unsigned Idx,
1188                          const Twine &Name = "") {
1189     return CreateConstInBoundsGEP2_32(Ty, Ptr, 0, Idx, Name);
1190   }
1191
1192   /// \brief Same as CreateGlobalString, but return a pointer with "i8*" type
1193   /// instead of a pointer to array of i8.
1194   Value *CreateGlobalStringPtr(StringRef Str, const Twine &Name = "") {
1195     GlobalVariable *gv = CreateGlobalString(Str, Name);
1196     Value *zero = ConstantInt::get(Type::getInt32Ty(Context), 0);
1197     Value *Args[] = { zero, zero };
1198     return CreateInBoundsGEP(gv->getValueType(), gv, Args, Name);
1199   }
1200
1201   //===--------------------------------------------------------------------===//
1202   // Instruction creation methods: Cast/Conversion Operators
1203   //===--------------------------------------------------------------------===//
1204
1205   Value *CreateTrunc(Value *V, Type *DestTy, const Twine &Name = "") {
1206     return CreateCast(Instruction::Trunc, V, DestTy, Name);
1207   }
1208   Value *CreateZExt(Value *V, Type *DestTy, const Twine &Name = "") {
1209     return CreateCast(Instruction::ZExt, V, DestTy, Name);
1210   }
1211   Value *CreateSExt(Value *V, Type *DestTy, const Twine &Name = "") {
1212     return CreateCast(Instruction::SExt, V, DestTy, Name);
1213   }
1214   /// \brief Create a ZExt or Trunc from the integer value V to DestTy. Return
1215   /// the value untouched if the type of V is already DestTy.
1216   Value *CreateZExtOrTrunc(Value *V, Type *DestTy,
1217                            const Twine &Name = "") {
1218     assert(V->getType()->isIntOrIntVectorTy() &&
1219            DestTy->isIntOrIntVectorTy() &&
1220            "Can only zero extend/truncate integers!");
1221     Type *VTy = V->getType();
1222     if (VTy->getScalarSizeInBits() < DestTy->getScalarSizeInBits())
1223       return CreateZExt(V, DestTy, Name);
1224     if (VTy->getScalarSizeInBits() > DestTy->getScalarSizeInBits())
1225       return CreateTrunc(V, DestTy, Name);
1226     return V;
1227   }
1228   /// \brief Create a SExt or Trunc from the integer value V to DestTy. Return
1229   /// the value untouched if the type of V is already DestTy.
1230   Value *CreateSExtOrTrunc(Value *V, Type *DestTy,
1231                            const Twine &Name = "") {
1232     assert(V->getType()->isIntOrIntVectorTy() &&
1233            DestTy->isIntOrIntVectorTy() &&
1234            "Can only sign extend/truncate integers!");
1235     Type *VTy = V->getType();
1236     if (VTy->getScalarSizeInBits() < DestTy->getScalarSizeInBits())
1237       return CreateSExt(V, DestTy, Name);
1238     if (VTy->getScalarSizeInBits() > DestTy->getScalarSizeInBits())
1239       return CreateTrunc(V, DestTy, Name);
1240     return V;
1241   }
1242   Value *CreateFPToUI(Value *V, Type *DestTy, const Twine &Name = ""){
1243     return CreateCast(Instruction::FPToUI, V, DestTy, Name);
1244   }
1245   Value *CreateFPToSI(Value *V, Type *DestTy, const Twine &Name = ""){
1246     return CreateCast(Instruction::FPToSI, V, DestTy, Name);
1247   }
1248   Value *CreateUIToFP(Value *V, Type *DestTy, const Twine &Name = ""){
1249     return CreateCast(Instruction::UIToFP, V, DestTy, Name);
1250   }
1251   Value *CreateSIToFP(Value *V, Type *DestTy, const Twine &Name = ""){
1252     return CreateCast(Instruction::SIToFP, V, DestTy, Name);
1253   }
1254   Value *CreateFPTrunc(Value *V, Type *DestTy,
1255                        const Twine &Name = "") {
1256     return CreateCast(Instruction::FPTrunc, V, DestTy, Name);
1257   }
1258   Value *CreateFPExt(Value *V, Type *DestTy, const Twine &Name = "") {
1259     return CreateCast(Instruction::FPExt, V, DestTy, Name);
1260   }
1261   Value *CreatePtrToInt(Value *V, Type *DestTy,
1262                         const Twine &Name = "") {
1263     return CreateCast(Instruction::PtrToInt, V, DestTy, Name);
1264   }
1265   Value *CreateIntToPtr(Value *V, Type *DestTy,
1266                         const Twine &Name = "") {
1267     return CreateCast(Instruction::IntToPtr, V, DestTy, Name);
1268   }
1269   Value *CreateBitCast(Value *V, Type *DestTy,
1270                        const Twine &Name = "") {
1271     return CreateCast(Instruction::BitCast, V, DestTy, Name);
1272   }
1273   Value *CreateAddrSpaceCast(Value *V, Type *DestTy,
1274                              const Twine &Name = "") {
1275     return CreateCast(Instruction::AddrSpaceCast, V, DestTy, Name);
1276   }
1277   Value *CreateZExtOrBitCast(Value *V, Type *DestTy,
1278                              const Twine &Name = "") {
1279     if (V->getType() == DestTy)
1280       return V;
1281     if (Constant *VC = dyn_cast<Constant>(V))
1282       return Insert(Folder.CreateZExtOrBitCast(VC, DestTy), Name);
1283     return Insert(CastInst::CreateZExtOrBitCast(V, DestTy), Name);
1284   }
1285   Value *CreateSExtOrBitCast(Value *V, Type *DestTy,
1286                              const Twine &Name = "") {
1287     if (V->getType() == DestTy)
1288       return V;
1289     if (Constant *VC = dyn_cast<Constant>(V))
1290       return Insert(Folder.CreateSExtOrBitCast(VC, DestTy), Name);
1291     return Insert(CastInst::CreateSExtOrBitCast(V, DestTy), Name);
1292   }
1293   Value *CreateTruncOrBitCast(Value *V, Type *DestTy,
1294                               const Twine &Name = "") {
1295     if (V->getType() == DestTy)
1296       return V;
1297     if (Constant *VC = dyn_cast<Constant>(V))
1298       return Insert(Folder.CreateTruncOrBitCast(VC, DestTy), Name);
1299     return Insert(CastInst::CreateTruncOrBitCast(V, DestTy), Name);
1300   }
1301   Value *CreateCast(Instruction::CastOps Op, Value *V, Type *DestTy,
1302                     const Twine &Name = "") {
1303     if (V->getType() == DestTy)
1304       return V;
1305     if (Constant *VC = dyn_cast<Constant>(V))
1306       return Insert(Folder.CreateCast(Op, VC, DestTy), Name);
1307     return Insert(CastInst::Create(Op, V, DestTy), Name);
1308   }
1309   Value *CreatePointerCast(Value *V, Type *DestTy,
1310                            const Twine &Name = "") {
1311     if (V->getType() == DestTy)
1312       return V;
1313     if (Constant *VC = dyn_cast<Constant>(V))
1314       return Insert(Folder.CreatePointerCast(VC, DestTy), Name);
1315     return Insert(CastInst::CreatePointerCast(V, DestTy), Name);
1316   }
1317
1318   Value *CreatePointerBitCastOrAddrSpaceCast(Value *V, Type *DestTy,
1319                                              const Twine &Name = "") {
1320     if (V->getType() == DestTy)
1321       return V;
1322
1323     if (Constant *VC = dyn_cast<Constant>(V)) {
1324       return Insert(Folder.CreatePointerBitCastOrAddrSpaceCast(VC, DestTy),
1325                     Name);
1326     }
1327
1328     return Insert(CastInst::CreatePointerBitCastOrAddrSpaceCast(V, DestTy),
1329                   Name);
1330   }
1331
1332   Value *CreateIntCast(Value *V, Type *DestTy, bool isSigned,
1333                        const Twine &Name = "") {
1334     if (V->getType() == DestTy)
1335       return V;
1336     if (Constant *VC = dyn_cast<Constant>(V))
1337       return Insert(Folder.CreateIntCast(VC, DestTy, isSigned), Name);
1338     return Insert(CastInst::CreateIntegerCast(V, DestTy, isSigned), Name);
1339   }
1340
1341   Value *CreateBitOrPointerCast(Value *V, Type *DestTy,
1342                                 const Twine &Name = "") {
1343     if (V->getType() == DestTy)
1344       return V;
1345     if (V->getType()->isPointerTy() && DestTy->isIntegerTy())
1346       return CreatePtrToInt(V, DestTy, Name);
1347     if (V->getType()->isIntegerTy() && DestTy->isPointerTy())
1348       return CreateIntToPtr(V, DestTy, Name);
1349
1350     return CreateBitCast(V, DestTy, Name);
1351   }
1352 private:
1353   // \brief Provided to resolve 'CreateIntCast(Ptr, Ptr, "...")', giving a
1354   // compile time error, instead of converting the string to bool for the
1355   // isSigned parameter.
1356   Value *CreateIntCast(Value *, Type *, const char *) = delete;
1357 public:
1358   Value *CreateFPCast(Value *V, Type *DestTy, const Twine &Name = "") {
1359     if (V->getType() == DestTy)
1360       return V;
1361     if (Constant *VC = dyn_cast<Constant>(V))
1362       return Insert(Folder.CreateFPCast(VC, DestTy), Name);
1363     return Insert(CastInst::CreateFPCast(V, DestTy), Name);
1364   }
1365
1366   //===--------------------------------------------------------------------===//
1367   // Instruction creation methods: Compare Instructions
1368   //===--------------------------------------------------------------------===//
1369
1370   Value *CreateICmpEQ(Value *LHS, Value *RHS, const Twine &Name = "") {
1371     return CreateICmp(ICmpInst::ICMP_EQ, LHS, RHS, Name);
1372   }
1373   Value *CreateICmpNE(Value *LHS, Value *RHS, const Twine &Name = "") {
1374     return CreateICmp(ICmpInst::ICMP_NE, LHS, RHS, Name);
1375   }
1376   Value *CreateICmpUGT(Value *LHS, Value *RHS, const Twine &Name = "") {
1377     return CreateICmp(ICmpInst::ICMP_UGT, LHS, RHS, Name);
1378   }
1379   Value *CreateICmpUGE(Value *LHS, Value *RHS, const Twine &Name = "") {
1380     return CreateICmp(ICmpInst::ICMP_UGE, LHS, RHS, Name);
1381   }
1382   Value *CreateICmpULT(Value *LHS, Value *RHS, const Twine &Name = "") {
1383     return CreateICmp(ICmpInst::ICMP_ULT, LHS, RHS, Name);
1384   }
1385   Value *CreateICmpULE(Value *LHS, Value *RHS, const Twine &Name = "") {
1386     return CreateICmp(ICmpInst::ICMP_ULE, LHS, RHS, Name);
1387   }
1388   Value *CreateICmpSGT(Value *LHS, Value *RHS, const Twine &Name = "") {
1389     return CreateICmp(ICmpInst::ICMP_SGT, LHS, RHS, Name);
1390   }
1391   Value *CreateICmpSGE(Value *LHS, Value *RHS, const Twine &Name = "") {
1392     return CreateICmp(ICmpInst::ICMP_SGE, LHS, RHS, Name);
1393   }
1394   Value *CreateICmpSLT(Value *LHS, Value *RHS, const Twine &Name = "") {
1395     return CreateICmp(ICmpInst::ICMP_SLT, LHS, RHS, Name);
1396   }
1397   Value *CreateICmpSLE(Value *LHS, Value *RHS, const Twine &Name = "") {
1398     return CreateICmp(ICmpInst::ICMP_SLE, LHS, RHS, Name);
1399   }
1400
1401   Value *CreateFCmpOEQ(Value *LHS, Value *RHS, const Twine &Name = "") {
1402     return CreateFCmp(FCmpInst::FCMP_OEQ, LHS, RHS, Name);
1403   }
1404   Value *CreateFCmpOGT(Value *LHS, Value *RHS, const Twine &Name = "") {
1405     return CreateFCmp(FCmpInst::FCMP_OGT, LHS, RHS, Name);
1406   }
1407   Value *CreateFCmpOGE(Value *LHS, Value *RHS, const Twine &Name = "") {
1408     return CreateFCmp(FCmpInst::FCMP_OGE, LHS, RHS, Name);
1409   }
1410   Value *CreateFCmpOLT(Value *LHS, Value *RHS, const Twine &Name = "") {
1411     return CreateFCmp(FCmpInst::FCMP_OLT, LHS, RHS, Name);
1412   }
1413   Value *CreateFCmpOLE(Value *LHS, Value *RHS, const Twine &Name = "") {
1414     return CreateFCmp(FCmpInst::FCMP_OLE, LHS, RHS, Name);
1415   }
1416   Value *CreateFCmpONE(Value *LHS, Value *RHS, const Twine &Name = "") {
1417     return CreateFCmp(FCmpInst::FCMP_ONE, LHS, RHS, Name);
1418   }
1419   Value *CreateFCmpORD(Value *LHS, Value *RHS, const Twine &Name = "") {
1420     return CreateFCmp(FCmpInst::FCMP_ORD, LHS, RHS, Name);
1421   }
1422   Value *CreateFCmpUNO(Value *LHS, Value *RHS, const Twine &Name = "") {
1423     return CreateFCmp(FCmpInst::FCMP_UNO, LHS, RHS, Name);
1424   }
1425   Value *CreateFCmpUEQ(Value *LHS, Value *RHS, const Twine &Name = "") {
1426     return CreateFCmp(FCmpInst::FCMP_UEQ, LHS, RHS, Name);
1427   }
1428   Value *CreateFCmpUGT(Value *LHS, Value *RHS, const Twine &Name = "") {
1429     return CreateFCmp(FCmpInst::FCMP_UGT, LHS, RHS, Name);
1430   }
1431   Value *CreateFCmpUGE(Value *LHS, Value *RHS, const Twine &Name = "") {
1432     return CreateFCmp(FCmpInst::FCMP_UGE, LHS, RHS, Name);
1433   }
1434   Value *CreateFCmpULT(Value *LHS, Value *RHS, const Twine &Name = "") {
1435     return CreateFCmp(FCmpInst::FCMP_ULT, LHS, RHS, Name);
1436   }
1437   Value *CreateFCmpULE(Value *LHS, Value *RHS, const Twine &Name = "") {
1438     return CreateFCmp(FCmpInst::FCMP_ULE, LHS, RHS, Name);
1439   }
1440   Value *CreateFCmpUNE(Value *LHS, Value *RHS, const Twine &Name = "") {
1441     return CreateFCmp(FCmpInst::FCMP_UNE, LHS, RHS, Name);
1442   }
1443
1444   Value *CreateICmp(CmpInst::Predicate P, Value *LHS, Value *RHS,
1445                     const Twine &Name = "") {
1446     if (Constant *LC = dyn_cast<Constant>(LHS))
1447       if (Constant *RC = dyn_cast<Constant>(RHS))
1448         return Insert(Folder.CreateICmp(P, LC, RC), Name);
1449     return Insert(new ICmpInst(P, LHS, RHS), Name);
1450   }
1451   Value *CreateFCmp(CmpInst::Predicate P, Value *LHS, Value *RHS,
1452                     const Twine &Name = "") {
1453     if (Constant *LC = dyn_cast<Constant>(LHS))
1454       if (Constant *RC = dyn_cast<Constant>(RHS))
1455         return Insert(Folder.CreateFCmp(P, LC, RC), Name);
1456     return Insert(new FCmpInst(P, LHS, RHS), Name);
1457   }
1458
1459   //===--------------------------------------------------------------------===//
1460   // Instruction creation methods: Other Instructions
1461   //===--------------------------------------------------------------------===//
1462
1463   PHINode *CreatePHI(Type *Ty, unsigned NumReservedValues,
1464                      const Twine &Name = "") {
1465     return Insert(PHINode::Create(Ty, NumReservedValues), Name);
1466   }
1467
1468   CallInst *CreateCall(Value *Callee, ArrayRef<Value *> Args,
1469                        const Twine &Name = "") {
1470     return Insert(CallInst::Create(Callee, Args), Name);
1471   }
1472
1473   CallInst *CreateCall(llvm::FunctionType *FTy, Value *Callee,
1474                        ArrayRef<Value *> Args, const Twine &Name = "") {
1475     return Insert(CallInst::Create(FTy, Callee, Args), Name);
1476   }
1477
1478   CallInst *CreateCall(Function *Callee, ArrayRef<Value *> Args,
1479                        const Twine &Name = "") {
1480     return CreateCall(Callee->getFunctionType(), Callee, Args, Name);
1481   }
1482
1483   Value *CreateSelect(Value *C, Value *True, Value *False,
1484                       const Twine &Name = "") {
1485     if (Constant *CC = dyn_cast<Constant>(C))
1486       if (Constant *TC = dyn_cast<Constant>(True))
1487         if (Constant *FC = dyn_cast<Constant>(False))
1488           return Insert(Folder.CreateSelect(CC, TC, FC), Name);
1489     return Insert(SelectInst::Create(C, True, False), Name);
1490   }
1491
1492   VAArgInst *CreateVAArg(Value *List, Type *Ty, const Twine &Name = "") {
1493     return Insert(new VAArgInst(List, Ty), Name);
1494   }
1495
1496   Value *CreateExtractElement(Value *Vec, Value *Idx,
1497                               const Twine &Name = "") {
1498     if (Constant *VC = dyn_cast<Constant>(Vec))
1499       if (Constant *IC = dyn_cast<Constant>(Idx))
1500         return Insert(Folder.CreateExtractElement(VC, IC), Name);
1501     return Insert(ExtractElementInst::Create(Vec, Idx), Name);
1502   }
1503
1504   Value *CreateExtractElement(Value *Vec, uint64_t Idx,
1505                               const Twine &Name = "") {
1506     return CreateExtractElement(Vec, getInt64(Idx), Name);
1507   }
1508
1509   Value *CreateInsertElement(Value *Vec, Value *NewElt, Value *Idx,
1510                              const Twine &Name = "") {
1511     if (Constant *VC = dyn_cast<Constant>(Vec))
1512       if (Constant *NC = dyn_cast<Constant>(NewElt))
1513         if (Constant *IC = dyn_cast<Constant>(Idx))
1514           return Insert(Folder.CreateInsertElement(VC, NC, IC), Name);
1515     return Insert(InsertElementInst::Create(Vec, NewElt, Idx), Name);
1516   }
1517
1518   Value *CreateInsertElement(Value *Vec, Value *NewElt, uint64_t Idx,
1519                              const Twine &Name = "") {
1520     return CreateInsertElement(Vec, NewElt, getInt64(Idx), Name);
1521   }
1522
1523   Value *CreateShuffleVector(Value *V1, Value *V2, Value *Mask,
1524                              const Twine &Name = "") {
1525     if (Constant *V1C = dyn_cast<Constant>(V1))
1526       if (Constant *V2C = dyn_cast<Constant>(V2))
1527         if (Constant *MC = dyn_cast<Constant>(Mask))
1528           return Insert(Folder.CreateShuffleVector(V1C, V2C, MC), Name);
1529     return Insert(new ShuffleVectorInst(V1, V2, Mask), Name);
1530   }
1531
1532   Value *CreateShuffleVector(Value *V1, Value *V2, ArrayRef<int> IntMask,
1533                              const Twine &Name = "") {
1534     size_t MaskSize = IntMask.size();
1535     SmallVector<Constant*, 8> MaskVec(MaskSize);
1536     for (size_t i = 0; i != MaskSize; ++i)
1537       MaskVec[i] = getInt32(IntMask[i]);
1538     Value *Mask = ConstantVector::get(MaskVec);
1539     return CreateShuffleVector(V1, V2, Mask, Name);
1540   }
1541
1542   Value *CreateExtractValue(Value *Agg,
1543                             ArrayRef<unsigned> Idxs,
1544                             const Twine &Name = "") {
1545     if (Constant *AggC = dyn_cast<Constant>(Agg))
1546       return Insert(Folder.CreateExtractValue(AggC, Idxs), Name);
1547     return Insert(ExtractValueInst::Create(Agg, Idxs), Name);
1548   }
1549
1550   Value *CreateInsertValue(Value *Agg, Value *Val,
1551                            ArrayRef<unsigned> Idxs,
1552                            const Twine &Name = "") {
1553     if (Constant *AggC = dyn_cast<Constant>(Agg))
1554       if (Constant *ValC = dyn_cast<Constant>(Val))
1555         return Insert(Folder.CreateInsertValue(AggC, ValC, Idxs), Name);
1556     return Insert(InsertValueInst::Create(Agg, Val, Idxs), Name);
1557   }
1558
1559   LandingPadInst *CreateLandingPad(Type *Ty, unsigned NumClauses,
1560                                    const Twine &Name = "") {
1561     return Insert(LandingPadInst::Create(Ty, NumClauses), Name);
1562   }
1563
1564   //===--------------------------------------------------------------------===//
1565   // Utility creation methods
1566   //===--------------------------------------------------------------------===//
1567
1568   /// \brief Return an i1 value testing if \p Arg is null.
1569   Value *CreateIsNull(Value *Arg, const Twine &Name = "") {
1570     return CreateICmpEQ(Arg, Constant::getNullValue(Arg->getType()),
1571                         Name);
1572   }
1573
1574   /// \brief Return an i1 value testing if \p Arg is not null.
1575   Value *CreateIsNotNull(Value *Arg, const Twine &Name = "") {
1576     return CreateICmpNE(Arg, Constant::getNullValue(Arg->getType()),
1577                         Name);
1578   }
1579
1580   /// \brief Return the i64 difference between two pointer values, dividing out
1581   /// the size of the pointed-to objects.
1582   ///
1583   /// This is intended to implement C-style pointer subtraction. As such, the
1584   /// pointers must be appropriately aligned for their element types and
1585   /// pointing into the same object.
1586   Value *CreatePtrDiff(Value *LHS, Value *RHS, const Twine &Name = "") {
1587     assert(LHS->getType() == RHS->getType() &&
1588            "Pointer subtraction operand types must match!");
1589     PointerType *ArgType = cast<PointerType>(LHS->getType());
1590     Value *LHS_int = CreatePtrToInt(LHS, Type::getInt64Ty(Context));
1591     Value *RHS_int = CreatePtrToInt(RHS, Type::getInt64Ty(Context));
1592     Value *Difference = CreateSub(LHS_int, RHS_int);
1593     return CreateExactSDiv(Difference,
1594                            ConstantExpr::getSizeOf(ArgType->getElementType()),
1595                            Name);
1596   }
1597
1598   /// \brief Return a vector value that contains \arg V broadcasted to \p
1599   /// NumElts elements.
1600   Value *CreateVectorSplat(unsigned NumElts, Value *V, const Twine &Name = "") {
1601     assert(NumElts > 0 && "Cannot splat to an empty vector!");
1602
1603     // First insert it into an undef vector so we can shuffle it.
1604     Type *I32Ty = getInt32Ty();
1605     Value *Undef = UndefValue::get(VectorType::get(V->getType(), NumElts));
1606     V = CreateInsertElement(Undef, V, ConstantInt::get(I32Ty, 0),
1607                             Name + ".splatinsert");
1608
1609     // Shuffle the value across the desired number of elements.
1610     Value *Zeros = ConstantAggregateZero::get(VectorType::get(I32Ty, NumElts));
1611     return CreateShuffleVector(V, Undef, Zeros, Name + ".splat");
1612   }
1613
1614   /// \brief Return a value that has been extracted from a larger integer type.
1615   Value *CreateExtractInteger(const DataLayout &DL, Value *From,
1616                               IntegerType *ExtractedTy, uint64_t Offset,
1617                               const Twine &Name) {
1618     IntegerType *IntTy = cast<IntegerType>(From->getType());
1619     assert(DL.getTypeStoreSize(ExtractedTy) + Offset <=
1620                DL.getTypeStoreSize(IntTy) &&
1621            "Element extends past full value");
1622     uint64_t ShAmt = 8 * Offset;
1623     Value *V = From;
1624     if (DL.isBigEndian())
1625       ShAmt = 8 * (DL.getTypeStoreSize(IntTy) -
1626                    DL.getTypeStoreSize(ExtractedTy) - Offset);
1627     if (ShAmt) {
1628       V = CreateLShr(V, ShAmt, Name + ".shift");
1629     }
1630     assert(ExtractedTy->getBitWidth() <= IntTy->getBitWidth() &&
1631            "Cannot extract to a larger integer!");
1632     if (ExtractedTy != IntTy) {
1633       V = CreateTrunc(V, ExtractedTy, Name + ".trunc");
1634     }
1635     return V;
1636   }
1637
1638   /// \brief Create an assume intrinsic call that represents an alignment
1639   /// assumption on the provided pointer.
1640   ///
1641   /// An optional offset can be provided, and if it is provided, the offset
1642   /// must be subtracted from the provided pointer to get the pointer with the
1643   /// specified alignment.
1644   CallInst *CreateAlignmentAssumption(const DataLayout &DL, Value *PtrValue,
1645                                       unsigned Alignment,
1646                                       Value *OffsetValue = nullptr) {
1647     assert(isa<PointerType>(PtrValue->getType()) &&
1648            "trying to create an alignment assumption on a non-pointer?");
1649
1650     PointerType *PtrTy = cast<PointerType>(PtrValue->getType());
1651     Type *IntPtrTy = getIntPtrTy(DL, PtrTy->getAddressSpace());
1652     Value *PtrIntValue = CreatePtrToInt(PtrValue, IntPtrTy, "ptrint");
1653
1654     Value *Mask = ConstantInt::get(IntPtrTy,
1655       Alignment > 0 ? Alignment - 1 : 0);
1656     if (OffsetValue) {
1657       bool IsOffsetZero = false;
1658       if (ConstantInt *CI = dyn_cast<ConstantInt>(OffsetValue))
1659         IsOffsetZero = CI->isZero();
1660
1661       if (!IsOffsetZero) {
1662         if (OffsetValue->getType() != IntPtrTy)
1663           OffsetValue = CreateIntCast(OffsetValue, IntPtrTy, /*isSigned*/ true,
1664                                       "offsetcast");
1665         PtrIntValue = CreateSub(PtrIntValue, OffsetValue, "offsetptr");
1666       }
1667     }
1668
1669     Value *Zero = ConstantInt::get(IntPtrTy, 0);
1670     Value *MaskedPtr = CreateAnd(PtrIntValue, Mask, "maskedptr");
1671     Value *InvCond = CreateICmpEQ(MaskedPtr, Zero, "maskcond");
1672
1673     return CreateAssumption(InvCond);
1674   }
1675 };
1676
1677 // Create wrappers for C Binding types (see CBindingWrapping.h).
1678 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(IRBuilder<>, LLVMBuilderRef)
1679
1680 }
1681
1682 #endif