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/None.h"
20 #include "llvm/ADT/StringRef.h"
21 #include "llvm/ADT/Twine.h"
22 #include "llvm/IR/BasicBlock.h"
23 #include "llvm/IR/Constant.h"
24 #include "llvm/IR/ConstantFolder.h"
25 #include "llvm/IR/Constants.h"
26 #include "llvm/IR/DataLayout.h"
27 #include "llvm/IR/DebugLoc.h"
28 #include "llvm/IR/DerivedTypes.h"
29 #include "llvm/IR/Function.h"
30 #include "llvm/IR/GlobalVariable.h"
31 #include "llvm/IR/InstrTypes.h"
32 #include "llvm/IR/Instruction.h"
33 #include "llvm/IR/Instructions.h"
34 #include "llvm/IR/Intrinsics.h"
35 #include "llvm/IR/LLVMContext.h"
36 #include "llvm/IR/Module.h"
37 #include "llvm/IR/Operator.h"
38 #include "llvm/IR/Type.h"
39 #include "llvm/IR/Value.h"
40 #include "llvm/IR/ValueHandle.h"
41 #include "llvm/Support/AtomicOrdering.h"
42 #include "llvm/Support/CBindingWrapping.h"
43 #include "llvm/Support/Casting.h"
44 #include "llvm-c/Types.h"
58 /// \brief This provides the default implementation of the IRBuilder
59 /// 'InsertHelper' method that is called whenever an instruction is created by
60 /// IRBuilder and needs to be inserted.
62 /// By default, this inserts the instruction at the insertion point.
63 class IRBuilderDefaultInserter {
65 void InsertHelper(Instruction *I, const Twine &Name,
66 BasicBlock *BB, BasicBlock::iterator InsertPt) const {
67 if (BB) BB->getInstList().insert(InsertPt, I);
72 /// Provides an 'InsertHelper' that calls a user-provided callback after
73 /// performing the default insertion.
74 class IRBuilderCallbackInserter : IRBuilderDefaultInserter {
75 std::function<void(Instruction *)> Callback;
78 IRBuilderCallbackInserter(std::function<void(Instruction *)> Callback)
79 : Callback(std::move(Callback)) {}
82 void InsertHelper(Instruction *I, const Twine &Name,
83 BasicBlock *BB, BasicBlock::iterator InsertPt) const {
84 IRBuilderDefaultInserter::InsertHelper(I, Name, BB, InsertPt);
89 /// \brief Common base class shared among various IRBuilders.
91 DebugLoc CurDbgLocation;
95 BasicBlock::iterator InsertPt;
98 MDNode *DefaultFPMathTag;
101 ArrayRef<OperandBundleDef> DefaultOperandBundles;
104 IRBuilderBase(LLVMContext &context, MDNode *FPMathTag = nullptr,
105 ArrayRef<OperandBundleDef> OpBundles = None)
106 : Context(context), DefaultFPMathTag(FPMathTag),
107 DefaultOperandBundles(OpBundles) {
108 ClearInsertionPoint();
111 //===--------------------------------------------------------------------===//
112 // Builder configuration methods
113 //===--------------------------------------------------------------------===//
115 /// \brief Clear the insertion point: created instructions will not be
116 /// inserted into a block.
117 void ClearInsertionPoint() {
119 InsertPt = BasicBlock::iterator();
122 BasicBlock *GetInsertBlock() const { return BB; }
123 BasicBlock::iterator GetInsertPoint() const { return InsertPt; }
124 LLVMContext &getContext() const { return Context; }
126 /// \brief This specifies that created instructions should be appended to the
127 /// end of the specified block.
128 void SetInsertPoint(BasicBlock *TheBB) {
130 InsertPt = BB->end();
133 /// \brief This specifies that created instructions should be inserted before
134 /// the specified instruction.
135 void SetInsertPoint(Instruction *I) {
137 InsertPt = I->getIterator();
138 assert(InsertPt != BB->end() && "Can't read debug loc from end()");
139 SetCurrentDebugLocation(I->getDebugLoc());
142 /// \brief This specifies that created instructions should be inserted at the
144 void SetInsertPoint(BasicBlock *TheBB, BasicBlock::iterator IP) {
147 if (IP != TheBB->end())
148 SetCurrentDebugLocation(IP->getDebugLoc());
151 /// \brief Set location information used by debugging information.
152 void SetCurrentDebugLocation(DebugLoc L) { CurDbgLocation = std::move(L); }
154 /// \brief Get location information used by debugging information.
155 const DebugLoc &getCurrentDebugLocation() const { return CurDbgLocation; }
157 /// \brief If this builder has a current debug location, set it on the
158 /// specified instruction.
159 void SetInstDebugLocation(Instruction *I) const {
161 I->setDebugLoc(CurDbgLocation);
164 /// \brief Get the return type of the current function that we're emitting
166 Type *getCurrentFunctionReturnType() const;
168 /// InsertPoint - A saved insertion point.
170 BasicBlock *Block = nullptr;
171 BasicBlock::iterator Point;
174 /// \brief Creates a new insertion point which doesn't point to anything.
175 InsertPoint() = default;
177 /// \brief Creates a new insertion point at the given location.
178 InsertPoint(BasicBlock *InsertBlock, BasicBlock::iterator InsertPoint)
179 : Block(InsertBlock), Point(InsertPoint) {}
181 /// \brief Returns true if this insert point is set.
182 bool isSet() const { return (Block != nullptr); }
184 BasicBlock *getBlock() const { return Block; }
185 BasicBlock::iterator getPoint() const { return Point; }
188 /// \brief Returns the current insert point.
189 InsertPoint saveIP() const {
190 return InsertPoint(GetInsertBlock(), GetInsertPoint());
193 /// \brief Returns the current insert point, clearing it in the process.
194 InsertPoint saveAndClearIP() {
195 InsertPoint IP(GetInsertBlock(), GetInsertPoint());
196 ClearInsertionPoint();
200 /// \brief Sets the current insert point to a previously-saved location.
201 void restoreIP(InsertPoint IP) {
203 SetInsertPoint(IP.getBlock(), IP.getPoint());
205 ClearInsertionPoint();
208 /// \brief Get the floating point math metadata being used.
209 MDNode *getDefaultFPMathTag() const { return DefaultFPMathTag; }
211 /// \brief Get the flags to be applied to created floating point ops
212 FastMathFlags getFastMathFlags() const { return FMF; }
214 /// \brief Clear the fast-math flags.
215 void clearFastMathFlags() { FMF.clear(); }
217 /// \brief Set the floating point math metadata to be used.
218 void setDefaultFPMathTag(MDNode *FPMathTag) { DefaultFPMathTag = FPMathTag; }
220 /// \brief Set the fast-math flags to be used with generated fp-math operators
221 void setFastMathFlags(FastMathFlags NewFMF) { FMF = NewFMF; }
223 //===--------------------------------------------------------------------===//
225 //===--------------------------------------------------------------------===//
227 // \brief RAII object that stores the current insertion point and restores it
228 // when the object is destroyed. This includes the debug location.
229 class InsertPointGuard {
230 IRBuilderBase &Builder;
231 AssertingVH<BasicBlock> Block;
232 BasicBlock::iterator Point;
236 InsertPointGuard(IRBuilderBase &B)
237 : Builder(B), Block(B.GetInsertBlock()), Point(B.GetInsertPoint()),
238 DbgLoc(B.getCurrentDebugLocation()) {}
240 InsertPointGuard(const InsertPointGuard &) = delete;
241 InsertPointGuard &operator=(const InsertPointGuard &) = delete;
243 ~InsertPointGuard() {
244 Builder.restoreIP(InsertPoint(Block, Point));
245 Builder.SetCurrentDebugLocation(DbgLoc);
249 // \brief RAII object that stores the current fast math settings and restores
250 // them when the object is destroyed.
251 class FastMathFlagGuard {
252 IRBuilderBase &Builder;
257 FastMathFlagGuard(IRBuilderBase &B)
258 : Builder(B), FMF(B.FMF), FPMathTag(B.DefaultFPMathTag) {}
260 FastMathFlagGuard(const FastMathFlagGuard &) = delete;
261 FastMathFlagGuard &operator=(const FastMathFlagGuard &) = delete;
263 ~FastMathFlagGuard() {
265 Builder.DefaultFPMathTag = FPMathTag;
269 //===--------------------------------------------------------------------===//
270 // Miscellaneous creation methods.
271 //===--------------------------------------------------------------------===//
273 /// \brief Make a new global variable with initializer type i8*
275 /// Make a new global variable with an initializer that has array of i8 type
276 /// filled in with the null terminated string value specified. The new global
277 /// variable will be marked mergable with any others of the same contents. If
278 /// Name is specified, it is the name of the global variable created.
279 GlobalVariable *CreateGlobalString(StringRef Str, const Twine &Name = "",
280 unsigned AddressSpace = 0);
282 /// \brief Get a constant value representing either true or false.
283 ConstantInt *getInt1(bool V) {
284 return ConstantInt::get(getInt1Ty(), V);
287 /// \brief Get the constant value for i1 true.
288 ConstantInt *getTrue() {
289 return ConstantInt::getTrue(Context);
292 /// \brief Get the constant value for i1 false.
293 ConstantInt *getFalse() {
294 return ConstantInt::getFalse(Context);
297 /// \brief Get a constant 8-bit value.
298 ConstantInt *getInt8(uint8_t C) {
299 return ConstantInt::get(getInt8Ty(), C);
302 /// \brief Get a constant 16-bit value.
303 ConstantInt *getInt16(uint16_t C) {
304 return ConstantInt::get(getInt16Ty(), C);
307 /// \brief Get a constant 32-bit value.
308 ConstantInt *getInt32(uint32_t C) {
309 return ConstantInt::get(getInt32Ty(), C);
312 /// \brief Get a constant 64-bit value.
313 ConstantInt *getInt64(uint64_t C) {
314 return ConstantInt::get(getInt64Ty(), C);
317 /// \brief Get a constant N-bit value, zero extended or truncated from
319 ConstantInt *getIntN(unsigned N, uint64_t C) {
320 return ConstantInt::get(getIntNTy(N), C);
323 /// \brief Get a constant integer value.
324 ConstantInt *getInt(const APInt &AI) {
325 return ConstantInt::get(Context, AI);
328 //===--------------------------------------------------------------------===//
329 // Type creation methods
330 //===--------------------------------------------------------------------===//
332 /// \brief Fetch the type representing a single bit
333 IntegerType *getInt1Ty() {
334 return Type::getInt1Ty(Context);
337 /// \brief Fetch the type representing an 8-bit integer.
338 IntegerType *getInt8Ty() {
339 return Type::getInt8Ty(Context);
342 /// \brief Fetch the type representing a 16-bit integer.
343 IntegerType *getInt16Ty() {
344 return Type::getInt16Ty(Context);
347 /// \brief Fetch the type representing a 32-bit integer.
348 IntegerType *getInt32Ty() {
349 return Type::getInt32Ty(Context);
352 /// \brief Fetch the type representing a 64-bit integer.
353 IntegerType *getInt64Ty() {
354 return Type::getInt64Ty(Context);
357 /// \brief Fetch the type representing a 128-bit integer.
358 IntegerType *getInt128Ty() { return Type::getInt128Ty(Context); }
360 /// \brief Fetch the type representing an N-bit integer.
361 IntegerType *getIntNTy(unsigned N) {
362 return Type::getIntNTy(Context, N);
365 /// \brief Fetch the type representing a 16-bit floating point value.
367 return Type::getHalfTy(Context);
370 /// \brief Fetch the type representing a 32-bit floating point value.
372 return Type::getFloatTy(Context);
375 /// \brief Fetch the type representing a 64-bit floating point value.
376 Type *getDoubleTy() {
377 return Type::getDoubleTy(Context);
380 /// \brief Fetch the type representing void.
382 return Type::getVoidTy(Context);
385 /// \brief Fetch the type representing a pointer to an 8-bit integer value.
386 PointerType *getInt8PtrTy(unsigned AddrSpace = 0) {
387 return Type::getInt8PtrTy(Context, AddrSpace);
390 /// \brief Fetch the type representing a pointer to an integer value.
391 IntegerType *getIntPtrTy(const DataLayout &DL, unsigned AddrSpace = 0) {
392 return DL.getIntPtrType(Context, AddrSpace);
395 //===--------------------------------------------------------------------===//
396 // Intrinsic creation methods
397 //===--------------------------------------------------------------------===//
399 /// \brief Create and insert a memset to the specified pointer and the
402 /// If the pointer isn't an i8*, it will be converted. If a TBAA tag is
403 /// specified, it will be added to the instruction. Likewise with alias.scope
404 /// and noalias tags.
405 CallInst *CreateMemSet(Value *Ptr, Value *Val, uint64_t Size, unsigned Align,
406 bool isVolatile = false, MDNode *TBAATag = nullptr,
407 MDNode *ScopeTag = nullptr,
408 MDNode *NoAliasTag = nullptr) {
409 return CreateMemSet(Ptr, Val, getInt64(Size), Align, isVolatile,
410 TBAATag, ScopeTag, NoAliasTag);
413 CallInst *CreateMemSet(Value *Ptr, Value *Val, Value *Size, unsigned Align,
414 bool isVolatile = false, MDNode *TBAATag = nullptr,
415 MDNode *ScopeTag = nullptr,
416 MDNode *NoAliasTag = nullptr);
418 /// \brief Create and insert a memcpy between the specified pointers.
420 /// If the pointers aren't i8*, they will be converted. If a TBAA tag is
421 /// specified, it will be added to the instruction. Likewise with alias.scope
422 /// and noalias tags.
423 CallInst *CreateMemCpy(Value *Dst, Value *Src, uint64_t Size, unsigned Align,
424 bool isVolatile = false, MDNode *TBAATag = nullptr,
425 MDNode *TBAAStructTag = nullptr,
426 MDNode *ScopeTag = nullptr,
427 MDNode *NoAliasTag = nullptr) {
428 return CreateMemCpy(Dst, Src, getInt64(Size), Align, isVolatile, TBAATag,
429 TBAAStructTag, ScopeTag, NoAliasTag);
432 CallInst *CreateMemCpy(Value *Dst, Value *Src, Value *Size, unsigned Align,
433 bool isVolatile = false, MDNode *TBAATag = nullptr,
434 MDNode *TBAAStructTag = nullptr,
435 MDNode *ScopeTag = nullptr,
436 MDNode *NoAliasTag = nullptr);
438 /// \brief Create and insert a memmove between the specified
441 /// If the pointers aren't i8*, they will be converted. If a TBAA tag is
442 /// specified, it will be added to the instruction. Likewise with alias.scope
443 /// and noalias tags.
444 CallInst *CreateMemMove(Value *Dst, Value *Src, uint64_t Size, unsigned Align,
445 bool isVolatile = false, MDNode *TBAATag = nullptr,
446 MDNode *ScopeTag = nullptr,
447 MDNode *NoAliasTag = nullptr) {
448 return CreateMemMove(Dst, Src, getInt64(Size), Align, isVolatile,
449 TBAATag, ScopeTag, NoAliasTag);
452 CallInst *CreateMemMove(Value *Dst, Value *Src, Value *Size, unsigned Align,
453 bool isVolatile = false, MDNode *TBAATag = nullptr,
454 MDNode *ScopeTag = nullptr,
455 MDNode *NoAliasTag = nullptr);
457 /// \brief Create a vector fadd reduction intrinsic of the source vector.
458 /// The first parameter is a scalar accumulator value for ordered reductions.
459 CallInst *CreateFAddReduce(Value *Acc, Value *Src);
461 /// \brief Create a vector fmul reduction intrinsic of the source vector.
462 /// The first parameter is a scalar accumulator value for ordered reductions.
463 CallInst *CreateFMulReduce(Value *Acc, Value *Src);
465 /// \brief Create a vector int add reduction intrinsic of the source vector.
466 CallInst *CreateAddReduce(Value *Src);
468 /// \brief Create a vector int mul reduction intrinsic of the source vector.
469 CallInst *CreateMulReduce(Value *Src);
471 /// \brief Create a vector int AND reduction intrinsic of the source vector.
472 CallInst *CreateAndReduce(Value *Src);
474 /// \brief Create a vector int OR reduction intrinsic of the source vector.
475 CallInst *CreateOrReduce(Value *Src);
477 /// \brief Create a vector int XOR reduction intrinsic of the source vector.
478 CallInst *CreateXorReduce(Value *Src);
480 /// \brief Create a vector integer max reduction intrinsic of the source
482 CallInst *CreateIntMaxReduce(Value *Src, bool IsSigned = false);
484 /// \brief Create a vector integer min reduction intrinsic of the source
486 CallInst *CreateIntMinReduce(Value *Src, bool IsSigned = false);
488 /// \brief Create a vector float max reduction intrinsic of the source
490 CallInst *CreateFPMaxReduce(Value *Src, bool NoNaN = false);
492 /// \brief Create a vector float min reduction intrinsic of the source
494 CallInst *CreateFPMinReduce(Value *Src, bool NoNaN = false);
496 /// \brief Create a lifetime.start intrinsic.
498 /// If the pointer isn't i8* it will be converted.
499 CallInst *CreateLifetimeStart(Value *Ptr, ConstantInt *Size = nullptr);
501 /// \brief Create a lifetime.end intrinsic.
503 /// If the pointer isn't i8* it will be converted.
504 CallInst *CreateLifetimeEnd(Value *Ptr, ConstantInt *Size = nullptr);
506 /// Create a call to invariant.start intrinsic.
508 /// If the pointer isn't i8* it will be converted.
509 CallInst *CreateInvariantStart(Value *Ptr, ConstantInt *Size = nullptr);
511 /// \brief Create a call to Masked Load intrinsic
512 CallInst *CreateMaskedLoad(Value *Ptr, unsigned Align, Value *Mask,
513 Value *PassThru = nullptr, const Twine &Name = "");
515 /// \brief Create a call to Masked Store intrinsic
516 CallInst *CreateMaskedStore(Value *Val, Value *Ptr, unsigned Align,
519 /// \brief Create a call to Masked Gather intrinsic
520 CallInst *CreateMaskedGather(Value *Ptrs, unsigned Align,
521 Value *Mask = nullptr,
522 Value *PassThru = nullptr,
523 const Twine& Name = "");
525 /// \brief Create a call to Masked Scatter intrinsic
526 CallInst *CreateMaskedScatter(Value *Val, Value *Ptrs, unsigned Align,
527 Value *Mask = nullptr);
529 /// \brief Create an assume intrinsic call that allows the optimizer to
530 /// assume that the provided condition will be true.
531 CallInst *CreateAssumption(Value *Cond);
533 /// \brief Create a call to the experimental.gc.statepoint intrinsic to
534 /// start a new statepoint sequence.
535 CallInst *CreateGCStatepointCall(uint64_t ID, uint32_t NumPatchBytes,
537 ArrayRef<Value *> CallArgs,
538 ArrayRef<Value *> DeoptArgs,
539 ArrayRef<Value *> GCArgs,
540 const Twine &Name = "");
542 /// \brief Create a call to the experimental.gc.statepoint intrinsic to
543 /// start a new statepoint sequence.
544 CallInst *CreateGCStatepointCall(uint64_t ID, uint32_t NumPatchBytes,
545 Value *ActualCallee, uint32_t Flags,
546 ArrayRef<Use> CallArgs,
547 ArrayRef<Use> TransitionArgs,
548 ArrayRef<Use> DeoptArgs,
549 ArrayRef<Value *> GCArgs,
550 const Twine &Name = "");
552 // \brief Conveninence function for the common case when CallArgs are filled
553 // in using makeArrayRef(CS.arg_begin(), CS.arg_end()); Use needs to be
554 // .get()'ed to get the Value pointer.
555 CallInst *CreateGCStatepointCall(uint64_t ID, uint32_t NumPatchBytes,
556 Value *ActualCallee, ArrayRef<Use> CallArgs,
557 ArrayRef<Value *> DeoptArgs,
558 ArrayRef<Value *> GCArgs,
559 const Twine &Name = "");
561 /// brief Create an invoke to the experimental.gc.statepoint intrinsic to
562 /// start a new statepoint sequence.
564 CreateGCStatepointInvoke(uint64_t ID, uint32_t NumPatchBytes,
565 Value *ActualInvokee, BasicBlock *NormalDest,
566 BasicBlock *UnwindDest, ArrayRef<Value *> InvokeArgs,
567 ArrayRef<Value *> DeoptArgs,
568 ArrayRef<Value *> GCArgs, const Twine &Name = "");
570 /// brief Create an invoke to the experimental.gc.statepoint intrinsic to
571 /// start a new statepoint sequence.
572 InvokeInst *CreateGCStatepointInvoke(
573 uint64_t ID, uint32_t NumPatchBytes, Value *ActualInvokee,
574 BasicBlock *NormalDest, BasicBlock *UnwindDest, uint32_t Flags,
575 ArrayRef<Use> InvokeArgs, ArrayRef<Use> TransitionArgs,
576 ArrayRef<Use> DeoptArgs, ArrayRef<Value *> GCArgs,
577 const Twine &Name = "");
579 // Conveninence function for the common case when CallArgs are filled in using
580 // makeArrayRef(CS.arg_begin(), CS.arg_end()); Use needs to be .get()'ed to
583 CreateGCStatepointInvoke(uint64_t ID, uint32_t NumPatchBytes,
584 Value *ActualInvokee, BasicBlock *NormalDest,
585 BasicBlock *UnwindDest, ArrayRef<Use> InvokeArgs,
586 ArrayRef<Value *> DeoptArgs,
587 ArrayRef<Value *> GCArgs, const Twine &Name = "");
589 /// \brief Create a call to the experimental.gc.result intrinsic to extract
590 /// the result from a call wrapped in a statepoint.
591 CallInst *CreateGCResult(Instruction *Statepoint,
593 const Twine &Name = "");
595 /// \brief Create a call to the experimental.gc.relocate intrinsics to
596 /// project the relocated value of one pointer from the statepoint.
597 CallInst *CreateGCRelocate(Instruction *Statepoint,
601 const Twine &Name = "");
603 /// Create a call to intrinsic \p ID with 2 operands which is mangled on the
605 CallInst *CreateBinaryIntrinsic(Intrinsic::ID ID,
606 Value *LHS, Value *RHS,
607 const Twine &Name = "");
609 /// Create call to the minnum intrinsic.
610 CallInst *CreateMinNum(Value *LHS, Value *RHS, const Twine &Name = "") {
611 return CreateBinaryIntrinsic(Intrinsic::minnum, LHS, RHS, Name);
614 /// Create call to the maxnum intrinsic.
615 CallInst *CreateMaxNum(Value *LHS, Value *RHS, const Twine &Name = "") {
616 return CreateBinaryIntrinsic(Intrinsic::minnum, LHS, RHS, Name);
620 /// \brief Create a call to a masked intrinsic with given Id.
621 CallInst *CreateMaskedIntrinsic(Intrinsic::ID Id, ArrayRef<Value *> Ops,
622 ArrayRef<Type *> OverloadedTypes,
623 const Twine &Name = "");
625 Value *getCastedInt8PtrValue(Value *Ptr);
628 /// \brief This provides a uniform API for creating instructions and inserting
629 /// them into a basic block: either at the end of a BasicBlock, or at a specific
630 /// iterator location in a block.
632 /// Note that the builder does not expose the full generality of LLVM
633 /// instructions. For access to extra instruction properties, use the mutators
634 /// (e.g. setVolatile) on the instructions after they have been
635 /// created. Convenience state exists to specify fast-math flags and fp-math
638 /// The first template argument specifies a class to use for creating constants.
639 /// This defaults to creating minimally folded constants. The second template
640 /// argument allows clients to specify custom insertion hooks that are called on
641 /// every newly created insertion.
642 template <typename T = ConstantFolder,
643 typename Inserter = IRBuilderDefaultInserter>
644 class IRBuilder : public IRBuilderBase, public Inserter {
648 IRBuilder(LLVMContext &C, const T &F, Inserter I = Inserter(),
649 MDNode *FPMathTag = nullptr,
650 ArrayRef<OperandBundleDef> OpBundles = None)
651 : IRBuilderBase(C, FPMathTag, OpBundles), Inserter(std::move(I)),
654 explicit IRBuilder(LLVMContext &C, MDNode *FPMathTag = nullptr,
655 ArrayRef<OperandBundleDef> OpBundles = None)
656 : IRBuilderBase(C, FPMathTag, OpBundles), Folder() {}
658 explicit IRBuilder(BasicBlock *TheBB, const T &F, MDNode *FPMathTag = nullptr,
659 ArrayRef<OperandBundleDef> OpBundles = None)
660 : IRBuilderBase(TheBB->getContext(), FPMathTag, OpBundles), Folder(F) {
661 SetInsertPoint(TheBB);
664 explicit IRBuilder(BasicBlock *TheBB, MDNode *FPMathTag = nullptr,
665 ArrayRef<OperandBundleDef> OpBundles = None)
666 : IRBuilderBase(TheBB->getContext(), FPMathTag, OpBundles), Folder() {
667 SetInsertPoint(TheBB);
670 explicit IRBuilder(Instruction *IP, MDNode *FPMathTag = nullptr,
671 ArrayRef<OperandBundleDef> OpBundles = None)
672 : IRBuilderBase(IP->getContext(), FPMathTag, OpBundles), Folder() {
676 IRBuilder(BasicBlock *TheBB, BasicBlock::iterator IP, const T &F,
677 MDNode *FPMathTag = nullptr,
678 ArrayRef<OperandBundleDef> OpBundles = None)
679 : IRBuilderBase(TheBB->getContext(), FPMathTag, OpBundles), Folder(F) {
680 SetInsertPoint(TheBB, IP);
683 IRBuilder(BasicBlock *TheBB, BasicBlock::iterator IP,
684 MDNode *FPMathTag = nullptr,
685 ArrayRef<OperandBundleDef> OpBundles = None)
686 : IRBuilderBase(TheBB->getContext(), FPMathTag, OpBundles), Folder() {
687 SetInsertPoint(TheBB, IP);
690 /// \brief Get the constant folder being used.
691 const T &getFolder() { return Folder; }
693 /// \brief Insert and return the specified instruction.
694 template<typename InstTy>
695 InstTy *Insert(InstTy *I, const Twine &Name = "") const {
696 this->InsertHelper(I, Name, BB, InsertPt);
697 this->SetInstDebugLocation(I);
701 /// \brief No-op overload to handle constants.
702 Constant *Insert(Constant *C, const Twine& = "") const {
706 //===--------------------------------------------------------------------===//
707 // Instruction creation methods: Terminators
708 //===--------------------------------------------------------------------===//
711 /// \brief Helper to add branch weight and unpredictable metadata onto an
713 /// \returns The annotated instruction.
714 template <typename InstTy>
715 InstTy *addBranchMetadata(InstTy *I, MDNode *Weights, MDNode *Unpredictable) {
717 I->setMetadata(LLVMContext::MD_prof, Weights);
719 I->setMetadata(LLVMContext::MD_unpredictable, Unpredictable);
724 /// \brief Create a 'ret void' instruction.
725 ReturnInst *CreateRetVoid() {
726 return Insert(ReturnInst::Create(Context));
729 /// \brief Create a 'ret <val>' instruction.
730 ReturnInst *CreateRet(Value *V) {
731 return Insert(ReturnInst::Create(Context, V));
734 /// \brief Create a sequence of N insertvalue instructions,
735 /// with one Value from the retVals array each, that build a aggregate
736 /// return value one value at a time, and a ret instruction to return
737 /// the resulting aggregate value.
739 /// This is a convenience function for code that uses aggregate return values
740 /// as a vehicle for having multiple return values.
741 ReturnInst *CreateAggregateRet(Value *const *retVals, unsigned N) {
742 Value *V = UndefValue::get(getCurrentFunctionReturnType());
743 for (unsigned i = 0; i != N; ++i)
744 V = CreateInsertValue(V, retVals[i], i, "mrv");
745 return Insert(ReturnInst::Create(Context, V));
748 /// \brief Create an unconditional 'br label X' instruction.
749 BranchInst *CreateBr(BasicBlock *Dest) {
750 return Insert(BranchInst::Create(Dest));
753 /// \brief Create a conditional 'br Cond, TrueDest, FalseDest'
755 BranchInst *CreateCondBr(Value *Cond, BasicBlock *True, BasicBlock *False,
756 MDNode *BranchWeights = nullptr,
757 MDNode *Unpredictable = nullptr) {
758 return Insert(addBranchMetadata(BranchInst::Create(True, False, Cond),
759 BranchWeights, Unpredictable));
762 /// \brief Create a conditional 'br Cond, TrueDest, FalseDest'
763 /// instruction. Copy branch meta data if available.
764 BranchInst *CreateCondBr(Value *Cond, BasicBlock *True, BasicBlock *False,
765 Instruction *MDSrc) {
766 BranchInst *Br = BranchInst::Create(True, False, Cond);
768 unsigned WL[4] = {LLVMContext::MD_prof, LLVMContext::MD_unpredictable,
769 LLVMContext::MD_make_implicit, LLVMContext::MD_dbg};
770 Br->copyMetadata(*MDSrc, makeArrayRef(&WL[0], 4));
775 /// \brief Create a switch instruction with the specified value, default dest,
776 /// and with a hint for the number of cases that will be added (for efficient
778 SwitchInst *CreateSwitch(Value *V, BasicBlock *Dest, unsigned NumCases = 10,
779 MDNode *BranchWeights = nullptr,
780 MDNode *Unpredictable = nullptr) {
781 return Insert(addBranchMetadata(SwitchInst::Create(V, Dest, NumCases),
782 BranchWeights, Unpredictable));
785 /// \brief Create an indirect branch instruction with the specified address
786 /// operand, with an optional hint for the number of destinations that will be
787 /// added (for efficient allocation).
788 IndirectBrInst *CreateIndirectBr(Value *Addr, unsigned NumDests = 10) {
789 return Insert(IndirectBrInst::Create(Addr, NumDests));
792 /// \brief Create an invoke instruction.
793 InvokeInst *CreateInvoke(Value *Callee, BasicBlock *NormalDest,
794 BasicBlock *UnwindDest,
795 ArrayRef<Value *> Args = None,
796 const Twine &Name = "") {
797 return Insert(InvokeInst::Create(Callee, NormalDest, UnwindDest, Args),
800 InvokeInst *CreateInvoke(Value *Callee, BasicBlock *NormalDest,
801 BasicBlock *UnwindDest, ArrayRef<Value *> Args,
802 ArrayRef<OperandBundleDef> OpBundles,
803 const Twine &Name = "") {
804 return Insert(InvokeInst::Create(Callee, NormalDest, UnwindDest, Args,
808 ResumeInst *CreateResume(Value *Exn) {
809 return Insert(ResumeInst::Create(Exn));
812 CleanupReturnInst *CreateCleanupRet(CleanupPadInst *CleanupPad,
813 BasicBlock *UnwindBB = nullptr) {
814 return Insert(CleanupReturnInst::Create(CleanupPad, UnwindBB));
817 CatchSwitchInst *CreateCatchSwitch(Value *ParentPad, BasicBlock *UnwindBB,
818 unsigned NumHandlers,
819 const Twine &Name = "") {
820 return Insert(CatchSwitchInst::Create(ParentPad, UnwindBB, NumHandlers),
824 CatchPadInst *CreateCatchPad(Value *ParentPad, ArrayRef<Value *> Args,
825 const Twine &Name = "") {
826 return Insert(CatchPadInst::Create(ParentPad, Args), Name);
829 CleanupPadInst *CreateCleanupPad(Value *ParentPad,
830 ArrayRef<Value *> Args = None,
831 const Twine &Name = "") {
832 return Insert(CleanupPadInst::Create(ParentPad, Args), Name);
835 CatchReturnInst *CreateCatchRet(CatchPadInst *CatchPad, BasicBlock *BB) {
836 return Insert(CatchReturnInst::Create(CatchPad, BB));
839 UnreachableInst *CreateUnreachable() {
840 return Insert(new UnreachableInst(Context));
843 //===--------------------------------------------------------------------===//
844 // Instruction creation methods: Binary Operators
845 //===--------------------------------------------------------------------===//
847 BinaryOperator *CreateInsertNUWNSWBinOp(BinaryOperator::BinaryOps Opc,
848 Value *LHS, Value *RHS,
850 bool HasNUW, bool HasNSW) {
851 BinaryOperator *BO = Insert(BinaryOperator::Create(Opc, LHS, RHS), Name);
852 if (HasNUW) BO->setHasNoUnsignedWrap();
853 if (HasNSW) BO->setHasNoSignedWrap();
857 Instruction *AddFPMathAttributes(Instruction *I,
859 FastMathFlags FMF) const {
861 FPMathTag = DefaultFPMathTag;
863 I->setMetadata(LLVMContext::MD_fpmath, FPMathTag);
864 I->setFastMathFlags(FMF);
869 Value *CreateAdd(Value *LHS, Value *RHS, const Twine &Name = "",
870 bool HasNUW = false, bool HasNSW = false) {
871 if (Constant *LC = dyn_cast<Constant>(LHS))
872 if (Constant *RC = dyn_cast<Constant>(RHS))
873 return Insert(Folder.CreateAdd(LC, RC, HasNUW, HasNSW), Name);
874 return CreateInsertNUWNSWBinOp(Instruction::Add, LHS, RHS, Name,
877 Value *CreateNSWAdd(Value *LHS, Value *RHS, const Twine &Name = "") {
878 return CreateAdd(LHS, RHS, Name, false, true);
880 Value *CreateNUWAdd(Value *LHS, Value *RHS, const Twine &Name = "") {
881 return CreateAdd(LHS, RHS, Name, true, false);
883 Value *CreateFAdd(Value *LHS, Value *RHS, const Twine &Name = "",
884 MDNode *FPMathTag = nullptr) {
885 if (Constant *LC = dyn_cast<Constant>(LHS))
886 if (Constant *RC = dyn_cast<Constant>(RHS))
887 return Insert(Folder.CreateFAdd(LC, RC), Name);
888 return Insert(AddFPMathAttributes(BinaryOperator::CreateFAdd(LHS, RHS),
889 FPMathTag, FMF), Name);
891 Value *CreateSub(Value *LHS, Value *RHS, const Twine &Name = "",
892 bool HasNUW = false, bool HasNSW = false) {
893 if (Constant *LC = dyn_cast<Constant>(LHS))
894 if (Constant *RC = dyn_cast<Constant>(RHS))
895 return Insert(Folder.CreateSub(LC, RC, HasNUW, HasNSW), Name);
896 return CreateInsertNUWNSWBinOp(Instruction::Sub, LHS, RHS, Name,
899 Value *CreateNSWSub(Value *LHS, Value *RHS, const Twine &Name = "") {
900 return CreateSub(LHS, RHS, Name, false, true);
902 Value *CreateNUWSub(Value *LHS, Value *RHS, const Twine &Name = "") {
903 return CreateSub(LHS, RHS, Name, true, false);
905 Value *CreateFSub(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.CreateFSub(LC, RC), Name);
910 return Insert(AddFPMathAttributes(BinaryOperator::CreateFSub(LHS, RHS),
911 FPMathTag, FMF), Name);
913 Value *CreateMul(Value *LHS, Value *RHS, const Twine &Name = "",
914 bool HasNUW = false, bool HasNSW = false) {
915 if (Constant *LC = dyn_cast<Constant>(LHS))
916 if (Constant *RC = dyn_cast<Constant>(RHS))
917 return Insert(Folder.CreateMul(LC, RC, HasNUW, HasNSW), Name);
918 return CreateInsertNUWNSWBinOp(Instruction::Mul, LHS, RHS, Name,
921 Value *CreateNSWMul(Value *LHS, Value *RHS, const Twine &Name = "") {
922 return CreateMul(LHS, RHS, Name, false, true);
924 Value *CreateNUWMul(Value *LHS, Value *RHS, const Twine &Name = "") {
925 return CreateMul(LHS, RHS, Name, true, false);
927 Value *CreateFMul(Value *LHS, Value *RHS, const Twine &Name = "",
928 MDNode *FPMathTag = nullptr) {
929 if (Constant *LC = dyn_cast<Constant>(LHS))
930 if (Constant *RC = dyn_cast<Constant>(RHS))
931 return Insert(Folder.CreateFMul(LC, RC), Name);
932 return Insert(AddFPMathAttributes(BinaryOperator::CreateFMul(LHS, RHS),
933 FPMathTag, FMF), Name);
935 Value *CreateUDiv(Value *LHS, Value *RHS, const Twine &Name = "",
936 bool isExact = false) {
937 if (Constant *LC = dyn_cast<Constant>(LHS))
938 if (Constant *RC = dyn_cast<Constant>(RHS))
939 return Insert(Folder.CreateUDiv(LC, RC, isExact), Name);
941 return Insert(BinaryOperator::CreateUDiv(LHS, RHS), Name);
942 return Insert(BinaryOperator::CreateExactUDiv(LHS, RHS), Name);
944 Value *CreateExactUDiv(Value *LHS, Value *RHS, const Twine &Name = "") {
945 return CreateUDiv(LHS, RHS, Name, true);
947 Value *CreateSDiv(Value *LHS, Value *RHS, const Twine &Name = "",
948 bool isExact = false) {
949 if (Constant *LC = dyn_cast<Constant>(LHS))
950 if (Constant *RC = dyn_cast<Constant>(RHS))
951 return Insert(Folder.CreateSDiv(LC, RC, isExact), Name);
953 return Insert(BinaryOperator::CreateSDiv(LHS, RHS), Name);
954 return Insert(BinaryOperator::CreateExactSDiv(LHS, RHS), Name);
956 Value *CreateExactSDiv(Value *LHS, Value *RHS, const Twine &Name = "") {
957 return CreateSDiv(LHS, RHS, Name, true);
959 Value *CreateFDiv(Value *LHS, Value *RHS, const Twine &Name = "",
960 MDNode *FPMathTag = nullptr) {
961 if (Constant *LC = dyn_cast<Constant>(LHS))
962 if (Constant *RC = dyn_cast<Constant>(RHS))
963 return Insert(Folder.CreateFDiv(LC, RC), Name);
964 return Insert(AddFPMathAttributes(BinaryOperator::CreateFDiv(LHS, RHS),
965 FPMathTag, FMF), Name);
967 Value *CreateURem(Value *LHS, Value *RHS, const Twine &Name = "") {
968 if (Constant *LC = dyn_cast<Constant>(LHS))
969 if (Constant *RC = dyn_cast<Constant>(RHS))
970 return Insert(Folder.CreateURem(LC, RC), Name);
971 return Insert(BinaryOperator::CreateURem(LHS, RHS), Name);
973 Value *CreateSRem(Value *LHS, Value *RHS, const Twine &Name = "") {
974 if (Constant *LC = dyn_cast<Constant>(LHS))
975 if (Constant *RC = dyn_cast<Constant>(RHS))
976 return Insert(Folder.CreateSRem(LC, RC), Name);
977 return Insert(BinaryOperator::CreateSRem(LHS, RHS), Name);
979 Value *CreateFRem(Value *LHS, Value *RHS, const Twine &Name = "",
980 MDNode *FPMathTag = nullptr) {
981 if (Constant *LC = dyn_cast<Constant>(LHS))
982 if (Constant *RC = dyn_cast<Constant>(RHS))
983 return Insert(Folder.CreateFRem(LC, RC), Name);
984 return Insert(AddFPMathAttributes(BinaryOperator::CreateFRem(LHS, RHS),
985 FPMathTag, FMF), Name);
988 Value *CreateShl(Value *LHS, Value *RHS, const Twine &Name = "",
989 bool HasNUW = false, bool HasNSW = false) {
990 if (Constant *LC = dyn_cast<Constant>(LHS))
991 if (Constant *RC = dyn_cast<Constant>(RHS))
992 return Insert(Folder.CreateShl(LC, RC, HasNUW, HasNSW), Name);
993 return CreateInsertNUWNSWBinOp(Instruction::Shl, LHS, RHS, Name,
996 Value *CreateShl(Value *LHS, const APInt &RHS, const Twine &Name = "",
997 bool HasNUW = false, bool HasNSW = false) {
998 return CreateShl(LHS, ConstantInt::get(LHS->getType(), RHS), Name,
1001 Value *CreateShl(Value *LHS, uint64_t RHS, const Twine &Name = "",
1002 bool HasNUW = false, bool HasNSW = false) {
1003 return CreateShl(LHS, ConstantInt::get(LHS->getType(), RHS), Name,
1007 Value *CreateLShr(Value *LHS, Value *RHS, const Twine &Name = "",
1008 bool isExact = false) {
1009 if (Constant *LC = dyn_cast<Constant>(LHS))
1010 if (Constant *RC = dyn_cast<Constant>(RHS))
1011 return Insert(Folder.CreateLShr(LC, RC, isExact), Name);
1013 return Insert(BinaryOperator::CreateLShr(LHS, RHS), Name);
1014 return Insert(BinaryOperator::CreateExactLShr(LHS, RHS), Name);
1016 Value *CreateLShr(Value *LHS, const APInt &RHS, const Twine &Name = "",
1017 bool isExact = false) {
1018 return CreateLShr(LHS, ConstantInt::get(LHS->getType(), RHS), Name,isExact);
1020 Value *CreateLShr(Value *LHS, uint64_t RHS, const Twine &Name = "",
1021 bool isExact = false) {
1022 return CreateLShr(LHS, ConstantInt::get(LHS->getType(), RHS), Name,isExact);
1025 Value *CreateAShr(Value *LHS, Value *RHS, const Twine &Name = "",
1026 bool isExact = false) {
1027 if (Constant *LC = dyn_cast<Constant>(LHS))
1028 if (Constant *RC = dyn_cast<Constant>(RHS))
1029 return Insert(Folder.CreateAShr(LC, RC, isExact), Name);
1031 return Insert(BinaryOperator::CreateAShr(LHS, RHS), Name);
1032 return Insert(BinaryOperator::CreateExactAShr(LHS, RHS), Name);
1034 Value *CreateAShr(Value *LHS, const APInt &RHS, const Twine &Name = "",
1035 bool isExact = false) {
1036 return CreateAShr(LHS, ConstantInt::get(LHS->getType(), RHS), Name,isExact);
1038 Value *CreateAShr(Value *LHS, uint64_t RHS, const Twine &Name = "",
1039 bool isExact = false) {
1040 return CreateAShr(LHS, ConstantInt::get(LHS->getType(), RHS), Name,isExact);
1043 Value *CreateAnd(Value *LHS, Value *RHS, const Twine &Name = "") {
1044 if (Constant *RC = dyn_cast<Constant>(RHS)) {
1045 if (isa<ConstantInt>(RC) && cast<ConstantInt>(RC)->isAllOnesValue())
1046 return LHS; // LHS & -1 -> LHS
1047 if (Constant *LC = dyn_cast<Constant>(LHS))
1048 return Insert(Folder.CreateAnd(LC, RC), Name);
1050 return Insert(BinaryOperator::CreateAnd(LHS, RHS), Name);
1052 Value *CreateAnd(Value *LHS, const APInt &RHS, const Twine &Name = "") {
1053 return CreateAnd(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
1055 Value *CreateAnd(Value *LHS, uint64_t RHS, const Twine &Name = "") {
1056 return CreateAnd(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
1059 Value *CreateOr(Value *LHS, Value *RHS, const Twine &Name = "") {
1060 if (Constant *RC = dyn_cast<Constant>(RHS)) {
1061 if (RC->isNullValue())
1062 return LHS; // LHS | 0 -> LHS
1063 if (Constant *LC = dyn_cast<Constant>(LHS))
1064 return Insert(Folder.CreateOr(LC, RC), Name);
1066 return Insert(BinaryOperator::CreateOr(LHS, RHS), Name);
1068 Value *CreateOr(Value *LHS, const APInt &RHS, const Twine &Name = "") {
1069 return CreateOr(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
1071 Value *CreateOr(Value *LHS, uint64_t RHS, const Twine &Name = "") {
1072 return CreateOr(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
1075 Value *CreateXor(Value *LHS, Value *RHS, const Twine &Name = "") {
1076 if (Constant *LC = dyn_cast<Constant>(LHS))
1077 if (Constant *RC = dyn_cast<Constant>(RHS))
1078 return Insert(Folder.CreateXor(LC, RC), Name);
1079 return Insert(BinaryOperator::CreateXor(LHS, RHS), Name);
1081 Value *CreateXor(Value *LHS, const APInt &RHS, const Twine &Name = "") {
1082 return CreateXor(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
1084 Value *CreateXor(Value *LHS, uint64_t RHS, const Twine &Name = "") {
1085 return CreateXor(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
1088 Value *CreateBinOp(Instruction::BinaryOps Opc,
1089 Value *LHS, Value *RHS, const Twine &Name = "",
1090 MDNode *FPMathTag = nullptr) {
1091 if (Constant *LC = dyn_cast<Constant>(LHS))
1092 if (Constant *RC = dyn_cast<Constant>(RHS))
1093 return Insert(Folder.CreateBinOp(Opc, LC, RC), Name);
1094 Instruction *BinOp = BinaryOperator::Create(Opc, LHS, RHS);
1095 if (isa<FPMathOperator>(BinOp))
1096 BinOp = AddFPMathAttributes(BinOp, FPMathTag, FMF);
1097 return Insert(BinOp, Name);
1100 Value *CreateNeg(Value *V, const Twine &Name = "",
1101 bool HasNUW = false, bool HasNSW = false) {
1102 if (Constant *VC = dyn_cast<Constant>(V))
1103 return Insert(Folder.CreateNeg(VC, HasNUW, HasNSW), Name);
1104 BinaryOperator *BO = Insert(BinaryOperator::CreateNeg(V), Name);
1105 if (HasNUW) BO->setHasNoUnsignedWrap();
1106 if (HasNSW) BO->setHasNoSignedWrap();
1109 Value *CreateNSWNeg(Value *V, const Twine &Name = "") {
1110 return CreateNeg(V, Name, false, true);
1112 Value *CreateNUWNeg(Value *V, const Twine &Name = "") {
1113 return CreateNeg(V, Name, true, false);
1115 Value *CreateFNeg(Value *V, const Twine &Name = "",
1116 MDNode *FPMathTag = nullptr) {
1117 if (Constant *VC = dyn_cast<Constant>(V))
1118 return Insert(Folder.CreateFNeg(VC), Name);
1119 return Insert(AddFPMathAttributes(BinaryOperator::CreateFNeg(V),
1120 FPMathTag, FMF), Name);
1122 Value *CreateNot(Value *V, const Twine &Name = "") {
1123 if (Constant *VC = dyn_cast<Constant>(V))
1124 return Insert(Folder.CreateNot(VC), Name);
1125 return Insert(BinaryOperator::CreateNot(V), Name);
1128 //===--------------------------------------------------------------------===//
1129 // Instruction creation methods: Memory Instructions
1130 //===--------------------------------------------------------------------===//
1132 AllocaInst *CreateAlloca(Type *Ty, unsigned AddrSpace,
1133 Value *ArraySize = nullptr, const Twine &Name = "") {
1134 return Insert(new AllocaInst(Ty, AddrSpace, ArraySize), Name);
1137 AllocaInst *CreateAlloca(Type *Ty, Value *ArraySize = nullptr,
1138 const Twine &Name = "") {
1139 const DataLayout &DL = BB->getParent()->getParent()->getDataLayout();
1140 return Insert(new AllocaInst(Ty, DL.getAllocaAddrSpace(), ArraySize), Name);
1142 // \brief Provided to resolve 'CreateLoad(Ptr, "...")' correctly, instead of
1143 // converting the string to 'bool' for the isVolatile parameter.
1144 LoadInst *CreateLoad(Value *Ptr, const char *Name) {
1145 return Insert(new LoadInst(Ptr), Name);
1147 LoadInst *CreateLoad(Value *Ptr, const Twine &Name = "") {
1148 return Insert(new LoadInst(Ptr), Name);
1150 LoadInst *CreateLoad(Type *Ty, Value *Ptr, const Twine &Name = "") {
1151 return Insert(new LoadInst(Ty, Ptr), Name);
1153 LoadInst *CreateLoad(Value *Ptr, bool isVolatile, const Twine &Name = "") {
1154 return Insert(new LoadInst(Ptr, nullptr, isVolatile), Name);
1156 StoreInst *CreateStore(Value *Val, Value *Ptr, bool isVolatile = false) {
1157 return Insert(new StoreInst(Val, Ptr, isVolatile));
1159 // \brief Provided to resolve 'CreateAlignedLoad(Ptr, Align, "...")'
1160 // correctly, instead of converting the string to 'bool' for the isVolatile
1162 LoadInst *CreateAlignedLoad(Value *Ptr, unsigned Align, const char *Name) {
1163 LoadInst *LI = CreateLoad(Ptr, Name);
1164 LI->setAlignment(Align);
1167 LoadInst *CreateAlignedLoad(Value *Ptr, unsigned Align,
1168 const Twine &Name = "") {
1169 LoadInst *LI = CreateLoad(Ptr, Name);
1170 LI->setAlignment(Align);
1173 LoadInst *CreateAlignedLoad(Value *Ptr, unsigned Align, bool isVolatile,
1174 const Twine &Name = "") {
1175 LoadInst *LI = CreateLoad(Ptr, isVolatile, Name);
1176 LI->setAlignment(Align);
1179 StoreInst *CreateAlignedStore(Value *Val, Value *Ptr, unsigned Align,
1180 bool isVolatile = false) {
1181 StoreInst *SI = CreateStore(Val, Ptr, isVolatile);
1182 SI->setAlignment(Align);
1185 FenceInst *CreateFence(AtomicOrdering Ordering,
1186 SynchronizationScope SynchScope = CrossThread,
1187 const Twine &Name = "") {
1188 return Insert(new FenceInst(Context, Ordering, SynchScope), Name);
1191 CreateAtomicCmpXchg(Value *Ptr, Value *Cmp, Value *New,
1192 AtomicOrdering SuccessOrdering,
1193 AtomicOrdering FailureOrdering,
1194 SynchronizationScope SynchScope = CrossThread) {
1195 return Insert(new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering,
1196 FailureOrdering, SynchScope));
1198 AtomicRMWInst *CreateAtomicRMW(AtomicRMWInst::BinOp Op, Value *Ptr, Value *Val,
1199 AtomicOrdering Ordering,
1200 SynchronizationScope SynchScope = CrossThread) {
1201 return Insert(new AtomicRMWInst(Op, Ptr, Val, Ordering, SynchScope));
1203 Value *CreateGEP(Value *Ptr, ArrayRef<Value *> IdxList,
1204 const Twine &Name = "") {
1205 return CreateGEP(nullptr, Ptr, IdxList, Name);
1207 Value *CreateGEP(Type *Ty, Value *Ptr, ArrayRef<Value *> IdxList,
1208 const Twine &Name = "") {
1209 if (Constant *PC = dyn_cast<Constant>(Ptr)) {
1210 // Every index must be constant.
1212 for (i = 0, e = IdxList.size(); i != e; ++i)
1213 if (!isa<Constant>(IdxList[i]))
1216 return Insert(Folder.CreateGetElementPtr(Ty, PC, IdxList), Name);
1218 return Insert(GetElementPtrInst::Create(Ty, Ptr, IdxList), Name);
1220 Value *CreateInBoundsGEP(Value *Ptr, ArrayRef<Value *> IdxList,
1221 const Twine &Name = "") {
1222 return CreateInBoundsGEP(nullptr, Ptr, IdxList, Name);
1224 Value *CreateInBoundsGEP(Type *Ty, Value *Ptr, ArrayRef<Value *> IdxList,
1225 const Twine &Name = "") {
1226 if (Constant *PC = dyn_cast<Constant>(Ptr)) {
1227 // Every index must be constant.
1229 for (i = 0, e = IdxList.size(); i != e; ++i)
1230 if (!isa<Constant>(IdxList[i]))
1233 return Insert(Folder.CreateInBoundsGetElementPtr(Ty, PC, IdxList),
1236 return Insert(GetElementPtrInst::CreateInBounds(Ty, Ptr, IdxList), Name);
1238 Value *CreateGEP(Value *Ptr, Value *Idx, const Twine &Name = "") {
1239 return CreateGEP(nullptr, Ptr, Idx, Name);
1241 Value *CreateGEP(Type *Ty, Value *Ptr, Value *Idx, const Twine &Name = "") {
1242 if (Constant *PC = dyn_cast<Constant>(Ptr))
1243 if (Constant *IC = dyn_cast<Constant>(Idx))
1244 return Insert(Folder.CreateGetElementPtr(Ty, PC, IC), Name);
1245 return Insert(GetElementPtrInst::Create(Ty, Ptr, Idx), Name);
1247 Value *CreateInBoundsGEP(Type *Ty, Value *Ptr, Value *Idx,
1248 const Twine &Name = "") {
1249 if (Constant *PC = dyn_cast<Constant>(Ptr))
1250 if (Constant *IC = dyn_cast<Constant>(Idx))
1251 return Insert(Folder.CreateInBoundsGetElementPtr(Ty, PC, IC), Name);
1252 return Insert(GetElementPtrInst::CreateInBounds(Ty, Ptr, Idx), Name);
1254 Value *CreateConstGEP1_32(Value *Ptr, unsigned Idx0, const Twine &Name = "") {
1255 return CreateConstGEP1_32(nullptr, Ptr, Idx0, Name);
1257 Value *CreateConstGEP1_32(Type *Ty, Value *Ptr, unsigned Idx0,
1258 const Twine &Name = "") {
1259 Value *Idx = ConstantInt::get(Type::getInt32Ty(Context), Idx0);
1261 if (Constant *PC = dyn_cast<Constant>(Ptr))
1262 return Insert(Folder.CreateGetElementPtr(Ty, PC, Idx), Name);
1264 return Insert(GetElementPtrInst::Create(Ty, Ptr, Idx), Name);
1266 Value *CreateConstInBoundsGEP1_32(Type *Ty, Value *Ptr, unsigned Idx0,
1267 const Twine &Name = "") {
1268 Value *Idx = ConstantInt::get(Type::getInt32Ty(Context), Idx0);
1270 if (Constant *PC = dyn_cast<Constant>(Ptr))
1271 return Insert(Folder.CreateInBoundsGetElementPtr(Ty, PC, Idx), Name);
1273 return Insert(GetElementPtrInst::CreateInBounds(Ty, Ptr, Idx), Name);
1275 Value *CreateConstGEP2_32(Type *Ty, Value *Ptr, unsigned Idx0, unsigned Idx1,
1276 const Twine &Name = "") {
1278 ConstantInt::get(Type::getInt32Ty(Context), Idx0),
1279 ConstantInt::get(Type::getInt32Ty(Context), Idx1)
1282 if (Constant *PC = dyn_cast<Constant>(Ptr))
1283 return Insert(Folder.CreateGetElementPtr(Ty, PC, Idxs), Name);
1285 return Insert(GetElementPtrInst::Create(Ty, Ptr, Idxs), Name);
1287 Value *CreateConstInBoundsGEP2_32(Type *Ty, Value *Ptr, unsigned Idx0,
1288 unsigned Idx1, const Twine &Name = "") {
1290 ConstantInt::get(Type::getInt32Ty(Context), Idx0),
1291 ConstantInt::get(Type::getInt32Ty(Context), Idx1)
1294 if (Constant *PC = dyn_cast<Constant>(Ptr))
1295 return Insert(Folder.CreateInBoundsGetElementPtr(Ty, PC, Idxs), Name);
1297 return Insert(GetElementPtrInst::CreateInBounds(Ty, Ptr, Idxs), Name);
1299 Value *CreateConstGEP1_64(Value *Ptr, uint64_t Idx0, const Twine &Name = "") {
1300 Value *Idx = ConstantInt::get(Type::getInt64Ty(Context), Idx0);
1302 if (Constant *PC = dyn_cast<Constant>(Ptr))
1303 return Insert(Folder.CreateGetElementPtr(nullptr, PC, Idx), Name);
1305 return Insert(GetElementPtrInst::Create(nullptr, Ptr, Idx), Name);
1307 Value *CreateConstInBoundsGEP1_64(Value *Ptr, uint64_t Idx0,
1308 const Twine &Name = "") {
1309 Value *Idx = ConstantInt::get(Type::getInt64Ty(Context), Idx0);
1311 if (Constant *PC = dyn_cast<Constant>(Ptr))
1312 return Insert(Folder.CreateInBoundsGetElementPtr(nullptr, PC, Idx), Name);
1314 return Insert(GetElementPtrInst::CreateInBounds(nullptr, Ptr, Idx), Name);
1316 Value *CreateConstGEP2_64(Value *Ptr, uint64_t Idx0, uint64_t Idx1,
1317 const Twine &Name = "") {
1319 ConstantInt::get(Type::getInt64Ty(Context), Idx0),
1320 ConstantInt::get(Type::getInt64Ty(Context), Idx1)
1323 if (Constant *PC = dyn_cast<Constant>(Ptr))
1324 return Insert(Folder.CreateGetElementPtr(nullptr, PC, Idxs), Name);
1326 return Insert(GetElementPtrInst::Create(nullptr, Ptr, Idxs), Name);
1328 Value *CreateConstInBoundsGEP2_64(Value *Ptr, uint64_t Idx0, uint64_t Idx1,
1329 const Twine &Name = "") {
1331 ConstantInt::get(Type::getInt64Ty(Context), Idx0),
1332 ConstantInt::get(Type::getInt64Ty(Context), Idx1)
1335 if (Constant *PC = dyn_cast<Constant>(Ptr))
1336 return Insert(Folder.CreateInBoundsGetElementPtr(nullptr, PC, Idxs),
1339 return Insert(GetElementPtrInst::CreateInBounds(nullptr, Ptr, Idxs), Name);
1341 Value *CreateStructGEP(Type *Ty, Value *Ptr, unsigned Idx,
1342 const Twine &Name = "") {
1343 return CreateConstInBoundsGEP2_32(Ty, Ptr, 0, Idx, Name);
1346 /// \brief Same as CreateGlobalString, but return a pointer with "i8*" type
1347 /// instead of a pointer to array of i8.
1348 Value *CreateGlobalStringPtr(StringRef Str, const Twine &Name = "",
1349 unsigned AddressSpace = 0) {
1350 GlobalVariable *gv = CreateGlobalString(Str, Name, AddressSpace);
1351 Value *zero = ConstantInt::get(Type::getInt32Ty(Context), 0);
1352 Value *Args[] = { zero, zero };
1353 return CreateInBoundsGEP(gv->getValueType(), gv, Args, Name);
1356 //===--------------------------------------------------------------------===//
1357 // Instruction creation methods: Cast/Conversion Operators
1358 //===--------------------------------------------------------------------===//
1360 Value *CreateTrunc(Value *V, Type *DestTy, const Twine &Name = "") {
1361 return CreateCast(Instruction::Trunc, V, DestTy, Name);
1363 Value *CreateZExt(Value *V, Type *DestTy, const Twine &Name = "") {
1364 return CreateCast(Instruction::ZExt, V, DestTy, Name);
1366 Value *CreateSExt(Value *V, Type *DestTy, const Twine &Name = "") {
1367 return CreateCast(Instruction::SExt, V, DestTy, Name);
1369 /// \brief Create a ZExt or Trunc from the integer value V to DestTy. Return
1370 /// the value untouched if the type of V is already DestTy.
1371 Value *CreateZExtOrTrunc(Value *V, Type *DestTy,
1372 const Twine &Name = "") {
1373 assert(V->getType()->isIntOrIntVectorTy() &&
1374 DestTy->isIntOrIntVectorTy() &&
1375 "Can only zero extend/truncate integers!");
1376 Type *VTy = V->getType();
1377 if (VTy->getScalarSizeInBits() < DestTy->getScalarSizeInBits())
1378 return CreateZExt(V, DestTy, Name);
1379 if (VTy->getScalarSizeInBits() > DestTy->getScalarSizeInBits())
1380 return CreateTrunc(V, DestTy, Name);
1383 /// \brief Create a SExt or Trunc from the integer value V to DestTy. Return
1384 /// the value untouched if the type of V is already DestTy.
1385 Value *CreateSExtOrTrunc(Value *V, Type *DestTy,
1386 const Twine &Name = "") {
1387 assert(V->getType()->isIntOrIntVectorTy() &&
1388 DestTy->isIntOrIntVectorTy() &&
1389 "Can only sign extend/truncate integers!");
1390 Type *VTy = V->getType();
1391 if (VTy->getScalarSizeInBits() < DestTy->getScalarSizeInBits())
1392 return CreateSExt(V, DestTy, Name);
1393 if (VTy->getScalarSizeInBits() > DestTy->getScalarSizeInBits())
1394 return CreateTrunc(V, DestTy, Name);
1397 Value *CreateFPToUI(Value *V, Type *DestTy, const Twine &Name = ""){
1398 return CreateCast(Instruction::FPToUI, V, DestTy, Name);
1400 Value *CreateFPToSI(Value *V, Type *DestTy, const Twine &Name = ""){
1401 return CreateCast(Instruction::FPToSI, V, DestTy, Name);
1403 Value *CreateUIToFP(Value *V, Type *DestTy, const Twine &Name = ""){
1404 return CreateCast(Instruction::UIToFP, V, DestTy, Name);
1406 Value *CreateSIToFP(Value *V, Type *DestTy, const Twine &Name = ""){
1407 return CreateCast(Instruction::SIToFP, V, DestTy, Name);
1409 Value *CreateFPTrunc(Value *V, Type *DestTy,
1410 const Twine &Name = "") {
1411 return CreateCast(Instruction::FPTrunc, V, DestTy, Name);
1413 Value *CreateFPExt(Value *V, Type *DestTy, const Twine &Name = "") {
1414 return CreateCast(Instruction::FPExt, V, DestTy, Name);
1416 Value *CreatePtrToInt(Value *V, Type *DestTy,
1417 const Twine &Name = "") {
1418 return CreateCast(Instruction::PtrToInt, V, DestTy, Name);
1420 Value *CreateIntToPtr(Value *V, Type *DestTy,
1421 const Twine &Name = "") {
1422 return CreateCast(Instruction::IntToPtr, V, DestTy, Name);
1424 Value *CreateBitCast(Value *V, Type *DestTy,
1425 const Twine &Name = "") {
1426 return CreateCast(Instruction::BitCast, V, DestTy, Name);
1428 Value *CreateAddrSpaceCast(Value *V, Type *DestTy,
1429 const Twine &Name = "") {
1430 return CreateCast(Instruction::AddrSpaceCast, V, DestTy, Name);
1432 Value *CreateZExtOrBitCast(Value *V, Type *DestTy,
1433 const Twine &Name = "") {
1434 if (V->getType() == DestTy)
1436 if (Constant *VC = dyn_cast<Constant>(V))
1437 return Insert(Folder.CreateZExtOrBitCast(VC, DestTy), Name);
1438 return Insert(CastInst::CreateZExtOrBitCast(V, DestTy), Name);
1440 Value *CreateSExtOrBitCast(Value *V, Type *DestTy,
1441 const Twine &Name = "") {
1442 if (V->getType() == DestTy)
1444 if (Constant *VC = dyn_cast<Constant>(V))
1445 return Insert(Folder.CreateSExtOrBitCast(VC, DestTy), Name);
1446 return Insert(CastInst::CreateSExtOrBitCast(V, DestTy), Name);
1448 Value *CreateTruncOrBitCast(Value *V, Type *DestTy,
1449 const Twine &Name = "") {
1450 if (V->getType() == DestTy)
1452 if (Constant *VC = dyn_cast<Constant>(V))
1453 return Insert(Folder.CreateTruncOrBitCast(VC, DestTy), Name);
1454 return Insert(CastInst::CreateTruncOrBitCast(V, DestTy), Name);
1456 Value *CreateCast(Instruction::CastOps Op, Value *V, Type *DestTy,
1457 const Twine &Name = "") {
1458 if (V->getType() == DestTy)
1460 if (Constant *VC = dyn_cast<Constant>(V))
1461 return Insert(Folder.CreateCast(Op, VC, DestTy), Name);
1462 return Insert(CastInst::Create(Op, V, DestTy), Name);
1464 Value *CreatePointerCast(Value *V, Type *DestTy,
1465 const Twine &Name = "") {
1466 if (V->getType() == DestTy)
1468 if (Constant *VC = dyn_cast<Constant>(V))
1469 return Insert(Folder.CreatePointerCast(VC, DestTy), Name);
1470 return Insert(CastInst::CreatePointerCast(V, DestTy), Name);
1473 Value *CreatePointerBitCastOrAddrSpaceCast(Value *V, Type *DestTy,
1474 const Twine &Name = "") {
1475 if (V->getType() == DestTy)
1478 if (Constant *VC = dyn_cast<Constant>(V)) {
1479 return Insert(Folder.CreatePointerBitCastOrAddrSpaceCast(VC, DestTy),
1483 return Insert(CastInst::CreatePointerBitCastOrAddrSpaceCast(V, DestTy),
1487 Value *CreateIntCast(Value *V, Type *DestTy, bool isSigned,
1488 const Twine &Name = "") {
1489 if (V->getType() == DestTy)
1491 if (Constant *VC = dyn_cast<Constant>(V))
1492 return Insert(Folder.CreateIntCast(VC, DestTy, isSigned), Name);
1493 return Insert(CastInst::CreateIntegerCast(V, DestTy, isSigned), Name);
1496 Value *CreateBitOrPointerCast(Value *V, Type *DestTy,
1497 const Twine &Name = "") {
1498 if (V->getType() == DestTy)
1500 if (V->getType()->getScalarType()->isPointerTy() &&
1501 DestTy->getScalarType()->isIntegerTy())
1502 return CreatePtrToInt(V, DestTy, Name);
1503 if (V->getType()->getScalarType()->isIntegerTy() &&
1504 DestTy->getScalarType()->isPointerTy())
1505 return CreateIntToPtr(V, DestTy, Name);
1507 return CreateBitCast(V, DestTy, Name);
1511 Value *CreateFPCast(Value *V, Type *DestTy, const Twine &Name = "") {
1512 if (V->getType() == DestTy)
1514 if (Constant *VC = dyn_cast<Constant>(V))
1515 return Insert(Folder.CreateFPCast(VC, DestTy), Name);
1516 return Insert(CastInst::CreateFPCast(V, DestTy), Name);
1519 // \brief Provided to resolve 'CreateIntCast(Ptr, Ptr, "...")', giving a
1520 // compile time error, instead of converting the string to bool for the
1521 // isSigned parameter.
1522 Value *CreateIntCast(Value *, Type *, const char *) = delete;
1524 //===--------------------------------------------------------------------===//
1525 // Instruction creation methods: Compare Instructions
1526 //===--------------------------------------------------------------------===//
1528 Value *CreateICmpEQ(Value *LHS, Value *RHS, const Twine &Name = "") {
1529 return CreateICmp(ICmpInst::ICMP_EQ, LHS, RHS, Name);
1531 Value *CreateICmpNE(Value *LHS, Value *RHS, const Twine &Name = "") {
1532 return CreateICmp(ICmpInst::ICMP_NE, LHS, RHS, Name);
1534 Value *CreateICmpUGT(Value *LHS, Value *RHS, const Twine &Name = "") {
1535 return CreateICmp(ICmpInst::ICMP_UGT, LHS, RHS, Name);
1537 Value *CreateICmpUGE(Value *LHS, Value *RHS, const Twine &Name = "") {
1538 return CreateICmp(ICmpInst::ICMP_UGE, LHS, RHS, Name);
1540 Value *CreateICmpULT(Value *LHS, Value *RHS, const Twine &Name = "") {
1541 return CreateICmp(ICmpInst::ICMP_ULT, LHS, RHS, Name);
1543 Value *CreateICmpULE(Value *LHS, Value *RHS, const Twine &Name = "") {
1544 return CreateICmp(ICmpInst::ICMP_ULE, LHS, RHS, Name);
1546 Value *CreateICmpSGT(Value *LHS, Value *RHS, const Twine &Name = "") {
1547 return CreateICmp(ICmpInst::ICMP_SGT, LHS, RHS, Name);
1549 Value *CreateICmpSGE(Value *LHS, Value *RHS, const Twine &Name = "") {
1550 return CreateICmp(ICmpInst::ICMP_SGE, LHS, RHS, Name);
1552 Value *CreateICmpSLT(Value *LHS, Value *RHS, const Twine &Name = "") {
1553 return CreateICmp(ICmpInst::ICMP_SLT, LHS, RHS, Name);
1555 Value *CreateICmpSLE(Value *LHS, Value *RHS, const Twine &Name = "") {
1556 return CreateICmp(ICmpInst::ICMP_SLE, LHS, RHS, Name);
1559 Value *CreateFCmpOEQ(Value *LHS, Value *RHS, const Twine &Name = "",
1560 MDNode *FPMathTag = nullptr) {
1561 return CreateFCmp(FCmpInst::FCMP_OEQ, LHS, RHS, Name, FPMathTag);
1563 Value *CreateFCmpOGT(Value *LHS, Value *RHS, const Twine &Name = "",
1564 MDNode *FPMathTag = nullptr) {
1565 return CreateFCmp(FCmpInst::FCMP_OGT, LHS, RHS, Name, FPMathTag);
1567 Value *CreateFCmpOGE(Value *LHS, Value *RHS, const Twine &Name = "",
1568 MDNode *FPMathTag = nullptr) {
1569 return CreateFCmp(FCmpInst::FCMP_OGE, LHS, RHS, Name, FPMathTag);
1571 Value *CreateFCmpOLT(Value *LHS, Value *RHS, const Twine &Name = "",
1572 MDNode *FPMathTag = nullptr) {
1573 return CreateFCmp(FCmpInst::FCMP_OLT, LHS, RHS, Name, FPMathTag);
1575 Value *CreateFCmpOLE(Value *LHS, Value *RHS, const Twine &Name = "",
1576 MDNode *FPMathTag = nullptr) {
1577 return CreateFCmp(FCmpInst::FCMP_OLE, LHS, RHS, Name, FPMathTag);
1579 Value *CreateFCmpONE(Value *LHS, Value *RHS, const Twine &Name = "",
1580 MDNode *FPMathTag = nullptr) {
1581 return CreateFCmp(FCmpInst::FCMP_ONE, LHS, RHS, Name, FPMathTag);
1583 Value *CreateFCmpORD(Value *LHS, Value *RHS, const Twine &Name = "",
1584 MDNode *FPMathTag = nullptr) {
1585 return CreateFCmp(FCmpInst::FCMP_ORD, LHS, RHS, Name, FPMathTag);
1587 Value *CreateFCmpUNO(Value *LHS, Value *RHS, const Twine &Name = "",
1588 MDNode *FPMathTag = nullptr) {
1589 return CreateFCmp(FCmpInst::FCMP_UNO, LHS, RHS, Name, FPMathTag);
1591 Value *CreateFCmpUEQ(Value *LHS, Value *RHS, const Twine &Name = "",
1592 MDNode *FPMathTag = nullptr) {
1593 return CreateFCmp(FCmpInst::FCMP_UEQ, LHS, RHS, Name, FPMathTag);
1595 Value *CreateFCmpUGT(Value *LHS, Value *RHS, const Twine &Name = "",
1596 MDNode *FPMathTag = nullptr) {
1597 return CreateFCmp(FCmpInst::FCMP_UGT, LHS, RHS, Name, FPMathTag);
1599 Value *CreateFCmpUGE(Value *LHS, Value *RHS, const Twine &Name = "",
1600 MDNode *FPMathTag = nullptr) {
1601 return CreateFCmp(FCmpInst::FCMP_UGE, LHS, RHS, Name, FPMathTag);
1603 Value *CreateFCmpULT(Value *LHS, Value *RHS, const Twine &Name = "",
1604 MDNode *FPMathTag = nullptr) {
1605 return CreateFCmp(FCmpInst::FCMP_ULT, LHS, RHS, Name, FPMathTag);
1607 Value *CreateFCmpULE(Value *LHS, Value *RHS, const Twine &Name = "",
1608 MDNode *FPMathTag = nullptr) {
1609 return CreateFCmp(FCmpInst::FCMP_ULE, LHS, RHS, Name, FPMathTag);
1611 Value *CreateFCmpUNE(Value *LHS, Value *RHS, const Twine &Name = "",
1612 MDNode *FPMathTag = nullptr) {
1613 return CreateFCmp(FCmpInst::FCMP_UNE, LHS, RHS, Name, FPMathTag);
1616 Value *CreateICmp(CmpInst::Predicate P, Value *LHS, Value *RHS,
1617 const Twine &Name = "") {
1618 if (Constant *LC = dyn_cast<Constant>(LHS))
1619 if (Constant *RC = dyn_cast<Constant>(RHS))
1620 return Insert(Folder.CreateICmp(P, LC, RC), Name);
1621 return Insert(new ICmpInst(P, LHS, RHS), Name);
1623 Value *CreateFCmp(CmpInst::Predicate P, Value *LHS, Value *RHS,
1624 const Twine &Name = "", MDNode *FPMathTag = nullptr) {
1625 if (Constant *LC = dyn_cast<Constant>(LHS))
1626 if (Constant *RC = dyn_cast<Constant>(RHS))
1627 return Insert(Folder.CreateFCmp(P, LC, RC), Name);
1628 return Insert(AddFPMathAttributes(new FCmpInst(P, LHS, RHS),
1629 FPMathTag, FMF), Name);
1632 //===--------------------------------------------------------------------===//
1633 // Instruction creation methods: Other Instructions
1634 //===--------------------------------------------------------------------===//
1636 PHINode *CreatePHI(Type *Ty, unsigned NumReservedValues,
1637 const Twine &Name = "") {
1638 return Insert(PHINode::Create(Ty, NumReservedValues), Name);
1641 CallInst *CreateCall(Value *Callee, ArrayRef<Value *> Args = None,
1642 const Twine &Name = "", MDNode *FPMathTag = nullptr) {
1643 PointerType *PTy = cast<PointerType>(Callee->getType());
1644 FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1645 return CreateCall(FTy, Callee, Args, Name, FPMathTag);
1648 CallInst *CreateCall(FunctionType *FTy, Value *Callee,
1649 ArrayRef<Value *> Args, const Twine &Name = "",
1650 MDNode *FPMathTag = nullptr) {
1651 CallInst *CI = CallInst::Create(FTy, Callee, Args, DefaultOperandBundles);
1652 if (isa<FPMathOperator>(CI))
1653 CI = cast<CallInst>(AddFPMathAttributes(CI, FPMathTag, FMF));
1654 return Insert(CI, Name);
1657 CallInst *CreateCall(Value *Callee, ArrayRef<Value *> Args,
1658 ArrayRef<OperandBundleDef> OpBundles,
1659 const Twine &Name = "", MDNode *FPMathTag = nullptr) {
1660 CallInst *CI = CallInst::Create(Callee, Args, OpBundles);
1661 if (isa<FPMathOperator>(CI))
1662 CI = cast<CallInst>(AddFPMathAttributes(CI, FPMathTag, FMF));
1663 return Insert(CI, Name);
1666 CallInst *CreateCall(Function *Callee, ArrayRef<Value *> Args,
1667 const Twine &Name = "", MDNode *FPMathTag = nullptr) {
1668 return CreateCall(Callee->getFunctionType(), Callee, Args, Name, FPMathTag);
1671 Value *CreateSelect(Value *C, Value *True, Value *False,
1672 const Twine &Name = "", Instruction *MDFrom = nullptr) {
1673 if (Constant *CC = dyn_cast<Constant>(C))
1674 if (Constant *TC = dyn_cast<Constant>(True))
1675 if (Constant *FC = dyn_cast<Constant>(False))
1676 return Insert(Folder.CreateSelect(CC, TC, FC), Name);
1678 SelectInst *Sel = SelectInst::Create(C, True, False);
1680 MDNode *Prof = MDFrom->getMetadata(LLVMContext::MD_prof);
1681 MDNode *Unpred = MDFrom->getMetadata(LLVMContext::MD_unpredictable);
1682 Sel = addBranchMetadata(Sel, Prof, Unpred);
1684 return Insert(Sel, Name);
1687 VAArgInst *CreateVAArg(Value *List, Type *Ty, const Twine &Name = "") {
1688 return Insert(new VAArgInst(List, Ty), Name);
1691 Value *CreateExtractElement(Value *Vec, Value *Idx,
1692 const Twine &Name = "") {
1693 if (Constant *VC = dyn_cast<Constant>(Vec))
1694 if (Constant *IC = dyn_cast<Constant>(Idx))
1695 return Insert(Folder.CreateExtractElement(VC, IC), Name);
1696 return Insert(ExtractElementInst::Create(Vec, Idx), Name);
1699 Value *CreateExtractElement(Value *Vec, uint64_t Idx,
1700 const Twine &Name = "") {
1701 return CreateExtractElement(Vec, getInt64(Idx), Name);
1704 Value *CreateInsertElement(Value *Vec, Value *NewElt, Value *Idx,
1705 const Twine &Name = "") {
1706 if (Constant *VC = dyn_cast<Constant>(Vec))
1707 if (Constant *NC = dyn_cast<Constant>(NewElt))
1708 if (Constant *IC = dyn_cast<Constant>(Idx))
1709 return Insert(Folder.CreateInsertElement(VC, NC, IC), Name);
1710 return Insert(InsertElementInst::Create(Vec, NewElt, Idx), Name);
1713 Value *CreateInsertElement(Value *Vec, Value *NewElt, uint64_t Idx,
1714 const Twine &Name = "") {
1715 return CreateInsertElement(Vec, NewElt, getInt64(Idx), Name);
1718 Value *CreateShuffleVector(Value *V1, Value *V2, Value *Mask,
1719 const Twine &Name = "") {
1720 if (Constant *V1C = dyn_cast<Constant>(V1))
1721 if (Constant *V2C = dyn_cast<Constant>(V2))
1722 if (Constant *MC = dyn_cast<Constant>(Mask))
1723 return Insert(Folder.CreateShuffleVector(V1C, V2C, MC), Name);
1724 return Insert(new ShuffleVectorInst(V1, V2, Mask), Name);
1727 Value *CreateShuffleVector(Value *V1, Value *V2, ArrayRef<uint32_t> IntMask,
1728 const Twine &Name = "") {
1729 Value *Mask = ConstantDataVector::get(Context, IntMask);
1730 return CreateShuffleVector(V1, V2, Mask, Name);
1733 Value *CreateExtractValue(Value *Agg,
1734 ArrayRef<unsigned> Idxs,
1735 const Twine &Name = "") {
1736 if (Constant *AggC = dyn_cast<Constant>(Agg))
1737 return Insert(Folder.CreateExtractValue(AggC, Idxs), Name);
1738 return Insert(ExtractValueInst::Create(Agg, Idxs), Name);
1741 Value *CreateInsertValue(Value *Agg, Value *Val,
1742 ArrayRef<unsigned> Idxs,
1743 const Twine &Name = "") {
1744 if (Constant *AggC = dyn_cast<Constant>(Agg))
1745 if (Constant *ValC = dyn_cast<Constant>(Val))
1746 return Insert(Folder.CreateInsertValue(AggC, ValC, Idxs), Name);
1747 return Insert(InsertValueInst::Create(Agg, Val, Idxs), Name);
1750 LandingPadInst *CreateLandingPad(Type *Ty, unsigned NumClauses,
1751 const Twine &Name = "") {
1752 return Insert(LandingPadInst::Create(Ty, NumClauses), Name);
1755 //===--------------------------------------------------------------------===//
1756 // Utility creation methods
1757 //===--------------------------------------------------------------------===//
1759 /// \brief Return an i1 value testing if \p Arg is null.
1760 Value *CreateIsNull(Value *Arg, const Twine &Name = "") {
1761 return CreateICmpEQ(Arg, Constant::getNullValue(Arg->getType()),
1765 /// \brief Return an i1 value testing if \p Arg is not null.
1766 Value *CreateIsNotNull(Value *Arg, const Twine &Name = "") {
1767 return CreateICmpNE(Arg, Constant::getNullValue(Arg->getType()),
1771 /// \brief Return the i64 difference between two pointer values, dividing out
1772 /// the size of the pointed-to objects.
1774 /// This is intended to implement C-style pointer subtraction. As such, the
1775 /// pointers must be appropriately aligned for their element types and
1776 /// pointing into the same object.
1777 Value *CreatePtrDiff(Value *LHS, Value *RHS, const Twine &Name = "") {
1778 assert(LHS->getType() == RHS->getType() &&
1779 "Pointer subtraction operand types must match!");
1780 PointerType *ArgType = cast<PointerType>(LHS->getType());
1781 Value *LHS_int = CreatePtrToInt(LHS, Type::getInt64Ty(Context));
1782 Value *RHS_int = CreatePtrToInt(RHS, Type::getInt64Ty(Context));
1783 Value *Difference = CreateSub(LHS_int, RHS_int);
1784 return CreateExactSDiv(Difference,
1785 ConstantExpr::getSizeOf(ArgType->getElementType()),
1789 /// \brief Create an invariant.group.barrier intrinsic call, that stops
1790 /// optimizer to propagate equality using invariant.group metadata.
1791 /// If Ptr type is different from i8*, it's casted to i8* before call
1792 /// and casted back to Ptr type after call.
1793 Value *CreateInvariantGroupBarrier(Value *Ptr) {
1794 Module *M = BB->getParent()->getParent();
1795 Function *FnInvariantGroupBarrier = Intrinsic::getDeclaration(M,
1796 Intrinsic::invariant_group_barrier);
1798 Type *ArgumentAndReturnType = FnInvariantGroupBarrier->getReturnType();
1799 assert(ArgumentAndReturnType ==
1800 FnInvariantGroupBarrier->getFunctionType()->getParamType(0) &&
1801 "InvariantGroupBarrier should take and return the same type");
1802 Type *PtrType = Ptr->getType();
1804 bool PtrTypeConversionNeeded = PtrType != ArgumentAndReturnType;
1805 if (PtrTypeConversionNeeded)
1806 Ptr = CreateBitCast(Ptr, ArgumentAndReturnType);
1808 CallInst *Fn = CreateCall(FnInvariantGroupBarrier, {Ptr});
1810 if (PtrTypeConversionNeeded)
1811 return CreateBitCast(Fn, PtrType);
1815 /// \brief Return a vector value that contains \arg V broadcasted to \p
1816 /// NumElts elements.
1817 Value *CreateVectorSplat(unsigned NumElts, Value *V, const Twine &Name = "") {
1818 assert(NumElts > 0 && "Cannot splat to an empty vector!");
1820 // First insert it into an undef vector so we can shuffle it.
1821 Type *I32Ty = getInt32Ty();
1822 Value *Undef = UndefValue::get(VectorType::get(V->getType(), NumElts));
1823 V = CreateInsertElement(Undef, V, ConstantInt::get(I32Ty, 0),
1824 Name + ".splatinsert");
1826 // Shuffle the value across the desired number of elements.
1827 Value *Zeros = ConstantAggregateZero::get(VectorType::get(I32Ty, NumElts));
1828 return CreateShuffleVector(V, Undef, Zeros, Name + ".splat");
1831 /// \brief Return a value that has been extracted from a larger integer type.
1832 Value *CreateExtractInteger(const DataLayout &DL, Value *From,
1833 IntegerType *ExtractedTy, uint64_t Offset,
1834 const Twine &Name) {
1835 IntegerType *IntTy = cast<IntegerType>(From->getType());
1836 assert(DL.getTypeStoreSize(ExtractedTy) + Offset <=
1837 DL.getTypeStoreSize(IntTy) &&
1838 "Element extends past full value");
1839 uint64_t ShAmt = 8 * Offset;
1841 if (DL.isBigEndian())
1842 ShAmt = 8 * (DL.getTypeStoreSize(IntTy) -
1843 DL.getTypeStoreSize(ExtractedTy) - Offset);
1845 V = CreateLShr(V, ShAmt, Name + ".shift");
1847 assert(ExtractedTy->getBitWidth() <= IntTy->getBitWidth() &&
1848 "Cannot extract to a larger integer!");
1849 if (ExtractedTy != IntTy) {
1850 V = CreateTrunc(V, ExtractedTy, Name + ".trunc");
1856 /// \brief Helper function that creates an assume intrinsic call that
1857 /// represents an alignment assumption on the provided Ptr, Mask, Type
1859 CallInst *CreateAlignmentAssumptionHelper(const DataLayout &DL,
1860 Value *PtrValue, Value *Mask,
1862 Value *OffsetValue) {
1863 Value *PtrIntValue = CreatePtrToInt(PtrValue, IntPtrTy, "ptrint");
1866 bool IsOffsetZero = false;
1867 if (ConstantInt *CI = dyn_cast<ConstantInt>(OffsetValue))
1868 IsOffsetZero = CI->isZero();
1870 if (!IsOffsetZero) {
1871 if (OffsetValue->getType() != IntPtrTy)
1872 OffsetValue = CreateIntCast(OffsetValue, IntPtrTy, /*isSigned*/ true,
1874 PtrIntValue = CreateSub(PtrIntValue, OffsetValue, "offsetptr");
1878 Value *Zero = ConstantInt::get(IntPtrTy, 0);
1879 Value *MaskedPtr = CreateAnd(PtrIntValue, Mask, "maskedptr");
1880 Value *InvCond = CreateICmpEQ(MaskedPtr, Zero, "maskcond");
1881 return CreateAssumption(InvCond);
1885 /// \brief Create an assume intrinsic call that represents an alignment
1886 /// assumption on the provided pointer.
1888 /// An optional offset can be provided, and if it is provided, the offset
1889 /// must be subtracted from the provided pointer to get the pointer with the
1890 /// specified alignment.
1891 CallInst *CreateAlignmentAssumption(const DataLayout &DL, Value *PtrValue,
1893 Value *OffsetValue = nullptr) {
1894 assert(isa<PointerType>(PtrValue->getType()) &&
1895 "trying to create an alignment assumption on a non-pointer?");
1896 PointerType *PtrTy = cast<PointerType>(PtrValue->getType());
1897 Type *IntPtrTy = getIntPtrTy(DL, PtrTy->getAddressSpace());
1899 Value *Mask = ConstantInt::get(IntPtrTy, Alignment > 0 ? Alignment - 1 : 0);
1900 return CreateAlignmentAssumptionHelper(DL, PtrValue, Mask, IntPtrTy,
1904 /// \brief Create an assume intrinsic call that represents an alignment
1905 /// assumption on the provided pointer.
1907 /// An optional offset can be provided, and if it is provided, the offset
1908 /// must be subtracted from the provided pointer to get the pointer with the
1909 /// specified alignment.
1911 /// This overload handles the condition where the Alignment is dependent
1912 /// on an existing value rather than a static value.
1913 CallInst *CreateAlignmentAssumption(const DataLayout &DL, Value *PtrValue,
1915 Value *OffsetValue = nullptr) {
1916 assert(isa<PointerType>(PtrValue->getType()) &&
1917 "trying to create an alignment assumption on a non-pointer?");
1918 PointerType *PtrTy = cast<PointerType>(PtrValue->getType());
1919 Type *IntPtrTy = getIntPtrTy(DL, PtrTy->getAddressSpace());
1921 if (Alignment->getType() != IntPtrTy)
1922 Alignment = CreateIntCast(Alignment, IntPtrTy, /*isSigned*/ true,
1925 CreateICmp(CmpInst::ICMP_SGT, Alignment,
1926 ConstantInt::get(Alignment->getType(), 0), "ispositive");
1927 Value *PositiveMask =
1928 CreateSub(Alignment, ConstantInt::get(IntPtrTy, 1), "positivemask");
1929 Value *Mask = CreateSelect(IsPositive, PositiveMask,
1930 ConstantInt::get(IntPtrTy, 0), "mask");
1932 return CreateAlignmentAssumptionHelper(DL, PtrValue, Mask, IntPtrTy,
1937 // Create wrappers for C Binding types (see CBindingWrapping.h).
1938 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(IRBuilder<>, LLVMBuilderRef)
1940 } // end namespace llvm
1942 #endif // LLVM_IR_IRBUILDER_H