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(const DebugLoc &L) {
122 /// \brief Get location information used by debugging information.
123 DebugLoc getCurrentDebugLocation() const { return CurDbgLocation; }
125 /// \brief If this builder has a current debug location, set it on the
126 /// specified instruction.
127 void SetInstDebugLocation(Instruction *I) const {
128 if (!CurDbgLocation.isUnknown())
129 I->setDebugLoc(CurDbgLocation);
132 /// \brief Get the return type of the current function that we're emitting
134 Type *getCurrentFunctionReturnType() const;
136 /// InsertPoint - A saved insertion point.
139 BasicBlock::iterator Point;
142 /// \brief Creates a new insertion point which doesn't point to anything.
143 InsertPoint() : Block(nullptr) {}
145 /// \brief Creates a new insertion point at the given location.
146 InsertPoint(BasicBlock *InsertBlock, BasicBlock::iterator InsertPoint)
147 : Block(InsertBlock), Point(InsertPoint) {}
149 /// \brief Returns true if this insert point is set.
150 bool isSet() const { return (Block != nullptr); }
152 llvm::BasicBlock *getBlock() const { return Block; }
153 llvm::BasicBlock::iterator getPoint() const { return Point; }
156 /// \brief Returns the current insert point.
157 InsertPoint saveIP() const {
158 return InsertPoint(GetInsertBlock(), GetInsertPoint());
161 /// \brief Returns the current insert point, clearing it in the process.
162 InsertPoint saveAndClearIP() {
163 InsertPoint IP(GetInsertBlock(), GetInsertPoint());
164 ClearInsertionPoint();
168 /// \brief Sets the current insert point to a previously-saved location.
169 void restoreIP(InsertPoint IP) {
171 SetInsertPoint(IP.getBlock(), IP.getPoint());
173 ClearInsertionPoint();
176 /// \brief Get the floating point math metadata being used.
177 MDNode *getDefaultFPMathTag() const { return DefaultFPMathTag; }
179 /// \brief Get the flags to be applied to created floating point ops
180 FastMathFlags getFastMathFlags() const { return FMF; }
182 /// \brief Clear the fast-math flags.
183 void clearFastMathFlags() { FMF.clear(); }
185 /// \brief Set the floating point math metadata to be used.
186 void SetDefaultFPMathTag(MDNode *FPMathTag) { DefaultFPMathTag = FPMathTag; }
188 /// \brief Set the fast-math flags to be used with generated fp-math operators
189 void SetFastMathFlags(FastMathFlags NewFMF) { FMF = NewFMF; }
191 //===--------------------------------------------------------------------===//
193 //===--------------------------------------------------------------------===//
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;
203 InsertPointGuard(const InsertPointGuard &) LLVM_DELETED_FUNCTION;
204 InsertPointGuard &operator=(const InsertPointGuard &) LLVM_DELETED_FUNCTION;
207 InsertPointGuard(IRBuilderBase &B)
208 : Builder(B), Block(B.GetInsertBlock()), Point(B.GetInsertPoint()),
209 DbgLoc(B.getCurrentDebugLocation()) {}
211 ~InsertPointGuard() {
212 Builder.restoreIP(InsertPoint(Block, Point));
213 Builder.SetCurrentDebugLocation(DbgLoc);
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;
224 FastMathFlagGuard(const FastMathFlagGuard &) LLVM_DELETED_FUNCTION;
225 FastMathFlagGuard &operator=(
226 const FastMathFlagGuard &) LLVM_DELETED_FUNCTION;
229 FastMathFlagGuard(IRBuilderBase &B)
230 : Builder(B), FMF(B.FMF), FPMathTag(B.DefaultFPMathTag) {}
232 ~FastMathFlagGuard() {
234 Builder.DefaultFPMathTag = FPMathTag;
238 //===--------------------------------------------------------------------===//
239 // Miscellaneous creation methods.
240 //===--------------------------------------------------------------------===//
242 /// \brief Make a new global variable with initializer type i8*
244 /// Make a new global variable with an initializer that has array of i8 type
245 /// filled in with the null terminated string value specified. The new global
246 /// variable will be marked mergable with any others of the same contents. If
247 /// Name is specified, it is the name of the global variable created.
248 Value *CreateGlobalString(StringRef Str, const Twine &Name = "");
250 /// \brief Get a constant value representing either true or false.
251 ConstantInt *getInt1(bool V) {
252 return ConstantInt::get(getInt1Ty(), V);
255 /// \brief Get the constant value for i1 true.
256 ConstantInt *getTrue() {
257 return ConstantInt::getTrue(Context);
260 /// \brief Get the constant value for i1 false.
261 ConstantInt *getFalse() {
262 return ConstantInt::getFalse(Context);
265 /// \brief Get a constant 8-bit value.
266 ConstantInt *getInt8(uint8_t C) {
267 return ConstantInt::get(getInt8Ty(), C);
270 /// \brief Get a constant 16-bit value.
271 ConstantInt *getInt16(uint16_t C) {
272 return ConstantInt::get(getInt16Ty(), C);
275 /// \brief Get a constant 32-bit value.
276 ConstantInt *getInt32(uint32_t C) {
277 return ConstantInt::get(getInt32Ty(), C);
280 /// \brief Get a constant 64-bit value.
281 ConstantInt *getInt64(uint64_t C) {
282 return ConstantInt::get(getInt64Ty(), C);
285 /// \brief Get a constant N-bit value, zero extended or truncated from
287 ConstantInt *getIntN(unsigned N, uint64_t C) {
288 return ConstantInt::get(getIntNTy(N), C);
291 /// \brief Get a constant integer value.
292 ConstantInt *getInt(const APInt &AI) {
293 return ConstantInt::get(Context, AI);
296 //===--------------------------------------------------------------------===//
297 // Type creation methods
298 //===--------------------------------------------------------------------===//
300 /// \brief Fetch the type representing a single bit
301 IntegerType *getInt1Ty() {
302 return Type::getInt1Ty(Context);
305 /// \brief Fetch the type representing an 8-bit integer.
306 IntegerType *getInt8Ty() {
307 return Type::getInt8Ty(Context);
310 /// \brief Fetch the type representing a 16-bit integer.
311 IntegerType *getInt16Ty() {
312 return Type::getInt16Ty(Context);
315 /// \brief Fetch the type representing a 32-bit integer.
316 IntegerType *getInt32Ty() {
317 return Type::getInt32Ty(Context);
320 /// \brief Fetch the type representing a 64-bit integer.
321 IntegerType *getInt64Ty() {
322 return Type::getInt64Ty(Context);
325 /// \brief Fetch the type representing an N-bit integer.
326 IntegerType *getIntNTy(unsigned N) {
327 return Type::getIntNTy(Context, N);
330 /// \brief Fetch the type representing a 16-bit floating point value.
332 return Type::getHalfTy(Context);
335 /// \brief Fetch the type representing a 32-bit floating point value.
337 return Type::getFloatTy(Context);
340 /// \brief Fetch the type representing a 64-bit floating point value.
341 Type *getDoubleTy() {
342 return Type::getDoubleTy(Context);
345 /// \brief Fetch the type representing void.
347 return Type::getVoidTy(Context);
350 /// \brief Fetch the type representing a pointer to an 8-bit integer value.
351 PointerType *getInt8PtrTy(unsigned AddrSpace = 0) {
352 return Type::getInt8PtrTy(Context, AddrSpace);
355 /// \brief Fetch the type representing a pointer to an integer value.
356 IntegerType* getIntPtrTy(const DataLayout *DL, unsigned AddrSpace = 0) {
357 return DL->getIntPtrType(Context, AddrSpace);
360 //===--------------------------------------------------------------------===//
361 // Intrinsic creation methods
362 //===--------------------------------------------------------------------===//
364 /// \brief Create and insert a memset to the specified pointer and the
367 /// If the pointer isn't an i8*, it will be converted. If a TBAA tag is
368 /// specified, it will be added to the instruction. Likewise with alias.scope
369 /// and noalias tags.
370 CallInst *CreateMemSet(Value *Ptr, Value *Val, uint64_t Size, unsigned Align,
371 bool isVolatile = false, MDNode *TBAATag = nullptr,
372 MDNode *ScopeTag = nullptr,
373 MDNode *NoAliasTag = nullptr) {
374 return CreateMemSet(Ptr, Val, getInt64(Size), Align, isVolatile,
375 TBAATag, ScopeTag, NoAliasTag);
378 CallInst *CreateMemSet(Value *Ptr, Value *Val, Value *Size, unsigned Align,
379 bool isVolatile = false, MDNode *TBAATag = nullptr,
380 MDNode *ScopeTag = nullptr,
381 MDNode *NoAliasTag = nullptr);
383 /// \brief Create and insert a memcpy between the specified pointers.
385 /// If the pointers aren't i8*, they will be converted. If a TBAA tag is
386 /// specified, it will be added to the instruction. Likewise with alias.scope
387 /// and noalias tags.
388 CallInst *CreateMemCpy(Value *Dst, Value *Src, uint64_t Size, unsigned Align,
389 bool isVolatile = false, MDNode *TBAATag = nullptr,
390 MDNode *TBAAStructTag = nullptr,
391 MDNode *ScopeTag = nullptr,
392 MDNode *NoAliasTag = nullptr) {
393 return CreateMemCpy(Dst, Src, getInt64(Size), Align, isVolatile, TBAATag,
394 TBAAStructTag, ScopeTag, NoAliasTag);
397 CallInst *CreateMemCpy(Value *Dst, Value *Src, Value *Size, unsigned Align,
398 bool isVolatile = false, MDNode *TBAATag = nullptr,
399 MDNode *TBAAStructTag = nullptr,
400 MDNode *ScopeTag = nullptr,
401 MDNode *NoAliasTag = nullptr);
403 /// \brief Create and insert a memmove between the specified
406 /// If the pointers aren't i8*, they will be converted. If a TBAA tag is
407 /// specified, it will be added to the instruction. Likewise with alias.scope
408 /// and noalias tags.
409 CallInst *CreateMemMove(Value *Dst, Value *Src, uint64_t Size, unsigned Align,
410 bool isVolatile = false, MDNode *TBAATag = nullptr,
411 MDNode *ScopeTag = nullptr,
412 MDNode *NoAliasTag = nullptr) {
413 return CreateMemMove(Dst, Src, getInt64(Size), Align, isVolatile,
414 TBAATag, ScopeTag, NoAliasTag);
417 CallInst *CreateMemMove(Value *Dst, Value *Src, Value *Size, unsigned Align,
418 bool isVolatile = false, MDNode *TBAATag = nullptr,
419 MDNode *ScopeTag = nullptr,
420 MDNode *NoAliasTag = nullptr);
422 /// \brief Create a lifetime.start intrinsic.
424 /// If the pointer isn't i8* it will be converted.
425 CallInst *CreateLifetimeStart(Value *Ptr, ConstantInt *Size = nullptr);
427 /// \brief Create a lifetime.end intrinsic.
429 /// If the pointer isn't i8* it will be converted.
430 CallInst *CreateLifetimeEnd(Value *Ptr, ConstantInt *Size = nullptr);
432 /// \brief Create an assume intrinsic call that allows the optimizer to
433 /// assume that the provided condition will be true.
434 CallInst *CreateAssumption(Value *Cond);
437 Value *getCastedInt8PtrValue(Value *Ptr);
440 /// \brief This provides a uniform API for creating instructions and inserting
441 /// them into a basic block: either at the end of a BasicBlock, or at a specific
442 /// iterator location in a block.
444 /// Note that the builder does not expose the full generality of LLVM
445 /// instructions. For access to extra instruction properties, use the mutators
446 /// (e.g. setVolatile) on the instructions after they have been
447 /// created. Convenience state exists to specify fast-math flags and fp-math
450 /// The first template argument handles whether or not to preserve names in the
451 /// final instruction output. This defaults to on. The second template argument
452 /// specifies a class to use for creating constants. This defaults to creating
453 /// minimally folded constants. The third template argument allows clients to
454 /// specify custom insertion hooks that are called on every newly created
456 template<bool preserveNames = true, typename T = ConstantFolder,
457 typename Inserter = IRBuilderDefaultInserter<preserveNames> >
458 class IRBuilder : public IRBuilderBase, public Inserter {
461 IRBuilder(LLVMContext &C, const T &F, const Inserter &I = Inserter(),
462 MDNode *FPMathTag = nullptr)
463 : IRBuilderBase(C, FPMathTag), Inserter(I), Folder(F) {
466 explicit IRBuilder(LLVMContext &C, MDNode *FPMathTag = nullptr)
467 : IRBuilderBase(C, FPMathTag), Folder() {
470 explicit IRBuilder(BasicBlock *TheBB, const T &F, MDNode *FPMathTag = nullptr)
471 : IRBuilderBase(TheBB->getContext(), FPMathTag), Folder(F) {
472 SetInsertPoint(TheBB);
475 explicit IRBuilder(BasicBlock *TheBB, MDNode *FPMathTag = nullptr)
476 : IRBuilderBase(TheBB->getContext(), FPMathTag), Folder() {
477 SetInsertPoint(TheBB);
480 explicit IRBuilder(Instruction *IP, MDNode *FPMathTag = nullptr)
481 : IRBuilderBase(IP->getContext(), FPMathTag), Folder() {
483 SetCurrentDebugLocation(IP->getDebugLoc());
486 explicit IRBuilder(Use &U, MDNode *FPMathTag = nullptr)
487 : IRBuilderBase(U->getContext(), FPMathTag), Folder() {
489 SetCurrentDebugLocation(cast<Instruction>(U.getUser())->getDebugLoc());
492 IRBuilder(BasicBlock *TheBB, BasicBlock::iterator IP, const T& F,
493 MDNode *FPMathTag = nullptr)
494 : IRBuilderBase(TheBB->getContext(), FPMathTag), Folder(F) {
495 SetInsertPoint(TheBB, IP);
498 IRBuilder(BasicBlock *TheBB, BasicBlock::iterator IP,
499 MDNode *FPMathTag = nullptr)
500 : IRBuilderBase(TheBB->getContext(), FPMathTag), Folder() {
501 SetInsertPoint(TheBB, IP);
504 /// \brief Get the constant folder being used.
505 const T &getFolder() { return Folder; }
507 /// \brief Return true if this builder is configured to actually add the
508 /// requested names to IR created through it.
509 bool isNamePreserving() const { return preserveNames; }
511 /// \brief Insert and return the specified instruction.
512 template<typename InstTy>
513 InstTy *Insert(InstTy *I, const Twine &Name = "") const {
514 this->InsertHelper(I, Name, BB, InsertPt);
515 this->SetInstDebugLocation(I);
519 /// \brief No-op overload to handle constants.
520 Constant *Insert(Constant *C, const Twine& = "") const {
524 //===--------------------------------------------------------------------===//
525 // Instruction creation methods: Terminators
526 //===--------------------------------------------------------------------===//
529 /// \brief Helper to add branch weight metadata onto an instruction.
530 /// \returns The annotated instruction.
531 template <typename InstTy>
532 InstTy *addBranchWeights(InstTy *I, MDNode *Weights) {
534 I->setMetadata(LLVMContext::MD_prof, Weights);
539 /// \brief Create a 'ret void' instruction.
540 ReturnInst *CreateRetVoid() {
541 return Insert(ReturnInst::Create(Context));
544 /// \brief Create a 'ret <val>' instruction.
545 ReturnInst *CreateRet(Value *V) {
546 return Insert(ReturnInst::Create(Context, V));
549 /// \brief Create a sequence of N insertvalue instructions,
550 /// with one Value from the retVals array each, that build a aggregate
551 /// return value one value at a time, and a ret instruction to return
552 /// the resulting aggregate value.
554 /// This is a convenience function for code that uses aggregate return values
555 /// as a vehicle for having multiple return values.
556 ReturnInst *CreateAggregateRet(Value *const *retVals, unsigned N) {
557 Value *V = UndefValue::get(getCurrentFunctionReturnType());
558 for (unsigned i = 0; i != N; ++i)
559 V = CreateInsertValue(V, retVals[i], i, "mrv");
560 return Insert(ReturnInst::Create(Context, V));
563 /// \brief Create an unconditional 'br label X' instruction.
564 BranchInst *CreateBr(BasicBlock *Dest) {
565 return Insert(BranchInst::Create(Dest));
568 /// \brief Create a conditional 'br Cond, TrueDest, FalseDest'
570 BranchInst *CreateCondBr(Value *Cond, BasicBlock *True, BasicBlock *False,
571 MDNode *BranchWeights = nullptr) {
572 return Insert(addBranchWeights(BranchInst::Create(True, False, Cond),
576 /// \brief Create a switch instruction with the specified value, default dest,
577 /// and with a hint for the number of cases that will be added (for efficient
579 SwitchInst *CreateSwitch(Value *V, BasicBlock *Dest, unsigned NumCases = 10,
580 MDNode *BranchWeights = nullptr) {
581 return Insert(addBranchWeights(SwitchInst::Create(V, Dest, NumCases),
585 /// \brief Create an indirect branch instruction with the specified address
586 /// operand, with an optional hint for the number of destinations that will be
587 /// added (for efficient allocation).
588 IndirectBrInst *CreateIndirectBr(Value *Addr, unsigned NumDests = 10) {
589 return Insert(IndirectBrInst::Create(Addr, NumDests));
592 InvokeInst *CreateInvoke(Value *Callee, BasicBlock *NormalDest,
593 BasicBlock *UnwindDest, const Twine &Name = "") {
594 return Insert(InvokeInst::Create(Callee, NormalDest, UnwindDest, None),
597 InvokeInst *CreateInvoke(Value *Callee, BasicBlock *NormalDest,
598 BasicBlock *UnwindDest, Value *Arg1,
599 const Twine &Name = "") {
600 return Insert(InvokeInst::Create(Callee, NormalDest, UnwindDest, Arg1),
603 InvokeInst *CreateInvoke3(Value *Callee, BasicBlock *NormalDest,
604 BasicBlock *UnwindDest, Value *Arg1,
605 Value *Arg2, Value *Arg3,
606 const Twine &Name = "") {
607 Value *Args[] = { Arg1, Arg2, Arg3 };
608 return Insert(InvokeInst::Create(Callee, NormalDest, UnwindDest, Args),
611 /// \brief Create an invoke instruction.
612 InvokeInst *CreateInvoke(Value *Callee, BasicBlock *NormalDest,
613 BasicBlock *UnwindDest, ArrayRef<Value *> Args,
614 const Twine &Name = "") {
615 return Insert(InvokeInst::Create(Callee, NormalDest, UnwindDest, Args),
619 ResumeInst *CreateResume(Value *Exn) {
620 return Insert(ResumeInst::Create(Exn));
623 UnreachableInst *CreateUnreachable() {
624 return Insert(new UnreachableInst(Context));
627 //===--------------------------------------------------------------------===//
628 // Instruction creation methods: Binary Operators
629 //===--------------------------------------------------------------------===//
631 BinaryOperator *CreateInsertNUWNSWBinOp(BinaryOperator::BinaryOps Opc,
632 Value *LHS, Value *RHS,
634 bool HasNUW, bool HasNSW) {
635 BinaryOperator *BO = Insert(BinaryOperator::Create(Opc, LHS, RHS), Name);
636 if (HasNUW) BO->setHasNoUnsignedWrap();
637 if (HasNSW) BO->setHasNoSignedWrap();
641 Instruction *AddFPMathAttributes(Instruction *I,
643 FastMathFlags FMF) const {
645 FPMathTag = DefaultFPMathTag;
647 I->setMetadata(LLVMContext::MD_fpmath, FPMathTag);
648 I->setFastMathFlags(FMF);
652 Value *CreateAdd(Value *LHS, Value *RHS, const Twine &Name = "",
653 bool HasNUW = false, bool HasNSW = false) {
654 if (Constant *LC = dyn_cast<Constant>(LHS))
655 if (Constant *RC = dyn_cast<Constant>(RHS))
656 return Insert(Folder.CreateAdd(LC, RC, HasNUW, HasNSW), Name);
657 return CreateInsertNUWNSWBinOp(Instruction::Add, LHS, RHS, Name,
660 Value *CreateNSWAdd(Value *LHS, Value *RHS, const Twine &Name = "") {
661 return CreateAdd(LHS, RHS, Name, false, true);
663 Value *CreateNUWAdd(Value *LHS, Value *RHS, const Twine &Name = "") {
664 return CreateAdd(LHS, RHS, Name, true, false);
666 Value *CreateFAdd(Value *LHS, Value *RHS, const Twine &Name = "",
667 MDNode *FPMathTag = nullptr) {
668 if (Constant *LC = dyn_cast<Constant>(LHS))
669 if (Constant *RC = dyn_cast<Constant>(RHS))
670 return Insert(Folder.CreateFAdd(LC, RC), Name);
671 return Insert(AddFPMathAttributes(BinaryOperator::CreateFAdd(LHS, RHS),
672 FPMathTag, FMF), Name);
674 Value *CreateSub(Value *LHS, Value *RHS, const Twine &Name = "",
675 bool HasNUW = false, bool HasNSW = false) {
676 if (Constant *LC = dyn_cast<Constant>(LHS))
677 if (Constant *RC = dyn_cast<Constant>(RHS))
678 return Insert(Folder.CreateSub(LC, RC, HasNUW, HasNSW), Name);
679 return CreateInsertNUWNSWBinOp(Instruction::Sub, LHS, RHS, Name,
682 Value *CreateNSWSub(Value *LHS, Value *RHS, const Twine &Name = "") {
683 return CreateSub(LHS, RHS, Name, false, true);
685 Value *CreateNUWSub(Value *LHS, Value *RHS, const Twine &Name = "") {
686 return CreateSub(LHS, RHS, Name, true, false);
688 Value *CreateFSub(Value *LHS, Value *RHS, const Twine &Name = "",
689 MDNode *FPMathTag = nullptr) {
690 if (Constant *LC = dyn_cast<Constant>(LHS))
691 if (Constant *RC = dyn_cast<Constant>(RHS))
692 return Insert(Folder.CreateFSub(LC, RC), Name);
693 return Insert(AddFPMathAttributes(BinaryOperator::CreateFSub(LHS, RHS),
694 FPMathTag, FMF), Name);
696 Value *CreateMul(Value *LHS, Value *RHS, const Twine &Name = "",
697 bool HasNUW = false, bool HasNSW = false) {
698 if (Constant *LC = dyn_cast<Constant>(LHS))
699 if (Constant *RC = dyn_cast<Constant>(RHS))
700 return Insert(Folder.CreateMul(LC, RC, HasNUW, HasNSW), Name);
701 return CreateInsertNUWNSWBinOp(Instruction::Mul, LHS, RHS, Name,
704 Value *CreateNSWMul(Value *LHS, Value *RHS, const Twine &Name = "") {
705 return CreateMul(LHS, RHS, Name, false, true);
707 Value *CreateNUWMul(Value *LHS, Value *RHS, const Twine &Name = "") {
708 return CreateMul(LHS, RHS, Name, true, false);
710 Value *CreateFMul(Value *LHS, Value *RHS, const Twine &Name = "",
711 MDNode *FPMathTag = nullptr) {
712 if (Constant *LC = dyn_cast<Constant>(LHS))
713 if (Constant *RC = dyn_cast<Constant>(RHS))
714 return Insert(Folder.CreateFMul(LC, RC), Name);
715 return Insert(AddFPMathAttributes(BinaryOperator::CreateFMul(LHS, RHS),
716 FPMathTag, FMF), Name);
718 Value *CreateUDiv(Value *LHS, Value *RHS, const Twine &Name = "",
719 bool isExact = false) {
720 if (Constant *LC = dyn_cast<Constant>(LHS))
721 if (Constant *RC = dyn_cast<Constant>(RHS))
722 return Insert(Folder.CreateUDiv(LC, RC, isExact), Name);
724 return Insert(BinaryOperator::CreateUDiv(LHS, RHS), Name);
725 return Insert(BinaryOperator::CreateExactUDiv(LHS, RHS), Name);
727 Value *CreateExactUDiv(Value *LHS, Value *RHS, const Twine &Name = "") {
728 return CreateUDiv(LHS, RHS, Name, true);
730 Value *CreateSDiv(Value *LHS, Value *RHS, const Twine &Name = "",
731 bool isExact = false) {
732 if (Constant *LC = dyn_cast<Constant>(LHS))
733 if (Constant *RC = dyn_cast<Constant>(RHS))
734 return Insert(Folder.CreateSDiv(LC, RC, isExact), Name);
736 return Insert(BinaryOperator::CreateSDiv(LHS, RHS), Name);
737 return Insert(BinaryOperator::CreateExactSDiv(LHS, RHS), Name);
739 Value *CreateExactSDiv(Value *LHS, Value *RHS, const Twine &Name = "") {
740 return CreateSDiv(LHS, RHS, Name, true);
742 Value *CreateFDiv(Value *LHS, Value *RHS, const Twine &Name = "",
743 MDNode *FPMathTag = nullptr) {
744 if (Constant *LC = dyn_cast<Constant>(LHS))
745 if (Constant *RC = dyn_cast<Constant>(RHS))
746 return Insert(Folder.CreateFDiv(LC, RC), Name);
747 return Insert(AddFPMathAttributes(BinaryOperator::CreateFDiv(LHS, RHS),
748 FPMathTag, FMF), Name);
750 Value *CreateURem(Value *LHS, Value *RHS, const Twine &Name = "") {
751 if (Constant *LC = dyn_cast<Constant>(LHS))
752 if (Constant *RC = dyn_cast<Constant>(RHS))
753 return Insert(Folder.CreateURem(LC, RC), Name);
754 return Insert(BinaryOperator::CreateURem(LHS, RHS), Name);
756 Value *CreateSRem(Value *LHS, Value *RHS, const Twine &Name = "") {
757 if (Constant *LC = dyn_cast<Constant>(LHS))
758 if (Constant *RC = dyn_cast<Constant>(RHS))
759 return Insert(Folder.CreateSRem(LC, RC), Name);
760 return Insert(BinaryOperator::CreateSRem(LHS, RHS), Name);
762 Value *CreateFRem(Value *LHS, Value *RHS, const Twine &Name = "",
763 MDNode *FPMathTag = nullptr) {
764 if (Constant *LC = dyn_cast<Constant>(LHS))
765 if (Constant *RC = dyn_cast<Constant>(RHS))
766 return Insert(Folder.CreateFRem(LC, RC), Name);
767 return Insert(AddFPMathAttributes(BinaryOperator::CreateFRem(LHS, RHS),
768 FPMathTag, FMF), Name);
771 Value *CreateShl(Value *LHS, Value *RHS, const Twine &Name = "",
772 bool HasNUW = false, bool HasNSW = false) {
773 if (Constant *LC = dyn_cast<Constant>(LHS))
774 if (Constant *RC = dyn_cast<Constant>(RHS))
775 return Insert(Folder.CreateShl(LC, RC, HasNUW, HasNSW), Name);
776 return CreateInsertNUWNSWBinOp(Instruction::Shl, LHS, RHS, Name,
779 Value *CreateShl(Value *LHS, const APInt &RHS, const Twine &Name = "",
780 bool HasNUW = false, bool HasNSW = false) {
781 return CreateShl(LHS, ConstantInt::get(LHS->getType(), RHS), Name,
784 Value *CreateShl(Value *LHS, uint64_t RHS, const Twine &Name = "",
785 bool HasNUW = false, bool HasNSW = false) {
786 return CreateShl(LHS, ConstantInt::get(LHS->getType(), RHS), Name,
790 Value *CreateLShr(Value *LHS, Value *RHS, const Twine &Name = "",
791 bool isExact = false) {
792 if (Constant *LC = dyn_cast<Constant>(LHS))
793 if (Constant *RC = dyn_cast<Constant>(RHS))
794 return Insert(Folder.CreateLShr(LC, RC, isExact), Name);
796 return Insert(BinaryOperator::CreateLShr(LHS, RHS), Name);
797 return Insert(BinaryOperator::CreateExactLShr(LHS, RHS), Name);
799 Value *CreateLShr(Value *LHS, const APInt &RHS, const Twine &Name = "",
800 bool isExact = false) {
801 return CreateLShr(LHS, ConstantInt::get(LHS->getType(), RHS), Name,isExact);
803 Value *CreateLShr(Value *LHS, uint64_t RHS, const Twine &Name = "",
804 bool isExact = false) {
805 return CreateLShr(LHS, ConstantInt::get(LHS->getType(), RHS), Name,isExact);
808 Value *CreateAShr(Value *LHS, Value *RHS, const Twine &Name = "",
809 bool isExact = false) {
810 if (Constant *LC = dyn_cast<Constant>(LHS))
811 if (Constant *RC = dyn_cast<Constant>(RHS))
812 return Insert(Folder.CreateAShr(LC, RC, isExact), Name);
814 return Insert(BinaryOperator::CreateAShr(LHS, RHS), Name);
815 return Insert(BinaryOperator::CreateExactAShr(LHS, RHS), Name);
817 Value *CreateAShr(Value *LHS, const APInt &RHS, const Twine &Name = "",
818 bool isExact = false) {
819 return CreateAShr(LHS, ConstantInt::get(LHS->getType(), RHS), Name,isExact);
821 Value *CreateAShr(Value *LHS, uint64_t RHS, const Twine &Name = "",
822 bool isExact = false) {
823 return CreateAShr(LHS, ConstantInt::get(LHS->getType(), RHS), Name,isExact);
826 Value *CreateAnd(Value *LHS, Value *RHS, const Twine &Name = "") {
827 if (Constant *RC = dyn_cast<Constant>(RHS)) {
828 if (isa<ConstantInt>(RC) && cast<ConstantInt>(RC)->isAllOnesValue())
829 return LHS; // LHS & -1 -> LHS
830 if (Constant *LC = dyn_cast<Constant>(LHS))
831 return Insert(Folder.CreateAnd(LC, RC), Name);
833 return Insert(BinaryOperator::CreateAnd(LHS, RHS), Name);
835 Value *CreateAnd(Value *LHS, const APInt &RHS, const Twine &Name = "") {
836 return CreateAnd(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
838 Value *CreateAnd(Value *LHS, uint64_t RHS, const Twine &Name = "") {
839 return CreateAnd(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
842 Value *CreateOr(Value *LHS, Value *RHS, const Twine &Name = "") {
843 if (Constant *RC = dyn_cast<Constant>(RHS)) {
844 if (RC->isNullValue())
845 return LHS; // LHS | 0 -> LHS
846 if (Constant *LC = dyn_cast<Constant>(LHS))
847 return Insert(Folder.CreateOr(LC, RC), Name);
849 return Insert(BinaryOperator::CreateOr(LHS, RHS), Name);
851 Value *CreateOr(Value *LHS, const APInt &RHS, const Twine &Name = "") {
852 return CreateOr(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
854 Value *CreateOr(Value *LHS, uint64_t RHS, const Twine &Name = "") {
855 return CreateOr(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
858 Value *CreateXor(Value *LHS, Value *RHS, const Twine &Name = "") {
859 if (Constant *LC = dyn_cast<Constant>(LHS))
860 if (Constant *RC = dyn_cast<Constant>(RHS))
861 return Insert(Folder.CreateXor(LC, RC), Name);
862 return Insert(BinaryOperator::CreateXor(LHS, RHS), Name);
864 Value *CreateXor(Value *LHS, const APInt &RHS, const Twine &Name = "") {
865 return CreateXor(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
867 Value *CreateXor(Value *LHS, uint64_t RHS, const Twine &Name = "") {
868 return CreateXor(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
871 Value *CreateBinOp(Instruction::BinaryOps Opc,
872 Value *LHS, Value *RHS, const Twine &Name = "",
873 MDNode *FPMathTag = nullptr) {
874 if (Constant *LC = dyn_cast<Constant>(LHS))
875 if (Constant *RC = dyn_cast<Constant>(RHS))
876 return Insert(Folder.CreateBinOp(Opc, LC, RC), Name);
877 llvm::Instruction *BinOp = BinaryOperator::Create(Opc, LHS, RHS);
878 if (isa<FPMathOperator>(BinOp))
879 BinOp = AddFPMathAttributes(BinOp, FPMathTag, FMF);
880 return Insert(BinOp, Name);
883 Value *CreateNeg(Value *V, const Twine &Name = "",
884 bool HasNUW = false, bool HasNSW = false) {
885 if (Constant *VC = dyn_cast<Constant>(V))
886 return Insert(Folder.CreateNeg(VC, HasNUW, HasNSW), Name);
887 BinaryOperator *BO = Insert(BinaryOperator::CreateNeg(V), Name);
888 if (HasNUW) BO->setHasNoUnsignedWrap();
889 if (HasNSW) BO->setHasNoSignedWrap();
892 Value *CreateNSWNeg(Value *V, const Twine &Name = "") {
893 return CreateNeg(V, Name, false, true);
895 Value *CreateNUWNeg(Value *V, const Twine &Name = "") {
896 return CreateNeg(V, Name, true, false);
898 Value *CreateFNeg(Value *V, const Twine &Name = "",
899 MDNode *FPMathTag = nullptr) {
900 if (Constant *VC = dyn_cast<Constant>(V))
901 return Insert(Folder.CreateFNeg(VC), Name);
902 return Insert(AddFPMathAttributes(BinaryOperator::CreateFNeg(V),
903 FPMathTag, FMF), Name);
905 Value *CreateNot(Value *V, const Twine &Name = "") {
906 if (Constant *VC = dyn_cast<Constant>(V))
907 return Insert(Folder.CreateNot(VC), Name);
908 return Insert(BinaryOperator::CreateNot(V), Name);
911 //===--------------------------------------------------------------------===//
912 // Instruction creation methods: Memory Instructions
913 //===--------------------------------------------------------------------===//
915 AllocaInst *CreateAlloca(Type *Ty, Value *ArraySize = nullptr,
916 const Twine &Name = "") {
917 return Insert(new AllocaInst(Ty, ArraySize), Name);
919 // \brief Provided to resolve 'CreateLoad(Ptr, "...")' correctly, instead of
920 // converting the string to 'bool' for the isVolatile parameter.
921 LoadInst *CreateLoad(Value *Ptr, const char *Name) {
922 return Insert(new LoadInst(Ptr), Name);
924 LoadInst *CreateLoad(Value *Ptr, const Twine &Name = "") {
925 return Insert(new LoadInst(Ptr), Name);
927 LoadInst *CreateLoad(Value *Ptr, bool isVolatile, const Twine &Name = "") {
928 return Insert(new LoadInst(Ptr, nullptr, isVolatile), Name);
930 StoreInst *CreateStore(Value *Val, Value *Ptr, bool isVolatile = false) {
931 return Insert(new StoreInst(Val, Ptr, isVolatile));
933 // \brief Provided to resolve 'CreateAlignedLoad(Ptr, Align, "...")'
934 // correctly, instead of converting the string to 'bool' for the isVolatile
936 LoadInst *CreateAlignedLoad(Value *Ptr, unsigned Align, const char *Name) {
937 LoadInst *LI = CreateLoad(Ptr, Name);
938 LI->setAlignment(Align);
941 LoadInst *CreateAlignedLoad(Value *Ptr, unsigned Align,
942 const Twine &Name = "") {
943 LoadInst *LI = CreateLoad(Ptr, Name);
944 LI->setAlignment(Align);
947 LoadInst *CreateAlignedLoad(Value *Ptr, unsigned Align, bool isVolatile,
948 const Twine &Name = "") {
949 LoadInst *LI = CreateLoad(Ptr, isVolatile, Name);
950 LI->setAlignment(Align);
953 StoreInst *CreateAlignedStore(Value *Val, Value *Ptr, unsigned Align,
954 bool isVolatile = false) {
955 StoreInst *SI = CreateStore(Val, Ptr, isVolatile);
956 SI->setAlignment(Align);
959 FenceInst *CreateFence(AtomicOrdering Ordering,
960 SynchronizationScope SynchScope = CrossThread,
961 const Twine &Name = "") {
962 return Insert(new FenceInst(Context, Ordering, SynchScope), Name);
965 CreateAtomicCmpXchg(Value *Ptr, Value *Cmp, Value *New,
966 AtomicOrdering SuccessOrdering,
967 AtomicOrdering FailureOrdering,
968 SynchronizationScope SynchScope = CrossThread) {
969 return Insert(new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering,
970 FailureOrdering, SynchScope));
972 AtomicRMWInst *CreateAtomicRMW(AtomicRMWInst::BinOp Op, Value *Ptr, Value *Val,
973 AtomicOrdering Ordering,
974 SynchronizationScope SynchScope = CrossThread) {
975 return Insert(new AtomicRMWInst(Op, Ptr, Val, Ordering, SynchScope));
977 Value *CreateGEP(Value *Ptr, ArrayRef<Value *> IdxList,
978 const Twine &Name = "") {
979 if (Constant *PC = dyn_cast<Constant>(Ptr)) {
980 // Every index must be constant.
982 for (i = 0, e = IdxList.size(); i != e; ++i)
983 if (!isa<Constant>(IdxList[i]))
986 return Insert(Folder.CreateGetElementPtr(PC, IdxList), Name);
988 return Insert(GetElementPtrInst::Create(Ptr, IdxList), Name);
990 Value *CreateInBoundsGEP(Value *Ptr, ArrayRef<Value *> IdxList,
991 const Twine &Name = "") {
992 if (Constant *PC = dyn_cast<Constant>(Ptr)) {
993 // Every index must be constant.
995 for (i = 0, e = IdxList.size(); i != e; ++i)
996 if (!isa<Constant>(IdxList[i]))
999 return Insert(Folder.CreateInBoundsGetElementPtr(PC, IdxList), Name);
1001 return Insert(GetElementPtrInst::CreateInBounds(Ptr, IdxList), Name);
1003 Value *CreateGEP(Value *Ptr, Value *Idx, const Twine &Name = "") {
1004 if (Constant *PC = dyn_cast<Constant>(Ptr))
1005 if (Constant *IC = dyn_cast<Constant>(Idx))
1006 return Insert(Folder.CreateGetElementPtr(PC, IC), Name);
1007 return Insert(GetElementPtrInst::Create(Ptr, Idx), Name);
1009 Value *CreateInBoundsGEP(Value *Ptr, Value *Idx, const Twine &Name = "") {
1010 if (Constant *PC = dyn_cast<Constant>(Ptr))
1011 if (Constant *IC = dyn_cast<Constant>(Idx))
1012 return Insert(Folder.CreateInBoundsGetElementPtr(PC, IC), Name);
1013 return Insert(GetElementPtrInst::CreateInBounds(Ptr, Idx), Name);
1015 Value *CreateConstGEP1_32(Value *Ptr, unsigned Idx0, const Twine &Name = "") {
1016 Value *Idx = ConstantInt::get(Type::getInt32Ty(Context), Idx0);
1018 if (Constant *PC = dyn_cast<Constant>(Ptr))
1019 return Insert(Folder.CreateGetElementPtr(PC, Idx), Name);
1021 return Insert(GetElementPtrInst::Create(Ptr, Idx), Name);
1023 Value *CreateConstInBoundsGEP1_32(Value *Ptr, unsigned Idx0,
1024 const Twine &Name = "") {
1025 Value *Idx = ConstantInt::get(Type::getInt32Ty(Context), Idx0);
1027 if (Constant *PC = dyn_cast<Constant>(Ptr))
1028 return Insert(Folder.CreateInBoundsGetElementPtr(PC, Idx), Name);
1030 return Insert(GetElementPtrInst::CreateInBounds(Ptr, Idx), Name);
1032 Value *CreateConstGEP2_32(Value *Ptr, unsigned Idx0, unsigned Idx1,
1033 const Twine &Name = "") {
1035 ConstantInt::get(Type::getInt32Ty(Context), Idx0),
1036 ConstantInt::get(Type::getInt32Ty(Context), Idx1)
1039 if (Constant *PC = dyn_cast<Constant>(Ptr))
1040 return Insert(Folder.CreateGetElementPtr(PC, Idxs), Name);
1042 return Insert(GetElementPtrInst::Create(Ptr, Idxs), Name);
1044 Value *CreateConstInBoundsGEP2_32(Value *Ptr, unsigned Idx0, unsigned Idx1,
1045 const Twine &Name = "") {
1047 ConstantInt::get(Type::getInt32Ty(Context), Idx0),
1048 ConstantInt::get(Type::getInt32Ty(Context), Idx1)
1051 if (Constant *PC = dyn_cast<Constant>(Ptr))
1052 return Insert(Folder.CreateInBoundsGetElementPtr(PC, Idxs), Name);
1054 return Insert(GetElementPtrInst::CreateInBounds(Ptr, Idxs), Name);
1056 Value *CreateConstGEP1_64(Value *Ptr, uint64_t Idx0, const Twine &Name = "") {
1057 Value *Idx = ConstantInt::get(Type::getInt64Ty(Context), Idx0);
1059 if (Constant *PC = dyn_cast<Constant>(Ptr))
1060 return Insert(Folder.CreateGetElementPtr(PC, Idx), Name);
1062 return Insert(GetElementPtrInst::Create(Ptr, Idx), Name);
1064 Value *CreateConstInBoundsGEP1_64(Value *Ptr, uint64_t Idx0,
1065 const Twine &Name = "") {
1066 Value *Idx = ConstantInt::get(Type::getInt64Ty(Context), Idx0);
1068 if (Constant *PC = dyn_cast<Constant>(Ptr))
1069 return Insert(Folder.CreateInBoundsGetElementPtr(PC, Idx), Name);
1071 return Insert(GetElementPtrInst::CreateInBounds(Ptr, Idx), Name);
1073 Value *CreateConstGEP2_64(Value *Ptr, uint64_t Idx0, uint64_t Idx1,
1074 const Twine &Name = "") {
1076 ConstantInt::get(Type::getInt64Ty(Context), Idx0),
1077 ConstantInt::get(Type::getInt64Ty(Context), Idx1)
1080 if (Constant *PC = dyn_cast<Constant>(Ptr))
1081 return Insert(Folder.CreateGetElementPtr(PC, Idxs), Name);
1083 return Insert(GetElementPtrInst::Create(Ptr, Idxs), Name);
1085 Value *CreateConstInBoundsGEP2_64(Value *Ptr, uint64_t Idx0, uint64_t Idx1,
1086 const Twine &Name = "") {
1088 ConstantInt::get(Type::getInt64Ty(Context), Idx0),
1089 ConstantInt::get(Type::getInt64Ty(Context), Idx1)
1092 if (Constant *PC = dyn_cast<Constant>(Ptr))
1093 return Insert(Folder.CreateInBoundsGetElementPtr(PC, Idxs), Name);
1095 return Insert(GetElementPtrInst::CreateInBounds(Ptr, Idxs), Name);
1097 Value *CreateStructGEP(Value *Ptr, unsigned Idx, const Twine &Name = "") {
1098 return CreateConstInBoundsGEP2_32(Ptr, 0, Idx, Name);
1101 /// \brief Same as CreateGlobalString, but return a pointer with "i8*" type
1102 /// instead of a pointer to array of i8.
1103 Value *CreateGlobalStringPtr(StringRef Str, const Twine &Name = "") {
1104 Value *gv = CreateGlobalString(Str, Name);
1105 Value *zero = ConstantInt::get(Type::getInt32Ty(Context), 0);
1106 Value *Args[] = { zero, zero };
1107 return CreateInBoundsGEP(gv, Args, Name);
1110 //===--------------------------------------------------------------------===//
1111 // Instruction creation methods: Cast/Conversion Operators
1112 //===--------------------------------------------------------------------===//
1114 Value *CreateTrunc(Value *V, Type *DestTy, const Twine &Name = "") {
1115 return CreateCast(Instruction::Trunc, V, DestTy, Name);
1117 Value *CreateZExt(Value *V, Type *DestTy, const Twine &Name = "") {
1118 return CreateCast(Instruction::ZExt, V, DestTy, Name);
1120 Value *CreateSExt(Value *V, Type *DestTy, const Twine &Name = "") {
1121 return CreateCast(Instruction::SExt, V, DestTy, Name);
1123 /// \brief Create a ZExt or Trunc from the integer value V to DestTy. Return
1124 /// the value untouched if the type of V is already DestTy.
1125 Value *CreateZExtOrTrunc(Value *V, Type *DestTy,
1126 const Twine &Name = "") {
1127 assert(V->getType()->isIntOrIntVectorTy() &&
1128 DestTy->isIntOrIntVectorTy() &&
1129 "Can only zero extend/truncate integers!");
1130 Type *VTy = V->getType();
1131 if (VTy->getScalarSizeInBits() < DestTy->getScalarSizeInBits())
1132 return CreateZExt(V, DestTy, Name);
1133 if (VTy->getScalarSizeInBits() > DestTy->getScalarSizeInBits())
1134 return CreateTrunc(V, DestTy, Name);
1137 /// \brief Create a SExt or Trunc from the integer value V to DestTy. Return
1138 /// the value untouched if the type of V is already DestTy.
1139 Value *CreateSExtOrTrunc(Value *V, Type *DestTy,
1140 const Twine &Name = "") {
1141 assert(V->getType()->isIntOrIntVectorTy() &&
1142 DestTy->isIntOrIntVectorTy() &&
1143 "Can only sign extend/truncate integers!");
1144 Type *VTy = V->getType();
1145 if (VTy->getScalarSizeInBits() < DestTy->getScalarSizeInBits())
1146 return CreateSExt(V, DestTy, Name);
1147 if (VTy->getScalarSizeInBits() > DestTy->getScalarSizeInBits())
1148 return CreateTrunc(V, DestTy, Name);
1151 Value *CreateFPToUI(Value *V, Type *DestTy, const Twine &Name = ""){
1152 return CreateCast(Instruction::FPToUI, V, DestTy, Name);
1154 Value *CreateFPToSI(Value *V, Type *DestTy, const Twine &Name = ""){
1155 return CreateCast(Instruction::FPToSI, V, DestTy, Name);
1157 Value *CreateUIToFP(Value *V, Type *DestTy, const Twine &Name = ""){
1158 return CreateCast(Instruction::UIToFP, V, DestTy, Name);
1160 Value *CreateSIToFP(Value *V, Type *DestTy, const Twine &Name = ""){
1161 return CreateCast(Instruction::SIToFP, V, DestTy, Name);
1163 Value *CreateFPTrunc(Value *V, Type *DestTy,
1164 const Twine &Name = "") {
1165 return CreateCast(Instruction::FPTrunc, V, DestTy, Name);
1167 Value *CreateFPExt(Value *V, Type *DestTy, const Twine &Name = "") {
1168 return CreateCast(Instruction::FPExt, V, DestTy, Name);
1170 Value *CreatePtrToInt(Value *V, Type *DestTy,
1171 const Twine &Name = "") {
1172 return CreateCast(Instruction::PtrToInt, V, DestTy, Name);
1174 Value *CreateIntToPtr(Value *V, Type *DestTy,
1175 const Twine &Name = "") {
1176 return CreateCast(Instruction::IntToPtr, V, DestTy, Name);
1178 Value *CreateBitCast(Value *V, Type *DestTy,
1179 const Twine &Name = "") {
1180 return CreateCast(Instruction::BitCast, V, DestTy, Name);
1182 Value *CreateAddrSpaceCast(Value *V, Type *DestTy,
1183 const Twine &Name = "") {
1184 return CreateCast(Instruction::AddrSpaceCast, V, DestTy, Name);
1186 Value *CreateZExtOrBitCast(Value *V, Type *DestTy,
1187 const Twine &Name = "") {
1188 if (V->getType() == DestTy)
1190 if (Constant *VC = dyn_cast<Constant>(V))
1191 return Insert(Folder.CreateZExtOrBitCast(VC, DestTy), Name);
1192 return Insert(CastInst::CreateZExtOrBitCast(V, DestTy), Name);
1194 Value *CreateSExtOrBitCast(Value *V, Type *DestTy,
1195 const Twine &Name = "") {
1196 if (V->getType() == DestTy)
1198 if (Constant *VC = dyn_cast<Constant>(V))
1199 return Insert(Folder.CreateSExtOrBitCast(VC, DestTy), Name);
1200 return Insert(CastInst::CreateSExtOrBitCast(V, DestTy), Name);
1202 Value *CreateTruncOrBitCast(Value *V, Type *DestTy,
1203 const Twine &Name = "") {
1204 if (V->getType() == DestTy)
1206 if (Constant *VC = dyn_cast<Constant>(V))
1207 return Insert(Folder.CreateTruncOrBitCast(VC, DestTy), Name);
1208 return Insert(CastInst::CreateTruncOrBitCast(V, DestTy), Name);
1210 Value *CreateCast(Instruction::CastOps Op, Value *V, Type *DestTy,
1211 const Twine &Name = "") {
1212 if (V->getType() == DestTy)
1214 if (Constant *VC = dyn_cast<Constant>(V))
1215 return Insert(Folder.CreateCast(Op, VC, DestTy), Name);
1216 return Insert(CastInst::Create(Op, V, DestTy), Name);
1218 Value *CreatePointerCast(Value *V, Type *DestTy,
1219 const Twine &Name = "") {
1220 if (V->getType() == DestTy)
1222 if (Constant *VC = dyn_cast<Constant>(V))
1223 return Insert(Folder.CreatePointerCast(VC, DestTy), Name);
1224 return Insert(CastInst::CreatePointerCast(V, DestTy), Name);
1227 Value *CreatePointerBitCastOrAddrSpaceCast(Value *V, Type *DestTy,
1228 const Twine &Name = "") {
1229 if (V->getType() == DestTy)
1232 if (Constant *VC = dyn_cast<Constant>(V)) {
1233 return Insert(Folder.CreatePointerBitCastOrAddrSpaceCast(VC, DestTy),
1237 return Insert(CastInst::CreatePointerBitCastOrAddrSpaceCast(V, DestTy),
1241 Value *CreateIntCast(Value *V, Type *DestTy, bool isSigned,
1242 const Twine &Name = "") {
1243 if (V->getType() == DestTy)
1245 if (Constant *VC = dyn_cast<Constant>(V))
1246 return Insert(Folder.CreateIntCast(VC, DestTy, isSigned), Name);
1247 return Insert(CastInst::CreateIntegerCast(V, DestTy, isSigned), Name);
1250 // \brief Provided to resolve 'CreateIntCast(Ptr, Ptr, "...")', giving a
1251 // compile time error, instead of converting the string to bool for the
1252 // isSigned parameter.
1253 Value *CreateIntCast(Value *, Type *, const char *) LLVM_DELETED_FUNCTION;
1255 Value *CreateFPCast(Value *V, Type *DestTy, const Twine &Name = "") {
1256 if (V->getType() == DestTy)
1258 if (Constant *VC = dyn_cast<Constant>(V))
1259 return Insert(Folder.CreateFPCast(VC, DestTy), Name);
1260 return Insert(CastInst::CreateFPCast(V, DestTy), Name);
1263 //===--------------------------------------------------------------------===//
1264 // Instruction creation methods: Compare Instructions
1265 //===--------------------------------------------------------------------===//
1267 Value *CreateICmpEQ(Value *LHS, Value *RHS, const Twine &Name = "") {
1268 return CreateICmp(ICmpInst::ICMP_EQ, LHS, RHS, Name);
1270 Value *CreateICmpNE(Value *LHS, Value *RHS, const Twine &Name = "") {
1271 return CreateICmp(ICmpInst::ICMP_NE, LHS, RHS, Name);
1273 Value *CreateICmpUGT(Value *LHS, Value *RHS, const Twine &Name = "") {
1274 return CreateICmp(ICmpInst::ICMP_UGT, LHS, RHS, Name);
1276 Value *CreateICmpUGE(Value *LHS, Value *RHS, const Twine &Name = "") {
1277 return CreateICmp(ICmpInst::ICMP_UGE, LHS, RHS, Name);
1279 Value *CreateICmpULT(Value *LHS, Value *RHS, const Twine &Name = "") {
1280 return CreateICmp(ICmpInst::ICMP_ULT, LHS, RHS, Name);
1282 Value *CreateICmpULE(Value *LHS, Value *RHS, const Twine &Name = "") {
1283 return CreateICmp(ICmpInst::ICMP_ULE, LHS, RHS, Name);
1285 Value *CreateICmpSGT(Value *LHS, Value *RHS, const Twine &Name = "") {
1286 return CreateICmp(ICmpInst::ICMP_SGT, LHS, RHS, Name);
1288 Value *CreateICmpSGE(Value *LHS, Value *RHS, const Twine &Name = "") {
1289 return CreateICmp(ICmpInst::ICMP_SGE, LHS, RHS, Name);
1291 Value *CreateICmpSLT(Value *LHS, Value *RHS, const Twine &Name = "") {
1292 return CreateICmp(ICmpInst::ICMP_SLT, LHS, RHS, Name);
1294 Value *CreateICmpSLE(Value *LHS, Value *RHS, const Twine &Name = "") {
1295 return CreateICmp(ICmpInst::ICMP_SLE, LHS, RHS, Name);
1298 Value *CreateFCmpOEQ(Value *LHS, Value *RHS, const Twine &Name = "") {
1299 return CreateFCmp(FCmpInst::FCMP_OEQ, LHS, RHS, Name);
1301 Value *CreateFCmpOGT(Value *LHS, Value *RHS, const Twine &Name = "") {
1302 return CreateFCmp(FCmpInst::FCMP_OGT, LHS, RHS, Name);
1304 Value *CreateFCmpOGE(Value *LHS, Value *RHS, const Twine &Name = "") {
1305 return CreateFCmp(FCmpInst::FCMP_OGE, LHS, RHS, Name);
1307 Value *CreateFCmpOLT(Value *LHS, Value *RHS, const Twine &Name = "") {
1308 return CreateFCmp(FCmpInst::FCMP_OLT, LHS, RHS, Name);
1310 Value *CreateFCmpOLE(Value *LHS, Value *RHS, const Twine &Name = "") {
1311 return CreateFCmp(FCmpInst::FCMP_OLE, LHS, RHS, Name);
1313 Value *CreateFCmpONE(Value *LHS, Value *RHS, const Twine &Name = "") {
1314 return CreateFCmp(FCmpInst::FCMP_ONE, LHS, RHS, Name);
1316 Value *CreateFCmpORD(Value *LHS, Value *RHS, const Twine &Name = "") {
1317 return CreateFCmp(FCmpInst::FCMP_ORD, LHS, RHS, Name);
1319 Value *CreateFCmpUNO(Value *LHS, Value *RHS, const Twine &Name = "") {
1320 return CreateFCmp(FCmpInst::FCMP_UNO, LHS, RHS, Name);
1322 Value *CreateFCmpUEQ(Value *LHS, Value *RHS, const Twine &Name = "") {
1323 return CreateFCmp(FCmpInst::FCMP_UEQ, LHS, RHS, Name);
1325 Value *CreateFCmpUGT(Value *LHS, Value *RHS, const Twine &Name = "") {
1326 return CreateFCmp(FCmpInst::FCMP_UGT, LHS, RHS, Name);
1328 Value *CreateFCmpUGE(Value *LHS, Value *RHS, const Twine &Name = "") {
1329 return CreateFCmp(FCmpInst::FCMP_UGE, LHS, RHS, Name);
1331 Value *CreateFCmpULT(Value *LHS, Value *RHS, const Twine &Name = "") {
1332 return CreateFCmp(FCmpInst::FCMP_ULT, LHS, RHS, Name);
1334 Value *CreateFCmpULE(Value *LHS, Value *RHS, const Twine &Name = "") {
1335 return CreateFCmp(FCmpInst::FCMP_ULE, LHS, RHS, Name);
1337 Value *CreateFCmpUNE(Value *LHS, Value *RHS, const Twine &Name = "") {
1338 return CreateFCmp(FCmpInst::FCMP_UNE, LHS, RHS, Name);
1341 Value *CreateICmp(CmpInst::Predicate P, Value *LHS, Value *RHS,
1342 const Twine &Name = "") {
1343 if (Constant *LC = dyn_cast<Constant>(LHS))
1344 if (Constant *RC = dyn_cast<Constant>(RHS))
1345 return Insert(Folder.CreateICmp(P, LC, RC), Name);
1346 return Insert(new ICmpInst(P, LHS, RHS), Name);
1348 Value *CreateFCmp(CmpInst::Predicate P, Value *LHS, Value *RHS,
1349 const Twine &Name = "") {
1350 if (Constant *LC = dyn_cast<Constant>(LHS))
1351 if (Constant *RC = dyn_cast<Constant>(RHS))
1352 return Insert(Folder.CreateFCmp(P, LC, RC), Name);
1353 return Insert(new FCmpInst(P, LHS, RHS), Name);
1356 //===--------------------------------------------------------------------===//
1357 // Instruction creation methods: Other Instructions
1358 //===--------------------------------------------------------------------===//
1360 PHINode *CreatePHI(Type *Ty, unsigned NumReservedValues,
1361 const Twine &Name = "") {
1362 return Insert(PHINode::Create(Ty, NumReservedValues), Name);
1365 CallInst *CreateCall(Value *Callee, const Twine &Name = "") {
1366 return Insert(CallInst::Create(Callee), Name);
1368 CallInst *CreateCall(Value *Callee, Value *Arg, const Twine &Name = "") {
1369 return Insert(CallInst::Create(Callee, Arg), Name);
1371 CallInst *CreateCall2(Value *Callee, Value *Arg1, Value *Arg2,
1372 const Twine &Name = "") {
1373 Value *Args[] = { Arg1, Arg2 };
1374 return Insert(CallInst::Create(Callee, Args), Name);
1376 CallInst *CreateCall3(Value *Callee, Value *Arg1, Value *Arg2, Value *Arg3,
1377 const Twine &Name = "") {
1378 Value *Args[] = { Arg1, Arg2, Arg3 };
1379 return Insert(CallInst::Create(Callee, Args), Name);
1381 CallInst *CreateCall4(Value *Callee, Value *Arg1, Value *Arg2, Value *Arg3,
1382 Value *Arg4, const Twine &Name = "") {
1383 Value *Args[] = { Arg1, Arg2, Arg3, Arg4 };
1384 return Insert(CallInst::Create(Callee, Args), Name);
1386 CallInst *CreateCall5(Value *Callee, Value *Arg1, Value *Arg2, Value *Arg3,
1387 Value *Arg4, Value *Arg5, const Twine &Name = "") {
1388 Value *Args[] = { Arg1, Arg2, Arg3, Arg4, Arg5 };
1389 return Insert(CallInst::Create(Callee, Args), Name);
1392 CallInst *CreateCall(Value *Callee, ArrayRef<Value *> Args,
1393 const Twine &Name = "") {
1394 return Insert(CallInst::Create(Callee, Args), Name);
1397 Value *CreateSelect(Value *C, Value *True, Value *False,
1398 const Twine &Name = "") {
1399 if (Constant *CC = dyn_cast<Constant>(C))
1400 if (Constant *TC = dyn_cast<Constant>(True))
1401 if (Constant *FC = dyn_cast<Constant>(False))
1402 return Insert(Folder.CreateSelect(CC, TC, FC), Name);
1403 return Insert(SelectInst::Create(C, True, False), Name);
1406 VAArgInst *CreateVAArg(Value *List, Type *Ty, const Twine &Name = "") {
1407 return Insert(new VAArgInst(List, Ty), Name);
1410 Value *CreateExtractElement(Value *Vec, Value *Idx,
1411 const Twine &Name = "") {
1412 if (Constant *VC = dyn_cast<Constant>(Vec))
1413 if (Constant *IC = dyn_cast<Constant>(Idx))
1414 return Insert(Folder.CreateExtractElement(VC, IC), Name);
1415 return Insert(ExtractElementInst::Create(Vec, Idx), Name);
1418 Value *CreateInsertElement(Value *Vec, Value *NewElt, Value *Idx,
1419 const Twine &Name = "") {
1420 if (Constant *VC = dyn_cast<Constant>(Vec))
1421 if (Constant *NC = dyn_cast<Constant>(NewElt))
1422 if (Constant *IC = dyn_cast<Constant>(Idx))
1423 return Insert(Folder.CreateInsertElement(VC, NC, IC), Name);
1424 return Insert(InsertElementInst::Create(Vec, NewElt, Idx), Name);
1427 Value *CreateShuffleVector(Value *V1, Value *V2, Value *Mask,
1428 const Twine &Name = "") {
1429 if (Constant *V1C = dyn_cast<Constant>(V1))
1430 if (Constant *V2C = dyn_cast<Constant>(V2))
1431 if (Constant *MC = dyn_cast<Constant>(Mask))
1432 return Insert(Folder.CreateShuffleVector(V1C, V2C, MC), Name);
1433 return Insert(new ShuffleVectorInst(V1, V2, Mask), Name);
1436 Value *CreateExtractValue(Value *Agg,
1437 ArrayRef<unsigned> Idxs,
1438 const Twine &Name = "") {
1439 if (Constant *AggC = dyn_cast<Constant>(Agg))
1440 return Insert(Folder.CreateExtractValue(AggC, Idxs), Name);
1441 return Insert(ExtractValueInst::Create(Agg, Idxs), Name);
1444 Value *CreateInsertValue(Value *Agg, Value *Val,
1445 ArrayRef<unsigned> Idxs,
1446 const Twine &Name = "") {
1447 if (Constant *AggC = dyn_cast<Constant>(Agg))
1448 if (Constant *ValC = dyn_cast<Constant>(Val))
1449 return Insert(Folder.CreateInsertValue(AggC, ValC, Idxs), Name);
1450 return Insert(InsertValueInst::Create(Agg, Val, Idxs), Name);
1453 LandingPadInst *CreateLandingPad(Type *Ty, Value *PersFn, unsigned NumClauses,
1454 const Twine &Name = "") {
1455 return Insert(LandingPadInst::Create(Ty, PersFn, NumClauses), Name);
1458 //===--------------------------------------------------------------------===//
1459 // Utility creation methods
1460 //===--------------------------------------------------------------------===//
1462 /// \brief Return an i1 value testing if \p Arg is null.
1463 Value *CreateIsNull(Value *Arg, const Twine &Name = "") {
1464 return CreateICmpEQ(Arg, Constant::getNullValue(Arg->getType()),
1468 /// \brief Return an i1 value testing if \p Arg is not null.
1469 Value *CreateIsNotNull(Value *Arg, const Twine &Name = "") {
1470 return CreateICmpNE(Arg, Constant::getNullValue(Arg->getType()),
1474 /// \brief Return the i64 difference between two pointer values, dividing out
1475 /// the size of the pointed-to objects.
1477 /// This is intended to implement C-style pointer subtraction. As such, the
1478 /// pointers must be appropriately aligned for their element types and
1479 /// pointing into the same object.
1480 Value *CreatePtrDiff(Value *LHS, Value *RHS, const Twine &Name = "") {
1481 assert(LHS->getType() == RHS->getType() &&
1482 "Pointer subtraction operand types must match!");
1483 PointerType *ArgType = cast<PointerType>(LHS->getType());
1484 Value *LHS_int = CreatePtrToInt(LHS, Type::getInt64Ty(Context));
1485 Value *RHS_int = CreatePtrToInt(RHS, Type::getInt64Ty(Context));
1486 Value *Difference = CreateSub(LHS_int, RHS_int);
1487 return CreateExactSDiv(Difference,
1488 ConstantExpr::getSizeOf(ArgType->getElementType()),
1492 /// \brief Return a vector value that contains \arg V broadcasted to \p
1493 /// NumElts elements.
1494 Value *CreateVectorSplat(unsigned NumElts, Value *V, const Twine &Name = "") {
1495 assert(NumElts > 0 && "Cannot splat to an empty vector!");
1497 // First insert it into an undef vector so we can shuffle it.
1498 Type *I32Ty = getInt32Ty();
1499 Value *Undef = UndefValue::get(VectorType::get(V->getType(), NumElts));
1500 V = CreateInsertElement(Undef, V, ConstantInt::get(I32Ty, 0),
1501 Name + ".splatinsert");
1503 // Shuffle the value across the desired number of elements.
1504 Value *Zeros = ConstantAggregateZero::get(VectorType::get(I32Ty, NumElts));
1505 return CreateShuffleVector(V, Undef, Zeros, Name + ".splat");
1508 /// \brief Return a value that has been extracted from a larger integer type.
1509 Value *CreateExtractInteger(const DataLayout &DL, Value *From,
1510 IntegerType *ExtractedTy, uint64_t Offset,
1511 const Twine &Name) {
1512 IntegerType *IntTy = cast<IntegerType>(From->getType());
1513 assert(DL.getTypeStoreSize(ExtractedTy) + Offset <=
1514 DL.getTypeStoreSize(IntTy) &&
1515 "Element extends past full value");
1516 uint64_t ShAmt = 8 * Offset;
1518 if (DL.isBigEndian())
1519 ShAmt = 8 * (DL.getTypeStoreSize(IntTy) -
1520 DL.getTypeStoreSize(ExtractedTy) - Offset);
1522 V = CreateLShr(V, ShAmt, Name + ".shift");
1524 assert(ExtractedTy->getBitWidth() <= IntTy->getBitWidth() &&
1525 "Cannot extract to a larger integer!");
1526 if (ExtractedTy != IntTy) {
1527 V = CreateTrunc(V, ExtractedTy, Name + ".trunc");
1532 /// \brief Create an assume intrinsic call that represents an alignment
1533 /// assumption on the provided pointer.
1535 /// An optional offset can be provided, and if it is provided, the offset
1536 /// must be subtracted from the provided pointer to get the pointer with the
1537 /// specified alignment.
1538 CallInst *CreateAlignmentAssumption(const DataLayout &DL, Value *PtrValue,
1540 Value *OffsetValue = nullptr) {
1541 assert(isa<PointerType>(PtrValue->getType()) &&
1542 "trying to create an alignment assumption on a non-pointer?");
1544 PointerType *PtrTy = cast<PointerType>(PtrValue->getType());
1545 Type *IntPtrTy = getIntPtrTy(&DL, PtrTy->getAddressSpace());
1546 Value *PtrIntValue = CreatePtrToInt(PtrValue, IntPtrTy, "ptrint");
1548 Value *Mask = ConstantInt::get(IntPtrTy,
1549 Alignment > 0 ? Alignment - 1 : 0);
1551 bool IsOffsetZero = false;
1552 if (ConstantInt *CI = dyn_cast<ConstantInt>(OffsetValue))
1553 IsOffsetZero = CI->isZero();
1555 if (!IsOffsetZero) {
1556 if (OffsetValue->getType() != IntPtrTy)
1557 OffsetValue = CreateIntCast(OffsetValue, IntPtrTy, /*isSigned*/ true,
1559 PtrIntValue = CreateSub(PtrIntValue, OffsetValue, "offsetptr");
1563 Value *Zero = ConstantInt::get(IntPtrTy, 0);
1564 Value *MaskedPtr = CreateAnd(PtrIntValue, Mask, "maskedptr");
1565 Value *InvCond = CreateICmpEQ(MaskedPtr, Zero, "maskcond");
1567 return CreateAssumption(InvCond);
1571 // Create wrappers for C Binding types (see CBindingWrapping.h).
1572 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(IRBuilder<>, LLVMBuilderRef)