1 //===---- llvm/IRBuilder.h - Builder for LLVM Instructions ------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
13 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_IR_IRBUILDER_H
16 #define LLVM_IR_IRBUILDER_H
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"
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.
37 /// By default, this inserts the instruction at the insertion point.
38 template <bool preserveNames = true>
39 class IRBuilderDefaultInserter {
41 void InsertHelper(Instruction *I, const Twine &Name,
42 BasicBlock *BB, BasicBlock::iterator InsertPt) const {
43 if (BB) BB->getInstList().insert(InsertPt, I);
49 /// \brief Common base class shared among various IRBuilders.
51 DebugLoc CurDbgLocation;
54 BasicBlock::iterator InsertPt;
57 MDNode *DefaultFPMathTag;
61 IRBuilderBase(LLVMContext &context, MDNode *FPMathTag = nullptr)
62 : Context(context), DefaultFPMathTag(FPMathTag), FMF() {
63 ClearInsertionPoint();
66 //===--------------------------------------------------------------------===//
67 // Builder configuration methods
68 //===--------------------------------------------------------------------===//
70 /// \brief Clear the insertion point: created instructions will not be
71 /// inserted into a block.
72 void ClearInsertionPoint() {
77 BasicBlock *GetInsertBlock() const { return BB; }
78 BasicBlock::iterator GetInsertPoint() const { return InsertPt; }
79 LLVMContext &getContext() const { return Context; }
81 /// \brief This specifies that created instructions should be appended to the
82 /// end of the specified block.
83 void SetInsertPoint(BasicBlock *TheBB) {
88 /// \brief This specifies that created instructions should be inserted before
89 /// the specified instruction.
90 void SetInsertPoint(Instruction *I) {
93 assert(I != BB->end() && "Can't read debug loc from end()");
94 SetCurrentDebugLocation(I->getDebugLoc());
97 /// \brief This specifies that created instructions should be inserted at the
99 void SetInsertPoint(BasicBlock *TheBB, BasicBlock::iterator IP) {
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());
114 SetInsertPoint(UseInst);
117 /// \brief Set location information used by debugging information.
118 void SetCurrentDebugLocation(DebugLoc L) { CurDbgLocation = std::move(L); }
120 /// \brief Get location information used by debugging information.
121 const DebugLoc &getCurrentDebugLocation() const { return CurDbgLocation; }
123 /// \brief If this builder has a current debug location, set it on the
124 /// specified instruction.
125 void SetInstDebugLocation(Instruction *I) const {
126 if (!CurDbgLocation.isUnknown())
127 I->setDebugLoc(CurDbgLocation);
130 /// \brief Get the return type of the current function that we're emitting
132 Type *getCurrentFunctionReturnType() const;
134 /// InsertPoint - A saved insertion point.
137 BasicBlock::iterator Point;
140 /// \brief Creates a new insertion point which doesn't point to anything.
141 InsertPoint() : Block(nullptr) {}
143 /// \brief Creates a new insertion point at the given location.
144 InsertPoint(BasicBlock *InsertBlock, BasicBlock::iterator InsertPoint)
145 : Block(InsertBlock), Point(InsertPoint) {}
147 /// \brief Returns true if this insert point is set.
148 bool isSet() const { return (Block != nullptr); }
150 llvm::BasicBlock *getBlock() const { return Block; }
151 llvm::BasicBlock::iterator getPoint() const { return Point; }
154 /// \brief Returns the current insert point.
155 InsertPoint saveIP() const {
156 return InsertPoint(GetInsertBlock(), GetInsertPoint());
159 /// \brief Returns the current insert point, clearing it in the process.
160 InsertPoint saveAndClearIP() {
161 InsertPoint IP(GetInsertBlock(), GetInsertPoint());
162 ClearInsertionPoint();
166 /// \brief Sets the current insert point to a previously-saved location.
167 void restoreIP(InsertPoint IP) {
169 SetInsertPoint(IP.getBlock(), IP.getPoint());
171 ClearInsertionPoint();
174 /// \brief Get the floating point math metadata being used.
175 MDNode *getDefaultFPMathTag() const { return DefaultFPMathTag; }
177 /// \brief Get the flags to be applied to created floating point ops
178 FastMathFlags getFastMathFlags() const { return FMF; }
180 /// \brief Clear the fast-math flags.
181 void clearFastMathFlags() { FMF.clear(); }
183 /// \brief Set the floating point math metadata to be used.
184 void SetDefaultFPMathTag(MDNode *FPMathTag) { DefaultFPMathTag = FPMathTag; }
186 /// \brief Set the fast-math flags to be used with generated fp-math operators
187 void SetFastMathFlags(FastMathFlags NewFMF) { FMF = NewFMF; }
189 //===--------------------------------------------------------------------===//
191 //===--------------------------------------------------------------------===//
193 // \brief RAII object that stores the current insertion point and restores it
194 // when the object is destroyed. This includes the debug location.
195 class InsertPointGuard {
196 IRBuilderBase &Builder;
197 AssertingVH<BasicBlock> Block;
198 BasicBlock::iterator Point;
201 InsertPointGuard(const InsertPointGuard &) = delete;
202 InsertPointGuard &operator=(const InsertPointGuard &) = delete;
205 InsertPointGuard(IRBuilderBase &B)
206 : Builder(B), Block(B.GetInsertBlock()), Point(B.GetInsertPoint()),
207 DbgLoc(B.getCurrentDebugLocation()) {}
209 ~InsertPointGuard() {
210 Builder.restoreIP(InsertPoint(Block, Point));
211 Builder.SetCurrentDebugLocation(DbgLoc);
215 // \brief RAII object that stores the current fast math settings and restores
216 // them when the object is destroyed.
217 class FastMathFlagGuard {
218 IRBuilderBase &Builder;
222 FastMathFlagGuard(const FastMathFlagGuard &) = delete;
223 FastMathFlagGuard &operator=(
224 const FastMathFlagGuard &) = delete;
227 FastMathFlagGuard(IRBuilderBase &B)
228 : Builder(B), FMF(B.FMF), FPMathTag(B.DefaultFPMathTag) {}
230 ~FastMathFlagGuard() {
232 Builder.DefaultFPMathTag = FPMathTag;
236 //===--------------------------------------------------------------------===//
237 // Miscellaneous creation methods.
238 //===--------------------------------------------------------------------===//
240 /// \brief Make a new global variable with initializer type i8*
242 /// Make a new global variable with an initializer that has array of i8 type
243 /// filled in with the null terminated string value specified. The new global
244 /// variable will be marked mergable with any others of the same contents. If
245 /// Name is specified, it is the name of the global variable created.
246 Value *CreateGlobalString(StringRef Str, const Twine &Name = "");
248 /// \brief Get a constant value representing either true or false.
249 ConstantInt *getInt1(bool V) {
250 return ConstantInt::get(getInt1Ty(), V);
253 /// \brief Get the constant value for i1 true.
254 ConstantInt *getTrue() {
255 return ConstantInt::getTrue(Context);
258 /// \brief Get the constant value for i1 false.
259 ConstantInt *getFalse() {
260 return ConstantInt::getFalse(Context);
263 /// \brief Get a constant 8-bit value.
264 ConstantInt *getInt8(uint8_t C) {
265 return ConstantInt::get(getInt8Ty(), C);
268 /// \brief Get a constant 16-bit value.
269 ConstantInt *getInt16(uint16_t C) {
270 return ConstantInt::get(getInt16Ty(), C);
273 /// \brief Get a constant 32-bit value.
274 ConstantInt *getInt32(uint32_t C) {
275 return ConstantInt::get(getInt32Ty(), C);
278 /// \brief Get a constant 64-bit value.
279 ConstantInt *getInt64(uint64_t C) {
280 return ConstantInt::get(getInt64Ty(), C);
283 /// \brief Get a constant N-bit value, zero extended or truncated from
285 ConstantInt *getIntN(unsigned N, uint64_t C) {
286 return ConstantInt::get(getIntNTy(N), C);
289 /// \brief Get a constant integer value.
290 ConstantInt *getInt(const APInt &AI) {
291 return ConstantInt::get(Context, AI);
294 //===--------------------------------------------------------------------===//
295 // Type creation methods
296 //===--------------------------------------------------------------------===//
298 /// \brief Fetch the type representing a single bit
299 IntegerType *getInt1Ty() {
300 return Type::getInt1Ty(Context);
303 /// \brief Fetch the type representing an 8-bit integer.
304 IntegerType *getInt8Ty() {
305 return Type::getInt8Ty(Context);
308 /// \brief Fetch the type representing a 16-bit integer.
309 IntegerType *getInt16Ty() {
310 return Type::getInt16Ty(Context);
313 /// \brief Fetch the type representing a 32-bit integer.
314 IntegerType *getInt32Ty() {
315 return Type::getInt32Ty(Context);
318 /// \brief Fetch the type representing a 64-bit integer.
319 IntegerType *getInt64Ty() {
320 return Type::getInt64Ty(Context);
323 /// \brief Fetch the type representing an N-bit integer.
324 IntegerType *getIntNTy(unsigned N) {
325 return Type::getIntNTy(Context, N);
328 /// \brief Fetch the type representing a 16-bit floating point value.
330 return Type::getHalfTy(Context);
333 /// \brief Fetch the type representing a 32-bit floating point value.
335 return Type::getFloatTy(Context);
338 /// \brief Fetch the type representing a 64-bit floating point value.
339 Type *getDoubleTy() {
340 return Type::getDoubleTy(Context);
343 /// \brief Fetch the type representing void.
345 return Type::getVoidTy(Context);
348 /// \brief Fetch the type representing a pointer to an 8-bit integer value.
349 PointerType *getInt8PtrTy(unsigned AddrSpace = 0) {
350 return Type::getInt8PtrTy(Context, AddrSpace);
353 /// \brief Fetch the type representing a pointer to an integer value.
354 IntegerType* getIntPtrTy(const DataLayout *DL, unsigned AddrSpace = 0) {
355 return DL->getIntPtrType(Context, AddrSpace);
358 //===--------------------------------------------------------------------===//
359 // Intrinsic creation methods
360 //===--------------------------------------------------------------------===//
362 /// \brief Create and insert a memset to the specified pointer and the
365 /// If the pointer isn't an i8*, it will be converted. If a TBAA tag is
366 /// specified, it will be added to the instruction. Likewise with alias.scope
367 /// and noalias tags.
368 CallInst *CreateMemSet(Value *Ptr, Value *Val, uint64_t Size, unsigned Align,
369 bool isVolatile = false, MDNode *TBAATag = nullptr,
370 MDNode *ScopeTag = nullptr,
371 MDNode *NoAliasTag = nullptr) {
372 return CreateMemSet(Ptr, Val, getInt64(Size), Align, isVolatile,
373 TBAATag, ScopeTag, NoAliasTag);
376 CallInst *CreateMemSet(Value *Ptr, Value *Val, Value *Size, unsigned Align,
377 bool isVolatile = false, MDNode *TBAATag = nullptr,
378 MDNode *ScopeTag = nullptr,
379 MDNode *NoAliasTag = nullptr);
381 /// \brief Create and insert a memcpy between the specified pointers.
383 /// If the pointers aren't i8*, they will be converted. If a TBAA tag is
384 /// specified, it will be added to the instruction. Likewise with alias.scope
385 /// and noalias tags.
386 CallInst *CreateMemCpy(Value *Dst, Value *Src, uint64_t Size, unsigned Align,
387 bool isVolatile = false, MDNode *TBAATag = nullptr,
388 MDNode *TBAAStructTag = nullptr,
389 MDNode *ScopeTag = nullptr,
390 MDNode *NoAliasTag = nullptr) {
391 return CreateMemCpy(Dst, Src, getInt64(Size), Align, isVolatile, TBAATag,
392 TBAAStructTag, ScopeTag, NoAliasTag);
395 CallInst *CreateMemCpy(Value *Dst, Value *Src, Value *Size, unsigned Align,
396 bool isVolatile = false, MDNode *TBAATag = nullptr,
397 MDNode *TBAAStructTag = nullptr,
398 MDNode *ScopeTag = nullptr,
399 MDNode *NoAliasTag = nullptr);
401 /// \brief Create and insert a memmove between the specified
404 /// If the pointers aren't i8*, they will be converted. If a TBAA tag is
405 /// specified, it will be added to the instruction. Likewise with alias.scope
406 /// and noalias tags.
407 CallInst *CreateMemMove(Value *Dst, Value *Src, uint64_t Size, unsigned Align,
408 bool isVolatile = false, MDNode *TBAATag = nullptr,
409 MDNode *ScopeTag = nullptr,
410 MDNode *NoAliasTag = nullptr) {
411 return CreateMemMove(Dst, Src, getInt64(Size), Align, isVolatile,
412 TBAATag, ScopeTag, NoAliasTag);
415 CallInst *CreateMemMove(Value *Dst, Value *Src, Value *Size, unsigned Align,
416 bool isVolatile = false, MDNode *TBAATag = nullptr,
417 MDNode *ScopeTag = nullptr,
418 MDNode *NoAliasTag = nullptr);
420 /// \brief Create a lifetime.start intrinsic.
422 /// If the pointer isn't i8* it will be converted.
423 CallInst *CreateLifetimeStart(Value *Ptr, ConstantInt *Size = nullptr);
425 /// \brief Create a lifetime.end intrinsic.
427 /// If the pointer isn't i8* it will be converted.
428 CallInst *CreateLifetimeEnd(Value *Ptr, ConstantInt *Size = nullptr);
430 /// \brief Create a call to Masked Load intrinsic
431 CallInst *CreateMaskedLoad(Value *Ptr, unsigned Align, Value *Mask,
432 Value *PassThru = 0, const Twine &Name = "");
434 /// \brief Create a call to Masked Store intrinsic
435 CallInst *CreateMaskedStore(Value *Val, Value *Ptr, unsigned Align,
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);
442 /// \brief Create a call to the experimental.gc.statepoint intrinsic to
443 /// start a new statepoint sequence.
444 CallInst *CreateGCStatepoint(Value *ActualCallee,
445 ArrayRef<Value *> CallArgs,
446 ArrayRef<Value *> DeoptArgs,
447 ArrayRef<Value *> GCArgs,
448 const Twine &Name = "");
450 /// \brief Create a call to the experimental.gc.result intrinsic to extract
451 /// the result from a call wrapped in a statepoint.
452 CallInst *CreateGCResult(Instruction *Statepoint,
454 const Twine &Name = "");
456 /// \brief Create a call to the experimental.gc.relocate intrinsics to
457 /// project the relocated value of one pointer from the statepoint.
458 CallInst *CreateGCRelocate(Instruction *Statepoint,
462 const Twine &Name = "");
465 /// \brief Create a call to a masked intrinsic with given Id.
466 /// Masked intrinsic has only one overloaded type - data type.
467 CallInst *CreateMaskedIntrinsic(unsigned Id, ArrayRef<Value *> Ops,
468 Type *DataTy, const Twine &Name = "");
470 Value *getCastedInt8PtrValue(Value *Ptr);
473 /// \brief This provides a uniform API for creating instructions and inserting
474 /// them into a basic block: either at the end of a BasicBlock, or at a specific
475 /// iterator location in a block.
477 /// Note that the builder does not expose the full generality of LLVM
478 /// instructions. For access to extra instruction properties, use the mutators
479 /// (e.g. setVolatile) on the instructions after they have been
480 /// created. Convenience state exists to specify fast-math flags and fp-math
483 /// The first template argument handles whether or not to preserve names in the
484 /// final instruction output. This defaults to on. The second template argument
485 /// specifies a class to use for creating constants. This defaults to creating
486 /// minimally folded constants. The third template argument allows clients to
487 /// specify custom insertion hooks that are called on every newly created
489 template<bool preserveNames = true, typename T = ConstantFolder,
490 typename Inserter = IRBuilderDefaultInserter<preserveNames> >
491 class IRBuilder : public IRBuilderBase, public Inserter {
494 IRBuilder(LLVMContext &C, const T &F, const Inserter &I = Inserter(),
495 MDNode *FPMathTag = nullptr)
496 : IRBuilderBase(C, FPMathTag), Inserter(I), Folder(F) {
499 explicit IRBuilder(LLVMContext &C, MDNode *FPMathTag = nullptr)
500 : IRBuilderBase(C, FPMathTag), Folder() {
503 explicit IRBuilder(BasicBlock *TheBB, const T &F, MDNode *FPMathTag = nullptr)
504 : IRBuilderBase(TheBB->getContext(), FPMathTag), Folder(F) {
505 SetInsertPoint(TheBB);
508 explicit IRBuilder(BasicBlock *TheBB, MDNode *FPMathTag = nullptr)
509 : IRBuilderBase(TheBB->getContext(), FPMathTag), Folder() {
510 SetInsertPoint(TheBB);
513 explicit IRBuilder(Instruction *IP, MDNode *FPMathTag = nullptr)
514 : IRBuilderBase(IP->getContext(), FPMathTag), Folder() {
516 SetCurrentDebugLocation(IP->getDebugLoc());
519 explicit IRBuilder(Use &U, MDNode *FPMathTag = nullptr)
520 : IRBuilderBase(U->getContext(), FPMathTag), Folder() {
522 SetCurrentDebugLocation(cast<Instruction>(U.getUser())->getDebugLoc());
525 IRBuilder(BasicBlock *TheBB, BasicBlock::iterator IP, const T& F,
526 MDNode *FPMathTag = nullptr)
527 : IRBuilderBase(TheBB->getContext(), FPMathTag), Folder(F) {
528 SetInsertPoint(TheBB, IP);
531 IRBuilder(BasicBlock *TheBB, BasicBlock::iterator IP,
532 MDNode *FPMathTag = nullptr)
533 : IRBuilderBase(TheBB->getContext(), FPMathTag), Folder() {
534 SetInsertPoint(TheBB, IP);
537 /// \brief Get the constant folder being used.
538 const T &getFolder() { return Folder; }
540 /// \brief Return true if this builder is configured to actually add the
541 /// requested names to IR created through it.
542 bool isNamePreserving() const { return preserveNames; }
544 /// \brief Insert and return the specified instruction.
545 template<typename InstTy>
546 InstTy *Insert(InstTy *I, const Twine &Name = "") const {
547 this->InsertHelper(I, Name, BB, InsertPt);
548 this->SetInstDebugLocation(I);
552 /// \brief No-op overload to handle constants.
553 Constant *Insert(Constant *C, const Twine& = "") const {
557 //===--------------------------------------------------------------------===//
558 // Instruction creation methods: Terminators
559 //===--------------------------------------------------------------------===//
562 /// \brief Helper to add branch weight metadata onto an instruction.
563 /// \returns The annotated instruction.
564 template <typename InstTy>
565 InstTy *addBranchWeights(InstTy *I, MDNode *Weights) {
567 I->setMetadata(LLVMContext::MD_prof, Weights);
572 /// \brief Create a 'ret void' instruction.
573 ReturnInst *CreateRetVoid() {
574 return Insert(ReturnInst::Create(Context));
577 /// \brief Create a 'ret <val>' instruction.
578 ReturnInst *CreateRet(Value *V) {
579 return Insert(ReturnInst::Create(Context, V));
582 /// \brief Create a sequence of N insertvalue instructions,
583 /// with one Value from the retVals array each, that build a aggregate
584 /// return value one value at a time, and a ret instruction to return
585 /// the resulting aggregate value.
587 /// This is a convenience function for code that uses aggregate return values
588 /// as a vehicle for having multiple return values.
589 ReturnInst *CreateAggregateRet(Value *const *retVals, unsigned N) {
590 Value *V = UndefValue::get(getCurrentFunctionReturnType());
591 for (unsigned i = 0; i != N; ++i)
592 V = CreateInsertValue(V, retVals[i], i, "mrv");
593 return Insert(ReturnInst::Create(Context, V));
596 /// \brief Create an unconditional 'br label X' instruction.
597 BranchInst *CreateBr(BasicBlock *Dest) {
598 return Insert(BranchInst::Create(Dest));
601 /// \brief Create a conditional 'br Cond, TrueDest, FalseDest'
603 BranchInst *CreateCondBr(Value *Cond, BasicBlock *True, BasicBlock *False,
604 MDNode *BranchWeights = nullptr) {
605 return Insert(addBranchWeights(BranchInst::Create(True, False, Cond),
609 /// \brief Create a switch instruction with the specified value, default dest,
610 /// and with a hint for the number of cases that will be added (for efficient
612 SwitchInst *CreateSwitch(Value *V, BasicBlock *Dest, unsigned NumCases = 10,
613 MDNode *BranchWeights = nullptr) {
614 return Insert(addBranchWeights(SwitchInst::Create(V, Dest, NumCases),
618 /// \brief Create an indirect branch instruction with the specified address
619 /// operand, with an optional hint for the number of destinations that will be
620 /// added (for efficient allocation).
621 IndirectBrInst *CreateIndirectBr(Value *Addr, unsigned NumDests = 10) {
622 return Insert(IndirectBrInst::Create(Addr, NumDests));
625 InvokeInst *CreateInvoke(Value *Callee, BasicBlock *NormalDest,
626 BasicBlock *UnwindDest, const Twine &Name = "") {
627 return Insert(InvokeInst::Create(Callee, NormalDest, UnwindDest, None),
630 InvokeInst *CreateInvoke(Value *Callee, BasicBlock *NormalDest,
631 BasicBlock *UnwindDest, Value *Arg1,
632 const Twine &Name = "") {
633 return Insert(InvokeInst::Create(Callee, NormalDest, UnwindDest, Arg1),
636 InvokeInst *CreateInvoke3(Value *Callee, BasicBlock *NormalDest,
637 BasicBlock *UnwindDest, Value *Arg1,
638 Value *Arg2, Value *Arg3,
639 const Twine &Name = "") {
640 Value *Args[] = { Arg1, Arg2, Arg3 };
641 return Insert(InvokeInst::Create(Callee, NormalDest, UnwindDest, Args),
644 /// \brief Create an invoke instruction.
645 InvokeInst *CreateInvoke(Value *Callee, BasicBlock *NormalDest,
646 BasicBlock *UnwindDest, ArrayRef<Value *> Args,
647 const Twine &Name = "") {
648 return Insert(InvokeInst::Create(Callee, NormalDest, UnwindDest, Args),
652 ResumeInst *CreateResume(Value *Exn) {
653 return Insert(ResumeInst::Create(Exn));
656 UnreachableInst *CreateUnreachable() {
657 return Insert(new UnreachableInst(Context));
660 //===--------------------------------------------------------------------===//
661 // Instruction creation methods: Binary Operators
662 //===--------------------------------------------------------------------===//
664 BinaryOperator *CreateInsertNUWNSWBinOp(BinaryOperator::BinaryOps Opc,
665 Value *LHS, Value *RHS,
667 bool HasNUW, bool HasNSW) {
668 BinaryOperator *BO = Insert(BinaryOperator::Create(Opc, LHS, RHS), Name);
669 if (HasNUW) BO->setHasNoUnsignedWrap();
670 if (HasNSW) BO->setHasNoSignedWrap();
674 Instruction *AddFPMathAttributes(Instruction *I,
676 FastMathFlags FMF) const {
678 FPMathTag = DefaultFPMathTag;
680 I->setMetadata(LLVMContext::MD_fpmath, FPMathTag);
681 I->setFastMathFlags(FMF);
685 Value *CreateAdd(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.CreateAdd(LC, RC, HasNUW, HasNSW), Name);
690 return CreateInsertNUWNSWBinOp(Instruction::Add, LHS, RHS, Name,
693 Value *CreateNSWAdd(Value *LHS, Value *RHS, const Twine &Name = "") {
694 return CreateAdd(LHS, RHS, Name, false, true);
696 Value *CreateNUWAdd(Value *LHS, Value *RHS, const Twine &Name = "") {
697 return CreateAdd(LHS, RHS, Name, true, false);
699 Value *CreateFAdd(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.CreateFAdd(LC, RC), Name);
704 return Insert(AddFPMathAttributes(BinaryOperator::CreateFAdd(LHS, RHS),
705 FPMathTag, FMF), Name);
707 Value *CreateSub(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.CreateSub(LC, RC, HasNUW, HasNSW), Name);
712 return CreateInsertNUWNSWBinOp(Instruction::Sub, LHS, RHS, Name,
715 Value *CreateNSWSub(Value *LHS, Value *RHS, const Twine &Name = "") {
716 return CreateSub(LHS, RHS, Name, false, true);
718 Value *CreateNUWSub(Value *LHS, Value *RHS, const Twine &Name = "") {
719 return CreateSub(LHS, RHS, Name, true, false);
721 Value *CreateFSub(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.CreateFSub(LC, RC), Name);
726 return Insert(AddFPMathAttributes(BinaryOperator::CreateFSub(LHS, RHS),
727 FPMathTag, FMF), Name);
729 Value *CreateMul(Value *LHS, Value *RHS, const Twine &Name = "",
730 bool HasNUW = false, bool HasNSW = false) {
731 if (Constant *LC = dyn_cast<Constant>(LHS))
732 if (Constant *RC = dyn_cast<Constant>(RHS))
733 return Insert(Folder.CreateMul(LC, RC, HasNUW, HasNSW), Name);
734 return CreateInsertNUWNSWBinOp(Instruction::Mul, LHS, RHS, Name,
737 Value *CreateNSWMul(Value *LHS, Value *RHS, const Twine &Name = "") {
738 return CreateMul(LHS, RHS, Name, false, true);
740 Value *CreateNUWMul(Value *LHS, Value *RHS, const Twine &Name = "") {
741 return CreateMul(LHS, RHS, Name, true, false);
743 Value *CreateFMul(Value *LHS, Value *RHS, const Twine &Name = "",
744 MDNode *FPMathTag = nullptr) {
745 if (Constant *LC = dyn_cast<Constant>(LHS))
746 if (Constant *RC = dyn_cast<Constant>(RHS))
747 return Insert(Folder.CreateFMul(LC, RC), Name);
748 return Insert(AddFPMathAttributes(BinaryOperator::CreateFMul(LHS, RHS),
749 FPMathTag, FMF), Name);
751 Value *CreateUDiv(Value *LHS, Value *RHS, const Twine &Name = "",
752 bool isExact = false) {
753 if (Constant *LC = dyn_cast<Constant>(LHS))
754 if (Constant *RC = dyn_cast<Constant>(RHS))
755 return Insert(Folder.CreateUDiv(LC, RC, isExact), Name);
757 return Insert(BinaryOperator::CreateUDiv(LHS, RHS), Name);
758 return Insert(BinaryOperator::CreateExactUDiv(LHS, RHS), Name);
760 Value *CreateExactUDiv(Value *LHS, Value *RHS, const Twine &Name = "") {
761 return CreateUDiv(LHS, RHS, Name, true);
763 Value *CreateSDiv(Value *LHS, Value *RHS, const Twine &Name = "",
764 bool isExact = false) {
765 if (Constant *LC = dyn_cast<Constant>(LHS))
766 if (Constant *RC = dyn_cast<Constant>(RHS))
767 return Insert(Folder.CreateSDiv(LC, RC, isExact), Name);
769 return Insert(BinaryOperator::CreateSDiv(LHS, RHS), Name);
770 return Insert(BinaryOperator::CreateExactSDiv(LHS, RHS), Name);
772 Value *CreateExactSDiv(Value *LHS, Value *RHS, const Twine &Name = "") {
773 return CreateSDiv(LHS, RHS, Name, true);
775 Value *CreateFDiv(Value *LHS, Value *RHS, const Twine &Name = "",
776 MDNode *FPMathTag = nullptr) {
777 if (Constant *LC = dyn_cast<Constant>(LHS))
778 if (Constant *RC = dyn_cast<Constant>(RHS))
779 return Insert(Folder.CreateFDiv(LC, RC), Name);
780 return Insert(AddFPMathAttributes(BinaryOperator::CreateFDiv(LHS, RHS),
781 FPMathTag, FMF), Name);
783 Value *CreateURem(Value *LHS, Value *RHS, const Twine &Name = "") {
784 if (Constant *LC = dyn_cast<Constant>(LHS))
785 if (Constant *RC = dyn_cast<Constant>(RHS))
786 return Insert(Folder.CreateURem(LC, RC), Name);
787 return Insert(BinaryOperator::CreateURem(LHS, RHS), Name);
789 Value *CreateSRem(Value *LHS, Value *RHS, const Twine &Name = "") {
790 if (Constant *LC = dyn_cast<Constant>(LHS))
791 if (Constant *RC = dyn_cast<Constant>(RHS))
792 return Insert(Folder.CreateSRem(LC, RC), Name);
793 return Insert(BinaryOperator::CreateSRem(LHS, RHS), Name);
795 Value *CreateFRem(Value *LHS, Value *RHS, const Twine &Name = "",
796 MDNode *FPMathTag = nullptr) {
797 if (Constant *LC = dyn_cast<Constant>(LHS))
798 if (Constant *RC = dyn_cast<Constant>(RHS))
799 return Insert(Folder.CreateFRem(LC, RC), Name);
800 return Insert(AddFPMathAttributes(BinaryOperator::CreateFRem(LHS, RHS),
801 FPMathTag, FMF), Name);
804 Value *CreateShl(Value *LHS, Value *RHS, const Twine &Name = "",
805 bool HasNUW = false, bool HasNSW = false) {
806 if (Constant *LC = dyn_cast<Constant>(LHS))
807 if (Constant *RC = dyn_cast<Constant>(RHS))
808 return Insert(Folder.CreateShl(LC, RC, HasNUW, HasNSW), Name);
809 return CreateInsertNUWNSWBinOp(Instruction::Shl, LHS, RHS, Name,
812 Value *CreateShl(Value *LHS, const APInt &RHS, const Twine &Name = "",
813 bool HasNUW = false, bool HasNSW = false) {
814 return CreateShl(LHS, ConstantInt::get(LHS->getType(), RHS), Name,
817 Value *CreateShl(Value *LHS, uint64_t RHS, const Twine &Name = "",
818 bool HasNUW = false, bool HasNSW = false) {
819 return CreateShl(LHS, ConstantInt::get(LHS->getType(), RHS), Name,
823 Value *CreateLShr(Value *LHS, Value *RHS, const Twine &Name = "",
824 bool isExact = false) {
825 if (Constant *LC = dyn_cast<Constant>(LHS))
826 if (Constant *RC = dyn_cast<Constant>(RHS))
827 return Insert(Folder.CreateLShr(LC, RC, isExact), Name);
829 return Insert(BinaryOperator::CreateLShr(LHS, RHS), Name);
830 return Insert(BinaryOperator::CreateExactLShr(LHS, RHS), Name);
832 Value *CreateLShr(Value *LHS, const APInt &RHS, const Twine &Name = "",
833 bool isExact = false) {
834 return CreateLShr(LHS, ConstantInt::get(LHS->getType(), RHS), Name,isExact);
836 Value *CreateLShr(Value *LHS, uint64_t RHS, const Twine &Name = "",
837 bool isExact = false) {
838 return CreateLShr(LHS, ConstantInt::get(LHS->getType(), RHS), Name,isExact);
841 Value *CreateAShr(Value *LHS, Value *RHS, const Twine &Name = "",
842 bool isExact = false) {
843 if (Constant *LC = dyn_cast<Constant>(LHS))
844 if (Constant *RC = dyn_cast<Constant>(RHS))
845 return Insert(Folder.CreateAShr(LC, RC, isExact), Name);
847 return Insert(BinaryOperator::CreateAShr(LHS, RHS), Name);
848 return Insert(BinaryOperator::CreateExactAShr(LHS, RHS), Name);
850 Value *CreateAShr(Value *LHS, const APInt &RHS, const Twine &Name = "",
851 bool isExact = false) {
852 return CreateAShr(LHS, ConstantInt::get(LHS->getType(), RHS), Name,isExact);
854 Value *CreateAShr(Value *LHS, uint64_t RHS, const Twine &Name = "",
855 bool isExact = false) {
856 return CreateAShr(LHS, ConstantInt::get(LHS->getType(), RHS), Name,isExact);
859 Value *CreateAnd(Value *LHS, Value *RHS, const Twine &Name = "") {
860 if (Constant *RC = dyn_cast<Constant>(RHS)) {
861 if (isa<ConstantInt>(RC) && cast<ConstantInt>(RC)->isAllOnesValue())
862 return LHS; // LHS & -1 -> LHS
863 if (Constant *LC = dyn_cast<Constant>(LHS))
864 return Insert(Folder.CreateAnd(LC, RC), Name);
866 return Insert(BinaryOperator::CreateAnd(LHS, RHS), Name);
868 Value *CreateAnd(Value *LHS, const APInt &RHS, const Twine &Name = "") {
869 return CreateAnd(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
871 Value *CreateAnd(Value *LHS, uint64_t RHS, const Twine &Name = "") {
872 return CreateAnd(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
875 Value *CreateOr(Value *LHS, Value *RHS, const Twine &Name = "") {
876 if (Constant *RC = dyn_cast<Constant>(RHS)) {
877 if (RC->isNullValue())
878 return LHS; // LHS | 0 -> LHS
879 if (Constant *LC = dyn_cast<Constant>(LHS))
880 return Insert(Folder.CreateOr(LC, RC), Name);
882 return Insert(BinaryOperator::CreateOr(LHS, RHS), Name);
884 Value *CreateOr(Value *LHS, const APInt &RHS, const Twine &Name = "") {
885 return CreateOr(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
887 Value *CreateOr(Value *LHS, uint64_t RHS, const Twine &Name = "") {
888 return CreateOr(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
891 Value *CreateXor(Value *LHS, Value *RHS, const Twine &Name = "") {
892 if (Constant *LC = dyn_cast<Constant>(LHS))
893 if (Constant *RC = dyn_cast<Constant>(RHS))
894 return Insert(Folder.CreateXor(LC, RC), Name);
895 return Insert(BinaryOperator::CreateXor(LHS, RHS), Name);
897 Value *CreateXor(Value *LHS, const APInt &RHS, const Twine &Name = "") {
898 return CreateXor(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
900 Value *CreateXor(Value *LHS, uint64_t RHS, const Twine &Name = "") {
901 return CreateXor(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
904 Value *CreateBinOp(Instruction::BinaryOps Opc,
905 Value *LHS, Value *RHS, const Twine &Name = "",
906 MDNode *FPMathTag = nullptr) {
907 if (Constant *LC = dyn_cast<Constant>(LHS))
908 if (Constant *RC = dyn_cast<Constant>(RHS))
909 return Insert(Folder.CreateBinOp(Opc, LC, RC), Name);
910 llvm::Instruction *BinOp = BinaryOperator::Create(Opc, LHS, RHS);
911 if (isa<FPMathOperator>(BinOp))
912 BinOp = AddFPMathAttributes(BinOp, FPMathTag, FMF);
913 return Insert(BinOp, Name);
916 Value *CreateNeg(Value *V, const Twine &Name = "",
917 bool HasNUW = false, bool HasNSW = false) {
918 if (Constant *VC = dyn_cast<Constant>(V))
919 return Insert(Folder.CreateNeg(VC, HasNUW, HasNSW), Name);
920 BinaryOperator *BO = Insert(BinaryOperator::CreateNeg(V), Name);
921 if (HasNUW) BO->setHasNoUnsignedWrap();
922 if (HasNSW) BO->setHasNoSignedWrap();
925 Value *CreateNSWNeg(Value *V, const Twine &Name = "") {
926 return CreateNeg(V, Name, false, true);
928 Value *CreateNUWNeg(Value *V, const Twine &Name = "") {
929 return CreateNeg(V, Name, true, false);
931 Value *CreateFNeg(Value *V, const Twine &Name = "",
932 MDNode *FPMathTag = nullptr) {
933 if (Constant *VC = dyn_cast<Constant>(V))
934 return Insert(Folder.CreateFNeg(VC), Name);
935 return Insert(AddFPMathAttributes(BinaryOperator::CreateFNeg(V),
936 FPMathTag, FMF), Name);
938 Value *CreateNot(Value *V, const Twine &Name = "") {
939 if (Constant *VC = dyn_cast<Constant>(V))
940 return Insert(Folder.CreateNot(VC), Name);
941 return Insert(BinaryOperator::CreateNot(V), Name);
944 //===--------------------------------------------------------------------===//
945 // Instruction creation methods: Memory Instructions
946 //===--------------------------------------------------------------------===//
948 AllocaInst *CreateAlloca(Type *Ty, Value *ArraySize = nullptr,
949 const Twine &Name = "") {
950 return Insert(new AllocaInst(Ty, ArraySize), Name);
952 // \brief Provided to resolve 'CreateLoad(Ptr, "...")' correctly, instead of
953 // converting the string to 'bool' for the isVolatile parameter.
954 LoadInst *CreateLoad(Value *Ptr, const char *Name) {
955 return Insert(new LoadInst(Ptr), Name);
957 LoadInst *CreateLoad(Value *Ptr, const Twine &Name = "") {
958 return Insert(new LoadInst(Ptr), Name);
960 LoadInst *CreateLoad(Value *Ptr, bool isVolatile, const Twine &Name = "") {
961 return Insert(new LoadInst(Ptr, nullptr, isVolatile), Name);
963 StoreInst *CreateStore(Value *Val, Value *Ptr, bool isVolatile = false) {
964 return Insert(new StoreInst(Val, Ptr, isVolatile));
966 // \brief Provided to resolve 'CreateAlignedLoad(Ptr, Align, "...")'
967 // correctly, instead of converting the string to 'bool' for the isVolatile
969 LoadInst *CreateAlignedLoad(Value *Ptr, unsigned Align, const char *Name) {
970 LoadInst *LI = CreateLoad(Ptr, Name);
971 LI->setAlignment(Align);
974 LoadInst *CreateAlignedLoad(Value *Ptr, unsigned Align,
975 const Twine &Name = "") {
976 LoadInst *LI = CreateLoad(Ptr, Name);
977 LI->setAlignment(Align);
980 LoadInst *CreateAlignedLoad(Value *Ptr, unsigned Align, bool isVolatile,
981 const Twine &Name = "") {
982 LoadInst *LI = CreateLoad(Ptr, isVolatile, Name);
983 LI->setAlignment(Align);
986 StoreInst *CreateAlignedStore(Value *Val, Value *Ptr, unsigned Align,
987 bool isVolatile = false) {
988 StoreInst *SI = CreateStore(Val, Ptr, isVolatile);
989 SI->setAlignment(Align);
992 FenceInst *CreateFence(AtomicOrdering Ordering,
993 SynchronizationScope SynchScope = CrossThread,
994 const Twine &Name = "") {
995 return Insert(new FenceInst(Context, Ordering, SynchScope), Name);
998 CreateAtomicCmpXchg(Value *Ptr, Value *Cmp, Value *New,
999 AtomicOrdering SuccessOrdering,
1000 AtomicOrdering FailureOrdering,
1001 SynchronizationScope SynchScope = CrossThread) {
1002 return Insert(new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering,
1003 FailureOrdering, SynchScope));
1005 AtomicRMWInst *CreateAtomicRMW(AtomicRMWInst::BinOp Op, Value *Ptr, Value *Val,
1006 AtomicOrdering Ordering,
1007 SynchronizationScope SynchScope = CrossThread) {
1008 return Insert(new AtomicRMWInst(Op, Ptr, Val, Ordering, SynchScope));
1010 Value *CreateGEP(Value *Ptr, ArrayRef<Value *> IdxList,
1011 const Twine &Name = "") {
1012 if (Constant *PC = dyn_cast<Constant>(Ptr)) {
1013 // Every index must be constant.
1015 for (i = 0, e = IdxList.size(); i != e; ++i)
1016 if (!isa<Constant>(IdxList[i]))
1019 return Insert(Folder.CreateGetElementPtr(PC, IdxList), Name);
1021 return Insert(GetElementPtrInst::Create(Ptr, IdxList), Name);
1023 Value *CreateInBoundsGEP(Value *Ptr, ArrayRef<Value *> IdxList,
1024 const Twine &Name = "") {
1025 if (Constant *PC = dyn_cast<Constant>(Ptr)) {
1026 // Every index must be constant.
1028 for (i = 0, e = IdxList.size(); i != e; ++i)
1029 if (!isa<Constant>(IdxList[i]))
1032 return Insert(Folder.CreateInBoundsGetElementPtr(PC, IdxList), Name);
1034 return Insert(GetElementPtrInst::CreateInBounds(Ptr, IdxList), Name);
1036 Value *CreateGEP(Value *Ptr, Value *Idx, const Twine &Name = "") {
1037 if (Constant *PC = dyn_cast<Constant>(Ptr))
1038 if (Constant *IC = dyn_cast<Constant>(Idx))
1039 return Insert(Folder.CreateGetElementPtr(PC, IC), Name);
1040 return Insert(GetElementPtrInst::Create(Ptr, Idx), Name);
1042 Value *CreateInBoundsGEP(Value *Ptr, Value *Idx, const Twine &Name = "") {
1043 if (Constant *PC = dyn_cast<Constant>(Ptr))
1044 if (Constant *IC = dyn_cast<Constant>(Idx))
1045 return Insert(Folder.CreateInBoundsGetElementPtr(PC, IC), Name);
1046 return Insert(GetElementPtrInst::CreateInBounds(Ptr, Idx), Name);
1048 Value *CreateConstGEP1_32(Value *Ptr, unsigned Idx0, const Twine &Name = "") {
1049 Value *Idx = ConstantInt::get(Type::getInt32Ty(Context), Idx0);
1051 if (Constant *PC = dyn_cast<Constant>(Ptr))
1052 return Insert(Folder.CreateGetElementPtr(PC, Idx), Name);
1054 return Insert(GetElementPtrInst::Create(Ptr, Idx), Name);
1056 Value *CreateConstInBoundsGEP1_32(Value *Ptr, unsigned Idx0,
1057 const Twine &Name = "") {
1058 Value *Idx = ConstantInt::get(Type::getInt32Ty(Context), Idx0);
1060 if (Constant *PC = dyn_cast<Constant>(Ptr))
1061 return Insert(Folder.CreateInBoundsGetElementPtr(PC, Idx), Name);
1063 return Insert(GetElementPtrInst::CreateInBounds(Ptr, Idx), Name);
1065 Value *CreateConstGEP2_32(Value *Ptr, unsigned Idx0, unsigned Idx1,
1066 const Twine &Name = "") {
1068 ConstantInt::get(Type::getInt32Ty(Context), Idx0),
1069 ConstantInt::get(Type::getInt32Ty(Context), Idx1)
1072 if (Constant *PC = dyn_cast<Constant>(Ptr))
1073 return Insert(Folder.CreateGetElementPtr(PC, Idxs), Name);
1075 return Insert(GetElementPtrInst::Create(Ptr, Idxs), Name);
1077 Value *CreateConstInBoundsGEP2_32(Value *Ptr, unsigned Idx0, unsigned Idx1,
1078 const Twine &Name = "") {
1080 ConstantInt::get(Type::getInt32Ty(Context), Idx0),
1081 ConstantInt::get(Type::getInt32Ty(Context), Idx1)
1084 if (Constant *PC = dyn_cast<Constant>(Ptr))
1085 return Insert(Folder.CreateInBoundsGetElementPtr(PC, Idxs), Name);
1087 return Insert(GetElementPtrInst::CreateInBounds(Ptr, Idxs), Name);
1089 Value *CreateConstGEP1_64(Value *Ptr, uint64_t Idx0, const Twine &Name = "") {
1090 Value *Idx = ConstantInt::get(Type::getInt64Ty(Context), Idx0);
1092 if (Constant *PC = dyn_cast<Constant>(Ptr))
1093 return Insert(Folder.CreateGetElementPtr(PC, Idx), Name);
1095 return Insert(GetElementPtrInst::Create(Ptr, Idx), Name);
1097 Value *CreateConstInBoundsGEP1_64(Value *Ptr, uint64_t Idx0,
1098 const Twine &Name = "") {
1099 Value *Idx = ConstantInt::get(Type::getInt64Ty(Context), Idx0);
1101 if (Constant *PC = dyn_cast<Constant>(Ptr))
1102 return Insert(Folder.CreateInBoundsGetElementPtr(PC, Idx), Name);
1104 return Insert(GetElementPtrInst::CreateInBounds(Ptr, Idx), Name);
1106 Value *CreateConstGEP2_64(Value *Ptr, uint64_t Idx0, uint64_t Idx1,
1107 const Twine &Name = "") {
1109 ConstantInt::get(Type::getInt64Ty(Context), Idx0),
1110 ConstantInt::get(Type::getInt64Ty(Context), Idx1)
1113 if (Constant *PC = dyn_cast<Constant>(Ptr))
1114 return Insert(Folder.CreateGetElementPtr(PC, Idxs), Name);
1116 return Insert(GetElementPtrInst::Create(Ptr, Idxs), Name);
1118 Value *CreateConstInBoundsGEP2_64(Value *Ptr, uint64_t Idx0, uint64_t Idx1,
1119 const Twine &Name = "") {
1121 ConstantInt::get(Type::getInt64Ty(Context), Idx0),
1122 ConstantInt::get(Type::getInt64Ty(Context), Idx1)
1125 if (Constant *PC = dyn_cast<Constant>(Ptr))
1126 return Insert(Folder.CreateInBoundsGetElementPtr(PC, Idxs), Name);
1128 return Insert(GetElementPtrInst::CreateInBounds(Ptr, Idxs), Name);
1130 Value *CreateStructGEP(Value *Ptr, unsigned Idx, const Twine &Name = "") {
1131 return CreateConstInBoundsGEP2_32(Ptr, 0, Idx, Name);
1134 /// \brief Same as CreateGlobalString, but return a pointer with "i8*" type
1135 /// instead of a pointer to array of i8.
1136 Value *CreateGlobalStringPtr(StringRef Str, const Twine &Name = "") {
1137 Value *gv = CreateGlobalString(Str, Name);
1138 Value *zero = ConstantInt::get(Type::getInt32Ty(Context), 0);
1139 Value *Args[] = { zero, zero };
1140 return CreateInBoundsGEP(gv, Args, Name);
1143 //===--------------------------------------------------------------------===//
1144 // Instruction creation methods: Cast/Conversion Operators
1145 //===--------------------------------------------------------------------===//
1147 Value *CreateTrunc(Value *V, Type *DestTy, const Twine &Name = "") {
1148 return CreateCast(Instruction::Trunc, V, DestTy, Name);
1150 Value *CreateZExt(Value *V, Type *DestTy, const Twine &Name = "") {
1151 return CreateCast(Instruction::ZExt, V, DestTy, Name);
1153 Value *CreateSExt(Value *V, Type *DestTy, const Twine &Name = "") {
1154 return CreateCast(Instruction::SExt, V, DestTy, Name);
1156 /// \brief Create a ZExt or Trunc from the integer value V to DestTy. Return
1157 /// the value untouched if the type of V is already DestTy.
1158 Value *CreateZExtOrTrunc(Value *V, Type *DestTy,
1159 const Twine &Name = "") {
1160 assert(V->getType()->isIntOrIntVectorTy() &&
1161 DestTy->isIntOrIntVectorTy() &&
1162 "Can only zero extend/truncate integers!");
1163 Type *VTy = V->getType();
1164 if (VTy->getScalarSizeInBits() < DestTy->getScalarSizeInBits())
1165 return CreateZExt(V, DestTy, Name);
1166 if (VTy->getScalarSizeInBits() > DestTy->getScalarSizeInBits())
1167 return CreateTrunc(V, DestTy, Name);
1170 /// \brief Create a SExt or Trunc from the integer value V to DestTy. Return
1171 /// the value untouched if the type of V is already DestTy.
1172 Value *CreateSExtOrTrunc(Value *V, Type *DestTy,
1173 const Twine &Name = "") {
1174 assert(V->getType()->isIntOrIntVectorTy() &&
1175 DestTy->isIntOrIntVectorTy() &&
1176 "Can only sign extend/truncate integers!");
1177 Type *VTy = V->getType();
1178 if (VTy->getScalarSizeInBits() < DestTy->getScalarSizeInBits())
1179 return CreateSExt(V, DestTy, Name);
1180 if (VTy->getScalarSizeInBits() > DestTy->getScalarSizeInBits())
1181 return CreateTrunc(V, DestTy, Name);
1184 Value *CreateFPToUI(Value *V, Type *DestTy, const Twine &Name = ""){
1185 return CreateCast(Instruction::FPToUI, V, DestTy, Name);
1187 Value *CreateFPToSI(Value *V, Type *DestTy, const Twine &Name = ""){
1188 return CreateCast(Instruction::FPToSI, V, DestTy, Name);
1190 Value *CreateUIToFP(Value *V, Type *DestTy, const Twine &Name = ""){
1191 return CreateCast(Instruction::UIToFP, V, DestTy, Name);
1193 Value *CreateSIToFP(Value *V, Type *DestTy, const Twine &Name = ""){
1194 return CreateCast(Instruction::SIToFP, V, DestTy, Name);
1196 Value *CreateFPTrunc(Value *V, Type *DestTy,
1197 const Twine &Name = "") {
1198 return CreateCast(Instruction::FPTrunc, V, DestTy, Name);
1200 Value *CreateFPExt(Value *V, Type *DestTy, const Twine &Name = "") {
1201 return CreateCast(Instruction::FPExt, V, DestTy, Name);
1203 Value *CreatePtrToInt(Value *V, Type *DestTy,
1204 const Twine &Name = "") {
1205 return CreateCast(Instruction::PtrToInt, V, DestTy, Name);
1207 Value *CreateIntToPtr(Value *V, Type *DestTy,
1208 const Twine &Name = "") {
1209 return CreateCast(Instruction::IntToPtr, V, DestTy, Name);
1211 Value *CreateBitCast(Value *V, Type *DestTy,
1212 const Twine &Name = "") {
1213 return CreateCast(Instruction::BitCast, V, DestTy, Name);
1215 Value *CreateAddrSpaceCast(Value *V, Type *DestTy,
1216 const Twine &Name = "") {
1217 return CreateCast(Instruction::AddrSpaceCast, V, DestTy, Name);
1219 Value *CreateZExtOrBitCast(Value *V, Type *DestTy,
1220 const Twine &Name = "") {
1221 if (V->getType() == DestTy)
1223 if (Constant *VC = dyn_cast<Constant>(V))
1224 return Insert(Folder.CreateZExtOrBitCast(VC, DestTy), Name);
1225 return Insert(CastInst::CreateZExtOrBitCast(V, DestTy), Name);
1227 Value *CreateSExtOrBitCast(Value *V, Type *DestTy,
1228 const Twine &Name = "") {
1229 if (V->getType() == DestTy)
1231 if (Constant *VC = dyn_cast<Constant>(V))
1232 return Insert(Folder.CreateSExtOrBitCast(VC, DestTy), Name);
1233 return Insert(CastInst::CreateSExtOrBitCast(V, DestTy), Name);
1235 Value *CreateTruncOrBitCast(Value *V, Type *DestTy,
1236 const Twine &Name = "") {
1237 if (V->getType() == DestTy)
1239 if (Constant *VC = dyn_cast<Constant>(V))
1240 return Insert(Folder.CreateTruncOrBitCast(VC, DestTy), Name);
1241 return Insert(CastInst::CreateTruncOrBitCast(V, DestTy), Name);
1243 Value *CreateCast(Instruction::CastOps Op, Value *V, Type *DestTy,
1244 const Twine &Name = "") {
1245 if (V->getType() == DestTy)
1247 if (Constant *VC = dyn_cast<Constant>(V))
1248 return Insert(Folder.CreateCast(Op, VC, DestTy), Name);
1249 return Insert(CastInst::Create(Op, V, DestTy), Name);
1251 Value *CreatePointerCast(Value *V, Type *DestTy,
1252 const Twine &Name = "") {
1253 if (V->getType() == DestTy)
1255 if (Constant *VC = dyn_cast<Constant>(V))
1256 return Insert(Folder.CreatePointerCast(VC, DestTy), Name);
1257 return Insert(CastInst::CreatePointerCast(V, DestTy), Name);
1260 Value *CreatePointerBitCastOrAddrSpaceCast(Value *V, Type *DestTy,
1261 const Twine &Name = "") {
1262 if (V->getType() == DestTy)
1265 if (Constant *VC = dyn_cast<Constant>(V)) {
1266 return Insert(Folder.CreatePointerBitCastOrAddrSpaceCast(VC, DestTy),
1270 return Insert(CastInst::CreatePointerBitCastOrAddrSpaceCast(V, DestTy),
1274 Value *CreateIntCast(Value *V, Type *DestTy, bool isSigned,
1275 const Twine &Name = "") {
1276 if (V->getType() == DestTy)
1278 if (Constant *VC = dyn_cast<Constant>(V))
1279 return Insert(Folder.CreateIntCast(VC, DestTy, isSigned), Name);
1280 return Insert(CastInst::CreateIntegerCast(V, DestTy, isSigned), Name);
1283 Value *CreateBitOrPointerCast(Value *V, Type *DestTy,
1284 const Twine &Name = "") {
1285 if (V->getType() == DestTy)
1287 if (V->getType()->isPointerTy() && DestTy->isIntegerTy())
1288 return CreatePtrToInt(V, DestTy, Name);
1289 if (V->getType()->isIntegerTy() && DestTy->isPointerTy())
1290 return CreateIntToPtr(V, DestTy, Name);
1292 return CreateBitCast(V, DestTy, Name);
1295 // \brief Provided to resolve 'CreateIntCast(Ptr, Ptr, "...")', giving a
1296 // compile time error, instead of converting the string to bool for the
1297 // isSigned parameter.
1298 Value *CreateIntCast(Value *, Type *, const char *) = delete;
1300 Value *CreateFPCast(Value *V, Type *DestTy, const Twine &Name = "") {
1301 if (V->getType() == DestTy)
1303 if (Constant *VC = dyn_cast<Constant>(V))
1304 return Insert(Folder.CreateFPCast(VC, DestTy), Name);
1305 return Insert(CastInst::CreateFPCast(V, DestTy), Name);
1308 //===--------------------------------------------------------------------===//
1309 // Instruction creation methods: Compare Instructions
1310 //===--------------------------------------------------------------------===//
1312 Value *CreateICmpEQ(Value *LHS, Value *RHS, const Twine &Name = "") {
1313 return CreateICmp(ICmpInst::ICMP_EQ, LHS, RHS, Name);
1315 Value *CreateICmpNE(Value *LHS, Value *RHS, const Twine &Name = "") {
1316 return CreateICmp(ICmpInst::ICMP_NE, LHS, RHS, Name);
1318 Value *CreateICmpUGT(Value *LHS, Value *RHS, const Twine &Name = "") {
1319 return CreateICmp(ICmpInst::ICMP_UGT, LHS, RHS, Name);
1321 Value *CreateICmpUGE(Value *LHS, Value *RHS, const Twine &Name = "") {
1322 return CreateICmp(ICmpInst::ICMP_UGE, LHS, RHS, Name);
1324 Value *CreateICmpULT(Value *LHS, Value *RHS, const Twine &Name = "") {
1325 return CreateICmp(ICmpInst::ICMP_ULT, LHS, RHS, Name);
1327 Value *CreateICmpULE(Value *LHS, Value *RHS, const Twine &Name = "") {
1328 return CreateICmp(ICmpInst::ICMP_ULE, LHS, RHS, Name);
1330 Value *CreateICmpSGT(Value *LHS, Value *RHS, const Twine &Name = "") {
1331 return CreateICmp(ICmpInst::ICMP_SGT, LHS, RHS, Name);
1333 Value *CreateICmpSGE(Value *LHS, Value *RHS, const Twine &Name = "") {
1334 return CreateICmp(ICmpInst::ICMP_SGE, LHS, RHS, Name);
1336 Value *CreateICmpSLT(Value *LHS, Value *RHS, const Twine &Name = "") {
1337 return CreateICmp(ICmpInst::ICMP_SLT, LHS, RHS, Name);
1339 Value *CreateICmpSLE(Value *LHS, Value *RHS, const Twine &Name = "") {
1340 return CreateICmp(ICmpInst::ICMP_SLE, LHS, RHS, Name);
1343 Value *CreateFCmpOEQ(Value *LHS, Value *RHS, const Twine &Name = "") {
1344 return CreateFCmp(FCmpInst::FCMP_OEQ, LHS, RHS, Name);
1346 Value *CreateFCmpOGT(Value *LHS, Value *RHS, const Twine &Name = "") {
1347 return CreateFCmp(FCmpInst::FCMP_OGT, LHS, RHS, Name);
1349 Value *CreateFCmpOGE(Value *LHS, Value *RHS, const Twine &Name = "") {
1350 return CreateFCmp(FCmpInst::FCMP_OGE, LHS, RHS, Name);
1352 Value *CreateFCmpOLT(Value *LHS, Value *RHS, const Twine &Name = "") {
1353 return CreateFCmp(FCmpInst::FCMP_OLT, LHS, RHS, Name);
1355 Value *CreateFCmpOLE(Value *LHS, Value *RHS, const Twine &Name = "") {
1356 return CreateFCmp(FCmpInst::FCMP_OLE, LHS, RHS, Name);
1358 Value *CreateFCmpONE(Value *LHS, Value *RHS, const Twine &Name = "") {
1359 return CreateFCmp(FCmpInst::FCMP_ONE, LHS, RHS, Name);
1361 Value *CreateFCmpORD(Value *LHS, Value *RHS, const Twine &Name = "") {
1362 return CreateFCmp(FCmpInst::FCMP_ORD, LHS, RHS, Name);
1364 Value *CreateFCmpUNO(Value *LHS, Value *RHS, const Twine &Name = "") {
1365 return CreateFCmp(FCmpInst::FCMP_UNO, LHS, RHS, Name);
1367 Value *CreateFCmpUEQ(Value *LHS, Value *RHS, const Twine &Name = "") {
1368 return CreateFCmp(FCmpInst::FCMP_UEQ, LHS, RHS, Name);
1370 Value *CreateFCmpUGT(Value *LHS, Value *RHS, const Twine &Name = "") {
1371 return CreateFCmp(FCmpInst::FCMP_UGT, LHS, RHS, Name);
1373 Value *CreateFCmpUGE(Value *LHS, Value *RHS, const Twine &Name = "") {
1374 return CreateFCmp(FCmpInst::FCMP_UGE, LHS, RHS, Name);
1376 Value *CreateFCmpULT(Value *LHS, Value *RHS, const Twine &Name = "") {
1377 return CreateFCmp(FCmpInst::FCMP_ULT, LHS, RHS, Name);
1379 Value *CreateFCmpULE(Value *LHS, Value *RHS, const Twine &Name = "") {
1380 return CreateFCmp(FCmpInst::FCMP_ULE, LHS, RHS, Name);
1382 Value *CreateFCmpUNE(Value *LHS, Value *RHS, const Twine &Name = "") {
1383 return CreateFCmp(FCmpInst::FCMP_UNE, LHS, RHS, Name);
1386 Value *CreateICmp(CmpInst::Predicate P, Value *LHS, Value *RHS,
1387 const Twine &Name = "") {
1388 if (Constant *LC = dyn_cast<Constant>(LHS))
1389 if (Constant *RC = dyn_cast<Constant>(RHS))
1390 return Insert(Folder.CreateICmp(P, LC, RC), Name);
1391 return Insert(new ICmpInst(P, LHS, RHS), Name);
1393 Value *CreateFCmp(CmpInst::Predicate P, Value *LHS, Value *RHS,
1394 const Twine &Name = "") {
1395 if (Constant *LC = dyn_cast<Constant>(LHS))
1396 if (Constant *RC = dyn_cast<Constant>(RHS))
1397 return Insert(Folder.CreateFCmp(P, LC, RC), Name);
1398 return Insert(new FCmpInst(P, LHS, RHS), Name);
1401 //===--------------------------------------------------------------------===//
1402 // Instruction creation methods: Other Instructions
1403 //===--------------------------------------------------------------------===//
1405 PHINode *CreatePHI(Type *Ty, unsigned NumReservedValues,
1406 const Twine &Name = "") {
1407 return Insert(PHINode::Create(Ty, NumReservedValues), Name);
1410 CallInst *CreateCall(Value *Callee, const Twine &Name = "") {
1411 return Insert(CallInst::Create(Callee), Name);
1413 CallInst *CreateCall(Value *Callee, Value *Arg, const Twine &Name = "") {
1414 return Insert(CallInst::Create(Callee, Arg), Name);
1416 CallInst *CreateCall2(Value *Callee, Value *Arg1, Value *Arg2,
1417 const Twine &Name = "") {
1418 Value *Args[] = { Arg1, Arg2 };
1419 return Insert(CallInst::Create(Callee, Args), Name);
1421 CallInst *CreateCall3(Value *Callee, Value *Arg1, Value *Arg2, Value *Arg3,
1422 const Twine &Name = "") {
1423 Value *Args[] = { Arg1, Arg2, Arg3 };
1424 return Insert(CallInst::Create(Callee, Args), Name);
1426 CallInst *CreateCall4(Value *Callee, Value *Arg1, Value *Arg2, Value *Arg3,
1427 Value *Arg4, const Twine &Name = "") {
1428 Value *Args[] = { Arg1, Arg2, Arg3, Arg4 };
1429 return Insert(CallInst::Create(Callee, Args), Name);
1431 CallInst *CreateCall5(Value *Callee, Value *Arg1, Value *Arg2, Value *Arg3,
1432 Value *Arg4, Value *Arg5, const Twine &Name = "") {
1433 Value *Args[] = { Arg1, Arg2, Arg3, Arg4, Arg5 };
1434 return Insert(CallInst::Create(Callee, Args), Name);
1437 CallInst *CreateCall(Value *Callee, ArrayRef<Value *> Args,
1438 const Twine &Name = "") {
1439 return Insert(CallInst::Create(Callee, Args), Name);
1442 Value *CreateSelect(Value *C, Value *True, Value *False,
1443 const Twine &Name = "") {
1444 if (Constant *CC = dyn_cast<Constant>(C))
1445 if (Constant *TC = dyn_cast<Constant>(True))
1446 if (Constant *FC = dyn_cast<Constant>(False))
1447 return Insert(Folder.CreateSelect(CC, TC, FC), Name);
1448 return Insert(SelectInst::Create(C, True, False), Name);
1451 VAArgInst *CreateVAArg(Value *List, Type *Ty, const Twine &Name = "") {
1452 return Insert(new VAArgInst(List, Ty), Name);
1455 Value *CreateExtractElement(Value *Vec, Value *Idx,
1456 const Twine &Name = "") {
1457 if (Constant *VC = dyn_cast<Constant>(Vec))
1458 if (Constant *IC = dyn_cast<Constant>(Idx))
1459 return Insert(Folder.CreateExtractElement(VC, IC), Name);
1460 return Insert(ExtractElementInst::Create(Vec, Idx), Name);
1463 Value *CreateInsertElement(Value *Vec, Value *NewElt, Value *Idx,
1464 const Twine &Name = "") {
1465 if (Constant *VC = dyn_cast<Constant>(Vec))
1466 if (Constant *NC = dyn_cast<Constant>(NewElt))
1467 if (Constant *IC = dyn_cast<Constant>(Idx))
1468 return Insert(Folder.CreateInsertElement(VC, NC, IC), Name);
1469 return Insert(InsertElementInst::Create(Vec, NewElt, Idx), Name);
1472 Value *CreateShuffleVector(Value *V1, Value *V2, Value *Mask,
1473 const Twine &Name = "") {
1474 if (Constant *V1C = dyn_cast<Constant>(V1))
1475 if (Constant *V2C = dyn_cast<Constant>(V2))
1476 if (Constant *MC = dyn_cast<Constant>(Mask))
1477 return Insert(Folder.CreateShuffleVector(V1C, V2C, MC), Name);
1478 return Insert(new ShuffleVectorInst(V1, V2, Mask), Name);
1481 Value *CreateExtractValue(Value *Agg,
1482 ArrayRef<unsigned> Idxs,
1483 const Twine &Name = "") {
1484 if (Constant *AggC = dyn_cast<Constant>(Agg))
1485 return Insert(Folder.CreateExtractValue(AggC, Idxs), Name);
1486 return Insert(ExtractValueInst::Create(Agg, Idxs), Name);
1489 Value *CreateInsertValue(Value *Agg, Value *Val,
1490 ArrayRef<unsigned> Idxs,
1491 const Twine &Name = "") {
1492 if (Constant *AggC = dyn_cast<Constant>(Agg))
1493 if (Constant *ValC = dyn_cast<Constant>(Val))
1494 return Insert(Folder.CreateInsertValue(AggC, ValC, Idxs), Name);
1495 return Insert(InsertValueInst::Create(Agg, Val, Idxs), Name);
1498 LandingPadInst *CreateLandingPad(Type *Ty, Value *PersFn, unsigned NumClauses,
1499 const Twine &Name = "") {
1500 return Insert(LandingPadInst::Create(Ty, PersFn, NumClauses), Name);
1503 //===--------------------------------------------------------------------===//
1504 // Utility creation methods
1505 //===--------------------------------------------------------------------===//
1507 /// \brief Return an i1 value testing if \p Arg is null.
1508 Value *CreateIsNull(Value *Arg, const Twine &Name = "") {
1509 return CreateICmpEQ(Arg, Constant::getNullValue(Arg->getType()),
1513 /// \brief Return an i1 value testing if \p Arg is not null.
1514 Value *CreateIsNotNull(Value *Arg, const Twine &Name = "") {
1515 return CreateICmpNE(Arg, Constant::getNullValue(Arg->getType()),
1519 /// \brief Return the i64 difference between two pointer values, dividing out
1520 /// the size of the pointed-to objects.
1522 /// This is intended to implement C-style pointer subtraction. As such, the
1523 /// pointers must be appropriately aligned for their element types and
1524 /// pointing into the same object.
1525 Value *CreatePtrDiff(Value *LHS, Value *RHS, const Twine &Name = "") {
1526 assert(LHS->getType() == RHS->getType() &&
1527 "Pointer subtraction operand types must match!");
1528 PointerType *ArgType = cast<PointerType>(LHS->getType());
1529 Value *LHS_int = CreatePtrToInt(LHS, Type::getInt64Ty(Context));
1530 Value *RHS_int = CreatePtrToInt(RHS, Type::getInt64Ty(Context));
1531 Value *Difference = CreateSub(LHS_int, RHS_int);
1532 return CreateExactSDiv(Difference,
1533 ConstantExpr::getSizeOf(ArgType->getElementType()),
1537 /// \brief Return a vector value that contains \arg V broadcasted to \p
1538 /// NumElts elements.
1539 Value *CreateVectorSplat(unsigned NumElts, Value *V, const Twine &Name = "") {
1540 assert(NumElts > 0 && "Cannot splat to an empty vector!");
1542 // First insert it into an undef vector so we can shuffle it.
1543 Type *I32Ty = getInt32Ty();
1544 Value *Undef = UndefValue::get(VectorType::get(V->getType(), NumElts));
1545 V = CreateInsertElement(Undef, V, ConstantInt::get(I32Ty, 0),
1546 Name + ".splatinsert");
1548 // Shuffle the value across the desired number of elements.
1549 Value *Zeros = ConstantAggregateZero::get(VectorType::get(I32Ty, NumElts));
1550 return CreateShuffleVector(V, Undef, Zeros, Name + ".splat");
1553 /// \brief Return a value that has been extracted from a larger integer type.
1554 Value *CreateExtractInteger(const DataLayout &DL, Value *From,
1555 IntegerType *ExtractedTy, uint64_t Offset,
1556 const Twine &Name) {
1557 IntegerType *IntTy = cast<IntegerType>(From->getType());
1558 assert(DL.getTypeStoreSize(ExtractedTy) + Offset <=
1559 DL.getTypeStoreSize(IntTy) &&
1560 "Element extends past full value");
1561 uint64_t ShAmt = 8 * Offset;
1563 if (DL.isBigEndian())
1564 ShAmt = 8 * (DL.getTypeStoreSize(IntTy) -
1565 DL.getTypeStoreSize(ExtractedTy) - Offset);
1567 V = CreateLShr(V, ShAmt, Name + ".shift");
1569 assert(ExtractedTy->getBitWidth() <= IntTy->getBitWidth() &&
1570 "Cannot extract to a larger integer!");
1571 if (ExtractedTy != IntTy) {
1572 V = CreateTrunc(V, ExtractedTy, Name + ".trunc");
1577 /// \brief Create an assume intrinsic call that represents an alignment
1578 /// assumption on the provided pointer.
1580 /// An optional offset can be provided, and if it is provided, the offset
1581 /// must be subtracted from the provided pointer to get the pointer with the
1582 /// specified alignment.
1583 CallInst *CreateAlignmentAssumption(const DataLayout &DL, Value *PtrValue,
1585 Value *OffsetValue = nullptr) {
1586 assert(isa<PointerType>(PtrValue->getType()) &&
1587 "trying to create an alignment assumption on a non-pointer?");
1589 PointerType *PtrTy = cast<PointerType>(PtrValue->getType());
1590 Type *IntPtrTy = getIntPtrTy(&DL, PtrTy->getAddressSpace());
1591 Value *PtrIntValue = CreatePtrToInt(PtrValue, IntPtrTy, "ptrint");
1593 Value *Mask = ConstantInt::get(IntPtrTy,
1594 Alignment > 0 ? Alignment - 1 : 0);
1596 bool IsOffsetZero = false;
1597 if (ConstantInt *CI = dyn_cast<ConstantInt>(OffsetValue))
1598 IsOffsetZero = CI->isZero();
1600 if (!IsOffsetZero) {
1601 if (OffsetValue->getType() != IntPtrTy)
1602 OffsetValue = CreateIntCast(OffsetValue, IntPtrTy, /*isSigned*/ true,
1604 PtrIntValue = CreateSub(PtrIntValue, OffsetValue, "offsetptr");
1608 Value *Zero = ConstantInt::get(IntPtrTy, 0);
1609 Value *MaskedPtr = CreateAnd(PtrIntValue, Mask, "maskedptr");
1610 Value *InvCond = CreateICmpEQ(MaskedPtr, Zero, "maskcond");
1612 return CreateAssumption(InvCond);
1616 // Create wrappers for C Binding types (see CBindingWrapping.h).
1617 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(IRBuilder<>, LLVMBuilderRef)