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/Function.h"
25 #include "llvm/IR/GlobalVariable.h"
26 #include "llvm/IR/Instructions.h"
27 #include "llvm/IR/Intrinsics.h"
28 #include "llvm/IR/LLVMContext.h"
29 #include "llvm/IR/Operator.h"
30 #include "llvm/IR/ValueHandle.h"
31 #include "llvm/Support/CBindingWrapping.h"
36 /// \brief This provides the default implementation of the IRBuilder
37 /// 'InsertHelper' method that is called whenever an instruction is created by
38 /// IRBuilder and needs to be inserted.
40 /// By default, this inserts the instruction at the insertion point.
41 template <bool preserveNames = true>
42 class IRBuilderDefaultInserter {
44 void InsertHelper(Instruction *I, const Twine &Name,
45 BasicBlock *BB, BasicBlock::iterator InsertPt) const {
46 if (BB) BB->getInstList().insert(InsertPt, I);
52 /// \brief Common base class shared among various IRBuilders.
54 DebugLoc CurDbgLocation;
57 BasicBlock::iterator InsertPt;
60 MDNode *DefaultFPMathTag;
64 IRBuilderBase(LLVMContext &context, MDNode *FPMathTag = nullptr)
65 : Context(context), DefaultFPMathTag(FPMathTag), FMF() {
66 ClearInsertionPoint();
69 //===--------------------------------------------------------------------===//
70 // Builder configuration methods
71 //===--------------------------------------------------------------------===//
73 /// \brief Clear the insertion point: created instructions will not be
74 /// inserted into a block.
75 void ClearInsertionPoint() {
80 BasicBlock *GetInsertBlock() const { return BB; }
81 BasicBlock::iterator GetInsertPoint() const { return InsertPt; }
82 LLVMContext &getContext() const { return Context; }
84 /// \brief This specifies that created instructions should be appended to the
85 /// end of the specified block.
86 void SetInsertPoint(BasicBlock *TheBB) {
91 /// \brief This specifies that created instructions should be inserted before
92 /// the specified instruction.
93 void SetInsertPoint(Instruction *I) {
96 assert(I != BB->end() && "Can't read debug loc from end()");
97 SetCurrentDebugLocation(I->getDebugLoc());
100 /// \brief This specifies that created instructions should be inserted at the
102 void SetInsertPoint(BasicBlock *TheBB, BasicBlock::iterator IP) {
105 if (IP != TheBB->end())
106 SetCurrentDebugLocation(IP->getDebugLoc());
109 /// \brief Set location information used by debugging information.
110 void SetCurrentDebugLocation(DebugLoc L) { CurDbgLocation = std::move(L); }
112 /// \brief Get location information used by debugging information.
113 const DebugLoc &getCurrentDebugLocation() const { return CurDbgLocation; }
115 /// \brief If this builder has a current debug location, set it on the
116 /// specified instruction.
117 void SetInstDebugLocation(Instruction *I) const {
119 I->setDebugLoc(CurDbgLocation);
122 /// \brief Get the return type of the current function that we're emitting
124 Type *getCurrentFunctionReturnType() const;
126 /// InsertPoint - A saved insertion point.
129 BasicBlock::iterator Point;
132 /// \brief Creates a new insertion point which doesn't point to anything.
133 InsertPoint() : Block(nullptr) {}
135 /// \brief Creates a new insertion point at the given location.
136 InsertPoint(BasicBlock *InsertBlock, BasicBlock::iterator InsertPoint)
137 : Block(InsertBlock), Point(InsertPoint) {}
139 /// \brief Returns true if this insert point is set.
140 bool isSet() const { return (Block != nullptr); }
142 llvm::BasicBlock *getBlock() const { return Block; }
143 llvm::BasicBlock::iterator getPoint() const { return Point; }
146 /// \brief Returns the current insert point.
147 InsertPoint saveIP() const {
148 return InsertPoint(GetInsertBlock(), GetInsertPoint());
151 /// \brief Returns the current insert point, clearing it in the process.
152 InsertPoint saveAndClearIP() {
153 InsertPoint IP(GetInsertBlock(), GetInsertPoint());
154 ClearInsertionPoint();
158 /// \brief Sets the current insert point to a previously-saved location.
159 void restoreIP(InsertPoint IP) {
161 SetInsertPoint(IP.getBlock(), IP.getPoint());
163 ClearInsertionPoint();
166 /// \brief Get the floating point math metadata being used.
167 MDNode *getDefaultFPMathTag() const { return DefaultFPMathTag; }
169 /// \brief Get the flags to be applied to created floating point ops
170 FastMathFlags getFastMathFlags() const { return FMF; }
172 /// \brief Clear the fast-math flags.
173 void clearFastMathFlags() { FMF.clear(); }
175 /// \brief Set the floating point math metadata to be used.
176 void SetDefaultFPMathTag(MDNode *FPMathTag) { DefaultFPMathTag = FPMathTag; }
178 /// \brief Set the fast-math flags to be used with generated fp-math operators
179 void SetFastMathFlags(FastMathFlags NewFMF) { FMF = NewFMF; }
181 //===--------------------------------------------------------------------===//
183 //===--------------------------------------------------------------------===//
185 // \brief RAII object that stores the current insertion point and restores it
186 // when the object is destroyed. This includes the debug location.
187 class InsertPointGuard {
188 IRBuilderBase &Builder;
189 AssertingVH<BasicBlock> Block;
190 BasicBlock::iterator Point;
193 InsertPointGuard(const InsertPointGuard &) = delete;
194 InsertPointGuard &operator=(const InsertPointGuard &) = delete;
197 InsertPointGuard(IRBuilderBase &B)
198 : Builder(B), Block(B.GetInsertBlock()), Point(B.GetInsertPoint()),
199 DbgLoc(B.getCurrentDebugLocation()) {}
201 ~InsertPointGuard() {
202 Builder.restoreIP(InsertPoint(Block, Point));
203 Builder.SetCurrentDebugLocation(DbgLoc);
207 // \brief RAII object that stores the current fast math settings and restores
208 // them when the object is destroyed.
209 class FastMathFlagGuard {
210 IRBuilderBase &Builder;
214 FastMathFlagGuard(const FastMathFlagGuard &) = delete;
215 FastMathFlagGuard &operator=(
216 const FastMathFlagGuard &) = delete;
219 FastMathFlagGuard(IRBuilderBase &B)
220 : Builder(B), FMF(B.FMF), FPMathTag(B.DefaultFPMathTag) {}
222 ~FastMathFlagGuard() {
224 Builder.DefaultFPMathTag = FPMathTag;
228 //===--------------------------------------------------------------------===//
229 // Miscellaneous creation methods.
230 //===--------------------------------------------------------------------===//
232 /// \brief Make a new global variable with initializer type i8*
234 /// Make a new global variable with an initializer that has array of i8 type
235 /// filled in with the null terminated string value specified. The new global
236 /// variable will be marked mergable with any others of the same contents. If
237 /// Name is specified, it is the name of the global variable created.
238 GlobalVariable *CreateGlobalString(StringRef Str, const Twine &Name = "",
239 unsigned AddressSpace = 0);
241 /// \brief Get a constant value representing either true or false.
242 ConstantInt *getInt1(bool V) {
243 return ConstantInt::get(getInt1Ty(), V);
246 /// \brief Get the constant value for i1 true.
247 ConstantInt *getTrue() {
248 return ConstantInt::getTrue(Context);
251 /// \brief Get the constant value for i1 false.
252 ConstantInt *getFalse() {
253 return ConstantInt::getFalse(Context);
256 /// \brief Get a constant 8-bit value.
257 ConstantInt *getInt8(uint8_t C) {
258 return ConstantInt::get(getInt8Ty(), C);
261 /// \brief Get a constant 16-bit value.
262 ConstantInt *getInt16(uint16_t C) {
263 return ConstantInt::get(getInt16Ty(), C);
266 /// \brief Get a constant 32-bit value.
267 ConstantInt *getInt32(uint32_t C) {
268 return ConstantInt::get(getInt32Ty(), C);
271 /// \brief Get a constant 64-bit value.
272 ConstantInt *getInt64(uint64_t C) {
273 return ConstantInt::get(getInt64Ty(), C);
276 /// \brief Get a constant N-bit value, zero extended or truncated from
278 ConstantInt *getIntN(unsigned N, uint64_t C) {
279 return ConstantInt::get(getIntNTy(N), C);
282 /// \brief Get a constant integer value.
283 ConstantInt *getInt(const APInt &AI) {
284 return ConstantInt::get(Context, AI);
287 //===--------------------------------------------------------------------===//
288 // Type creation methods
289 //===--------------------------------------------------------------------===//
291 /// \brief Fetch the type representing a single bit
292 IntegerType *getInt1Ty() {
293 return Type::getInt1Ty(Context);
296 /// \brief Fetch the type representing an 8-bit integer.
297 IntegerType *getInt8Ty() {
298 return Type::getInt8Ty(Context);
301 /// \brief Fetch the type representing a 16-bit integer.
302 IntegerType *getInt16Ty() {
303 return Type::getInt16Ty(Context);
306 /// \brief Fetch the type representing a 32-bit integer.
307 IntegerType *getInt32Ty() {
308 return Type::getInt32Ty(Context);
311 /// \brief Fetch the type representing a 64-bit integer.
312 IntegerType *getInt64Ty() {
313 return Type::getInt64Ty(Context);
316 /// \brief Fetch the type representing a 128-bit integer.
317 IntegerType *getInt128Ty() {
318 return Type::getInt128Ty(Context);
321 /// \brief Fetch the type representing an N-bit integer.
322 IntegerType *getIntNTy(unsigned N) {
323 return Type::getIntNTy(Context, N);
326 /// \brief Fetch the type representing a 16-bit floating point value.
328 return Type::getHalfTy(Context);
331 /// \brief Fetch the type representing a 32-bit floating point value.
333 return Type::getFloatTy(Context);
336 /// \brief Fetch the type representing a 64-bit floating point value.
337 Type *getDoubleTy() {
338 return Type::getDoubleTy(Context);
341 /// \brief Fetch the type representing void.
343 return Type::getVoidTy(Context);
346 /// \brief Fetch the type representing a pointer to an 8-bit integer value.
347 PointerType *getInt8PtrTy(unsigned AddrSpace = 0) {
348 return Type::getInt8PtrTy(Context, AddrSpace);
351 /// \brief Fetch the type representing a pointer to an integer value.
352 IntegerType *getIntPtrTy(const DataLayout &DL, unsigned AddrSpace = 0) {
353 return DL.getIntPtrType(Context, AddrSpace);
356 //===--------------------------------------------------------------------===//
357 // Intrinsic creation methods
358 //===--------------------------------------------------------------------===//
360 /// \brief Create and insert a memset to the specified pointer and the
363 /// If the pointer isn't an i8*, it will be converted. If a TBAA tag is
364 /// specified, it will be added to the instruction. Likewise with alias.scope
365 /// and noalias tags.
366 CallInst *CreateMemSet(Value *Ptr, Value *Val, uint64_t Size, unsigned Align,
367 bool isVolatile = false, MDNode *TBAATag = nullptr,
368 MDNode *ScopeTag = nullptr,
369 MDNode *NoAliasTag = nullptr) {
370 return CreateMemSet(Ptr, Val, getInt64(Size), Align, isVolatile,
371 TBAATag, ScopeTag, NoAliasTag);
374 CallInst *CreateMemSet(Value *Ptr, Value *Val, Value *Size, unsigned Align,
375 bool isVolatile = false, MDNode *TBAATag = nullptr,
376 MDNode *ScopeTag = nullptr,
377 MDNode *NoAliasTag = nullptr);
379 /// \brief Create and insert a memcpy between the specified pointers.
381 /// If the pointers aren't i8*, they will be converted. If a TBAA tag is
382 /// specified, it will be added to the instruction. Likewise with alias.scope
383 /// and noalias tags.
384 CallInst *CreateMemCpy(Value *Dst, Value *Src, uint64_t Size, unsigned Align,
385 bool isVolatile = false, MDNode *TBAATag = nullptr,
386 MDNode *TBAAStructTag = nullptr,
387 MDNode *ScopeTag = nullptr,
388 MDNode *NoAliasTag = nullptr) {
389 return CreateMemCpy(Dst, Src, getInt64(Size), Align, isVolatile, TBAATag,
390 TBAAStructTag, ScopeTag, NoAliasTag);
393 CallInst *CreateMemCpy(Value *Dst, Value *Src, Value *Size, unsigned Align,
394 bool isVolatile = false, MDNode *TBAATag = nullptr,
395 MDNode *TBAAStructTag = nullptr,
396 MDNode *ScopeTag = nullptr,
397 MDNode *NoAliasTag = nullptr);
399 /// \brief Create and insert a memmove between the specified
402 /// If the pointers aren't i8*, they 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 *CreateMemMove(Value *Dst, Value *Src, uint64_t Size, unsigned Align,
406 bool isVolatile = false, MDNode *TBAATag = nullptr,
407 MDNode *ScopeTag = nullptr,
408 MDNode *NoAliasTag = nullptr) {
409 return CreateMemMove(Dst, Src, getInt64(Size), Align, isVolatile,
410 TBAATag, ScopeTag, NoAliasTag);
413 CallInst *CreateMemMove(Value *Dst, Value *Src, Value *Size, unsigned Align,
414 bool isVolatile = false, MDNode *TBAATag = nullptr,
415 MDNode *ScopeTag = nullptr,
416 MDNode *NoAliasTag = nullptr);
418 /// \brief Create a lifetime.start intrinsic.
420 /// If the pointer isn't i8* it will be converted.
421 CallInst *CreateLifetimeStart(Value *Ptr, ConstantInt *Size = nullptr);
423 /// \brief Create a lifetime.end intrinsic.
425 /// If the pointer isn't i8* it will be converted.
426 CallInst *CreateLifetimeEnd(Value *Ptr, ConstantInt *Size = nullptr);
428 /// \brief Create a call to Masked Load intrinsic
429 CallInst *CreateMaskedLoad(Value *Ptr, unsigned Align, Value *Mask,
430 Value *PassThru = 0, const Twine &Name = "");
432 /// \brief Create a call to Masked Store intrinsic
433 CallInst *CreateMaskedStore(Value *Val, Value *Ptr, unsigned Align,
436 /// \brief Create an assume intrinsic call that allows the optimizer to
437 /// assume that the provided condition will be true.
438 CallInst *CreateAssumption(Value *Cond);
440 /// \brief Create a call to the experimental.gc.statepoint intrinsic to
441 /// start a new statepoint sequence.
442 CallInst *CreateGCStatepointCall(uint64_t ID, uint32_t NumPatchBytes,
444 ArrayRef<Value *> CallArgs,
445 ArrayRef<Value *> DeoptArgs,
446 ArrayRef<Value *> GCArgs,
447 const Twine &Name = "");
449 // \brief Conveninence function for the common case when CallArgs are filled
450 // in using makeArrayRef(CS.arg_begin(), CS.arg_end()); Use needs to be
451 // .get()'ed to get the Value pointer.
452 CallInst *CreateGCStatepointCall(uint64_t ID, uint32_t NumPatchBytes,
453 Value *ActualCallee, ArrayRef<Use> CallArgs,
454 ArrayRef<Value *> DeoptArgs,
455 ArrayRef<Value *> GCArgs,
456 const Twine &Name = "");
458 /// brief Create an invoke to the experimental.gc.statepoint intrinsic to
459 /// start a new statepoint sequence.
461 CreateGCStatepointInvoke(uint64_t ID, uint32_t NumPatchBytes,
462 Value *ActualInvokee, BasicBlock *NormalDest,
463 BasicBlock *UnwindDest, ArrayRef<Value *> InvokeArgs,
464 ArrayRef<Value *> DeoptArgs,
465 ArrayRef<Value *> GCArgs, const Twine &Name = "");
467 // Conveninence function for the common case when CallArgs are filled in using
468 // makeArrayRef(CS.arg_begin(), CS.arg_end()); Use needs to be .get()'ed to
471 CreateGCStatepointInvoke(uint64_t ID, uint32_t NumPatchBytes,
472 Value *ActualInvokee, BasicBlock *NormalDest,
473 BasicBlock *UnwindDest, ArrayRef<Use> InvokeArgs,
474 ArrayRef<Value *> DeoptArgs,
475 ArrayRef<Value *> GCArgs, const Twine &Name = "");
477 /// \brief Create a call to the experimental.gc.result intrinsic to extract
478 /// the result from a call wrapped in a statepoint.
479 CallInst *CreateGCResult(Instruction *Statepoint,
481 const Twine &Name = "");
483 /// \brief Create a call to the experimental.gc.relocate intrinsics to
484 /// project the relocated value of one pointer from the statepoint.
485 CallInst *CreateGCRelocate(Instruction *Statepoint,
489 const Twine &Name = "");
492 /// \brief Create a call to a masked intrinsic with given Id.
493 /// Masked intrinsic has only one overloaded type - data type.
494 CallInst *CreateMaskedIntrinsic(Intrinsic::ID Id, ArrayRef<Value *> Ops,
495 Type *DataTy, const Twine &Name = "");
497 Value *getCastedInt8PtrValue(Value *Ptr);
500 /// \brief This provides a uniform API for creating instructions and inserting
501 /// them into a basic block: either at the end of a BasicBlock, or at a specific
502 /// iterator location in a block.
504 /// Note that the builder does not expose the full generality of LLVM
505 /// instructions. For access to extra instruction properties, use the mutators
506 /// (e.g. setVolatile) on the instructions after they have been
507 /// created. Convenience state exists to specify fast-math flags and fp-math
510 /// The first template argument handles whether or not to preserve names in the
511 /// final instruction output. This defaults to on. The second template argument
512 /// specifies a class to use for creating constants. This defaults to creating
513 /// minimally folded constants. The third template argument allows clients to
514 /// specify custom insertion hooks that are called on every newly created
516 template<bool preserveNames = true, typename T = ConstantFolder,
517 typename Inserter = IRBuilderDefaultInserter<preserveNames> >
518 class IRBuilder : public IRBuilderBase, public Inserter {
521 IRBuilder(LLVMContext &C, const T &F, Inserter I = Inserter(),
522 MDNode *FPMathTag = nullptr)
523 : IRBuilderBase(C, FPMathTag), Inserter(std::move(I)), Folder(F) {}
525 explicit IRBuilder(LLVMContext &C, MDNode *FPMathTag = nullptr)
526 : IRBuilderBase(C, FPMathTag), Folder() {
529 explicit IRBuilder(BasicBlock *TheBB, const T &F, MDNode *FPMathTag = nullptr)
530 : IRBuilderBase(TheBB->getContext(), FPMathTag), Folder(F) {
531 SetInsertPoint(TheBB);
534 explicit IRBuilder(BasicBlock *TheBB, MDNode *FPMathTag = nullptr)
535 : IRBuilderBase(TheBB->getContext(), FPMathTag), Folder() {
536 SetInsertPoint(TheBB);
539 explicit IRBuilder(Instruction *IP, MDNode *FPMathTag = nullptr)
540 : IRBuilderBase(IP->getContext(), FPMathTag), Folder() {
544 IRBuilder(BasicBlock *TheBB, BasicBlock::iterator IP, const T& F,
545 MDNode *FPMathTag = nullptr)
546 : IRBuilderBase(TheBB->getContext(), FPMathTag), Folder(F) {
547 SetInsertPoint(TheBB, IP);
550 IRBuilder(BasicBlock *TheBB, BasicBlock::iterator IP,
551 MDNode *FPMathTag = nullptr)
552 : IRBuilderBase(TheBB->getContext(), FPMathTag), Folder() {
553 SetInsertPoint(TheBB, IP);
556 /// \brief Get the constant folder being used.
557 const T &getFolder() { return Folder; }
559 /// \brief Return true if this builder is configured to actually add the
560 /// requested names to IR created through it.
561 bool isNamePreserving() const { return preserveNames; }
563 /// \brief Insert and return the specified instruction.
564 template<typename InstTy>
565 InstTy *Insert(InstTy *I, const Twine &Name = "") const {
566 this->InsertHelper(I, Name, BB, InsertPt);
567 this->SetInstDebugLocation(I);
571 /// \brief No-op overload to handle constants.
572 Constant *Insert(Constant *C, const Twine& = "") const {
576 //===--------------------------------------------------------------------===//
577 // Instruction creation methods: Terminators
578 //===--------------------------------------------------------------------===//
581 /// \brief Helper to add branch weight and unpredictable metadata onto an
583 /// \returns The annotated instruction.
584 template <typename InstTy>
585 InstTy *addBranchMetadata(InstTy *I, MDNode *Weights, MDNode *Unpredictable) {
587 I->setMetadata(LLVMContext::MD_prof, Weights);
589 I->setMetadata(LLVMContext::MD_unpredictable, Unpredictable);
594 /// \brief Create a 'ret void' instruction.
595 ReturnInst *CreateRetVoid() {
596 return Insert(ReturnInst::Create(Context));
599 /// \brief Create a 'ret <val>' instruction.
600 ReturnInst *CreateRet(Value *V) {
601 return Insert(ReturnInst::Create(Context, V));
604 /// \brief Create a sequence of N insertvalue instructions,
605 /// with one Value from the retVals array each, that build a aggregate
606 /// return value one value at a time, and a ret instruction to return
607 /// the resulting aggregate value.
609 /// This is a convenience function for code that uses aggregate return values
610 /// as a vehicle for having multiple return values.
611 ReturnInst *CreateAggregateRet(Value *const *retVals, unsigned N) {
612 Value *V = UndefValue::get(getCurrentFunctionReturnType());
613 for (unsigned i = 0; i != N; ++i)
614 V = CreateInsertValue(V, retVals[i], i, "mrv");
615 return Insert(ReturnInst::Create(Context, V));
618 /// \brief Create an unconditional 'br label X' instruction.
619 BranchInst *CreateBr(BasicBlock *Dest) {
620 return Insert(BranchInst::Create(Dest));
623 /// \brief Create a conditional 'br Cond, TrueDest, FalseDest'
625 BranchInst *CreateCondBr(Value *Cond, BasicBlock *True, BasicBlock *False,
626 MDNode *BranchWeights = nullptr,
627 MDNode *Unpredictable = nullptr) {
628 return Insert(addBranchMetadata(BranchInst::Create(True, False, Cond),
629 BranchWeights, Unpredictable));
632 /// \brief Create a switch instruction with the specified value, default dest,
633 /// and with a hint for the number of cases that will be added (for efficient
635 SwitchInst *CreateSwitch(Value *V, BasicBlock *Dest, unsigned NumCases = 10,
636 MDNode *BranchWeights = nullptr,
637 MDNode *Unpredictable = nullptr) {
638 return Insert(addBranchMetadata(SwitchInst::Create(V, Dest, NumCases),
639 BranchWeights, Unpredictable));
642 /// \brief Create an indirect branch instruction with the specified address
643 /// operand, with an optional hint for the number of destinations that will be
644 /// added (for efficient allocation).
645 IndirectBrInst *CreateIndirectBr(Value *Addr, unsigned NumDests = 10) {
646 return Insert(IndirectBrInst::Create(Addr, NumDests));
649 InvokeInst *CreateInvoke(Value *Callee, BasicBlock *NormalDest,
650 BasicBlock *UnwindDest, const Twine &Name = "") {
651 return Insert(InvokeInst::Create(Callee, NormalDest, UnwindDest, None),
654 InvokeInst *CreateInvoke(Value *Callee, BasicBlock *NormalDest,
655 BasicBlock *UnwindDest, Value *Arg1,
656 const Twine &Name = "") {
657 return Insert(InvokeInst::Create(Callee, NormalDest, UnwindDest, Arg1),
660 InvokeInst *CreateInvoke3(Value *Callee, BasicBlock *NormalDest,
661 BasicBlock *UnwindDest, Value *Arg1,
662 Value *Arg2, Value *Arg3,
663 const Twine &Name = "") {
664 Value *Args[] = { Arg1, Arg2, Arg3 };
665 return Insert(InvokeInst::Create(Callee, NormalDest, UnwindDest, Args),
668 /// \brief Create an invoke instruction.
669 InvokeInst *CreateInvoke(Value *Callee, BasicBlock *NormalDest,
670 BasicBlock *UnwindDest, ArrayRef<Value *> Args,
671 const Twine &Name = "") {
672 return Insert(InvokeInst::Create(Callee, NormalDest, UnwindDest, Args),
676 ResumeInst *CreateResume(Value *Exn) {
677 return Insert(ResumeInst::Create(Exn));
680 CleanupReturnInst *CreateCleanupRet(CleanupPadInst *CleanupPad,
681 BasicBlock *UnwindBB = nullptr) {
682 return Insert(CleanupReturnInst::Create(CleanupPad, UnwindBB));
685 CleanupEndPadInst *CreateCleanupEndPad(CleanupPadInst *CleanupPad,
686 BasicBlock *UnwindBB = nullptr) {
687 return Insert(CleanupEndPadInst::Create(CleanupPad, UnwindBB));
690 CatchPadInst *CreateCatchPad(BasicBlock *NormalDest, BasicBlock *UnwindDest,
691 ArrayRef<Value *> Args, const Twine &Name = "") {
692 return Insert(CatchPadInst::Create(NormalDest, UnwindDest, Args), Name);
695 CatchEndPadInst *CreateCatchEndPad(BasicBlock *UnwindBB = nullptr) {
696 return Insert(CatchEndPadInst::Create(Context, UnwindBB));
699 TerminatePadInst *CreateTerminatePad(BasicBlock *UnwindBB = nullptr,
700 ArrayRef<Value *> Args = {},
701 const Twine &Name = "") {
702 return Insert(TerminatePadInst::Create(Context, UnwindBB, Args), Name);
705 CleanupPadInst *CreateCleanupPad(ArrayRef<Value *> Args,
706 const Twine &Name = "") {
707 return Insert(CleanupPadInst::Create(Context, Args), Name);
710 CatchReturnInst *CreateCatchRet(CatchPadInst *CatchPad, BasicBlock *BB) {
711 return Insert(CatchReturnInst::Create(CatchPad, BB));
714 UnreachableInst *CreateUnreachable() {
715 return Insert(new UnreachableInst(Context));
718 //===--------------------------------------------------------------------===//
719 // Instruction creation methods: Binary Operators
720 //===--------------------------------------------------------------------===//
722 BinaryOperator *CreateInsertNUWNSWBinOp(BinaryOperator::BinaryOps Opc,
723 Value *LHS, Value *RHS,
725 bool HasNUW, bool HasNSW) {
726 BinaryOperator *BO = Insert(BinaryOperator::Create(Opc, LHS, RHS), Name);
727 if (HasNUW) BO->setHasNoUnsignedWrap();
728 if (HasNSW) BO->setHasNoSignedWrap();
732 Instruction *AddFPMathAttributes(Instruction *I,
734 FastMathFlags FMF) const {
736 FPMathTag = DefaultFPMathTag;
738 I->setMetadata(LLVMContext::MD_fpmath, FPMathTag);
739 I->setFastMathFlags(FMF);
743 Value *CreateAdd(Value *LHS, Value *RHS, const Twine &Name = "",
744 bool HasNUW = false, bool HasNSW = false) {
745 if (Constant *LC = dyn_cast<Constant>(LHS))
746 if (Constant *RC = dyn_cast<Constant>(RHS))
747 return Insert(Folder.CreateAdd(LC, RC, HasNUW, HasNSW), Name);
748 return CreateInsertNUWNSWBinOp(Instruction::Add, LHS, RHS, Name,
751 Value *CreateNSWAdd(Value *LHS, Value *RHS, const Twine &Name = "") {
752 return CreateAdd(LHS, RHS, Name, false, true);
754 Value *CreateNUWAdd(Value *LHS, Value *RHS, const Twine &Name = "") {
755 return CreateAdd(LHS, RHS, Name, true, false);
757 Value *CreateFAdd(Value *LHS, Value *RHS, const Twine &Name = "",
758 MDNode *FPMathTag = nullptr) {
759 if (Constant *LC = dyn_cast<Constant>(LHS))
760 if (Constant *RC = dyn_cast<Constant>(RHS))
761 return Insert(Folder.CreateFAdd(LC, RC), Name);
762 return Insert(AddFPMathAttributes(BinaryOperator::CreateFAdd(LHS, RHS),
763 FPMathTag, FMF), Name);
765 Value *CreateSub(Value *LHS, Value *RHS, const Twine &Name = "",
766 bool HasNUW = false, bool HasNSW = false) {
767 if (Constant *LC = dyn_cast<Constant>(LHS))
768 if (Constant *RC = dyn_cast<Constant>(RHS))
769 return Insert(Folder.CreateSub(LC, RC, HasNUW, HasNSW), Name);
770 return CreateInsertNUWNSWBinOp(Instruction::Sub, LHS, RHS, Name,
773 Value *CreateNSWSub(Value *LHS, Value *RHS, const Twine &Name = "") {
774 return CreateSub(LHS, RHS, Name, false, true);
776 Value *CreateNUWSub(Value *LHS, Value *RHS, const Twine &Name = "") {
777 return CreateSub(LHS, RHS, Name, true, false);
779 Value *CreateFSub(Value *LHS, Value *RHS, const Twine &Name = "",
780 MDNode *FPMathTag = nullptr) {
781 if (Constant *LC = dyn_cast<Constant>(LHS))
782 if (Constant *RC = dyn_cast<Constant>(RHS))
783 return Insert(Folder.CreateFSub(LC, RC), Name);
784 return Insert(AddFPMathAttributes(BinaryOperator::CreateFSub(LHS, RHS),
785 FPMathTag, FMF), Name);
787 Value *CreateMul(Value *LHS, Value *RHS, const Twine &Name = "",
788 bool HasNUW = false, bool HasNSW = false) {
789 if (Constant *LC = dyn_cast<Constant>(LHS))
790 if (Constant *RC = dyn_cast<Constant>(RHS))
791 return Insert(Folder.CreateMul(LC, RC, HasNUW, HasNSW), Name);
792 return CreateInsertNUWNSWBinOp(Instruction::Mul, LHS, RHS, Name,
795 Value *CreateNSWMul(Value *LHS, Value *RHS, const Twine &Name = "") {
796 return CreateMul(LHS, RHS, Name, false, true);
798 Value *CreateNUWMul(Value *LHS, Value *RHS, const Twine &Name = "") {
799 return CreateMul(LHS, RHS, Name, true, false);
801 Value *CreateFMul(Value *LHS, Value *RHS, const Twine &Name = "",
802 MDNode *FPMathTag = nullptr) {
803 if (Constant *LC = dyn_cast<Constant>(LHS))
804 if (Constant *RC = dyn_cast<Constant>(RHS))
805 return Insert(Folder.CreateFMul(LC, RC), Name);
806 return Insert(AddFPMathAttributes(BinaryOperator::CreateFMul(LHS, RHS),
807 FPMathTag, FMF), Name);
809 Value *CreateUDiv(Value *LHS, Value *RHS, const Twine &Name = "",
810 bool isExact = false) {
811 if (Constant *LC = dyn_cast<Constant>(LHS))
812 if (Constant *RC = dyn_cast<Constant>(RHS))
813 return Insert(Folder.CreateUDiv(LC, RC, isExact), Name);
815 return Insert(BinaryOperator::CreateUDiv(LHS, RHS), Name);
816 return Insert(BinaryOperator::CreateExactUDiv(LHS, RHS), Name);
818 Value *CreateExactUDiv(Value *LHS, Value *RHS, const Twine &Name = "") {
819 return CreateUDiv(LHS, RHS, Name, true);
821 Value *CreateSDiv(Value *LHS, Value *RHS, const Twine &Name = "",
822 bool isExact = false) {
823 if (Constant *LC = dyn_cast<Constant>(LHS))
824 if (Constant *RC = dyn_cast<Constant>(RHS))
825 return Insert(Folder.CreateSDiv(LC, RC, isExact), Name);
827 return Insert(BinaryOperator::CreateSDiv(LHS, RHS), Name);
828 return Insert(BinaryOperator::CreateExactSDiv(LHS, RHS), Name);
830 Value *CreateExactSDiv(Value *LHS, Value *RHS, const Twine &Name = "") {
831 return CreateSDiv(LHS, RHS, Name, true);
833 Value *CreateFDiv(Value *LHS, Value *RHS, const Twine &Name = "",
834 MDNode *FPMathTag = nullptr) {
835 if (Constant *LC = dyn_cast<Constant>(LHS))
836 if (Constant *RC = dyn_cast<Constant>(RHS))
837 return Insert(Folder.CreateFDiv(LC, RC), Name);
838 return Insert(AddFPMathAttributes(BinaryOperator::CreateFDiv(LHS, RHS),
839 FPMathTag, FMF), Name);
841 Value *CreateURem(Value *LHS, Value *RHS, const Twine &Name = "") {
842 if (Constant *LC = dyn_cast<Constant>(LHS))
843 if (Constant *RC = dyn_cast<Constant>(RHS))
844 return Insert(Folder.CreateURem(LC, RC), Name);
845 return Insert(BinaryOperator::CreateURem(LHS, RHS), Name);
847 Value *CreateSRem(Value *LHS, Value *RHS, const Twine &Name = "") {
848 if (Constant *LC = dyn_cast<Constant>(LHS))
849 if (Constant *RC = dyn_cast<Constant>(RHS))
850 return Insert(Folder.CreateSRem(LC, RC), Name);
851 return Insert(BinaryOperator::CreateSRem(LHS, RHS), Name);
853 Value *CreateFRem(Value *LHS, Value *RHS, const Twine &Name = "",
854 MDNode *FPMathTag = nullptr) {
855 if (Constant *LC = dyn_cast<Constant>(LHS))
856 if (Constant *RC = dyn_cast<Constant>(RHS))
857 return Insert(Folder.CreateFRem(LC, RC), Name);
858 return Insert(AddFPMathAttributes(BinaryOperator::CreateFRem(LHS, RHS),
859 FPMathTag, FMF), Name);
862 Value *CreateShl(Value *LHS, Value *RHS, const Twine &Name = "",
863 bool HasNUW = false, bool HasNSW = false) {
864 if (Constant *LC = dyn_cast<Constant>(LHS))
865 if (Constant *RC = dyn_cast<Constant>(RHS))
866 return Insert(Folder.CreateShl(LC, RC, HasNUW, HasNSW), Name);
867 return CreateInsertNUWNSWBinOp(Instruction::Shl, LHS, RHS, Name,
870 Value *CreateShl(Value *LHS, const APInt &RHS, const Twine &Name = "",
871 bool HasNUW = false, bool HasNSW = false) {
872 return CreateShl(LHS, ConstantInt::get(LHS->getType(), RHS), Name,
875 Value *CreateShl(Value *LHS, uint64_t RHS, const Twine &Name = "",
876 bool HasNUW = false, bool HasNSW = false) {
877 return CreateShl(LHS, ConstantInt::get(LHS->getType(), RHS), Name,
881 Value *CreateLShr(Value *LHS, Value *RHS, const Twine &Name = "",
882 bool isExact = false) {
883 if (Constant *LC = dyn_cast<Constant>(LHS))
884 if (Constant *RC = dyn_cast<Constant>(RHS))
885 return Insert(Folder.CreateLShr(LC, RC, isExact), Name);
887 return Insert(BinaryOperator::CreateLShr(LHS, RHS), Name);
888 return Insert(BinaryOperator::CreateExactLShr(LHS, RHS), Name);
890 Value *CreateLShr(Value *LHS, const APInt &RHS, const Twine &Name = "",
891 bool isExact = false) {
892 return CreateLShr(LHS, ConstantInt::get(LHS->getType(), RHS), Name,isExact);
894 Value *CreateLShr(Value *LHS, uint64_t RHS, const Twine &Name = "",
895 bool isExact = false) {
896 return CreateLShr(LHS, ConstantInt::get(LHS->getType(), RHS), Name,isExact);
899 Value *CreateAShr(Value *LHS, Value *RHS, const Twine &Name = "",
900 bool isExact = false) {
901 if (Constant *LC = dyn_cast<Constant>(LHS))
902 if (Constant *RC = dyn_cast<Constant>(RHS))
903 return Insert(Folder.CreateAShr(LC, RC, isExact), Name);
905 return Insert(BinaryOperator::CreateAShr(LHS, RHS), Name);
906 return Insert(BinaryOperator::CreateExactAShr(LHS, RHS), Name);
908 Value *CreateAShr(Value *LHS, const APInt &RHS, const Twine &Name = "",
909 bool isExact = false) {
910 return CreateAShr(LHS, ConstantInt::get(LHS->getType(), RHS), Name,isExact);
912 Value *CreateAShr(Value *LHS, uint64_t RHS, const Twine &Name = "",
913 bool isExact = false) {
914 return CreateAShr(LHS, ConstantInt::get(LHS->getType(), RHS), Name,isExact);
917 Value *CreateAnd(Value *LHS, Value *RHS, const Twine &Name = "") {
918 if (Constant *RC = dyn_cast<Constant>(RHS)) {
919 if (isa<ConstantInt>(RC) && cast<ConstantInt>(RC)->isAllOnesValue())
920 return LHS; // LHS & -1 -> LHS
921 if (Constant *LC = dyn_cast<Constant>(LHS))
922 return Insert(Folder.CreateAnd(LC, RC), Name);
924 return Insert(BinaryOperator::CreateAnd(LHS, RHS), Name);
926 Value *CreateAnd(Value *LHS, const APInt &RHS, const Twine &Name = "") {
927 return CreateAnd(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
929 Value *CreateAnd(Value *LHS, uint64_t RHS, const Twine &Name = "") {
930 return CreateAnd(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
933 Value *CreateOr(Value *LHS, Value *RHS, const Twine &Name = "") {
934 if (Constant *RC = dyn_cast<Constant>(RHS)) {
935 if (RC->isNullValue())
936 return LHS; // LHS | 0 -> LHS
937 if (Constant *LC = dyn_cast<Constant>(LHS))
938 return Insert(Folder.CreateOr(LC, RC), Name);
940 return Insert(BinaryOperator::CreateOr(LHS, RHS), Name);
942 Value *CreateOr(Value *LHS, const APInt &RHS, const Twine &Name = "") {
943 return CreateOr(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
945 Value *CreateOr(Value *LHS, uint64_t RHS, const Twine &Name = "") {
946 return CreateOr(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
949 Value *CreateXor(Value *LHS, Value *RHS, const Twine &Name = "") {
950 if (Constant *LC = dyn_cast<Constant>(LHS))
951 if (Constant *RC = dyn_cast<Constant>(RHS))
952 return Insert(Folder.CreateXor(LC, RC), Name);
953 return Insert(BinaryOperator::CreateXor(LHS, RHS), Name);
955 Value *CreateXor(Value *LHS, const APInt &RHS, const Twine &Name = "") {
956 return CreateXor(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
958 Value *CreateXor(Value *LHS, uint64_t RHS, const Twine &Name = "") {
959 return CreateXor(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
962 Value *CreateBinOp(Instruction::BinaryOps Opc,
963 Value *LHS, Value *RHS, const Twine &Name = "",
964 MDNode *FPMathTag = nullptr) {
965 if (Constant *LC = dyn_cast<Constant>(LHS))
966 if (Constant *RC = dyn_cast<Constant>(RHS))
967 return Insert(Folder.CreateBinOp(Opc, LC, RC), Name);
968 llvm::Instruction *BinOp = BinaryOperator::Create(Opc, LHS, RHS);
969 if (isa<FPMathOperator>(BinOp))
970 BinOp = AddFPMathAttributes(BinOp, FPMathTag, FMF);
971 return Insert(BinOp, Name);
974 Value *CreateNeg(Value *V, const Twine &Name = "",
975 bool HasNUW = false, bool HasNSW = false) {
976 if (Constant *VC = dyn_cast<Constant>(V))
977 return Insert(Folder.CreateNeg(VC, HasNUW, HasNSW), Name);
978 BinaryOperator *BO = Insert(BinaryOperator::CreateNeg(V), Name);
979 if (HasNUW) BO->setHasNoUnsignedWrap();
980 if (HasNSW) BO->setHasNoSignedWrap();
983 Value *CreateNSWNeg(Value *V, const Twine &Name = "") {
984 return CreateNeg(V, Name, false, true);
986 Value *CreateNUWNeg(Value *V, const Twine &Name = "") {
987 return CreateNeg(V, Name, true, false);
989 Value *CreateFNeg(Value *V, const Twine &Name = "",
990 MDNode *FPMathTag = nullptr) {
991 if (Constant *VC = dyn_cast<Constant>(V))
992 return Insert(Folder.CreateFNeg(VC), Name);
993 return Insert(AddFPMathAttributes(BinaryOperator::CreateFNeg(V),
994 FPMathTag, FMF), Name);
996 Value *CreateNot(Value *V, const Twine &Name = "") {
997 if (Constant *VC = dyn_cast<Constant>(V))
998 return Insert(Folder.CreateNot(VC), Name);
999 return Insert(BinaryOperator::CreateNot(V), Name);
1002 //===--------------------------------------------------------------------===//
1003 // Instruction creation methods: Memory Instructions
1004 //===--------------------------------------------------------------------===//
1006 AllocaInst *CreateAlloca(Type *Ty, Value *ArraySize = nullptr,
1007 const Twine &Name = "") {
1008 return Insert(new AllocaInst(Ty, ArraySize), Name);
1010 // \brief Provided to resolve 'CreateLoad(Ptr, "...")' correctly, instead of
1011 // converting the string to 'bool' for the isVolatile parameter.
1012 LoadInst *CreateLoad(Value *Ptr, const char *Name) {
1013 return Insert(new LoadInst(Ptr), Name);
1015 LoadInst *CreateLoad(Value *Ptr, const Twine &Name = "") {
1016 return Insert(new LoadInst(Ptr), Name);
1018 LoadInst *CreateLoad(Type *Ty, Value *Ptr, const Twine &Name = "") {
1019 return Insert(new LoadInst(Ty, Ptr), Name);
1021 LoadInst *CreateLoad(Value *Ptr, bool isVolatile, const Twine &Name = "") {
1022 return Insert(new LoadInst(Ptr, nullptr, isVolatile), Name);
1024 StoreInst *CreateStore(Value *Val, Value *Ptr, bool isVolatile = false) {
1025 return Insert(new StoreInst(Val, Ptr, isVolatile));
1027 // \brief Provided to resolve 'CreateAlignedLoad(Ptr, Align, "...")'
1028 // correctly, instead of converting the string to 'bool' for the isVolatile
1030 LoadInst *CreateAlignedLoad(Value *Ptr, unsigned Align, const char *Name) {
1031 LoadInst *LI = CreateLoad(Ptr, Name);
1032 LI->setAlignment(Align);
1035 LoadInst *CreateAlignedLoad(Value *Ptr, unsigned Align,
1036 const Twine &Name = "") {
1037 LoadInst *LI = CreateLoad(Ptr, Name);
1038 LI->setAlignment(Align);
1041 LoadInst *CreateAlignedLoad(Value *Ptr, unsigned Align, bool isVolatile,
1042 const Twine &Name = "") {
1043 LoadInst *LI = CreateLoad(Ptr, isVolatile, Name);
1044 LI->setAlignment(Align);
1047 StoreInst *CreateAlignedStore(Value *Val, Value *Ptr, unsigned Align,
1048 bool isVolatile = false) {
1049 StoreInst *SI = CreateStore(Val, Ptr, isVolatile);
1050 SI->setAlignment(Align);
1053 FenceInst *CreateFence(AtomicOrdering Ordering,
1054 SynchronizationScope SynchScope = CrossThread,
1055 const Twine &Name = "") {
1056 return Insert(new FenceInst(Context, Ordering, SynchScope), Name);
1059 CreateAtomicCmpXchg(Value *Ptr, Value *Cmp, Value *New,
1060 AtomicOrdering SuccessOrdering,
1061 AtomicOrdering FailureOrdering,
1062 SynchronizationScope SynchScope = CrossThread) {
1063 return Insert(new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering,
1064 FailureOrdering, SynchScope));
1066 AtomicRMWInst *CreateAtomicRMW(AtomicRMWInst::BinOp Op, Value *Ptr, Value *Val,
1067 AtomicOrdering Ordering,
1068 SynchronizationScope SynchScope = CrossThread) {
1069 return Insert(new AtomicRMWInst(Op, Ptr, Val, Ordering, SynchScope));
1071 Value *CreateGEP(Value *Ptr, ArrayRef<Value *> IdxList,
1072 const Twine &Name = "") {
1073 return CreateGEP(nullptr, Ptr, IdxList, Name);
1075 Value *CreateGEP(Type *Ty, Value *Ptr, ArrayRef<Value *> IdxList,
1076 const Twine &Name = "") {
1077 if (Constant *PC = dyn_cast<Constant>(Ptr)) {
1078 // Every index must be constant.
1080 for (i = 0, e = IdxList.size(); i != e; ++i)
1081 if (!isa<Constant>(IdxList[i]))
1084 return Insert(Folder.CreateGetElementPtr(Ty, PC, IdxList), Name);
1086 return Insert(GetElementPtrInst::Create(Ty, Ptr, IdxList), Name);
1088 Value *CreateInBoundsGEP(Value *Ptr, ArrayRef<Value *> IdxList,
1089 const Twine &Name = "") {
1090 return CreateInBoundsGEP(nullptr, Ptr, IdxList, Name);
1092 Value *CreateInBoundsGEP(Type *Ty, Value *Ptr, ArrayRef<Value *> IdxList,
1093 const Twine &Name = "") {
1094 if (Constant *PC = dyn_cast<Constant>(Ptr)) {
1095 // Every index must be constant.
1097 for (i = 0, e = IdxList.size(); i != e; ++i)
1098 if (!isa<Constant>(IdxList[i]))
1101 return Insert(Folder.CreateInBoundsGetElementPtr(Ty, PC, IdxList),
1104 return Insert(GetElementPtrInst::CreateInBounds(Ty, Ptr, IdxList), Name);
1106 Value *CreateGEP(Value *Ptr, Value *Idx, const Twine &Name = "") {
1107 return CreateGEP(nullptr, Ptr, Idx, Name);
1109 Value *CreateGEP(Type *Ty, Value *Ptr, Value *Idx, const Twine &Name = "") {
1110 if (Constant *PC = dyn_cast<Constant>(Ptr))
1111 if (Constant *IC = dyn_cast<Constant>(Idx))
1112 return Insert(Folder.CreateGetElementPtr(Ty, PC, IC), Name);
1113 return Insert(GetElementPtrInst::Create(Ty, Ptr, Idx), Name);
1115 Value *CreateInBoundsGEP(Type *Ty, Value *Ptr, Value *Idx,
1116 const Twine &Name = "") {
1117 if (Constant *PC = dyn_cast<Constant>(Ptr))
1118 if (Constant *IC = dyn_cast<Constant>(Idx))
1119 return Insert(Folder.CreateInBoundsGetElementPtr(Ty, PC, IC), Name);
1120 return Insert(GetElementPtrInst::CreateInBounds(Ty, Ptr, Idx), Name);
1122 Value *CreateConstGEP1_32(Value *Ptr, unsigned Idx0, const Twine &Name = "") {
1123 return CreateConstGEP1_32(nullptr, Ptr, Idx0, Name);
1125 Value *CreateConstGEP1_32(Type *Ty, Value *Ptr, unsigned Idx0,
1126 const Twine &Name = "") {
1127 Value *Idx = ConstantInt::get(Type::getInt32Ty(Context), Idx0);
1129 if (Constant *PC = dyn_cast<Constant>(Ptr))
1130 return Insert(Folder.CreateGetElementPtr(Ty, PC, Idx), Name);
1132 return Insert(GetElementPtrInst::Create(Ty, Ptr, Idx), Name);
1134 Value *CreateConstInBoundsGEP1_32(Type *Ty, Value *Ptr, unsigned Idx0,
1135 const Twine &Name = "") {
1136 Value *Idx = ConstantInt::get(Type::getInt32Ty(Context), Idx0);
1138 if (Constant *PC = dyn_cast<Constant>(Ptr))
1139 return Insert(Folder.CreateInBoundsGetElementPtr(Ty, PC, Idx), Name);
1141 return Insert(GetElementPtrInst::CreateInBounds(Ty, Ptr, Idx), Name);
1143 Value *CreateConstGEP2_32(Type *Ty, Value *Ptr, unsigned Idx0, unsigned Idx1,
1144 const Twine &Name = "") {
1146 ConstantInt::get(Type::getInt32Ty(Context), Idx0),
1147 ConstantInt::get(Type::getInt32Ty(Context), Idx1)
1150 if (Constant *PC = dyn_cast<Constant>(Ptr))
1151 return Insert(Folder.CreateGetElementPtr(Ty, PC, Idxs), Name);
1153 return Insert(GetElementPtrInst::Create(Ty, Ptr, Idxs), Name);
1155 Value *CreateConstInBoundsGEP2_32(Type *Ty, Value *Ptr, unsigned Idx0,
1156 unsigned Idx1, const Twine &Name = "") {
1158 ConstantInt::get(Type::getInt32Ty(Context), Idx0),
1159 ConstantInt::get(Type::getInt32Ty(Context), Idx1)
1162 if (Constant *PC = dyn_cast<Constant>(Ptr))
1163 return Insert(Folder.CreateInBoundsGetElementPtr(Ty, PC, Idxs), Name);
1165 return Insert(GetElementPtrInst::CreateInBounds(Ty, Ptr, Idxs), Name);
1167 Value *CreateConstGEP1_64(Value *Ptr, uint64_t Idx0, const Twine &Name = "") {
1168 Value *Idx = ConstantInt::get(Type::getInt64Ty(Context), Idx0);
1170 if (Constant *PC = dyn_cast<Constant>(Ptr))
1171 return Insert(Folder.CreateGetElementPtr(nullptr, PC, Idx), Name);
1173 return Insert(GetElementPtrInst::Create(nullptr, Ptr, Idx), Name);
1175 Value *CreateConstInBoundsGEP1_64(Value *Ptr, uint64_t Idx0,
1176 const Twine &Name = "") {
1177 Value *Idx = ConstantInt::get(Type::getInt64Ty(Context), Idx0);
1179 if (Constant *PC = dyn_cast<Constant>(Ptr))
1180 return Insert(Folder.CreateInBoundsGetElementPtr(nullptr, PC, Idx), Name);
1182 return Insert(GetElementPtrInst::CreateInBounds(nullptr, Ptr, Idx), Name);
1184 Value *CreateConstGEP2_64(Value *Ptr, uint64_t Idx0, uint64_t Idx1,
1185 const Twine &Name = "") {
1187 ConstantInt::get(Type::getInt64Ty(Context), Idx0),
1188 ConstantInt::get(Type::getInt64Ty(Context), Idx1)
1191 if (Constant *PC = dyn_cast<Constant>(Ptr))
1192 return Insert(Folder.CreateGetElementPtr(nullptr, PC, Idxs), Name);
1194 return Insert(GetElementPtrInst::Create(nullptr, Ptr, Idxs), Name);
1196 Value *CreateConstInBoundsGEP2_64(Value *Ptr, uint64_t Idx0, uint64_t Idx1,
1197 const Twine &Name = "") {
1199 ConstantInt::get(Type::getInt64Ty(Context), Idx0),
1200 ConstantInt::get(Type::getInt64Ty(Context), Idx1)
1203 if (Constant *PC = dyn_cast<Constant>(Ptr))
1204 return Insert(Folder.CreateInBoundsGetElementPtr(nullptr, PC, Idxs),
1207 return Insert(GetElementPtrInst::CreateInBounds(nullptr, Ptr, Idxs), Name);
1209 Value *CreateStructGEP(Type *Ty, Value *Ptr, unsigned Idx,
1210 const Twine &Name = "") {
1211 return CreateConstInBoundsGEP2_32(Ty, Ptr, 0, Idx, Name);
1214 /// \brief Same as CreateGlobalString, but return a pointer with "i8*" type
1215 /// instead of a pointer to array of i8.
1216 Value *CreateGlobalStringPtr(StringRef Str, const Twine &Name = "",
1217 unsigned AddressSpace = 0) {
1218 GlobalVariable *gv = CreateGlobalString(Str, Name, AddressSpace);
1219 Value *zero = ConstantInt::get(Type::getInt32Ty(Context), 0);
1220 Value *Args[] = { zero, zero };
1221 return CreateInBoundsGEP(gv->getValueType(), gv, Args, Name);
1224 //===--------------------------------------------------------------------===//
1225 // Instruction creation methods: Cast/Conversion Operators
1226 //===--------------------------------------------------------------------===//
1228 Value *CreateTrunc(Value *V, Type *DestTy, const Twine &Name = "") {
1229 return CreateCast(Instruction::Trunc, V, DestTy, Name);
1231 Value *CreateZExt(Value *V, Type *DestTy, const Twine &Name = "") {
1232 return CreateCast(Instruction::ZExt, V, DestTy, Name);
1234 Value *CreateSExt(Value *V, Type *DestTy, const Twine &Name = "") {
1235 return CreateCast(Instruction::SExt, V, DestTy, Name);
1237 /// \brief Create a ZExt or Trunc from the integer value V to DestTy. Return
1238 /// the value untouched if the type of V is already DestTy.
1239 Value *CreateZExtOrTrunc(Value *V, Type *DestTy,
1240 const Twine &Name = "") {
1241 assert(V->getType()->isIntOrIntVectorTy() &&
1242 DestTy->isIntOrIntVectorTy() &&
1243 "Can only zero extend/truncate integers!");
1244 Type *VTy = V->getType();
1245 if (VTy->getScalarSizeInBits() < DestTy->getScalarSizeInBits())
1246 return CreateZExt(V, DestTy, Name);
1247 if (VTy->getScalarSizeInBits() > DestTy->getScalarSizeInBits())
1248 return CreateTrunc(V, DestTy, Name);
1251 /// \brief Create a SExt or Trunc from the integer value V to DestTy. Return
1252 /// the value untouched if the type of V is already DestTy.
1253 Value *CreateSExtOrTrunc(Value *V, Type *DestTy,
1254 const Twine &Name = "") {
1255 assert(V->getType()->isIntOrIntVectorTy() &&
1256 DestTy->isIntOrIntVectorTy() &&
1257 "Can only sign extend/truncate integers!");
1258 Type *VTy = V->getType();
1259 if (VTy->getScalarSizeInBits() < DestTy->getScalarSizeInBits())
1260 return CreateSExt(V, DestTy, Name);
1261 if (VTy->getScalarSizeInBits() > DestTy->getScalarSizeInBits())
1262 return CreateTrunc(V, DestTy, Name);
1265 Value *CreateFPToUI(Value *V, Type *DestTy, const Twine &Name = ""){
1266 return CreateCast(Instruction::FPToUI, V, DestTy, Name);
1268 Value *CreateFPToSI(Value *V, Type *DestTy, const Twine &Name = ""){
1269 return CreateCast(Instruction::FPToSI, V, DestTy, Name);
1271 Value *CreateUIToFP(Value *V, Type *DestTy, const Twine &Name = ""){
1272 return CreateCast(Instruction::UIToFP, V, DestTy, Name);
1274 Value *CreateSIToFP(Value *V, Type *DestTy, const Twine &Name = ""){
1275 return CreateCast(Instruction::SIToFP, V, DestTy, Name);
1277 Value *CreateFPTrunc(Value *V, Type *DestTy,
1278 const Twine &Name = "") {
1279 return CreateCast(Instruction::FPTrunc, V, DestTy, Name);
1281 Value *CreateFPExt(Value *V, Type *DestTy, const Twine &Name = "") {
1282 return CreateCast(Instruction::FPExt, V, DestTy, Name);
1284 Value *CreatePtrToInt(Value *V, Type *DestTy,
1285 const Twine &Name = "") {
1286 return CreateCast(Instruction::PtrToInt, V, DestTy, Name);
1288 Value *CreateIntToPtr(Value *V, Type *DestTy,
1289 const Twine &Name = "") {
1290 return CreateCast(Instruction::IntToPtr, V, DestTy, Name);
1292 Value *CreateBitCast(Value *V, Type *DestTy,
1293 const Twine &Name = "") {
1294 return CreateCast(Instruction::BitCast, V, DestTy, Name);
1296 Value *CreateAddrSpaceCast(Value *V, Type *DestTy,
1297 const Twine &Name = "") {
1298 return CreateCast(Instruction::AddrSpaceCast, V, DestTy, Name);
1300 Value *CreateZExtOrBitCast(Value *V, Type *DestTy,
1301 const Twine &Name = "") {
1302 if (V->getType() == DestTy)
1304 if (Constant *VC = dyn_cast<Constant>(V))
1305 return Insert(Folder.CreateZExtOrBitCast(VC, DestTy), Name);
1306 return Insert(CastInst::CreateZExtOrBitCast(V, DestTy), Name);
1308 Value *CreateSExtOrBitCast(Value *V, Type *DestTy,
1309 const Twine &Name = "") {
1310 if (V->getType() == DestTy)
1312 if (Constant *VC = dyn_cast<Constant>(V))
1313 return Insert(Folder.CreateSExtOrBitCast(VC, DestTy), Name);
1314 return Insert(CastInst::CreateSExtOrBitCast(V, DestTy), Name);
1316 Value *CreateTruncOrBitCast(Value *V, Type *DestTy,
1317 const Twine &Name = "") {
1318 if (V->getType() == DestTy)
1320 if (Constant *VC = dyn_cast<Constant>(V))
1321 return Insert(Folder.CreateTruncOrBitCast(VC, DestTy), Name);
1322 return Insert(CastInst::CreateTruncOrBitCast(V, DestTy), Name);
1324 Value *CreateCast(Instruction::CastOps Op, Value *V, Type *DestTy,
1325 const Twine &Name = "") {
1326 if (V->getType() == DestTy)
1328 if (Constant *VC = dyn_cast<Constant>(V))
1329 return Insert(Folder.CreateCast(Op, VC, DestTy), Name);
1330 return Insert(CastInst::Create(Op, V, DestTy), Name);
1332 Value *CreatePointerCast(Value *V, Type *DestTy,
1333 const Twine &Name = "") {
1334 if (V->getType() == DestTy)
1336 if (Constant *VC = dyn_cast<Constant>(V))
1337 return Insert(Folder.CreatePointerCast(VC, DestTy), Name);
1338 return Insert(CastInst::CreatePointerCast(V, DestTy), Name);
1341 Value *CreatePointerBitCastOrAddrSpaceCast(Value *V, Type *DestTy,
1342 const Twine &Name = "") {
1343 if (V->getType() == DestTy)
1346 if (Constant *VC = dyn_cast<Constant>(V)) {
1347 return Insert(Folder.CreatePointerBitCastOrAddrSpaceCast(VC, DestTy),
1351 return Insert(CastInst::CreatePointerBitCastOrAddrSpaceCast(V, DestTy),
1355 Value *CreateIntCast(Value *V, Type *DestTy, bool isSigned,
1356 const Twine &Name = "") {
1357 if (V->getType() == DestTy)
1359 if (Constant *VC = dyn_cast<Constant>(V))
1360 return Insert(Folder.CreateIntCast(VC, DestTy, isSigned), Name);
1361 return Insert(CastInst::CreateIntegerCast(V, DestTy, isSigned), Name);
1364 Value *CreateBitOrPointerCast(Value *V, Type *DestTy,
1365 const Twine &Name = "") {
1366 if (V->getType() == DestTy)
1368 if (V->getType()->getScalarType()->isPointerTy() &&
1369 DestTy->getScalarType()->isIntegerTy())
1370 return CreatePtrToInt(V, DestTy, Name);
1371 if (V->getType()->getScalarType()->isIntegerTy() &&
1372 DestTy->getScalarType()->isPointerTy())
1373 return CreateIntToPtr(V, DestTy, Name);
1375 return CreateBitCast(V, DestTy, Name);
1378 // \brief Provided to resolve 'CreateIntCast(Ptr, Ptr, "...")', giving a
1379 // compile time error, instead of converting the string to bool for the
1380 // isSigned parameter.
1381 Value *CreateIntCast(Value *, Type *, const char *) = delete;
1383 Value *CreateFPCast(Value *V, Type *DestTy, const Twine &Name = "") {
1384 if (V->getType() == DestTy)
1386 if (Constant *VC = dyn_cast<Constant>(V))
1387 return Insert(Folder.CreateFPCast(VC, DestTy), Name);
1388 return Insert(CastInst::CreateFPCast(V, DestTy), Name);
1391 //===--------------------------------------------------------------------===//
1392 // Instruction creation methods: Compare Instructions
1393 //===--------------------------------------------------------------------===//
1395 Value *CreateICmpEQ(Value *LHS, Value *RHS, const Twine &Name = "") {
1396 return CreateICmp(ICmpInst::ICMP_EQ, LHS, RHS, Name);
1398 Value *CreateICmpNE(Value *LHS, Value *RHS, const Twine &Name = "") {
1399 return CreateICmp(ICmpInst::ICMP_NE, LHS, RHS, Name);
1401 Value *CreateICmpUGT(Value *LHS, Value *RHS, const Twine &Name = "") {
1402 return CreateICmp(ICmpInst::ICMP_UGT, LHS, RHS, Name);
1404 Value *CreateICmpUGE(Value *LHS, Value *RHS, const Twine &Name = "") {
1405 return CreateICmp(ICmpInst::ICMP_UGE, LHS, RHS, Name);
1407 Value *CreateICmpULT(Value *LHS, Value *RHS, const Twine &Name = "") {
1408 return CreateICmp(ICmpInst::ICMP_ULT, LHS, RHS, Name);
1410 Value *CreateICmpULE(Value *LHS, Value *RHS, const Twine &Name = "") {
1411 return CreateICmp(ICmpInst::ICMP_ULE, LHS, RHS, Name);
1413 Value *CreateICmpSGT(Value *LHS, Value *RHS, const Twine &Name = "") {
1414 return CreateICmp(ICmpInst::ICMP_SGT, LHS, RHS, Name);
1416 Value *CreateICmpSGE(Value *LHS, Value *RHS, const Twine &Name = "") {
1417 return CreateICmp(ICmpInst::ICMP_SGE, LHS, RHS, Name);
1419 Value *CreateICmpSLT(Value *LHS, Value *RHS, const Twine &Name = "") {
1420 return CreateICmp(ICmpInst::ICMP_SLT, LHS, RHS, Name);
1422 Value *CreateICmpSLE(Value *LHS, Value *RHS, const Twine &Name = "") {
1423 return CreateICmp(ICmpInst::ICMP_SLE, LHS, RHS, Name);
1426 Value *CreateFCmpOEQ(Value *LHS, Value *RHS, const Twine &Name = "",
1427 MDNode *FPMathTag = nullptr) {
1428 return CreateFCmp(FCmpInst::FCMP_OEQ, LHS, RHS, Name, FPMathTag);
1430 Value *CreateFCmpOGT(Value *LHS, Value *RHS, const Twine &Name = "",
1431 MDNode *FPMathTag = nullptr) {
1432 return CreateFCmp(FCmpInst::FCMP_OGT, LHS, RHS, Name, FPMathTag);
1434 Value *CreateFCmpOGE(Value *LHS, Value *RHS, const Twine &Name = "",
1435 MDNode *FPMathTag = nullptr) {
1436 return CreateFCmp(FCmpInst::FCMP_OGE, LHS, RHS, Name, FPMathTag);
1438 Value *CreateFCmpOLT(Value *LHS, Value *RHS, const Twine &Name = "",
1439 MDNode *FPMathTag = nullptr) {
1440 return CreateFCmp(FCmpInst::FCMP_OLT, LHS, RHS, Name, FPMathTag);
1442 Value *CreateFCmpOLE(Value *LHS, Value *RHS, const Twine &Name = "",
1443 MDNode *FPMathTag = nullptr) {
1444 return CreateFCmp(FCmpInst::FCMP_OLE, LHS, RHS, Name, FPMathTag);
1446 Value *CreateFCmpONE(Value *LHS, Value *RHS, const Twine &Name = "",
1447 MDNode *FPMathTag = nullptr) {
1448 return CreateFCmp(FCmpInst::FCMP_ONE, LHS, RHS, Name, FPMathTag);
1450 Value *CreateFCmpORD(Value *LHS, Value *RHS, const Twine &Name = "",
1451 MDNode *FPMathTag = nullptr) {
1452 return CreateFCmp(FCmpInst::FCMP_ORD, LHS, RHS, Name, FPMathTag);
1454 Value *CreateFCmpUNO(Value *LHS, Value *RHS, const Twine &Name = "",
1455 MDNode *FPMathTag = nullptr) {
1456 return CreateFCmp(FCmpInst::FCMP_UNO, LHS, RHS, Name, FPMathTag);
1458 Value *CreateFCmpUEQ(Value *LHS, Value *RHS, const Twine &Name = "",
1459 MDNode *FPMathTag = nullptr) {
1460 return CreateFCmp(FCmpInst::FCMP_UEQ, LHS, RHS, Name, FPMathTag);
1462 Value *CreateFCmpUGT(Value *LHS, Value *RHS, const Twine &Name = "",
1463 MDNode *FPMathTag = nullptr) {
1464 return CreateFCmp(FCmpInst::FCMP_UGT, LHS, RHS, Name, FPMathTag);
1466 Value *CreateFCmpUGE(Value *LHS, Value *RHS, const Twine &Name = "",
1467 MDNode *FPMathTag = nullptr) {
1468 return CreateFCmp(FCmpInst::FCMP_UGE, LHS, RHS, Name, FPMathTag);
1470 Value *CreateFCmpULT(Value *LHS, Value *RHS, const Twine &Name = "",
1471 MDNode *FPMathTag = nullptr) {
1472 return CreateFCmp(FCmpInst::FCMP_ULT, LHS, RHS, Name, FPMathTag);
1474 Value *CreateFCmpULE(Value *LHS, Value *RHS, const Twine &Name = "",
1475 MDNode *FPMathTag = nullptr) {
1476 return CreateFCmp(FCmpInst::FCMP_ULE, LHS, RHS, Name, FPMathTag);
1478 Value *CreateFCmpUNE(Value *LHS, Value *RHS, const Twine &Name = "",
1479 MDNode *FPMathTag = nullptr) {
1480 return CreateFCmp(FCmpInst::FCMP_UNE, LHS, RHS, Name, FPMathTag);
1483 Value *CreateICmp(CmpInst::Predicate P, Value *LHS, Value *RHS,
1484 const Twine &Name = "") {
1485 if (Constant *LC = dyn_cast<Constant>(LHS))
1486 if (Constant *RC = dyn_cast<Constant>(RHS))
1487 return Insert(Folder.CreateICmp(P, LC, RC), Name);
1488 return Insert(new ICmpInst(P, LHS, RHS), Name);
1490 Value *CreateFCmp(CmpInst::Predicate P, Value *LHS, Value *RHS,
1491 const Twine &Name = "", MDNode *FPMathTag = nullptr) {
1492 if (Constant *LC = dyn_cast<Constant>(LHS))
1493 if (Constant *RC = dyn_cast<Constant>(RHS))
1494 return Insert(Folder.CreateFCmp(P, LC, RC), Name);
1495 return Insert(AddFPMathAttributes(new FCmpInst(P, LHS, RHS),
1496 FPMathTag, FMF), Name);
1499 //===--------------------------------------------------------------------===//
1500 // Instruction creation methods: Other Instructions
1501 //===--------------------------------------------------------------------===//
1503 PHINode *CreatePHI(Type *Ty, unsigned NumReservedValues,
1504 const Twine &Name = "") {
1505 return Insert(PHINode::Create(Ty, NumReservedValues), Name);
1508 CallInst *CreateCall(Value *Callee, ArrayRef<Value *> Args = None,
1509 const Twine &Name = "") {
1510 return Insert(CallInst::Create(Callee, Args), Name);
1513 CallInst *CreateCall(llvm::FunctionType *FTy, Value *Callee,
1514 ArrayRef<Value *> Args, const Twine &Name = "") {
1515 return Insert(CallInst::Create(FTy, Callee, Args), Name);
1518 CallInst *CreateCall(Function *Callee, ArrayRef<Value *> Args,
1519 const Twine &Name = "") {
1520 return CreateCall(Callee->getFunctionType(), Callee, Args, Name);
1523 Value *CreateSelect(Value *C, Value *True, Value *False,
1524 const Twine &Name = "") {
1525 if (Constant *CC = dyn_cast<Constant>(C))
1526 if (Constant *TC = dyn_cast<Constant>(True))
1527 if (Constant *FC = dyn_cast<Constant>(False))
1528 return Insert(Folder.CreateSelect(CC, TC, FC), Name);
1529 return Insert(SelectInst::Create(C, True, False), Name);
1532 VAArgInst *CreateVAArg(Value *List, Type *Ty, const Twine &Name = "") {
1533 return Insert(new VAArgInst(List, Ty), Name);
1536 Value *CreateExtractElement(Value *Vec, Value *Idx,
1537 const Twine &Name = "") {
1538 if (Constant *VC = dyn_cast<Constant>(Vec))
1539 if (Constant *IC = dyn_cast<Constant>(Idx))
1540 return Insert(Folder.CreateExtractElement(VC, IC), Name);
1541 return Insert(ExtractElementInst::Create(Vec, Idx), Name);
1544 Value *CreateExtractElement(Value *Vec, uint64_t Idx,
1545 const Twine &Name = "") {
1546 return CreateExtractElement(Vec, getInt64(Idx), Name);
1549 Value *CreateInsertElement(Value *Vec, Value *NewElt, Value *Idx,
1550 const Twine &Name = "") {
1551 if (Constant *VC = dyn_cast<Constant>(Vec))
1552 if (Constant *NC = dyn_cast<Constant>(NewElt))
1553 if (Constant *IC = dyn_cast<Constant>(Idx))
1554 return Insert(Folder.CreateInsertElement(VC, NC, IC), Name);
1555 return Insert(InsertElementInst::Create(Vec, NewElt, Idx), Name);
1558 Value *CreateInsertElement(Value *Vec, Value *NewElt, uint64_t Idx,
1559 const Twine &Name = "") {
1560 return CreateInsertElement(Vec, NewElt, getInt64(Idx), Name);
1563 Value *CreateShuffleVector(Value *V1, Value *V2, Value *Mask,
1564 const Twine &Name = "") {
1565 if (Constant *V1C = dyn_cast<Constant>(V1))
1566 if (Constant *V2C = dyn_cast<Constant>(V2))
1567 if (Constant *MC = dyn_cast<Constant>(Mask))
1568 return Insert(Folder.CreateShuffleVector(V1C, V2C, MC), Name);
1569 return Insert(new ShuffleVectorInst(V1, V2, Mask), Name);
1572 Value *CreateShuffleVector(Value *V1, Value *V2, ArrayRef<int> IntMask,
1573 const Twine &Name = "") {
1574 size_t MaskSize = IntMask.size();
1575 SmallVector<Constant*, 8> MaskVec(MaskSize);
1576 for (size_t i = 0; i != MaskSize; ++i)
1577 MaskVec[i] = getInt32(IntMask[i]);
1578 Value *Mask = ConstantVector::get(MaskVec);
1579 return CreateShuffleVector(V1, V2, Mask, Name);
1582 Value *CreateExtractValue(Value *Agg,
1583 ArrayRef<unsigned> Idxs,
1584 const Twine &Name = "") {
1585 if (Constant *AggC = dyn_cast<Constant>(Agg))
1586 return Insert(Folder.CreateExtractValue(AggC, Idxs), Name);
1587 return Insert(ExtractValueInst::Create(Agg, Idxs), Name);
1590 Value *CreateInsertValue(Value *Agg, Value *Val,
1591 ArrayRef<unsigned> Idxs,
1592 const Twine &Name = "") {
1593 if (Constant *AggC = dyn_cast<Constant>(Agg))
1594 if (Constant *ValC = dyn_cast<Constant>(Val))
1595 return Insert(Folder.CreateInsertValue(AggC, ValC, Idxs), Name);
1596 return Insert(InsertValueInst::Create(Agg, Val, Idxs), Name);
1599 LandingPadInst *CreateLandingPad(Type *Ty, unsigned NumClauses,
1600 const Twine &Name = "") {
1601 return Insert(LandingPadInst::Create(Ty, NumClauses), Name);
1604 //===--------------------------------------------------------------------===//
1605 // Utility creation methods
1606 //===--------------------------------------------------------------------===//
1608 /// \brief Return an i1 value testing if \p Arg is null.
1609 Value *CreateIsNull(Value *Arg, const Twine &Name = "") {
1610 return CreateICmpEQ(Arg, Constant::getNullValue(Arg->getType()),
1614 /// \brief Return an i1 value testing if \p Arg is not null.
1615 Value *CreateIsNotNull(Value *Arg, const Twine &Name = "") {
1616 return CreateICmpNE(Arg, Constant::getNullValue(Arg->getType()),
1620 /// \brief Return the i64 difference between two pointer values, dividing out
1621 /// the size of the pointed-to objects.
1623 /// This is intended to implement C-style pointer subtraction. As such, the
1624 /// pointers must be appropriately aligned for their element types and
1625 /// pointing into the same object.
1626 Value *CreatePtrDiff(Value *LHS, Value *RHS, const Twine &Name = "") {
1627 assert(LHS->getType() == RHS->getType() &&
1628 "Pointer subtraction operand types must match!");
1629 PointerType *ArgType = cast<PointerType>(LHS->getType());
1630 Value *LHS_int = CreatePtrToInt(LHS, Type::getInt64Ty(Context));
1631 Value *RHS_int = CreatePtrToInt(RHS, Type::getInt64Ty(Context));
1632 Value *Difference = CreateSub(LHS_int, RHS_int);
1633 return CreateExactSDiv(Difference,
1634 ConstantExpr::getSizeOf(ArgType->getElementType()),
1638 /// \brief Create an invariant.group.barrier intrinsic call, that stops
1639 /// optimizer to propagate equality using invariant.group metadata.
1640 /// If Ptr type is different from i8*, it's casted to i8* before call
1641 /// and casted back to Ptr type after call.
1642 Value *CreateInvariantGroupBarrier(Value *Ptr) {
1643 Module *M = BB->getParent()->getParent();
1644 Function *FnInvariantGroupBarrier = Intrinsic::getDeclaration(M,
1645 Intrinsic::invariant_group_barrier);
1647 Type *ArgumentAndReturnType = FnInvariantGroupBarrier->getReturnType();
1648 assert(ArgumentAndReturnType ==
1649 FnInvariantGroupBarrier->getFunctionType()->getParamType(0) &&
1650 "InvariantGroupBarrier should take and return the same type");
1651 Type *PtrType = Ptr->getType();
1653 bool PtrTypeConversionNeeded = PtrType != ArgumentAndReturnType;
1654 if (PtrTypeConversionNeeded)
1655 Ptr = CreateBitCast(Ptr, ArgumentAndReturnType);
1657 CallInst *Fn = CreateCall(FnInvariantGroupBarrier, {Ptr});
1659 if (PtrTypeConversionNeeded)
1660 return CreateBitCast(Fn, PtrType);
1664 /// \brief Return a vector value that contains \arg V broadcasted to \p
1665 /// NumElts elements.
1666 Value *CreateVectorSplat(unsigned NumElts, Value *V, const Twine &Name = "") {
1667 assert(NumElts > 0 && "Cannot splat to an empty vector!");
1669 // First insert it into an undef vector so we can shuffle it.
1670 Type *I32Ty = getInt32Ty();
1671 Value *Undef = UndefValue::get(VectorType::get(V->getType(), NumElts));
1672 V = CreateInsertElement(Undef, V, ConstantInt::get(I32Ty, 0),
1673 Name + ".splatinsert");
1675 // Shuffle the value across the desired number of elements.
1676 Value *Zeros = ConstantAggregateZero::get(VectorType::get(I32Ty, NumElts));
1677 return CreateShuffleVector(V, Undef, Zeros, Name + ".splat");
1680 /// \brief Return a value that has been extracted from a larger integer type.
1681 Value *CreateExtractInteger(const DataLayout &DL, Value *From,
1682 IntegerType *ExtractedTy, uint64_t Offset,
1683 const Twine &Name) {
1684 IntegerType *IntTy = cast<IntegerType>(From->getType());
1685 assert(DL.getTypeStoreSize(ExtractedTy) + Offset <=
1686 DL.getTypeStoreSize(IntTy) &&
1687 "Element extends past full value");
1688 uint64_t ShAmt = 8 * Offset;
1690 if (DL.isBigEndian())
1691 ShAmt = 8 * (DL.getTypeStoreSize(IntTy) -
1692 DL.getTypeStoreSize(ExtractedTy) - Offset);
1694 V = CreateLShr(V, ShAmt, Name + ".shift");
1696 assert(ExtractedTy->getBitWidth() <= IntTy->getBitWidth() &&
1697 "Cannot extract to a larger integer!");
1698 if (ExtractedTy != IntTy) {
1699 V = CreateTrunc(V, ExtractedTy, Name + ".trunc");
1704 /// \brief Create an assume intrinsic call that represents an alignment
1705 /// assumption on the provided pointer.
1707 /// An optional offset can be provided, and if it is provided, the offset
1708 /// must be subtracted from the provided pointer to get the pointer with the
1709 /// specified alignment.
1710 CallInst *CreateAlignmentAssumption(const DataLayout &DL, Value *PtrValue,
1712 Value *OffsetValue = nullptr) {
1713 assert(isa<PointerType>(PtrValue->getType()) &&
1714 "trying to create an alignment assumption on a non-pointer?");
1716 PointerType *PtrTy = cast<PointerType>(PtrValue->getType());
1717 Type *IntPtrTy = getIntPtrTy(DL, PtrTy->getAddressSpace());
1718 Value *PtrIntValue = CreatePtrToInt(PtrValue, IntPtrTy, "ptrint");
1720 Value *Mask = ConstantInt::get(IntPtrTy,
1721 Alignment > 0 ? Alignment - 1 : 0);
1723 bool IsOffsetZero = false;
1724 if (ConstantInt *CI = dyn_cast<ConstantInt>(OffsetValue))
1725 IsOffsetZero = CI->isZero();
1727 if (!IsOffsetZero) {
1728 if (OffsetValue->getType() != IntPtrTy)
1729 OffsetValue = CreateIntCast(OffsetValue, IntPtrTy, /*isSigned*/ true,
1731 PtrIntValue = CreateSub(PtrIntValue, OffsetValue, "offsetptr");
1735 Value *Zero = ConstantInt::get(IntPtrTy, 0);
1736 Value *MaskedPtr = CreateAnd(PtrIntValue, Mask, "maskedptr");
1737 Value *InvCond = CreateICmpEQ(MaskedPtr, Zero, "maskcond");
1739 return CreateAssumption(InvCond);
1743 // Create wrappers for C Binding types (see CBindingWrapping.h).
1744 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(IRBuilder<>, LLVMBuilderRef)