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;
58 BasicBlock::iterator InsertPt;
61 MDNode *DefaultFPMathTag;
65 IRBuilderBase(LLVMContext &context, MDNode *FPMathTag = nullptr)
66 : Context(context), DefaultFPMathTag(FPMathTag), FMF() {
67 ClearInsertionPoint();
70 //===--------------------------------------------------------------------===//
71 // Builder configuration methods
72 //===--------------------------------------------------------------------===//
74 /// \brief Clear the insertion point: created instructions will not be
75 /// inserted into a block.
76 void ClearInsertionPoint() {
81 BasicBlock *GetInsertBlock() const { return BB; }
82 BasicBlock::iterator GetInsertPoint() const { return InsertPt; }
83 LLVMContext &getContext() const { return Context; }
85 /// \brief This specifies that created instructions should be appended to the
86 /// end of the specified block.
87 void SetInsertPoint(BasicBlock *TheBB) {
92 /// \brief This specifies that created instructions should be inserted before
93 /// the specified instruction.
94 void SetInsertPoint(Instruction *I) {
97 assert(I != BB->end() && "Can't read debug loc from end()");
98 SetCurrentDebugLocation(I->getDebugLoc());
101 /// \brief This specifies that created instructions should be inserted at the
103 void SetInsertPoint(BasicBlock *TheBB, BasicBlock::iterator IP) {
106 if (IP != TheBB->end())
107 SetCurrentDebugLocation(IP->getDebugLoc());
110 /// \brief Set location information used by debugging information.
111 void SetCurrentDebugLocation(DebugLoc L) { CurDbgLocation = std::move(L); }
113 /// \brief Get location information used by debugging information.
114 const DebugLoc &getCurrentDebugLocation() const { return CurDbgLocation; }
116 /// \brief If this builder has a current debug location, set it on the
117 /// specified instruction.
118 void SetInstDebugLocation(Instruction *I) const {
120 I->setDebugLoc(CurDbgLocation);
123 /// \brief Get the return type of the current function that we're emitting
125 Type *getCurrentFunctionReturnType() const;
127 /// InsertPoint - A saved insertion point.
130 BasicBlock::iterator Point;
133 /// \brief Creates a new insertion point which doesn't point to anything.
134 InsertPoint() : Block(nullptr) {}
136 /// \brief Creates a new insertion point at the given location.
137 InsertPoint(BasicBlock *InsertBlock, BasicBlock::iterator InsertPoint)
138 : Block(InsertBlock), Point(InsertPoint) {}
140 /// \brief Returns true if this insert point is set.
141 bool isSet() const { return (Block != nullptr); }
143 llvm::BasicBlock *getBlock() const { return Block; }
144 llvm::BasicBlock::iterator getPoint() const { return Point; }
147 /// \brief Returns the current insert point.
148 InsertPoint saveIP() const {
149 return InsertPoint(GetInsertBlock(), GetInsertPoint());
152 /// \brief Returns the current insert point, clearing it in the process.
153 InsertPoint saveAndClearIP() {
154 InsertPoint IP(GetInsertBlock(), GetInsertPoint());
155 ClearInsertionPoint();
159 /// \brief Sets the current insert point to a previously-saved location.
160 void restoreIP(InsertPoint IP) {
162 SetInsertPoint(IP.getBlock(), IP.getPoint());
164 ClearInsertionPoint();
167 /// \brief Get the floating point math metadata being used.
168 MDNode *getDefaultFPMathTag() const { return DefaultFPMathTag; }
170 /// \brief Get the flags to be applied to created floating point ops
171 FastMathFlags getFastMathFlags() const { return FMF; }
173 /// \brief Clear the fast-math flags.
174 void clearFastMathFlags() { FMF.clear(); }
176 /// \brief Set the floating point math metadata to be used.
177 void SetDefaultFPMathTag(MDNode *FPMathTag) { DefaultFPMathTag = FPMathTag; }
179 /// \brief Set the fast-math flags to be used with generated fp-math operators
180 void SetFastMathFlags(FastMathFlags NewFMF) { FMF = NewFMF; }
182 //===--------------------------------------------------------------------===//
184 //===--------------------------------------------------------------------===//
186 // \brief RAII object that stores the current insertion point and restores it
187 // when the object is destroyed. This includes the debug location.
188 class InsertPointGuard {
189 IRBuilderBase &Builder;
190 AssertingVH<BasicBlock> Block;
191 BasicBlock::iterator Point;
194 InsertPointGuard(const InsertPointGuard &) = delete;
195 InsertPointGuard &operator=(const InsertPointGuard &) = delete;
198 InsertPointGuard(IRBuilderBase &B)
199 : Builder(B), Block(B.GetInsertBlock()), Point(B.GetInsertPoint()),
200 DbgLoc(B.getCurrentDebugLocation()) {}
202 ~InsertPointGuard() {
203 Builder.restoreIP(InsertPoint(Block, Point));
204 Builder.SetCurrentDebugLocation(DbgLoc);
208 // \brief RAII object that stores the current fast math settings and restores
209 // them when the object is destroyed.
210 class FastMathFlagGuard {
211 IRBuilderBase &Builder;
215 FastMathFlagGuard(const FastMathFlagGuard &) = delete;
216 FastMathFlagGuard &operator=(
217 const FastMathFlagGuard &) = delete;
220 FastMathFlagGuard(IRBuilderBase &B)
221 : Builder(B), FMF(B.FMF), FPMathTag(B.DefaultFPMathTag) {}
223 ~FastMathFlagGuard() {
225 Builder.DefaultFPMathTag = FPMathTag;
229 //===--------------------------------------------------------------------===//
230 // Miscellaneous creation methods.
231 //===--------------------------------------------------------------------===//
233 /// \brief Make a new global variable with initializer type i8*
235 /// Make a new global variable with an initializer that has array of i8 type
236 /// filled in with the null terminated string value specified. The new global
237 /// variable will be marked mergable with any others of the same contents. If
238 /// Name is specified, it is the name of the global variable created.
239 GlobalVariable *CreateGlobalString(StringRef Str, const Twine &Name = "",
240 unsigned AddressSpace = 0);
242 /// \brief Get a constant value representing either true or false.
243 ConstantInt *getInt1(bool V) {
244 return ConstantInt::get(getInt1Ty(), V);
247 /// \brief Get the constant value for i1 true.
248 ConstantInt *getTrue() {
249 return ConstantInt::getTrue(Context);
252 /// \brief Get the constant value for i1 false.
253 ConstantInt *getFalse() {
254 return ConstantInt::getFalse(Context);
257 /// \brief Get a constant 8-bit value.
258 ConstantInt *getInt8(uint8_t C) {
259 return ConstantInt::get(getInt8Ty(), C);
262 /// \brief Get a constant 16-bit value.
263 ConstantInt *getInt16(uint16_t C) {
264 return ConstantInt::get(getInt16Ty(), C);
267 /// \brief Get a constant 32-bit value.
268 ConstantInt *getInt32(uint32_t C) {
269 return ConstantInt::get(getInt32Ty(), C);
272 /// \brief Get a constant 64-bit value.
273 ConstantInt *getInt64(uint64_t C) {
274 return ConstantInt::get(getInt64Ty(), C);
277 /// \brief Get a constant N-bit value, zero extended or truncated from
279 ConstantInt *getIntN(unsigned N, uint64_t C) {
280 return ConstantInt::get(getIntNTy(N), C);
283 /// \brief Get a constant integer value.
284 ConstantInt *getInt(const APInt &AI) {
285 return ConstantInt::get(Context, AI);
288 //===--------------------------------------------------------------------===//
289 // Type creation methods
290 //===--------------------------------------------------------------------===//
292 /// \brief Fetch the type representing a single bit
293 IntegerType *getInt1Ty() {
294 return Type::getInt1Ty(Context);
297 /// \brief Fetch the type representing an 8-bit integer.
298 IntegerType *getInt8Ty() {
299 return Type::getInt8Ty(Context);
302 /// \brief Fetch the type representing a 16-bit integer.
303 IntegerType *getInt16Ty() {
304 return Type::getInt16Ty(Context);
307 /// \brief Fetch the type representing a 32-bit integer.
308 IntegerType *getInt32Ty() {
309 return Type::getInt32Ty(Context);
312 /// \brief Fetch the type representing a 64-bit integer.
313 IntegerType *getInt64Ty() {
314 return Type::getInt64Ty(Context);
317 /// \brief Fetch the type representing a 128-bit integer.
318 IntegerType *getInt128Ty() { return Type::getInt128Ty(Context); }
320 /// \brief Fetch the type representing an N-bit integer.
321 IntegerType *getIntNTy(unsigned N) {
322 return Type::getIntNTy(Context, N);
325 /// \brief Fetch the type representing a 16-bit floating point value.
327 return Type::getHalfTy(Context);
330 /// \brief Fetch the type representing a 32-bit floating point value.
332 return Type::getFloatTy(Context);
335 /// \brief Fetch the type representing a 64-bit floating point value.
336 Type *getDoubleTy() {
337 return Type::getDoubleTy(Context);
340 /// \brief Fetch the type representing void.
342 return Type::getVoidTy(Context);
345 /// \brief Fetch the type representing a pointer to an 8-bit integer value.
346 PointerType *getInt8PtrTy(unsigned AddrSpace = 0) {
347 return Type::getInt8PtrTy(Context, AddrSpace);
350 /// \brief Fetch the type representing a pointer to an integer value.
351 IntegerType *getIntPtrTy(const DataLayout &DL, unsigned AddrSpace = 0) {
352 return DL.getIntPtrType(Context, AddrSpace);
355 //===--------------------------------------------------------------------===//
356 // Intrinsic creation methods
357 //===--------------------------------------------------------------------===//
359 /// \brief Create and insert a memset to the specified pointer and the
362 /// If the pointer isn't an i8*, it will be converted. If a TBAA tag is
363 /// specified, it will be added to the instruction. Likewise with alias.scope
364 /// and noalias tags.
365 CallInst *CreateMemSet(Value *Ptr, Value *Val, uint64_t Size, unsigned Align,
366 bool isVolatile = false, MDNode *TBAATag = nullptr,
367 MDNode *ScopeTag = nullptr,
368 MDNode *NoAliasTag = nullptr) {
369 return CreateMemSet(Ptr, Val, getInt64(Size), Align, isVolatile,
370 TBAATag, ScopeTag, NoAliasTag);
373 CallInst *CreateMemSet(Value *Ptr, Value *Val, Value *Size, unsigned Align,
374 bool isVolatile = false, MDNode *TBAATag = nullptr,
375 MDNode *ScopeTag = nullptr,
376 MDNode *NoAliasTag = nullptr);
378 /// \brief Create and insert a memcpy between the specified pointers.
380 /// If the pointers aren't i8*, they will be converted. If a TBAA tag is
381 /// specified, it will be added to the instruction. Likewise with alias.scope
382 /// and noalias tags.
383 CallInst *CreateMemCpy(Value *Dst, Value *Src, uint64_t Size, unsigned Align,
384 bool isVolatile = false, MDNode *TBAATag = nullptr,
385 MDNode *TBAAStructTag = nullptr,
386 MDNode *ScopeTag = nullptr,
387 MDNode *NoAliasTag = nullptr) {
388 return CreateMemCpy(Dst, Src, getInt64(Size), Align, isVolatile, TBAATag,
389 TBAAStructTag, ScopeTag, NoAliasTag);
392 CallInst *CreateMemCpy(Value *Dst, Value *Src, Value *Size, unsigned Align,
393 bool isVolatile = false, MDNode *TBAATag = nullptr,
394 MDNode *TBAAStructTag = nullptr,
395 MDNode *ScopeTag = nullptr,
396 MDNode *NoAliasTag = nullptr);
398 /// \brief Create and insert a memmove between the specified
401 /// If the pointers aren't i8*, they will be converted. If a TBAA tag is
402 /// specified, it will be added to the instruction. Likewise with alias.scope
403 /// and noalias tags.
404 CallInst *CreateMemMove(Value *Dst, Value *Src, uint64_t Size, unsigned Align,
405 bool isVolatile = false, MDNode *TBAATag = nullptr,
406 MDNode *ScopeTag = nullptr,
407 MDNode *NoAliasTag = nullptr) {
408 return CreateMemMove(Dst, Src, getInt64(Size), Align, isVolatile,
409 TBAATag, ScopeTag, NoAliasTag);
412 CallInst *CreateMemMove(Value *Dst, Value *Src, Value *Size, unsigned Align,
413 bool isVolatile = false, MDNode *TBAATag = nullptr,
414 MDNode *ScopeTag = nullptr,
415 MDNode *NoAliasTag = nullptr);
417 /// \brief Create a lifetime.start intrinsic.
419 /// If the pointer isn't i8* it will be converted.
420 CallInst *CreateLifetimeStart(Value *Ptr, ConstantInt *Size = nullptr);
422 /// \brief Create a lifetime.end intrinsic.
424 /// If the pointer isn't i8* it will be converted.
425 CallInst *CreateLifetimeEnd(Value *Ptr, ConstantInt *Size = nullptr);
427 /// \brief Create a call to Masked Load intrinsic
428 CallInst *CreateMaskedLoad(Value *Ptr, unsigned Align, Value *Mask,
429 Value *PassThru = 0, const Twine &Name = "");
431 /// \brief Create a call to Masked Store intrinsic
432 CallInst *CreateMaskedStore(Value *Val, Value *Ptr, unsigned Align,
435 /// \brief Create an assume intrinsic call that allows the optimizer to
436 /// assume that the provided condition will be true.
437 CallInst *CreateAssumption(Value *Cond);
439 /// \brief Create a call to the experimental.gc.statepoint intrinsic to
440 /// start a new statepoint sequence.
441 CallInst *CreateGCStatepointCall(uint64_t ID, uint32_t NumPatchBytes,
443 ArrayRef<Value *> CallArgs,
444 ArrayRef<Value *> DeoptArgs,
445 ArrayRef<Value *> GCArgs,
446 const Twine &Name = "");
448 // \brief Conveninence function for the common case when CallArgs are filled
449 // in using makeArrayRef(CS.arg_begin(), CS.arg_end()); Use needs to be
450 // .get()'ed to get the Value pointer.
451 CallInst *CreateGCStatepointCall(uint64_t ID, uint32_t NumPatchBytes,
452 Value *ActualCallee, ArrayRef<Use> CallArgs,
453 ArrayRef<Value *> DeoptArgs,
454 ArrayRef<Value *> GCArgs,
455 const Twine &Name = "");
457 /// brief Create an invoke to the experimental.gc.statepoint intrinsic to
458 /// start a new statepoint sequence.
460 CreateGCStatepointInvoke(uint64_t ID, uint32_t NumPatchBytes,
461 Value *ActualInvokee, BasicBlock *NormalDest,
462 BasicBlock *UnwindDest, ArrayRef<Value *> InvokeArgs,
463 ArrayRef<Value *> DeoptArgs,
464 ArrayRef<Value *> GCArgs, const Twine &Name = "");
466 // Conveninence function for the common case when CallArgs are filled in using
467 // makeArrayRef(CS.arg_begin(), CS.arg_end()); Use needs to be .get()'ed to
470 CreateGCStatepointInvoke(uint64_t ID, uint32_t NumPatchBytes,
471 Value *ActualInvokee, BasicBlock *NormalDest,
472 BasicBlock *UnwindDest, ArrayRef<Use> InvokeArgs,
473 ArrayRef<Value *> DeoptArgs,
474 ArrayRef<Value *> GCArgs, const Twine &Name = "");
476 /// \brief Create a call to the experimental.gc.result intrinsic to extract
477 /// the result from a call wrapped in a statepoint.
478 CallInst *CreateGCResult(Instruction *Statepoint,
480 const Twine &Name = "");
482 /// \brief Create a call to the experimental.gc.relocate intrinsics to
483 /// project the relocated value of one pointer from the statepoint.
484 CallInst *CreateGCRelocate(Instruction *Statepoint,
488 const Twine &Name = "");
491 /// \brief Create a call to a masked intrinsic with given Id.
492 /// Masked intrinsic has only one overloaded type - data type.
493 CallInst *CreateMaskedIntrinsic(Intrinsic::ID Id, ArrayRef<Value *> Ops,
494 Type *DataTy, const Twine &Name = "");
496 Value *getCastedInt8PtrValue(Value *Ptr);
499 /// \brief This provides a uniform API for creating instructions and inserting
500 /// them into a basic block: either at the end of a BasicBlock, or at a specific
501 /// iterator location in a block.
503 /// Note that the builder does not expose the full generality of LLVM
504 /// instructions. For access to extra instruction properties, use the mutators
505 /// (e.g. setVolatile) on the instructions after they have been
506 /// created. Convenience state exists to specify fast-math flags and fp-math
509 /// The first template argument handles whether or not to preserve names in the
510 /// final instruction output. This defaults to on. The second template argument
511 /// specifies a class to use for creating constants. This defaults to creating
512 /// minimally folded constants. The third template argument allows clients to
513 /// specify custom insertion hooks that are called on every newly created
515 template<bool preserveNames = true, typename T = ConstantFolder,
516 typename Inserter = IRBuilderDefaultInserter<preserveNames> >
517 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);
744 Value *CreateAdd(Value *LHS, Value *RHS, const Twine &Name = "",
745 bool HasNUW = false, bool HasNSW = false) {
746 if (Constant *LC = dyn_cast<Constant>(LHS))
747 if (Constant *RC = dyn_cast<Constant>(RHS))
748 return Insert(Folder.CreateAdd(LC, RC, HasNUW, HasNSW), Name);
749 return CreateInsertNUWNSWBinOp(Instruction::Add, LHS, RHS, Name,
752 Value *CreateNSWAdd(Value *LHS, Value *RHS, const Twine &Name = "") {
753 return CreateAdd(LHS, RHS, Name, false, true);
755 Value *CreateNUWAdd(Value *LHS, Value *RHS, const Twine &Name = "") {
756 return CreateAdd(LHS, RHS, Name, true, false);
758 Value *CreateFAdd(Value *LHS, Value *RHS, const Twine &Name = "",
759 MDNode *FPMathTag = nullptr) {
760 if (Constant *LC = dyn_cast<Constant>(LHS))
761 if (Constant *RC = dyn_cast<Constant>(RHS))
762 return Insert(Folder.CreateFAdd(LC, RC), Name);
763 return Insert(AddFPMathAttributes(BinaryOperator::CreateFAdd(LHS, RHS),
764 FPMathTag, FMF), Name);
766 Value *CreateSub(Value *LHS, Value *RHS, const Twine &Name = "",
767 bool HasNUW = false, bool HasNSW = false) {
768 if (Constant *LC = dyn_cast<Constant>(LHS))
769 if (Constant *RC = dyn_cast<Constant>(RHS))
770 return Insert(Folder.CreateSub(LC, RC, HasNUW, HasNSW), Name);
771 return CreateInsertNUWNSWBinOp(Instruction::Sub, LHS, RHS, Name,
774 Value *CreateNSWSub(Value *LHS, Value *RHS, const Twine &Name = "") {
775 return CreateSub(LHS, RHS, Name, false, true);
777 Value *CreateNUWSub(Value *LHS, Value *RHS, const Twine &Name = "") {
778 return CreateSub(LHS, RHS, Name, true, false);
780 Value *CreateFSub(Value *LHS, Value *RHS, const Twine &Name = "",
781 MDNode *FPMathTag = nullptr) {
782 if (Constant *LC = dyn_cast<Constant>(LHS))
783 if (Constant *RC = dyn_cast<Constant>(RHS))
784 return Insert(Folder.CreateFSub(LC, RC), Name);
785 return Insert(AddFPMathAttributes(BinaryOperator::CreateFSub(LHS, RHS),
786 FPMathTag, FMF), Name);
788 Value *CreateMul(Value *LHS, Value *RHS, const Twine &Name = "",
789 bool HasNUW = false, bool HasNSW = false) {
790 if (Constant *LC = dyn_cast<Constant>(LHS))
791 if (Constant *RC = dyn_cast<Constant>(RHS))
792 return Insert(Folder.CreateMul(LC, RC, HasNUW, HasNSW), Name);
793 return CreateInsertNUWNSWBinOp(Instruction::Mul, LHS, RHS, Name,
796 Value *CreateNSWMul(Value *LHS, Value *RHS, const Twine &Name = "") {
797 return CreateMul(LHS, RHS, Name, false, true);
799 Value *CreateNUWMul(Value *LHS, Value *RHS, const Twine &Name = "") {
800 return CreateMul(LHS, RHS, Name, true, false);
802 Value *CreateFMul(Value *LHS, Value *RHS, const Twine &Name = "",
803 MDNode *FPMathTag = nullptr) {
804 if (Constant *LC = dyn_cast<Constant>(LHS))
805 if (Constant *RC = dyn_cast<Constant>(RHS))
806 return Insert(Folder.CreateFMul(LC, RC), Name);
807 return Insert(AddFPMathAttributes(BinaryOperator::CreateFMul(LHS, RHS),
808 FPMathTag, FMF), Name);
810 Value *CreateUDiv(Value *LHS, Value *RHS, const Twine &Name = "",
811 bool isExact = false) {
812 if (Constant *LC = dyn_cast<Constant>(LHS))
813 if (Constant *RC = dyn_cast<Constant>(RHS))
814 return Insert(Folder.CreateUDiv(LC, RC, isExact), Name);
816 return Insert(BinaryOperator::CreateUDiv(LHS, RHS), Name);
817 return Insert(BinaryOperator::CreateExactUDiv(LHS, RHS), Name);
819 Value *CreateExactUDiv(Value *LHS, Value *RHS, const Twine &Name = "") {
820 return CreateUDiv(LHS, RHS, Name, true);
822 Value *CreateSDiv(Value *LHS, Value *RHS, const Twine &Name = "",
823 bool isExact = false) {
824 if (Constant *LC = dyn_cast<Constant>(LHS))
825 if (Constant *RC = dyn_cast<Constant>(RHS))
826 return Insert(Folder.CreateSDiv(LC, RC, isExact), Name);
828 return Insert(BinaryOperator::CreateSDiv(LHS, RHS), Name);
829 return Insert(BinaryOperator::CreateExactSDiv(LHS, RHS), Name);
831 Value *CreateExactSDiv(Value *LHS, Value *RHS, const Twine &Name = "") {
832 return CreateSDiv(LHS, RHS, Name, true);
834 Value *CreateFDiv(Value *LHS, Value *RHS, const Twine &Name = "",
835 MDNode *FPMathTag = nullptr) {
836 if (Constant *LC = dyn_cast<Constant>(LHS))
837 if (Constant *RC = dyn_cast<Constant>(RHS))
838 return Insert(Folder.CreateFDiv(LC, RC), Name);
839 return Insert(AddFPMathAttributes(BinaryOperator::CreateFDiv(LHS, RHS),
840 FPMathTag, FMF), Name);
842 Value *CreateURem(Value *LHS, Value *RHS, const Twine &Name = "") {
843 if (Constant *LC = dyn_cast<Constant>(LHS))
844 if (Constant *RC = dyn_cast<Constant>(RHS))
845 return Insert(Folder.CreateURem(LC, RC), Name);
846 return Insert(BinaryOperator::CreateURem(LHS, RHS), Name);
848 Value *CreateSRem(Value *LHS, Value *RHS, const Twine &Name = "") {
849 if (Constant *LC = dyn_cast<Constant>(LHS))
850 if (Constant *RC = dyn_cast<Constant>(RHS))
851 return Insert(Folder.CreateSRem(LC, RC), Name);
852 return Insert(BinaryOperator::CreateSRem(LHS, RHS), Name);
854 Value *CreateFRem(Value *LHS, Value *RHS, const Twine &Name = "",
855 MDNode *FPMathTag = nullptr) {
856 if (Constant *LC = dyn_cast<Constant>(LHS))
857 if (Constant *RC = dyn_cast<Constant>(RHS))
858 return Insert(Folder.CreateFRem(LC, RC), Name);
859 return Insert(AddFPMathAttributes(BinaryOperator::CreateFRem(LHS, RHS),
860 FPMathTag, FMF), Name);
863 Value *CreateShl(Value *LHS, Value *RHS, const Twine &Name = "",
864 bool HasNUW = false, bool HasNSW = false) {
865 if (Constant *LC = dyn_cast<Constant>(LHS))
866 if (Constant *RC = dyn_cast<Constant>(RHS))
867 return Insert(Folder.CreateShl(LC, RC, HasNUW, HasNSW), Name);
868 return CreateInsertNUWNSWBinOp(Instruction::Shl, LHS, RHS, Name,
871 Value *CreateShl(Value *LHS, const APInt &RHS, const Twine &Name = "",
872 bool HasNUW = false, bool HasNSW = false) {
873 return CreateShl(LHS, ConstantInt::get(LHS->getType(), RHS), Name,
876 Value *CreateShl(Value *LHS, uint64_t RHS, const Twine &Name = "",
877 bool HasNUW = false, bool HasNSW = false) {
878 return CreateShl(LHS, ConstantInt::get(LHS->getType(), RHS), Name,
882 Value *CreateLShr(Value *LHS, Value *RHS, const Twine &Name = "",
883 bool isExact = false) {
884 if (Constant *LC = dyn_cast<Constant>(LHS))
885 if (Constant *RC = dyn_cast<Constant>(RHS))
886 return Insert(Folder.CreateLShr(LC, RC, isExact), Name);
888 return Insert(BinaryOperator::CreateLShr(LHS, RHS), Name);
889 return Insert(BinaryOperator::CreateExactLShr(LHS, RHS), Name);
891 Value *CreateLShr(Value *LHS, const APInt &RHS, const Twine &Name = "",
892 bool isExact = false) {
893 return CreateLShr(LHS, ConstantInt::get(LHS->getType(), RHS), Name,isExact);
895 Value *CreateLShr(Value *LHS, uint64_t RHS, const Twine &Name = "",
896 bool isExact = false) {
897 return CreateLShr(LHS, ConstantInt::get(LHS->getType(), RHS), Name,isExact);
900 Value *CreateAShr(Value *LHS, Value *RHS, const Twine &Name = "",
901 bool isExact = false) {
902 if (Constant *LC = dyn_cast<Constant>(LHS))
903 if (Constant *RC = dyn_cast<Constant>(RHS))
904 return Insert(Folder.CreateAShr(LC, RC, isExact), Name);
906 return Insert(BinaryOperator::CreateAShr(LHS, RHS), Name);
907 return Insert(BinaryOperator::CreateExactAShr(LHS, RHS), Name);
909 Value *CreateAShr(Value *LHS, const APInt &RHS, const Twine &Name = "",
910 bool isExact = false) {
911 return CreateAShr(LHS, ConstantInt::get(LHS->getType(), RHS), Name,isExact);
913 Value *CreateAShr(Value *LHS, uint64_t RHS, const Twine &Name = "",
914 bool isExact = false) {
915 return CreateAShr(LHS, ConstantInt::get(LHS->getType(), RHS), Name,isExact);
918 Value *CreateAnd(Value *LHS, Value *RHS, const Twine &Name = "") {
919 if (Constant *RC = dyn_cast<Constant>(RHS)) {
920 if (isa<ConstantInt>(RC) && cast<ConstantInt>(RC)->isAllOnesValue())
921 return LHS; // LHS & -1 -> LHS
922 if (Constant *LC = dyn_cast<Constant>(LHS))
923 return Insert(Folder.CreateAnd(LC, RC), Name);
925 return Insert(BinaryOperator::CreateAnd(LHS, RHS), Name);
927 Value *CreateAnd(Value *LHS, const APInt &RHS, const Twine &Name = "") {
928 return CreateAnd(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
930 Value *CreateAnd(Value *LHS, uint64_t RHS, const Twine &Name = "") {
931 return CreateAnd(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
934 Value *CreateOr(Value *LHS, Value *RHS, const Twine &Name = "") {
935 if (Constant *RC = dyn_cast<Constant>(RHS)) {
936 if (RC->isNullValue())
937 return LHS; // LHS | 0 -> LHS
938 if (Constant *LC = dyn_cast<Constant>(LHS))
939 return Insert(Folder.CreateOr(LC, RC), Name);
941 return Insert(BinaryOperator::CreateOr(LHS, RHS), Name);
943 Value *CreateOr(Value *LHS, const APInt &RHS, const Twine &Name = "") {
944 return CreateOr(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
946 Value *CreateOr(Value *LHS, uint64_t RHS, const Twine &Name = "") {
947 return CreateOr(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
950 Value *CreateXor(Value *LHS, Value *RHS, const Twine &Name = "") {
951 if (Constant *LC = dyn_cast<Constant>(LHS))
952 if (Constant *RC = dyn_cast<Constant>(RHS))
953 return Insert(Folder.CreateXor(LC, RC), Name);
954 return Insert(BinaryOperator::CreateXor(LHS, RHS), Name);
956 Value *CreateXor(Value *LHS, const APInt &RHS, const Twine &Name = "") {
957 return CreateXor(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
959 Value *CreateXor(Value *LHS, uint64_t RHS, const Twine &Name = "") {
960 return CreateXor(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
963 Value *CreateBinOp(Instruction::BinaryOps Opc,
964 Value *LHS, Value *RHS, const Twine &Name = "",
965 MDNode *FPMathTag = nullptr) {
966 if (Constant *LC = dyn_cast<Constant>(LHS))
967 if (Constant *RC = dyn_cast<Constant>(RHS))
968 return Insert(Folder.CreateBinOp(Opc, LC, RC), Name);
969 llvm::Instruction *BinOp = BinaryOperator::Create(Opc, LHS, RHS);
970 if (isa<FPMathOperator>(BinOp))
971 BinOp = AddFPMathAttributes(BinOp, FPMathTag, FMF);
972 return Insert(BinOp, Name);
975 Value *CreateNeg(Value *V, const Twine &Name = "",
976 bool HasNUW = false, bool HasNSW = false) {
977 if (Constant *VC = dyn_cast<Constant>(V))
978 return Insert(Folder.CreateNeg(VC, HasNUW, HasNSW), Name);
979 BinaryOperator *BO = Insert(BinaryOperator::CreateNeg(V), Name);
980 if (HasNUW) BO->setHasNoUnsignedWrap();
981 if (HasNSW) BO->setHasNoSignedWrap();
984 Value *CreateNSWNeg(Value *V, const Twine &Name = "") {
985 return CreateNeg(V, Name, false, true);
987 Value *CreateNUWNeg(Value *V, const Twine &Name = "") {
988 return CreateNeg(V, Name, true, false);
990 Value *CreateFNeg(Value *V, const Twine &Name = "",
991 MDNode *FPMathTag = nullptr) {
992 if (Constant *VC = dyn_cast<Constant>(V))
993 return Insert(Folder.CreateFNeg(VC), Name);
994 return Insert(AddFPMathAttributes(BinaryOperator::CreateFNeg(V),
995 FPMathTag, FMF), Name);
997 Value *CreateNot(Value *V, const Twine &Name = "") {
998 if (Constant *VC = dyn_cast<Constant>(V))
999 return Insert(Folder.CreateNot(VC), Name);
1000 return Insert(BinaryOperator::CreateNot(V), Name);
1003 //===--------------------------------------------------------------------===//
1004 // Instruction creation methods: Memory Instructions
1005 //===--------------------------------------------------------------------===//
1007 AllocaInst *CreateAlloca(Type *Ty, Value *ArraySize = nullptr,
1008 const Twine &Name = "") {
1009 return Insert(new AllocaInst(Ty, ArraySize), Name);
1011 // \brief Provided to resolve 'CreateLoad(Ptr, "...")' correctly, instead of
1012 // converting the string to 'bool' for the isVolatile parameter.
1013 LoadInst *CreateLoad(Value *Ptr, const char *Name) {
1014 return Insert(new LoadInst(Ptr), Name);
1016 LoadInst *CreateLoad(Value *Ptr, const Twine &Name = "") {
1017 return Insert(new LoadInst(Ptr), Name);
1019 LoadInst *CreateLoad(Type *Ty, Value *Ptr, const Twine &Name = "") {
1020 return Insert(new LoadInst(Ty, Ptr), Name);
1022 LoadInst *CreateLoad(Value *Ptr, bool isVolatile, const Twine &Name = "") {
1023 return Insert(new LoadInst(Ptr, nullptr, isVolatile), Name);
1025 StoreInst *CreateStore(Value *Val, Value *Ptr, bool isVolatile = false) {
1026 return Insert(new StoreInst(Val, Ptr, isVolatile));
1028 // \brief Provided to resolve 'CreateAlignedLoad(Ptr, Align, "...")'
1029 // correctly, instead of converting the string to 'bool' for the isVolatile
1031 LoadInst *CreateAlignedLoad(Value *Ptr, unsigned Align, const char *Name) {
1032 LoadInst *LI = CreateLoad(Ptr, Name);
1033 LI->setAlignment(Align);
1036 LoadInst *CreateAlignedLoad(Value *Ptr, unsigned Align,
1037 const Twine &Name = "") {
1038 LoadInst *LI = CreateLoad(Ptr, Name);
1039 LI->setAlignment(Align);
1042 LoadInst *CreateAlignedLoad(Value *Ptr, unsigned Align, bool isVolatile,
1043 const Twine &Name = "") {
1044 LoadInst *LI = CreateLoad(Ptr, isVolatile, Name);
1045 LI->setAlignment(Align);
1048 StoreInst *CreateAlignedStore(Value *Val, Value *Ptr, unsigned Align,
1049 bool isVolatile = false) {
1050 StoreInst *SI = CreateStore(Val, Ptr, isVolatile);
1051 SI->setAlignment(Align);
1054 FenceInst *CreateFence(AtomicOrdering Ordering,
1055 SynchronizationScope SynchScope = CrossThread,
1056 const Twine &Name = "") {
1057 return Insert(new FenceInst(Context, Ordering, SynchScope), Name);
1060 CreateAtomicCmpXchg(Value *Ptr, Value *Cmp, Value *New,
1061 AtomicOrdering SuccessOrdering,
1062 AtomicOrdering FailureOrdering,
1063 SynchronizationScope SynchScope = CrossThread) {
1064 return Insert(new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering,
1065 FailureOrdering, SynchScope));
1067 AtomicRMWInst *CreateAtomicRMW(AtomicRMWInst::BinOp Op, Value *Ptr, Value *Val,
1068 AtomicOrdering Ordering,
1069 SynchronizationScope SynchScope = CrossThread) {
1070 return Insert(new AtomicRMWInst(Op, Ptr, Val, Ordering, SynchScope));
1072 Value *CreateGEP(Value *Ptr, ArrayRef<Value *> IdxList,
1073 const Twine &Name = "") {
1074 return CreateGEP(nullptr, Ptr, IdxList, Name);
1076 Value *CreateGEP(Type *Ty, Value *Ptr, ArrayRef<Value *> IdxList,
1077 const Twine &Name = "") {
1078 if (Constant *PC = dyn_cast<Constant>(Ptr)) {
1079 // Every index must be constant.
1081 for (i = 0, e = IdxList.size(); i != e; ++i)
1082 if (!isa<Constant>(IdxList[i]))
1085 return Insert(Folder.CreateGetElementPtr(Ty, PC, IdxList), Name);
1087 return Insert(GetElementPtrInst::Create(Ty, Ptr, IdxList), Name);
1089 Value *CreateInBoundsGEP(Value *Ptr, ArrayRef<Value *> IdxList,
1090 const Twine &Name = "") {
1091 return CreateInBoundsGEP(nullptr, Ptr, IdxList, Name);
1093 Value *CreateInBoundsGEP(Type *Ty, Value *Ptr, ArrayRef<Value *> IdxList,
1094 const Twine &Name = "") {
1095 if (Constant *PC = dyn_cast<Constant>(Ptr)) {
1096 // Every index must be constant.
1098 for (i = 0, e = IdxList.size(); i != e; ++i)
1099 if (!isa<Constant>(IdxList[i]))
1102 return Insert(Folder.CreateInBoundsGetElementPtr(Ty, PC, IdxList),
1105 return Insert(GetElementPtrInst::CreateInBounds(Ty, Ptr, IdxList), Name);
1107 Value *CreateGEP(Value *Ptr, Value *Idx, const Twine &Name = "") {
1108 return CreateGEP(nullptr, Ptr, Idx, Name);
1110 Value *CreateGEP(Type *Ty, Value *Ptr, Value *Idx, const Twine &Name = "") {
1111 if (Constant *PC = dyn_cast<Constant>(Ptr))
1112 if (Constant *IC = dyn_cast<Constant>(Idx))
1113 return Insert(Folder.CreateGetElementPtr(Ty, PC, IC), Name);
1114 return Insert(GetElementPtrInst::Create(Ty, Ptr, Idx), Name);
1116 Value *CreateInBoundsGEP(Type *Ty, Value *Ptr, Value *Idx,
1117 const Twine &Name = "") {
1118 if (Constant *PC = dyn_cast<Constant>(Ptr))
1119 if (Constant *IC = dyn_cast<Constant>(Idx))
1120 return Insert(Folder.CreateInBoundsGetElementPtr(Ty, PC, IC), Name);
1121 return Insert(GetElementPtrInst::CreateInBounds(Ty, Ptr, Idx), Name);
1123 Value *CreateConstGEP1_32(Value *Ptr, unsigned Idx0, const Twine &Name = "") {
1124 return CreateConstGEP1_32(nullptr, Ptr, Idx0, Name);
1126 Value *CreateConstGEP1_32(Type *Ty, Value *Ptr, unsigned Idx0,
1127 const Twine &Name = "") {
1128 Value *Idx = ConstantInt::get(Type::getInt32Ty(Context), Idx0);
1130 if (Constant *PC = dyn_cast<Constant>(Ptr))
1131 return Insert(Folder.CreateGetElementPtr(Ty, PC, Idx), Name);
1133 return Insert(GetElementPtrInst::Create(Ty, Ptr, Idx), Name);
1135 Value *CreateConstInBoundsGEP1_32(Type *Ty, Value *Ptr, unsigned Idx0,
1136 const Twine &Name = "") {
1137 Value *Idx = ConstantInt::get(Type::getInt32Ty(Context), Idx0);
1139 if (Constant *PC = dyn_cast<Constant>(Ptr))
1140 return Insert(Folder.CreateInBoundsGetElementPtr(Ty, PC, Idx), Name);
1142 return Insert(GetElementPtrInst::CreateInBounds(Ty, Ptr, Idx), Name);
1144 Value *CreateConstGEP2_32(Type *Ty, Value *Ptr, unsigned Idx0, unsigned Idx1,
1145 const Twine &Name = "") {
1147 ConstantInt::get(Type::getInt32Ty(Context), Idx0),
1148 ConstantInt::get(Type::getInt32Ty(Context), Idx1)
1151 if (Constant *PC = dyn_cast<Constant>(Ptr))
1152 return Insert(Folder.CreateGetElementPtr(Ty, PC, Idxs), Name);
1154 return Insert(GetElementPtrInst::Create(Ty, Ptr, Idxs), Name);
1156 Value *CreateConstInBoundsGEP2_32(Type *Ty, Value *Ptr, unsigned Idx0,
1157 unsigned Idx1, const Twine &Name = "") {
1159 ConstantInt::get(Type::getInt32Ty(Context), Idx0),
1160 ConstantInt::get(Type::getInt32Ty(Context), Idx1)
1163 if (Constant *PC = dyn_cast<Constant>(Ptr))
1164 return Insert(Folder.CreateInBoundsGetElementPtr(Ty, PC, Idxs), Name);
1166 return Insert(GetElementPtrInst::CreateInBounds(Ty, Ptr, Idxs), Name);
1168 Value *CreateConstGEP1_64(Value *Ptr, uint64_t Idx0, const Twine &Name = "") {
1169 Value *Idx = ConstantInt::get(Type::getInt64Ty(Context), Idx0);
1171 if (Constant *PC = dyn_cast<Constant>(Ptr))
1172 return Insert(Folder.CreateGetElementPtr(nullptr, PC, Idx), Name);
1174 return Insert(GetElementPtrInst::Create(nullptr, Ptr, Idx), Name);
1176 Value *CreateConstInBoundsGEP1_64(Value *Ptr, uint64_t Idx0,
1177 const Twine &Name = "") {
1178 Value *Idx = ConstantInt::get(Type::getInt64Ty(Context), Idx0);
1180 if (Constant *PC = dyn_cast<Constant>(Ptr))
1181 return Insert(Folder.CreateInBoundsGetElementPtr(nullptr, PC, Idx), Name);
1183 return Insert(GetElementPtrInst::CreateInBounds(nullptr, Ptr, Idx), Name);
1185 Value *CreateConstGEP2_64(Value *Ptr, uint64_t Idx0, uint64_t Idx1,
1186 const Twine &Name = "") {
1188 ConstantInt::get(Type::getInt64Ty(Context), Idx0),
1189 ConstantInt::get(Type::getInt64Ty(Context), Idx1)
1192 if (Constant *PC = dyn_cast<Constant>(Ptr))
1193 return Insert(Folder.CreateGetElementPtr(nullptr, PC, Idxs), Name);
1195 return Insert(GetElementPtrInst::Create(nullptr, Ptr, Idxs), Name);
1197 Value *CreateConstInBoundsGEP2_64(Value *Ptr, uint64_t Idx0, uint64_t Idx1,
1198 const Twine &Name = "") {
1200 ConstantInt::get(Type::getInt64Ty(Context), Idx0),
1201 ConstantInt::get(Type::getInt64Ty(Context), Idx1)
1204 if (Constant *PC = dyn_cast<Constant>(Ptr))
1205 return Insert(Folder.CreateInBoundsGetElementPtr(nullptr, PC, Idxs),
1208 return Insert(GetElementPtrInst::CreateInBounds(nullptr, Ptr, Idxs), Name);
1210 Value *CreateStructGEP(Type *Ty, Value *Ptr, unsigned Idx,
1211 const Twine &Name = "") {
1212 return CreateConstInBoundsGEP2_32(Ty, Ptr, 0, Idx, Name);
1215 /// \brief Same as CreateGlobalString, but return a pointer with "i8*" type
1216 /// instead of a pointer to array of i8.
1217 Value *CreateGlobalStringPtr(StringRef Str, const Twine &Name = "",
1218 unsigned AddressSpace = 0) {
1219 GlobalVariable *gv = CreateGlobalString(Str, Name, AddressSpace);
1220 Value *zero = ConstantInt::get(Type::getInt32Ty(Context), 0);
1221 Value *Args[] = { zero, zero };
1222 return CreateInBoundsGEP(gv->getValueType(), gv, Args, Name);
1225 //===--------------------------------------------------------------------===//
1226 // Instruction creation methods: Cast/Conversion Operators
1227 //===--------------------------------------------------------------------===//
1229 Value *CreateTrunc(Value *V, Type *DestTy, const Twine &Name = "") {
1230 return CreateCast(Instruction::Trunc, V, DestTy, Name);
1232 Value *CreateZExt(Value *V, Type *DestTy, const Twine &Name = "") {
1233 return CreateCast(Instruction::ZExt, V, DestTy, Name);
1235 Value *CreateSExt(Value *V, Type *DestTy, const Twine &Name = "") {
1236 return CreateCast(Instruction::SExt, V, DestTy, Name);
1238 /// \brief Create a ZExt or Trunc from the integer value V to DestTy. Return
1239 /// the value untouched if the type of V is already DestTy.
1240 Value *CreateZExtOrTrunc(Value *V, Type *DestTy,
1241 const Twine &Name = "") {
1242 assert(V->getType()->isIntOrIntVectorTy() &&
1243 DestTy->isIntOrIntVectorTy() &&
1244 "Can only zero extend/truncate integers!");
1245 Type *VTy = V->getType();
1246 if (VTy->getScalarSizeInBits() < DestTy->getScalarSizeInBits())
1247 return CreateZExt(V, DestTy, Name);
1248 if (VTy->getScalarSizeInBits() > DestTy->getScalarSizeInBits())
1249 return CreateTrunc(V, DestTy, Name);
1252 /// \brief Create a SExt or Trunc from the integer value V to DestTy. Return
1253 /// the value untouched if the type of V is already DestTy.
1254 Value *CreateSExtOrTrunc(Value *V, Type *DestTy,
1255 const Twine &Name = "") {
1256 assert(V->getType()->isIntOrIntVectorTy() &&
1257 DestTy->isIntOrIntVectorTy() &&
1258 "Can only sign extend/truncate integers!");
1259 Type *VTy = V->getType();
1260 if (VTy->getScalarSizeInBits() < DestTy->getScalarSizeInBits())
1261 return CreateSExt(V, DestTy, Name);
1262 if (VTy->getScalarSizeInBits() > DestTy->getScalarSizeInBits())
1263 return CreateTrunc(V, DestTy, Name);
1266 Value *CreateFPToUI(Value *V, Type *DestTy, const Twine &Name = ""){
1267 return CreateCast(Instruction::FPToUI, V, DestTy, Name);
1269 Value *CreateFPToSI(Value *V, Type *DestTy, const Twine &Name = ""){
1270 return CreateCast(Instruction::FPToSI, V, DestTy, Name);
1272 Value *CreateUIToFP(Value *V, Type *DestTy, const Twine &Name = ""){
1273 return CreateCast(Instruction::UIToFP, V, DestTy, Name);
1275 Value *CreateSIToFP(Value *V, Type *DestTy, const Twine &Name = ""){
1276 return CreateCast(Instruction::SIToFP, V, DestTy, Name);
1278 Value *CreateFPTrunc(Value *V, Type *DestTy,
1279 const Twine &Name = "") {
1280 return CreateCast(Instruction::FPTrunc, V, DestTy, Name);
1282 Value *CreateFPExt(Value *V, Type *DestTy, const Twine &Name = "") {
1283 return CreateCast(Instruction::FPExt, V, DestTy, Name);
1285 Value *CreatePtrToInt(Value *V, Type *DestTy,
1286 const Twine &Name = "") {
1287 return CreateCast(Instruction::PtrToInt, V, DestTy, Name);
1289 Value *CreateIntToPtr(Value *V, Type *DestTy,
1290 const Twine &Name = "") {
1291 return CreateCast(Instruction::IntToPtr, V, DestTy, Name);
1293 Value *CreateBitCast(Value *V, Type *DestTy,
1294 const Twine &Name = "") {
1295 return CreateCast(Instruction::BitCast, V, DestTy, Name);
1297 Value *CreateAddrSpaceCast(Value *V, Type *DestTy,
1298 const Twine &Name = "") {
1299 return CreateCast(Instruction::AddrSpaceCast, V, DestTy, Name);
1301 Value *CreateZExtOrBitCast(Value *V, Type *DestTy,
1302 const Twine &Name = "") {
1303 if (V->getType() == DestTy)
1305 if (Constant *VC = dyn_cast<Constant>(V))
1306 return Insert(Folder.CreateZExtOrBitCast(VC, DestTy), Name);
1307 return Insert(CastInst::CreateZExtOrBitCast(V, DestTy), Name);
1309 Value *CreateSExtOrBitCast(Value *V, Type *DestTy,
1310 const Twine &Name = "") {
1311 if (V->getType() == DestTy)
1313 if (Constant *VC = dyn_cast<Constant>(V))
1314 return Insert(Folder.CreateSExtOrBitCast(VC, DestTy), Name);
1315 return Insert(CastInst::CreateSExtOrBitCast(V, DestTy), Name);
1317 Value *CreateTruncOrBitCast(Value *V, Type *DestTy,
1318 const Twine &Name = "") {
1319 if (V->getType() == DestTy)
1321 if (Constant *VC = dyn_cast<Constant>(V))
1322 return Insert(Folder.CreateTruncOrBitCast(VC, DestTy), Name);
1323 return Insert(CastInst::CreateTruncOrBitCast(V, DestTy), Name);
1325 Value *CreateCast(Instruction::CastOps Op, Value *V, Type *DestTy,
1326 const Twine &Name = "") {
1327 if (V->getType() == DestTy)
1329 if (Constant *VC = dyn_cast<Constant>(V))
1330 return Insert(Folder.CreateCast(Op, VC, DestTy), Name);
1331 return Insert(CastInst::Create(Op, V, DestTy), Name);
1333 Value *CreatePointerCast(Value *V, Type *DestTy,
1334 const Twine &Name = "") {
1335 if (V->getType() == DestTy)
1337 if (Constant *VC = dyn_cast<Constant>(V))
1338 return Insert(Folder.CreatePointerCast(VC, DestTy), Name);
1339 return Insert(CastInst::CreatePointerCast(V, DestTy), Name);
1342 Value *CreatePointerBitCastOrAddrSpaceCast(Value *V, Type *DestTy,
1343 const Twine &Name = "") {
1344 if (V->getType() == DestTy)
1347 if (Constant *VC = dyn_cast<Constant>(V)) {
1348 return Insert(Folder.CreatePointerBitCastOrAddrSpaceCast(VC, DestTy),
1352 return Insert(CastInst::CreatePointerBitCastOrAddrSpaceCast(V, DestTy),
1356 Value *CreateIntCast(Value *V, Type *DestTy, bool isSigned,
1357 const Twine &Name = "") {
1358 if (V->getType() == DestTy)
1360 if (Constant *VC = dyn_cast<Constant>(V))
1361 return Insert(Folder.CreateIntCast(VC, DestTy, isSigned), Name);
1362 return Insert(CastInst::CreateIntegerCast(V, DestTy, isSigned), Name);
1365 Value *CreateBitOrPointerCast(Value *V, Type *DestTy,
1366 const Twine &Name = "") {
1367 if (V->getType() == DestTy)
1369 if (V->getType()->getScalarType()->isPointerTy() &&
1370 DestTy->getScalarType()->isIntegerTy())
1371 return CreatePtrToInt(V, DestTy, Name);
1372 if (V->getType()->getScalarType()->isIntegerTy() &&
1373 DestTy->getScalarType()->isPointerTy())
1374 return CreateIntToPtr(V, DestTy, Name);
1376 return CreateBitCast(V, DestTy, Name);
1380 // \brief Provided to resolve 'CreateIntCast(Ptr, Ptr, "...")', giving a
1381 // compile time error, instead of converting the string to bool for the
1382 // isSigned parameter.
1383 Value *CreateIntCast(Value *, Type *, const char *) = delete;
1386 Value *CreateFPCast(Value *V, Type *DestTy, const Twine &Name = "") {
1387 if (V->getType() == DestTy)
1389 if (Constant *VC = dyn_cast<Constant>(V))
1390 return Insert(Folder.CreateFPCast(VC, DestTy), Name);
1391 return Insert(CastInst::CreateFPCast(V, DestTy), Name);
1394 //===--------------------------------------------------------------------===//
1395 // Instruction creation methods: Compare Instructions
1396 //===--------------------------------------------------------------------===//
1398 Value *CreateICmpEQ(Value *LHS, Value *RHS, const Twine &Name = "") {
1399 return CreateICmp(ICmpInst::ICMP_EQ, LHS, RHS, Name);
1401 Value *CreateICmpNE(Value *LHS, Value *RHS, const Twine &Name = "") {
1402 return CreateICmp(ICmpInst::ICMP_NE, LHS, RHS, Name);
1404 Value *CreateICmpUGT(Value *LHS, Value *RHS, const Twine &Name = "") {
1405 return CreateICmp(ICmpInst::ICMP_UGT, LHS, RHS, Name);
1407 Value *CreateICmpUGE(Value *LHS, Value *RHS, const Twine &Name = "") {
1408 return CreateICmp(ICmpInst::ICMP_UGE, LHS, RHS, Name);
1410 Value *CreateICmpULT(Value *LHS, Value *RHS, const Twine &Name = "") {
1411 return CreateICmp(ICmpInst::ICMP_ULT, LHS, RHS, Name);
1413 Value *CreateICmpULE(Value *LHS, Value *RHS, const Twine &Name = "") {
1414 return CreateICmp(ICmpInst::ICMP_ULE, LHS, RHS, Name);
1416 Value *CreateICmpSGT(Value *LHS, Value *RHS, const Twine &Name = "") {
1417 return CreateICmp(ICmpInst::ICMP_SGT, LHS, RHS, Name);
1419 Value *CreateICmpSGE(Value *LHS, Value *RHS, const Twine &Name = "") {
1420 return CreateICmp(ICmpInst::ICMP_SGE, LHS, RHS, Name);
1422 Value *CreateICmpSLT(Value *LHS, Value *RHS, const Twine &Name = "") {
1423 return CreateICmp(ICmpInst::ICMP_SLT, LHS, RHS, Name);
1425 Value *CreateICmpSLE(Value *LHS, Value *RHS, const Twine &Name = "") {
1426 return CreateICmp(ICmpInst::ICMP_SLE, LHS, RHS, Name);
1429 Value *CreateFCmpOEQ(Value *LHS, Value *RHS, const Twine &Name = "",
1430 MDNode *FPMathTag = nullptr) {
1431 return CreateFCmp(FCmpInst::FCMP_OEQ, LHS, RHS, Name, FPMathTag);
1433 Value *CreateFCmpOGT(Value *LHS, Value *RHS, const Twine &Name = "",
1434 MDNode *FPMathTag = nullptr) {
1435 return CreateFCmp(FCmpInst::FCMP_OGT, LHS, RHS, Name, FPMathTag);
1437 Value *CreateFCmpOGE(Value *LHS, Value *RHS, const Twine &Name = "",
1438 MDNode *FPMathTag = nullptr) {
1439 return CreateFCmp(FCmpInst::FCMP_OGE, LHS, RHS, Name, FPMathTag);
1441 Value *CreateFCmpOLT(Value *LHS, Value *RHS, const Twine &Name = "",
1442 MDNode *FPMathTag = nullptr) {
1443 return CreateFCmp(FCmpInst::FCMP_OLT, LHS, RHS, Name, FPMathTag);
1445 Value *CreateFCmpOLE(Value *LHS, Value *RHS, const Twine &Name = "",
1446 MDNode *FPMathTag = nullptr) {
1447 return CreateFCmp(FCmpInst::FCMP_OLE, LHS, RHS, Name, FPMathTag);
1449 Value *CreateFCmpONE(Value *LHS, Value *RHS, const Twine &Name = "",
1450 MDNode *FPMathTag = nullptr) {
1451 return CreateFCmp(FCmpInst::FCMP_ONE, LHS, RHS, Name, FPMathTag);
1453 Value *CreateFCmpORD(Value *LHS, Value *RHS, const Twine &Name = "",
1454 MDNode *FPMathTag = nullptr) {
1455 return CreateFCmp(FCmpInst::FCMP_ORD, LHS, RHS, Name, FPMathTag);
1457 Value *CreateFCmpUNO(Value *LHS, Value *RHS, const Twine &Name = "",
1458 MDNode *FPMathTag = nullptr) {
1459 return CreateFCmp(FCmpInst::FCMP_UNO, LHS, RHS, Name, FPMathTag);
1461 Value *CreateFCmpUEQ(Value *LHS, Value *RHS, const Twine &Name = "",
1462 MDNode *FPMathTag = nullptr) {
1463 return CreateFCmp(FCmpInst::FCMP_UEQ, LHS, RHS, Name, FPMathTag);
1465 Value *CreateFCmpUGT(Value *LHS, Value *RHS, const Twine &Name = "",
1466 MDNode *FPMathTag = nullptr) {
1467 return CreateFCmp(FCmpInst::FCMP_UGT, LHS, RHS, Name, FPMathTag);
1469 Value *CreateFCmpUGE(Value *LHS, Value *RHS, const Twine &Name = "",
1470 MDNode *FPMathTag = nullptr) {
1471 return CreateFCmp(FCmpInst::FCMP_UGE, LHS, RHS, Name, FPMathTag);
1473 Value *CreateFCmpULT(Value *LHS, Value *RHS, const Twine &Name = "",
1474 MDNode *FPMathTag = nullptr) {
1475 return CreateFCmp(FCmpInst::FCMP_ULT, LHS, RHS, Name, FPMathTag);
1477 Value *CreateFCmpULE(Value *LHS, Value *RHS, const Twine &Name = "",
1478 MDNode *FPMathTag = nullptr) {
1479 return CreateFCmp(FCmpInst::FCMP_ULE, LHS, RHS, Name, FPMathTag);
1481 Value *CreateFCmpUNE(Value *LHS, Value *RHS, const Twine &Name = "",
1482 MDNode *FPMathTag = nullptr) {
1483 return CreateFCmp(FCmpInst::FCMP_UNE, LHS, RHS, Name, FPMathTag);
1486 Value *CreateICmp(CmpInst::Predicate P, Value *LHS, Value *RHS,
1487 const Twine &Name = "") {
1488 if (Constant *LC = dyn_cast<Constant>(LHS))
1489 if (Constant *RC = dyn_cast<Constant>(RHS))
1490 return Insert(Folder.CreateICmp(P, LC, RC), Name);
1491 return Insert(new ICmpInst(P, LHS, RHS), Name);
1493 Value *CreateFCmp(CmpInst::Predicate P, Value *LHS, Value *RHS,
1494 const Twine &Name = "", MDNode *FPMathTag = nullptr) {
1495 if (Constant *LC = dyn_cast<Constant>(LHS))
1496 if (Constant *RC = dyn_cast<Constant>(RHS))
1497 return Insert(Folder.CreateFCmp(P, LC, RC), Name);
1498 return Insert(AddFPMathAttributes(new FCmpInst(P, LHS, RHS),
1499 FPMathTag, FMF), Name);
1502 //===--------------------------------------------------------------------===//
1503 // Instruction creation methods: Other Instructions
1504 //===--------------------------------------------------------------------===//
1506 PHINode *CreatePHI(Type *Ty, unsigned NumReservedValues,
1507 const Twine &Name = "") {
1508 return Insert(PHINode::Create(Ty, NumReservedValues), Name);
1511 CallInst *CreateCall(Value *Callee, ArrayRef<Value *> Args = None,
1512 const Twine &Name = "") {
1513 return Insert(CallInst::Create(Callee, Args), Name);
1516 CallInst *CreateCall(llvm::FunctionType *FTy, Value *Callee,
1517 ArrayRef<Value *> Args, const Twine &Name = "") {
1518 return Insert(CallInst::Create(FTy, Callee, Args), Name);
1521 CallInst *CreateCall(Function *Callee, ArrayRef<Value *> Args,
1522 const Twine &Name = "") {
1523 return CreateCall(Callee->getFunctionType(), Callee, Args, Name);
1526 Value *CreateSelect(Value *C, Value *True, Value *False,
1527 const Twine &Name = "") {
1528 if (Constant *CC = dyn_cast<Constant>(C))
1529 if (Constant *TC = dyn_cast<Constant>(True))
1530 if (Constant *FC = dyn_cast<Constant>(False))
1531 return Insert(Folder.CreateSelect(CC, TC, FC), Name);
1532 return Insert(SelectInst::Create(C, True, False), Name);
1535 VAArgInst *CreateVAArg(Value *List, Type *Ty, const Twine &Name = "") {
1536 return Insert(new VAArgInst(List, Ty), Name);
1539 Value *CreateExtractElement(Value *Vec, Value *Idx,
1540 const Twine &Name = "") {
1541 if (Constant *VC = dyn_cast<Constant>(Vec))
1542 if (Constant *IC = dyn_cast<Constant>(Idx))
1543 return Insert(Folder.CreateExtractElement(VC, IC), Name);
1544 return Insert(ExtractElementInst::Create(Vec, Idx), Name);
1547 Value *CreateExtractElement(Value *Vec, uint64_t Idx,
1548 const Twine &Name = "") {
1549 return CreateExtractElement(Vec, getInt64(Idx), Name);
1552 Value *CreateInsertElement(Value *Vec, Value *NewElt, Value *Idx,
1553 const Twine &Name = "") {
1554 if (Constant *VC = dyn_cast<Constant>(Vec))
1555 if (Constant *NC = dyn_cast<Constant>(NewElt))
1556 if (Constant *IC = dyn_cast<Constant>(Idx))
1557 return Insert(Folder.CreateInsertElement(VC, NC, IC), Name);
1558 return Insert(InsertElementInst::Create(Vec, NewElt, Idx), Name);
1561 Value *CreateInsertElement(Value *Vec, Value *NewElt, uint64_t Idx,
1562 const Twine &Name = "") {
1563 return CreateInsertElement(Vec, NewElt, getInt64(Idx), Name);
1566 Value *CreateShuffleVector(Value *V1, Value *V2, Value *Mask,
1567 const Twine &Name = "") {
1568 if (Constant *V1C = dyn_cast<Constant>(V1))
1569 if (Constant *V2C = dyn_cast<Constant>(V2))
1570 if (Constant *MC = dyn_cast<Constant>(Mask))
1571 return Insert(Folder.CreateShuffleVector(V1C, V2C, MC), Name);
1572 return Insert(new ShuffleVectorInst(V1, V2, Mask), Name);
1575 Value *CreateShuffleVector(Value *V1, Value *V2, ArrayRef<int> IntMask,
1576 const Twine &Name = "") {
1577 size_t MaskSize = IntMask.size();
1578 SmallVector<Constant*, 8> MaskVec(MaskSize);
1579 for (size_t i = 0; i != MaskSize; ++i)
1580 MaskVec[i] = getInt32(IntMask[i]);
1581 Value *Mask = ConstantVector::get(MaskVec);
1582 return CreateShuffleVector(V1, V2, Mask, Name);
1585 Value *CreateExtractValue(Value *Agg,
1586 ArrayRef<unsigned> Idxs,
1587 const Twine &Name = "") {
1588 if (Constant *AggC = dyn_cast<Constant>(Agg))
1589 return Insert(Folder.CreateExtractValue(AggC, Idxs), Name);
1590 return Insert(ExtractValueInst::Create(Agg, Idxs), Name);
1593 Value *CreateInsertValue(Value *Agg, Value *Val,
1594 ArrayRef<unsigned> Idxs,
1595 const Twine &Name = "") {
1596 if (Constant *AggC = dyn_cast<Constant>(Agg))
1597 if (Constant *ValC = dyn_cast<Constant>(Val))
1598 return Insert(Folder.CreateInsertValue(AggC, ValC, Idxs), Name);
1599 return Insert(InsertValueInst::Create(Agg, Val, Idxs), Name);
1602 LandingPadInst *CreateLandingPad(Type *Ty, unsigned NumClauses,
1603 const Twine &Name = "") {
1604 return Insert(LandingPadInst::Create(Ty, NumClauses), Name);
1607 //===--------------------------------------------------------------------===//
1608 // Utility creation methods
1609 //===--------------------------------------------------------------------===//
1611 /// \brief Return an i1 value testing if \p Arg is null.
1612 Value *CreateIsNull(Value *Arg, const Twine &Name = "") {
1613 return CreateICmpEQ(Arg, Constant::getNullValue(Arg->getType()),
1617 /// \brief Return an i1 value testing if \p Arg is not null.
1618 Value *CreateIsNotNull(Value *Arg, const Twine &Name = "") {
1619 return CreateICmpNE(Arg, Constant::getNullValue(Arg->getType()),
1623 /// \brief Return the i64 difference between two pointer values, dividing out
1624 /// the size of the pointed-to objects.
1626 /// This is intended to implement C-style pointer subtraction. As such, the
1627 /// pointers must be appropriately aligned for their element types and
1628 /// pointing into the same object.
1629 Value *CreatePtrDiff(Value *LHS, Value *RHS, const Twine &Name = "") {
1630 assert(LHS->getType() == RHS->getType() &&
1631 "Pointer subtraction operand types must match!");
1632 PointerType *ArgType = cast<PointerType>(LHS->getType());
1633 Value *LHS_int = CreatePtrToInt(LHS, Type::getInt64Ty(Context));
1634 Value *RHS_int = CreatePtrToInt(RHS, Type::getInt64Ty(Context));
1635 Value *Difference = CreateSub(LHS_int, RHS_int);
1636 return CreateExactSDiv(Difference,
1637 ConstantExpr::getSizeOf(ArgType->getElementType()),
1641 /// \brief Create an invariant.group.barrier intrinsic call, that stops
1642 /// optimizer to propagate equality using invariant.group metadata.
1643 /// If Ptr type is different from i8*, it's casted to i8* before call
1644 /// and casted back to Ptr type after call.
1645 Value *CreateInvariantGroupBarrier(Value *Ptr) {
1646 Module *M = BB->getParent()->getParent();
1647 Function *FnInvariantGroupBarrier = Intrinsic::getDeclaration(M,
1648 Intrinsic::invariant_group_barrier);
1650 Type *ArgumentAndReturnType = FnInvariantGroupBarrier->getReturnType();
1651 assert(ArgumentAndReturnType ==
1652 FnInvariantGroupBarrier->getFunctionType()->getParamType(0) &&
1653 "InvariantGroupBarrier should take and return the same type");
1654 Type *PtrType = Ptr->getType();
1656 bool PtrTypeConversionNeeded = PtrType != ArgumentAndReturnType;
1657 if (PtrTypeConversionNeeded)
1658 Ptr = CreateBitCast(Ptr, ArgumentAndReturnType);
1660 CallInst *Fn = CreateCall(FnInvariantGroupBarrier, {Ptr});
1662 if (PtrTypeConversionNeeded)
1663 return CreateBitCast(Fn, PtrType);
1667 /// \brief Return a vector value that contains \arg V broadcasted to \p
1668 /// NumElts elements.
1669 Value *CreateVectorSplat(unsigned NumElts, Value *V, const Twine &Name = "") {
1670 assert(NumElts > 0 && "Cannot splat to an empty vector!");
1672 // First insert it into an undef vector so we can shuffle it.
1673 Type *I32Ty = getInt32Ty();
1674 Value *Undef = UndefValue::get(VectorType::get(V->getType(), NumElts));
1675 V = CreateInsertElement(Undef, V, ConstantInt::get(I32Ty, 0),
1676 Name + ".splatinsert");
1678 // Shuffle the value across the desired number of elements.
1679 Value *Zeros = ConstantAggregateZero::get(VectorType::get(I32Ty, NumElts));
1680 return CreateShuffleVector(V, Undef, Zeros, Name + ".splat");
1683 /// \brief Return a value that has been extracted from a larger integer type.
1684 Value *CreateExtractInteger(const DataLayout &DL, Value *From,
1685 IntegerType *ExtractedTy, uint64_t Offset,
1686 const Twine &Name) {
1687 IntegerType *IntTy = cast<IntegerType>(From->getType());
1688 assert(DL.getTypeStoreSize(ExtractedTy) + Offset <=
1689 DL.getTypeStoreSize(IntTy) &&
1690 "Element extends past full value");
1691 uint64_t ShAmt = 8 * Offset;
1693 if (DL.isBigEndian())
1694 ShAmt = 8 * (DL.getTypeStoreSize(IntTy) -
1695 DL.getTypeStoreSize(ExtractedTy) - Offset);
1697 V = CreateLShr(V, ShAmt, Name + ".shift");
1699 assert(ExtractedTy->getBitWidth() <= IntTy->getBitWidth() &&
1700 "Cannot extract to a larger integer!");
1701 if (ExtractedTy != IntTy) {
1702 V = CreateTrunc(V, ExtractedTy, Name + ".trunc");
1707 /// \brief Create an assume intrinsic call that represents an alignment
1708 /// assumption on the provided pointer.
1710 /// An optional offset can be provided, and if it is provided, the offset
1711 /// must be subtracted from the provided pointer to get the pointer with the
1712 /// specified alignment.
1713 CallInst *CreateAlignmentAssumption(const DataLayout &DL, Value *PtrValue,
1715 Value *OffsetValue = nullptr) {
1716 assert(isa<PointerType>(PtrValue->getType()) &&
1717 "trying to create an alignment assumption on a non-pointer?");
1719 PointerType *PtrTy = cast<PointerType>(PtrValue->getType());
1720 Type *IntPtrTy = getIntPtrTy(DL, PtrTy->getAddressSpace());
1721 Value *PtrIntValue = CreatePtrToInt(PtrValue, IntPtrTy, "ptrint");
1723 Value *Mask = ConstantInt::get(IntPtrTy,
1724 Alignment > 0 ? Alignment - 1 : 0);
1726 bool IsOffsetZero = false;
1727 if (ConstantInt *CI = dyn_cast<ConstantInt>(OffsetValue))
1728 IsOffsetZero = CI->isZero();
1730 if (!IsOffsetZero) {
1731 if (OffsetValue->getType() != IntPtrTy)
1732 OffsetValue = CreateIntCast(OffsetValue, IntPtrTy, /*isSigned*/ true,
1734 PtrIntValue = CreateSub(PtrIntValue, OffsetValue, "offsetptr");
1738 Value *Zero = ConstantInt::get(IntPtrTy, 0);
1739 Value *MaskedPtr = CreateAnd(PtrIntValue, Mask, "maskedptr");
1740 Value *InvCond = CreateICmpEQ(MaskedPtr, Zero, "maskcond");
1742 return CreateAssumption(InvCond);
1746 // Create wrappers for C Binding types (see CBindingWrapping.h).
1747 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(IRBuilder<>, LLVMBuilderRef)