Debian Codegraph @

suite/synctools/tablegen/include/llvm/IR/IRBuilder.h

raw symbols SCIP
1 //===- llvm/IRBuilder.h - Builder for LLVM Instructions ---------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines the IRBuilder class, which is used as a convenient way
10 // to create LLVM instructions with a consistent and simplified interface.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #ifndef LLVM_IR_IRBUILDER_H
15 #define LLVM_IR_IRBUILDER_H
16
17 #include "llvm-c/Types.h"
18 #include "llvm/ADT/ArrayRef.h"
19 #include "llvm/ADT/None.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/StringRef.h"
22 #include "llvm/ADT/Twine.h"
23 #include "llvm/IR/BasicBlock.h"
24 #include "llvm/IR/Constant.h"
25 #include "llvm/IR/ConstantFolder.h"
26 #include "llvm/IR/Constants.h"
27 #include "llvm/IR/DataLayout.h"
28 #include "llvm/IR/DebugInfoMetadata.h"
29 #include "llvm/IR/DebugLoc.h"
30 #include "llvm/IR/DerivedTypes.h"
31 #include "llvm/IR/FPEnv.h"
32 #include "llvm/IR/Function.h"
33 #include "llvm/IR/GlobalVariable.h"
34 #include "llvm/IR/InstrTypes.h"
35 #include "llvm/IR/Instruction.h"
36 #include "llvm/IR/Instructions.h"
37 #include "llvm/IR/Intrinsics.h"
38 #include "llvm/IR/LLVMContext.h"
39 #include "llvm/IR/Module.h"
40 #include "llvm/IR/Operator.h"
41 #include "llvm/IR/Type.h"
42 #include "llvm/IR/Value.h"
43 #include "llvm/IR/ValueHandle.h"
44 #include "llvm/Support/AtomicOrdering.h"
45 #include "llvm/Support/CBindingWrapping.h"
46 #include "llvm/Support/Casting.h"
47 #include <cassert>
48 #include <cstdint>
49 #include <functional>
50 #include <utility>
51
52 namespace llvm {
53
54 class APInt;
55 class Use;
56
57 /// This provides the default implementation of the IRBuilder
58 /// 'InsertHelper' method that is called whenever an instruction is created by
59 /// IRBuilder and needs to be inserted.
60 ///
61 /// By default, this inserts the instruction at the insertion point.
62 class IRBuilderDefaultInserter {
63 public:
64 virtual ~IRBuilderDefaultInserter();
65
66 virtual void InsertHelper(Instruction *I, const Twine &Name,
67 BasicBlock *BB,
68 BasicBlock::iterator InsertPt) const {
69 if (BB) BB->getInstList().insert(InsertPt, I);
70 I->setName(Name);
71 }
72 };
73
74 /// Provides an 'InsertHelper' that calls a user-provided callback after
75 /// performing the default insertion.
76 class IRBuilderCallbackInserter : public IRBuilderDefaultInserter {
77 std::function<void(Instruction *)> Callback;
78
79 public:
80 virtual ~IRBuilderCallbackInserter();
81
82 IRBuilderCallbackInserter(std::function<void(Instruction *)> Callback)
83 : Callback(std::move(Callback)) {}
84
85 void InsertHelper(Instruction *I, const Twine &Name,
86 BasicBlock *BB,
87 BasicBlock::iterator InsertPt) const override {
88 IRBuilderDefaultInserter::InsertHelper(I, Name, BB, InsertPt);
89 Callback(I);
90 }
91 };
92
93 /// Common base class shared among various IRBuilders.
94 class IRBuilderBase {
95 /// Pairs of (metadata kind, MDNode *) that should be added to all newly
96 /// created instructions, like !dbg metadata.
97 SmallVector<std::pair<unsigned, MDNode *>, 2> MetadataToCopy;
98
99 /// Add or update the an entry (Kind, MD) to MetadataToCopy, if \p MD is not
100 /// null. If \p MD is null, remove the entry with \p Kind.
101 void AddOrRemoveMetadataToCopy(unsigned Kind, MDNode *MD) {
102 if (!MD) {
103 erase_if(MetadataToCopy, [Kind](const std::pair<unsigned, MDNode *> &KV) {
104 return KV.first == Kind;
105 });
106 return;
107 }
108
109 for (auto &KV : MetadataToCopy)
110 if (KV.first == Kind) {
111 KV.second = MD;
112 return;
113 }
114
115 MetadataToCopy.emplace_back(Kind, MD);
116 }
117
118 protected:
119 BasicBlock *BB;
120 BasicBlock::iterator InsertPt;
121 LLVMContext &Context;
122 const IRBuilderFolder &Folder;
123 const IRBuilderDefaultInserter &Inserter;
124
125 MDNode *DefaultFPMathTag;
126 FastMathFlags FMF;
127
128 bool IsFPConstrained;
129 fp::ExceptionBehavior DefaultConstrainedExcept;
130 RoundingMode DefaultConstrainedRounding;
131
132 ArrayRef<OperandBundleDef> DefaultOperandBundles;
133
134 public:
135 IRBuilderBase(LLVMContext &context, const IRBuilderFolder &Folder,
136 const IRBuilderDefaultInserter &Inserter,
137 MDNode *FPMathTag, ArrayRef<OperandBundleDef> OpBundles)
138 : Context(context), Folder(Folder), Inserter(Inserter),
139 DefaultFPMathTag(FPMathTag), IsFPConstrained(false),
140 DefaultConstrainedExcept(fp::ebStrict),
141 DefaultConstrainedRounding(RoundingMode::Dynamic),
142 DefaultOperandBundles(OpBundles) {
143 ClearInsertionPoint();
144 }
145
146 /// Insert and return the specified instruction.
147 template<typename InstTy>
148 InstTy *Insert(InstTy *I, const Twine &Name = "") const {
149 Inserter.InsertHelper(I, Name, BB, InsertPt);
150 AddMetadataToInst(I);
151 return I;
152 }
153
154 /// No-op overload to handle constants.
155 Constant *Insert(Constant *C, const Twine& = "") const {
156 return C;
157 }
158
159 Value *Insert(Value *V, const Twine &Name = "") const {
160 if (Instruction *I = dyn_cast<Instruction>(V))
161 return Insert(I, Name);
162 assert(isa<Constant>(V));
163 return V;
164 }
165
166 //===--------------------------------------------------------------------===//
167 // Builder configuration methods
168 //===--------------------------------------------------------------------===//
169
170 /// Clear the insertion point: created instructions will not be
171 /// inserted into a block.
172 void ClearInsertionPoint() {
173 BB = nullptr;
174 InsertPt = BasicBlock::iterator();
175 }
176
177 BasicBlock *GetInsertBlock() const { return BB; }
178 BasicBlock::iterator GetInsertPoint() const { return InsertPt; }
179 LLVMContext &getContext() const { return Context; }
180
181 /// This specifies that created instructions should be appended to the
182 /// end of the specified block.
183 void SetInsertPoint(BasicBlock *TheBB) {
184 BB = TheBB;
185 InsertPt = BB->end();
186 }
187
188 /// This specifies that created instructions should be inserted before
189 /// the specified instruction.
190 void SetInsertPoint(Instruction *I) {
191 BB = I->getParent();
192 InsertPt = I->getIterator();
193 assert(InsertPt != BB->end() && "Can't read debug loc from end()");
194 SetCurrentDebugLocation(I->getDebugLoc());
195 }
196
197 /// This specifies that created instructions should be inserted at the
198 /// specified point.
199 void SetInsertPoint(BasicBlock *TheBB, BasicBlock::iterator IP) {
200 BB = TheBB;
201 InsertPt = IP;
202 if (IP != TheBB->end())
203 SetCurrentDebugLocation(IP->getDebugLoc());
204 }
205
206 /// Set location information used by debugging information.
207 void SetCurrentDebugLocation(DebugLoc L) {
208 AddOrRemoveMetadataToCopy(LLVMContext::MD_dbg, L.getAsMDNode());
209 }
210
211 /// Collect metadata with IDs \p MetadataKinds from \p Src which should be
212 /// added to all created instructions. Entries present in MedataDataToCopy but
213 /// not on \p Src will be dropped from MetadataToCopy.
214 void CollectMetadataToCopy(Instruction *Src,
215 ArrayRef<unsigned> MetadataKinds) {
216 for (unsigned K : MetadataKinds)
217 AddOrRemoveMetadataToCopy(K, Src->getMetadata(K));
218 }
219
220 /// Get location information used by debugging information.
221 DebugLoc getCurrentDebugLocation() const {
222 for (auto &KV : MetadataToCopy)
223 if (KV.first == LLVMContext::MD_dbg)
224 return {cast<DILocation>(KV.second)};
225
226 return {};
227 }
228
229 /// If this builder has a current debug location, set it on the
230 /// specified instruction.
231 void SetInstDebugLocation(Instruction *I) const {
232 for (const auto &KV : MetadataToCopy)
233 if (KV.first == LLVMContext::MD_dbg) {
234 I->setDebugLoc(DebugLoc(KV.second));
235 return;
236 }
237 }
238
239 /// Add all entries in MetadataToCopy to \p I.
240 void AddMetadataToInst(Instruction *I) const {
241 for (auto &KV : MetadataToCopy)
242 I->setMetadata(KV.first, KV.second);
243 }
244
245 /// Get the return type of the current function that we're emitting
246 /// into.
247 Type *getCurrentFunctionReturnType() const;
248
249 /// InsertPoint - A saved insertion point.
250 class InsertPoint {
251 BasicBlock *Block = nullptr;
252 BasicBlock::iterator Point;
253
254 public:
255 /// Creates a new insertion point which doesn't point to anything.
256 InsertPoint() = default;
257
258 /// Creates a new insertion point at the given location.
259 InsertPoint(BasicBlock *InsertBlock, BasicBlock::iterator InsertPoint)
260 : Block(InsertBlock), Point(InsertPoint) {}
261
262 /// Returns true if this insert point is set.
263 bool isSet() const { return (Block != nullptr); }
264
265 BasicBlock *getBlock() const { return Block; }
266 BasicBlock::iterator getPoint() const { return Point; }
267 };
268
269 /// Returns the current insert point.
270 InsertPoint saveIP() const {
271 return InsertPoint(GetInsertBlock(), GetInsertPoint());
272 }
273
274 /// Returns the current insert point, clearing it in the process.
275 InsertPoint saveAndClearIP() {
276 InsertPoint IP(GetInsertBlock(), GetInsertPoint());
277 ClearInsertionPoint();
278 return IP;
279 }
280
281 /// Sets the current insert point to a previously-saved location.
282 void restoreIP(InsertPoint IP) {
283 if (IP.isSet())
284 SetInsertPoint(IP.getBlock(), IP.getPoint());
285 else
286 ClearInsertionPoint();
287 }
288
289 /// Get the floating point math metadata being used.
290 MDNode *getDefaultFPMathTag() const { return DefaultFPMathTag; }
291
292 /// Get the flags to be applied to created floating point ops
293 FastMathFlags getFastMathFlags() const { return FMF; }
294
295 FastMathFlags &getFastMathFlags() { return FMF; }
296
297 /// Clear the fast-math flags.
298 void clearFastMathFlags() { FMF.clear(); }
299
300 /// Set the floating point math metadata to be used.
301 void setDefaultFPMathTag(MDNode *FPMathTag) { DefaultFPMathTag = FPMathTag; }
302
303 /// Set the fast-math flags to be used with generated fp-math operators
304 void setFastMathFlags(FastMathFlags NewFMF) { FMF = NewFMF; }
305
306 /// Enable/Disable use of constrained floating point math. When
307 /// enabled the CreateF<op>() calls instead create constrained
308 /// floating point intrinsic calls. Fast math flags are unaffected
309 /// by this setting.
310 void setIsFPConstrained(bool IsCon) { IsFPConstrained = IsCon; }
311
312 /// Query for the use of constrained floating point math
313 bool getIsFPConstrained() { return IsFPConstrained; }
314
315 /// Set the exception handling to be used with constrained floating point
316 void setDefaultConstrainedExcept(fp::ExceptionBehavior NewExcept) {
317 #ifndef NDEBUG
318 Optional<StringRef> ExceptStr = convertExceptionBehaviorToStr(NewExcept);
319 assert(ExceptStr.hasValue() && "Garbage strict exception behavior!");
320 #endif
321 DefaultConstrainedExcept = NewExcept;
322 }
323
324 /// Set the rounding mode handling to be used with constrained floating point
325 void setDefaultConstrainedRounding(RoundingMode NewRounding) {
326 #ifndef NDEBUG
327 Optional<StringRef> RoundingStr = convertRoundingModeToStr(NewRounding);
328 assert(RoundingStr.hasValue() && "Garbage strict rounding mode!");
329 #endif
330 DefaultConstrainedRounding = NewRounding;
331 }
332
333 /// Get the exception handling used with constrained floating point
334 fp::ExceptionBehavior getDefaultConstrainedExcept() {
335 return DefaultConstrainedExcept;
336 }
337
338 /// Get the rounding mode handling used with constrained floating point
339 RoundingMode getDefaultConstrainedRounding() {
340 return DefaultConstrainedRounding;
341 }
342
343 void setConstrainedFPFunctionAttr() {
344 assert(BB && "Must have a basic block to set any function attributes!");
345
346 Function *F = BB->getParent();
347 if (!F->hasFnAttribute(Attribute::StrictFP)) {
348 F->addFnAttr(Attribute::StrictFP);
349 }
350 }
351
352 void setConstrainedFPCallAttr(CallBase *I) {
353 I->addFnAttr(Attribute::StrictFP);
354 }
355
356 void setDefaultOperandBundles(ArrayRef<OperandBundleDef> OpBundles) {
357 DefaultOperandBundles = OpBundles;
358 }
359
360 //===--------------------------------------------------------------------===//
361 // RAII helpers.
362 //===--------------------------------------------------------------------===//
363
364 // RAII object that stores the current insertion point and restores it
365 // when the object is destroyed. This includes the debug location.
366 class InsertPointGuard {
367 IRBuilderBase &Builder;
368 AssertingVH<BasicBlock> Block;
369 BasicBlock::iterator Point;
370 DebugLoc DbgLoc;
371
372 public:
373 InsertPointGuard(IRBuilderBase &B)
374 : Builder(B), Block(B.GetInsertBlock()), Point(B.GetInsertPoint()),
375 DbgLoc(B.getCurrentDebugLocation()) {}
376
377 InsertPointGuard(const InsertPointGuard &) = delete;
378 InsertPointGuard &operator=(const InsertPointGuard &) = delete;
379
380 ~InsertPointGuard() {
381 Builder.restoreIP(InsertPoint(Block, Point));
382 Builder.SetCurrentDebugLocation(DbgLoc);
383 }
384 };
385
386 // RAII object that stores the current fast math settings and restores
387 // them when the object is destroyed.
388 class FastMathFlagGuard {
389 IRBuilderBase &Builder;
390 FastMathFlags FMF;
391 MDNode *FPMathTag;
392 bool IsFPConstrained;
393 fp::ExceptionBehavior DefaultConstrainedExcept;
394 RoundingMode DefaultConstrainedRounding;
395
396 public:
397 FastMathFlagGuard(IRBuilderBase &B)
398 : Builder(B), FMF(B.FMF), FPMathTag(B.DefaultFPMathTag),
399 IsFPConstrained(B.IsFPConstrained),
400 DefaultConstrainedExcept(B.DefaultConstrainedExcept),
401 DefaultConstrainedRounding(B.DefaultConstrainedRounding) {}
402
403 FastMathFlagGuard(const FastMathFlagGuard &) = delete;
404 FastMathFlagGuard &operator=(const FastMathFlagGuard &) = delete;
405
406 ~FastMathFlagGuard() {
407 Builder.FMF = FMF;
408 Builder.DefaultFPMathTag = FPMathTag;
409 Builder.IsFPConstrained = IsFPConstrained;
410 Builder.DefaultConstrainedExcept = DefaultConstrainedExcept;
411 Builder.DefaultConstrainedRounding = DefaultConstrainedRounding;
412 }
413 };
414
415 // RAII object that stores the current default operand bundles and restores
416 // them when the object is destroyed.
417 class OperandBundlesGuard {
418 IRBuilderBase &Builder;
419 ArrayRef<OperandBundleDef> DefaultOperandBundles;
420
421 public:
422 OperandBundlesGuard(IRBuilderBase &B)
423 : Builder(B), DefaultOperandBundles(B.DefaultOperandBundles) {}
424
425 OperandBundlesGuard(const OperandBundlesGuard &) = delete;
426 OperandBundlesGuard &operator=(const OperandBundlesGuard &) = delete;
427
428 ~OperandBundlesGuard() {
429 Builder.DefaultOperandBundles = DefaultOperandBundles;
430 }
431 };
432
433
434 //===--------------------------------------------------------------------===//
435 // Miscellaneous creation methods.
436 //===--------------------------------------------------------------------===//
437
438 /// Make a new global variable with initializer type i8*
439 ///
440 /// Make a new global variable with an initializer that has array of i8 type
441 /// filled in with the null terminated string value specified. The new global
442 /// variable will be marked mergable with any others of the same contents. If
443 /// Name is specified, it is the name of the global variable created.
444 ///
445 /// If no module is given via \p M, it is take from the insertion point basic
446 /// block.
447 GlobalVariable *CreateGlobalString(StringRef Str, const Twine &Name = "",
448 unsigned AddressSpace = 0,
449 Module *M = nullptr);
450
451 /// Get a constant value representing either true or false.
452 ConstantInt *getInt1(bool V) {
453 return ConstantInt::get(getInt1Ty(), V);
454 }
455
456 /// Get the constant value for i1 true.
457 ConstantInt *getTrue() {
458 return ConstantInt::getTrue(Context);
459 }
460
461 /// Get the constant value for i1 false.
462 ConstantInt *getFalse() {
463 return ConstantInt::getFalse(Context);
464 }
465
466 /// Get a constant 8-bit value.
467 ConstantInt *getInt8(uint8_t C) {
468 return ConstantInt::get(getInt8Ty(), C);
469 }
470
471 /// Get a constant 16-bit value.
472 ConstantInt *getInt16(uint16_t C) {
473 return ConstantInt::get(getInt16Ty(), C);
474 }
475
476 /// Get a constant 32-bit value.
477 ConstantInt *getInt32(uint32_t C) {
478 return ConstantInt::get(getInt32Ty(), C);
479 }
480
481 /// Get a constant 64-bit value.
482 ConstantInt *getInt64(uint64_t C) {
483 return ConstantInt::get(getInt64Ty(), C);
484 }
485
486 /// Get a constant N-bit value, zero extended or truncated from
487 /// a 64-bit value.
488 ConstantInt *getIntN(unsigned N, uint64_t C) {
489 return ConstantInt::get(getIntNTy(N), C);
490 }
491
492 /// Get a constant integer value.
493 ConstantInt *getInt(const APInt &AI) {
494 return ConstantInt::get(Context, AI);
495 }
496
497 //===--------------------------------------------------------------------===//
498 // Type creation methods
499 //===--------------------------------------------------------------------===//
500
501 /// Fetch the type representing a single bit
502 IntegerType *getInt1Ty() {
503 return Type::getInt1Ty(Context);
504 }
505
506 /// Fetch the type representing an 8-bit integer.
507 IntegerType *getInt8Ty() {
508 return Type::getInt8Ty(Context);
509 }
510
511 /// Fetch the type representing a 16-bit integer.
512 IntegerType *getInt16Ty() {
513 return Type::getInt16Ty(Context);
514 }
515
516 /// Fetch the type representing a 32-bit integer.
517 IntegerType *getInt32Ty() {
518 return Type::getInt32Ty(Context);
519 }
520
521 /// Fetch the type representing a 64-bit integer.
522 IntegerType *getInt64Ty() {
523 return Type::getInt64Ty(Context);
524 }
525
526 /// Fetch the type representing a 128-bit integer.
527 IntegerType *getInt128Ty() { return Type::getInt128Ty(Context); }
528
529 /// Fetch the type representing an N-bit integer.
530 IntegerType *getIntNTy(unsigned N) {
531 return Type::getIntNTy(Context, N);
532 }
533
534 /// Fetch the type representing a 16-bit floating point value.
535 Type *getHalfTy() {
536 return Type::getHalfTy(Context);
537 }
538
539 /// Fetch the type representing a 16-bit brain floating point value.
540 Type *getBFloatTy() {
541 return Type::getBFloatTy(Context);
542 }
543
544 /// Fetch the type representing a 32-bit floating point value.
545 Type *getFloatTy() {
546 return Type::getFloatTy(Context);
547 }
548
549 /// Fetch the type representing a 64-bit floating point value.
550 Type *getDoubleTy() {
551 return Type::getDoubleTy(Context);
552 }
553
554 /// Fetch the type representing void.
555 Type *getVoidTy() {
556 return Type::getVoidTy(Context);
557 }
558
559 /// Fetch the type representing a pointer to an 8-bit integer value.
560 PointerType *getInt8PtrTy(unsigned AddrSpace = 0) {
561 return Type::getInt8PtrTy(Context, AddrSpace);
562 }
563
564 /// Fetch the type representing a pointer to an integer value.
565 IntegerType *getIntPtrTy(const DataLayout &DL, unsigned AddrSpace = 0) {
566 return DL.getIntPtrType(Context, AddrSpace);
567 }
568
569 //===--------------------------------------------------------------------===//
570 // Intrinsic creation methods
571 //===--------------------------------------------------------------------===//
572
573 /// Create and insert a memset to the specified pointer and the
574 /// specified value.
575 ///
576 /// If the pointer isn't an i8*, it will be converted. If a TBAA tag is
577 /// specified, it will be added to the instruction. Likewise with alias.scope
578 /// and noalias tags.
579 CallInst *CreateMemSet(Value *Ptr, Value *Val, uint64_t Size,
580 MaybeAlign Align, bool isVolatile = false,
581 MDNode *TBAATag = nullptr, MDNode *ScopeTag = nullptr,
582 MDNode *NoAliasTag = nullptr) {
583 return CreateMemSet(Ptr, Val, getInt64(Size), Align, isVolatile,
584 TBAATag, ScopeTag, NoAliasTag);
585 }
586
587 CallInst *CreateMemSet(Value *Ptr, Value *Val, Value *Size, MaybeAlign Align,
588 bool isVolatile = false, MDNode *TBAATag = nullptr,
589 MDNode *ScopeTag = nullptr,
590 MDNode *NoAliasTag = nullptr);
591
592 /// Create and insert an element unordered-atomic memset of the region of
593 /// memory starting at the given pointer to the given value.
594 ///
595 /// If the pointer isn't an i8*, it will be converted. If a TBAA tag is
596 /// specified, it will be added to the instruction. Likewise with alias.scope
597 /// and noalias tags.
598 CallInst *CreateElementUnorderedAtomicMemSet(Value *Ptr, Value *Val,
599 uint64_t Size, Align Alignment,
600 uint32_t ElementSize,
601 MDNode *TBAATag = nullptr,
602 MDNode *ScopeTag = nullptr,
603 MDNode *NoAliasTag = nullptr) {
604 return CreateElementUnorderedAtomicMemSet(Ptr, Val, getInt64(Size),
605 Align(Alignment), ElementSize,
606 TBAATag, ScopeTag, NoAliasTag);
607 }
608
609 CallInst *CreateElementUnorderedAtomicMemSet(Value *Ptr, Value *Val,
610 Value *Size, Align Alignment,
611 uint32_t ElementSize,
612 MDNode *TBAATag = nullptr,
613 MDNode *ScopeTag = nullptr,
614 MDNode *NoAliasTag = nullptr);
615
616 /// Create and insert a memcpy between the specified pointers.
617 ///
618 /// If the pointers aren't i8*, they will be converted. If a TBAA tag is
619 /// specified, it will be added to the instruction. Likewise with alias.scope
620 /// and noalias tags.
621 CallInst *CreateMemCpy(Value *Dst, MaybeAlign DstAlign, Value *Src,
622 MaybeAlign SrcAlign, uint64_t Size,
623 bool isVolatile = false, MDNode *TBAATag = nullptr,
624 MDNode *TBAAStructTag = nullptr,
625 MDNode *ScopeTag = nullptr,
626 MDNode *NoAliasTag = nullptr) {
627 return CreateMemCpy(Dst, DstAlign, Src, SrcAlign, getInt64(Size),
628 isVolatile, TBAATag, TBAAStructTag, ScopeTag,
629 NoAliasTag);
630 }
631
632 CallInst *CreateMemTransferInst(
633 Intrinsic::ID IntrID, Value *Dst, MaybeAlign DstAlign, Value *Src,
634 MaybeAlign SrcAlign, Value *Size, bool isVolatile = false,
635 MDNode *TBAATag = nullptr, MDNode *TBAAStructTag = nullptr,
636 MDNode *ScopeTag = nullptr, MDNode *NoAliasTag = nullptr);
637
638 CallInst *CreateMemCpy(Value *Dst, MaybeAlign DstAlign, Value *Src,
639 MaybeAlign SrcAlign, Value *Size,
640 bool isVolatile = false, MDNode *TBAATag = nullptr,
641 MDNode *TBAAStructTag = nullptr,
642 MDNode *ScopeTag = nullptr,
643 MDNode *NoAliasTag = nullptr) {
644 return CreateMemTransferInst(Intrinsic::memcpy, Dst, DstAlign, Src,
645 SrcAlign, Size, isVolatile, TBAATag,
646 TBAAStructTag, ScopeTag, NoAliasTag);
647 }
648
649 CallInst *
650 CreateMemCpyInline(Value *Dst, MaybeAlign DstAlign, Value *Src,
651 MaybeAlign SrcAlign, Value *Size, bool IsVolatile = false,
652 MDNode *TBAATag = nullptr, MDNode *TBAAStructTag = nullptr,
653 MDNode *ScopeTag = nullptr, MDNode *NoAliasTag = nullptr);
654
655 /// Create and insert an element unordered-atomic memcpy between the
656 /// specified pointers.
657 ///
658 /// DstAlign/SrcAlign are the alignments of the Dst/Src pointers, respectively.
659 ///
660 /// If the pointers aren't i8*, they will be converted. If a TBAA tag is
661 /// specified, it will be added to the instruction. Likewise with alias.scope
662 /// and noalias tags.
663 CallInst *CreateElementUnorderedAtomicMemCpy(
664 Value *Dst, Align DstAlign, Value *Src, Align SrcAlign, Value *Size,
665 uint32_t ElementSize, MDNode *TBAATag = nullptr,
666 MDNode *TBAAStructTag = nullptr, MDNode *ScopeTag = nullptr,
667 MDNode *NoAliasTag = nullptr);
668
669 CallInst *CreateMemMove(Value *Dst, MaybeAlign DstAlign, Value *Src,
670 MaybeAlign SrcAlign, uint64_t Size,
671 bool isVolatile = false, MDNode *TBAATag = nullptr,
672 MDNode *ScopeTag = nullptr,
673 MDNode *NoAliasTag = nullptr) {
674 return CreateMemMove(Dst, DstAlign, Src, SrcAlign, getInt64(Size),
675 isVolatile, TBAATag, ScopeTag, NoAliasTag);
676 }
677
678 CallInst *CreateMemMove(Value *Dst, MaybeAlign DstAlign, Value *Src,
679 MaybeAlign SrcAlign, Value *Size,
680 bool isVolatile = false, MDNode *TBAATag = nullptr,
681 MDNode *ScopeTag = nullptr,
682 MDNode *NoAliasTag = nullptr);
683
684 /// \brief Create and insert an element unordered-atomic memmove between the
685 /// specified pointers.
686 ///
687 /// DstAlign/SrcAlign are the alignments of the Dst/Src pointers,
688 /// respectively.
689 ///
690 /// If the pointers aren't i8*, they will be converted. If a TBAA tag is
691 /// specified, it will be added to the instruction. Likewise with alias.scope
692 /// and noalias tags.
693 CallInst *CreateElementUnorderedAtomicMemMove(
694 Value *Dst, Align DstAlign, Value *Src, Align SrcAlign, Value *Size,
695 uint32_t ElementSize, MDNode *TBAATag = nullptr,
696 MDNode *TBAAStructTag = nullptr, MDNode *ScopeTag = nullptr,
697 MDNode *NoAliasTag = nullptr);
698
699 /// Create a sequential vector fadd reduction intrinsic of the source vector.
700 /// The first parameter is a scalar accumulator value. An unordered reduction
701 /// can be created by adding the reassoc fast-math flag to the resulting
702 /// sequential reduction.
703 CallInst *CreateFAddReduce(Value *Acc, Value *Src);
704
705 /// Create a sequential vector fmul reduction intrinsic of the source vector.
706 /// The first parameter is a scalar accumulator value. An unordered reduction
707 /// can be created by adding the reassoc fast-math flag to the resulting
708 /// sequential reduction.
709 CallInst *CreateFMulReduce(Value *Acc, Value *Src);
710
711 /// Create a vector int add reduction intrinsic of the source vector.
712 CallInst *CreateAddReduce(Value *Src);
713
714 /// Create a vector int mul reduction intrinsic of the source vector.
715 CallInst *CreateMulReduce(Value *Src);
716
717 /// Create a vector int AND reduction intrinsic of the source vector.
718 CallInst *CreateAndReduce(Value *Src);
719
720 /// Create a vector int OR reduction intrinsic of the source vector.
721 CallInst *CreateOrReduce(Value *Src);
722
723 /// Create a vector int XOR reduction intrinsic of the source vector.
724 CallInst *CreateXorReduce(Value *Src);
725
726 /// Create a vector integer max reduction intrinsic of the source
727 /// vector.
728 CallInst *CreateIntMaxReduce(Value *Src, bool IsSigned = false);
729
730 /// Create a vector integer min reduction intrinsic of the source
731 /// vector.
732 CallInst *CreateIntMinReduce(Value *Src, bool IsSigned = false);
733
734 /// Create a vector float max reduction intrinsic of the source
735 /// vector.
736 CallInst *CreateFPMaxReduce(Value *Src);
737
738 /// Create a vector float min reduction intrinsic of the source
739 /// vector.
740 CallInst *CreateFPMinReduce(Value *Src);
741
742 /// Create a lifetime.start intrinsic.
743 ///
744 /// If the pointer isn't i8* it will be converted.
745 CallInst *CreateLifetimeStart(Value *Ptr, ConstantInt *Size = nullptr);
746
747 /// Create a lifetime.end intrinsic.
748 ///
749 /// If the pointer isn't i8* it will be converted.
750 CallInst *CreateLifetimeEnd(Value *Ptr, ConstantInt *Size = nullptr);
751
752 /// Create a call to invariant.start intrinsic.
753 ///
754 /// If the pointer isn't i8* it will be converted.
755 CallInst *CreateInvariantStart(Value *Ptr, ConstantInt *Size = nullptr);
756
757 /// Create a call to Masked Load intrinsic
758 CallInst *CreateMaskedLoad(Type *Ty, Value *Ptr, Align Alignment, Value *Mask,
759 Value *PassThru = nullptr, const Twine &Name = "");
760
761 /// Create a call to Masked Store intrinsic
762 CallInst *CreateMaskedStore(Value *Val, Value *Ptr, Align Alignment,
763 Value *Mask);
764
765 /// Create a call to Masked Gather intrinsic
766 CallInst *CreateMaskedGather(Type *Ty, Value *Ptrs, Align Alignment,
767 Value *Mask = nullptr, Value *PassThru = nullptr,
768 const Twine &Name = "");
769
770 /// Create a call to Masked Scatter intrinsic
771 CallInst *CreateMaskedScatter(Value *Val, Value *Ptrs, Align Alignment,
772 Value *Mask = nullptr);
773
774 /// Create an assume intrinsic call that allows the optimizer to
775 /// assume that the provided condition will be true.
776 ///
777 /// The optional argument \p OpBundles specifies operand bundles that are
778 /// added to the call instruction.
779 CallInst *CreateAssumption(Value *Cond,
780 ArrayRef<OperandBundleDef> OpBundles = llvm::None);
781
782 /// Create a llvm.experimental.noalias.scope.decl intrinsic call.
783 Instruction *CreateNoAliasScopeDeclaration(Value *Scope);
784 Instruction *CreateNoAliasScopeDeclaration(MDNode *ScopeTag) {
785 return CreateNoAliasScopeDeclaration(
786 MetadataAsValue::get(Context, ScopeTag));
787 }
788
789 /// Create a call to the experimental.gc.statepoint intrinsic to
790 /// start a new statepoint sequence.
791 CallInst *CreateGCStatepointCall(uint64_t ID, uint32_t NumPatchBytes,
792 Value *ActualCallee,
793 ArrayRef<Value *> CallArgs,
794 Optional<ArrayRef<Value *>> DeoptArgs,
795 ArrayRef<Value *> GCArgs,
796 const Twine &Name = "");
797
798 /// Create a call to the experimental.gc.statepoint intrinsic to
799 /// start a new statepoint sequence.
800 CallInst *CreateGCStatepointCall(uint64_t ID, uint32_t NumPatchBytes,
801 Value *ActualCallee, uint32_t Flags,
802 ArrayRef<Value *> CallArgs,
803 Optional<ArrayRef<Use>> TransitionArgs,
804 Optional<ArrayRef<Use>> DeoptArgs,
805 ArrayRef<Value *> GCArgs,
806 const Twine &Name = "");
807
808 /// Conveninence function for the common case when CallArgs are filled
809 /// in using makeArrayRef(CS.arg_begin(), CS.arg_end()); Use needs to be
810 /// .get()'ed to get the Value pointer.
811 CallInst *CreateGCStatepointCall(uint64_t ID, uint32_t NumPatchBytes,
812 Value *ActualCallee, ArrayRef<Use> CallArgs,
813 Optional<ArrayRef<Value *>> DeoptArgs,
814 ArrayRef<Value *> GCArgs,
815 const Twine &Name = "");
816
817 /// Create an invoke to the experimental.gc.statepoint intrinsic to
818 /// start a new statepoint sequence.
819 InvokeInst *
820 CreateGCStatepointInvoke(uint64_t ID, uint32_t NumPatchBytes,
821 Value *ActualInvokee, BasicBlock *NormalDest,
822 BasicBlock *UnwindDest, ArrayRef<Value *> InvokeArgs,
823 Optional<ArrayRef<Value *>> DeoptArgs,
824 ArrayRef<Value *> GCArgs, const Twine &Name = "");
825
826 /// Create an invoke to the experimental.gc.statepoint intrinsic to
827 /// start a new statepoint sequence.
828 InvokeInst *CreateGCStatepointInvoke(
829 uint64_t ID, uint32_t NumPatchBytes, Value *ActualInvokee,
830 BasicBlock *NormalDest, BasicBlock *UnwindDest, uint32_t Flags,
831 ArrayRef<Value *> InvokeArgs, Optional<ArrayRef<Use>> TransitionArgs,
832 Optional<ArrayRef<Use>> DeoptArgs, ArrayRef<Value *> GCArgs,
833 const Twine &Name = "");
834
835 // Convenience function for the common case when CallArgs are filled in using
836 // makeArrayRef(CS.arg_begin(), CS.arg_end()); Use needs to be .get()'ed to
837 // get the Value *.
838 InvokeInst *
839 CreateGCStatepointInvoke(uint64_t ID, uint32_t NumPatchBytes,
840 Value *ActualInvokee, BasicBlock *NormalDest,
841 BasicBlock *UnwindDest, ArrayRef<Use> InvokeArgs,
842 Optional<ArrayRef<Value *>> DeoptArgs,
843 ArrayRef<Value *> GCArgs, const Twine &Name = "");
844
845 /// Create a call to the experimental.gc.result intrinsic to extract
846 /// the result from a call wrapped in a statepoint.
847 CallInst *CreateGCResult(Instruction *Statepoint,
848 Type *ResultType,
849 const Twine &Name = "");
850
851 /// Create a call to the experimental.gc.relocate intrinsics to
852 /// project the relocated value of one pointer from the statepoint.
853 CallInst *CreateGCRelocate(Instruction *Statepoint,
854 int BaseOffset,
855 int DerivedOffset,
856 Type *ResultType,
857 const Twine &Name = "");
858
859 /// Create a call to the experimental.gc.pointer.base intrinsic to get the
860 /// base pointer for the specified derived pointer.
861 CallInst *CreateGCGetPointerBase(Value *DerivedPtr, const Twine &Name = "");
862
863 /// Create a call to the experimental.gc.get.pointer.offset intrinsic to get
864 /// the offset of the specified derived pointer from its base.
865 CallInst *CreateGCGetPointerOffset(Value *DerivedPtr, const Twine &Name = "");
866
867 /// Create a call to llvm.vscale, multiplied by \p Scaling. The type of VScale
868 /// will be the same type as that of \p Scaling.
869 Value *CreateVScale(Constant *Scaling, const Twine &Name = "");
870
871 /// Creates a vector of type \p DstType with the linear sequence <0, 1, ...>
872 Value *CreateStepVector(Type *DstType, const Twine &Name = "");
873
874 /// Create a call to intrinsic \p ID with 1 operand which is mangled on its
875 /// type.
876 CallInst *CreateUnaryIntrinsic(Intrinsic::ID ID, Value *V,
877 Instruction *FMFSource = nullptr,
878 const Twine &Name = "");
879
880 /// Create a call to intrinsic \p ID with 2 operands which is mangled on the
881 /// first type.
882 CallInst *CreateBinaryIntrinsic(Intrinsic::ID ID, Value *LHS, Value *RHS,
883 Instruction *FMFSource = nullptr,
884 const Twine &Name = "");
885
886 /// Create a call to intrinsic \p ID with \p args, mangled using \p Types. If
887 /// \p FMFSource is provided, copy fast-math-flags from that instruction to
888 /// the intrinsic.
889 CallInst *CreateIntrinsic(Intrinsic::ID ID, ArrayRef<Type *> Types,
890 ArrayRef<Value *> Args,
891 Instruction *FMFSource = nullptr,
892 const Twine &Name = "");
893
894 /// Create call to the minnum intrinsic.
895 CallInst *CreateMinNum(Value *LHS, Value *RHS, const Twine &Name = "") {
896 return CreateBinaryIntrinsic(Intrinsic::minnum, LHS, RHS, nullptr, Name);
897 }
898
899 /// Create call to the maxnum intrinsic.
900 CallInst *CreateMaxNum(Value *LHS, Value *RHS, const Twine &Name = "") {
901 return CreateBinaryIntrinsic(Intrinsic::maxnum, LHS, RHS, nullptr, Name);
902 }
903
904 /// Create call to the minimum intrinsic.
905 CallInst *CreateMinimum(Value *LHS, Value *RHS, const Twine &Name = "") {
906 return CreateBinaryIntrinsic(Intrinsic::minimum, LHS, RHS, nullptr, Name);
907 }
908
909 /// Create call to the maximum intrinsic.
910 CallInst *CreateMaximum(Value *LHS, Value *RHS, const Twine &Name = "") {
911 return CreateBinaryIntrinsic(Intrinsic::maximum, LHS, RHS, nullptr, Name);
912 }
913
914 /// Create a call to the arithmetic_fence intrinsic.
915 CallInst *CreateArithmeticFence(Value *Val, Type *DstType,
916 const Twine &Name = "") {
917 return CreateIntrinsic(Intrinsic::arithmetic_fence, DstType, Val, nullptr,
918 Name);
919 }
920
921 /// Create a call to the experimental.vector.extract intrinsic.
922 CallInst *CreateExtractVector(Type *DstType, Value *SrcVec, Value *Idx,
923 const Twine &Name = "") {
924 return CreateIntrinsic(Intrinsic::experimental_vector_extract,
925 {DstType, SrcVec->getType()}, {SrcVec, Idx}, nullptr,
926 Name);
927 }
928
929 /// Create a call to the experimental.vector.insert intrinsic.
930 CallInst *CreateInsertVector(Type *DstType, Value *SrcVec, Value *SubVec,
931 Value *Idx, const Twine &Name = "") {
932 return CreateIntrinsic(Intrinsic::experimental_vector_insert,
933 {DstType, SubVec->getType()}, {SrcVec, SubVec, Idx},
934 nullptr, Name);
935 }
936
937 private:
938 /// Create a call to a masked intrinsic with given Id.
939 CallInst *CreateMaskedIntrinsic(Intrinsic::ID Id, ArrayRef<Value *> Ops,
940 ArrayRef<Type *> OverloadedTypes,
941 const Twine &Name = "");
942
943 Value *getCastedInt8PtrValue(Value *Ptr);
944
945 //===--------------------------------------------------------------------===//
946 // Instruction creation methods: Terminators
947 //===--------------------------------------------------------------------===//
948
949 private:
950 /// Helper to add branch weight and unpredictable metadata onto an
951 /// instruction.
952 /// \returns The annotated instruction.
953 template <typename InstTy>
954 InstTy *addBranchMetadata(InstTy *I, MDNode *Weights, MDNode *Unpredictable) {
955 if (Weights)
956 I->setMetadata(LLVMContext::MD_prof, Weights);
957 if (Unpredictable)
958 I->setMetadata(LLVMContext::MD_unpredictable, Unpredictable);
959 return I;
960 }
961
962 public:
963 /// Create a 'ret void' instruction.
964 ReturnInst *CreateRetVoid() {
965 return Insert(ReturnInst::Create(Context));
966 }
967
968 /// Create a 'ret <val>' instruction.
969 ReturnInst *CreateRet(Value *V) {
970 return Insert(ReturnInst::Create(Context, V));
971 }
972
973 /// Create a sequence of N insertvalue instructions,
974 /// with one Value from the retVals array each, that build a aggregate
975 /// return value one value at a time, and a ret instruction to return
976 /// the resulting aggregate value.
977 ///
978 /// This is a convenience function for code that uses aggregate return values
979 /// as a vehicle for having multiple return values.
980 ReturnInst *CreateAggregateRet(Value *const *retVals, unsigned N) {
981 Value *V = UndefValue::get(getCurrentFunctionReturnType());
982 for (unsigned i = 0; i != N; ++i)
983 V = CreateInsertValue(V, retVals[i], i, "mrv");
984 return Insert(ReturnInst::Create(Context, V));
985 }
986
987 /// Create an unconditional 'br label X' instruction.
988 BranchInst *CreateBr(BasicBlock *Dest) {
989 return Insert(BranchInst::Create(Dest));
990 }
991
992 /// Create a conditional 'br Cond, TrueDest, FalseDest'
993 /// instruction.
994 BranchInst *CreateCondBr(Value *Cond, BasicBlock *True, BasicBlock *False,
995 MDNode *BranchWeights = nullptr,
996 MDNode *Unpredictable = nullptr) {
997 return Insert(addBranchMetadata(BranchInst::Create(True, False, Cond),
998 BranchWeights, Unpredictable));
999 }
1000
1001 /// Create a conditional 'br Cond, TrueDest, FalseDest'
1002 /// instruction. Copy branch meta data if available.
1003 BranchInst *CreateCondBr(Value *Cond, BasicBlock *True, BasicBlock *False,
1004 Instruction *MDSrc) {
1005 BranchInst *Br = BranchInst::Create(True, False, Cond);
1006 if (MDSrc) {
1007 unsigned WL[4] = {LLVMContext::MD_prof, LLVMContext::MD_unpredictable,
1008 LLVMContext::MD_make_implicit, LLVMContext::MD_dbg};
1009 Br->copyMetadata(*MDSrc, makeArrayRef(&WL[0], 4));
1010 }
1011 return Insert(Br);
1012 }
1013
1014 /// Create a switch instruction with the specified value, default dest,
1015 /// and with a hint for the number of cases that will be added (for efficient
1016 /// allocation).
1017 SwitchInst *CreateSwitch(Value *V, BasicBlock *Dest, unsigned NumCases = 10,
1018 MDNode *BranchWeights = nullptr,
1019 MDNode *Unpredictable = nullptr) {
1020 return Insert(addBranchMetadata(SwitchInst::Create(V, Dest, NumCases),
1021 BranchWeights, Unpredictable));
1022 }
1023
1024 /// Create an indirect branch instruction with the specified address
1025 /// operand, with an optional hint for the number of destinations that will be
1026 /// added (for efficient allocation).
1027 IndirectBrInst *CreateIndirectBr(Value *Addr, unsigned NumDests = 10) {
1028 return Insert(IndirectBrInst::Create(Addr, NumDests));
1029 }
1030
1031 /// Create an invoke instruction.
1032 InvokeInst *CreateInvoke(FunctionType *Ty, Value *Callee,
1033 BasicBlock *NormalDest, BasicBlock *UnwindDest,
1034 ArrayRef<Value *> Args,
1035 ArrayRef<OperandBundleDef> OpBundles,
1036 const Twine &Name = "") {
1037 InvokeInst *II =
1038 InvokeInst::Create(Ty, Callee, NormalDest, UnwindDest, Args, OpBundles);
1039 if (IsFPConstrained)
1040 setConstrainedFPCallAttr(II);
1041 return Insert(II, Name);
1042 }
1043 InvokeInst *CreateInvoke(FunctionType *Ty, Value *Callee,
1044 BasicBlock *NormalDest, BasicBlock *UnwindDest,
1045 ArrayRef<Value *> Args = None,
1046 const Twine &Name = "") {
1047 InvokeInst *II =
1048 InvokeInst::Create(Ty, Callee, NormalDest, UnwindDest, Args);
1049 if (IsFPConstrained)
1050 setConstrainedFPCallAttr(II);
1051 return Insert(II, Name);
1052 }
1053
1054 InvokeInst *CreateInvoke(FunctionCallee Callee, BasicBlock *NormalDest,
1055 BasicBlock *UnwindDest, ArrayRef<Value *> Args,
1056 ArrayRef<OperandBundleDef> OpBundles,
1057 const Twine &Name = "") {
1058 return CreateInvoke(Callee.getFunctionType(), Callee.getCallee(),
1059 NormalDest, UnwindDest, Args, OpBundles, Name);
1060 }
1061
1062 InvokeInst *CreateInvoke(FunctionCallee Callee, BasicBlock *NormalDest,
1063 BasicBlock *UnwindDest,
1064 ArrayRef<Value *> Args = None,
1065 const Twine &Name = "") {
1066 return CreateInvoke(Callee.getFunctionType(), Callee.getCallee(),
1067 NormalDest, UnwindDest, Args, Name);
1068 }
1069
1070 /// \brief Create a callbr instruction.
1071 CallBrInst *CreateCallBr(FunctionType *Ty, Value *Callee,
1072 BasicBlock *DefaultDest,
1073 ArrayRef<BasicBlock *> IndirectDests,
1074 ArrayRef<Value *> Args = None,
1075 const Twine &Name = "") {
1076 return Insert(CallBrInst::Create(Ty, Callee, DefaultDest, IndirectDests,
1077 Args), Name);
1078 }
1079 CallBrInst *CreateCallBr(FunctionType *Ty, Value *Callee,
1080 BasicBlock *DefaultDest,
1081 ArrayRef<BasicBlock *> IndirectDests,
1082 ArrayRef<Value *> Args,
1083 ArrayRef<OperandBundleDef> OpBundles,
1084 const Twine &Name = "") {
1085 return Insert(
1086 CallBrInst::Create(Ty, Callee, DefaultDest, IndirectDests, Args,
1087 OpBundles), Name);
1088 }
1089
1090 CallBrInst *CreateCallBr(FunctionCallee Callee, BasicBlock *DefaultDest,
1091 ArrayRef<BasicBlock *> IndirectDests,
1092 ArrayRef<Value *> Args = None,
1093 const Twine &Name = "") {
1094 return CreateCallBr(Callee.getFunctionType(), Callee.getCallee(),
1095 DefaultDest, IndirectDests, Args, Name);
1096 }
1097 CallBrInst *CreateCallBr(FunctionCallee Callee, BasicBlock *DefaultDest,
1098 ArrayRef<BasicBlock *> IndirectDests,
1099 ArrayRef<Value *> Args,
1100 ArrayRef<OperandBundleDef> OpBundles,
1101 const Twine &Name = "") {
1102 return CreateCallBr(Callee.getFunctionType(), Callee.getCallee(),
1103 DefaultDest, IndirectDests, Args, Name);
1104 }
1105
1106 ResumeInst *CreateResume(Value *Exn) {
1107 return Insert(ResumeInst::Create(Exn));
1108 }
1109
1110 CleanupReturnInst *CreateCleanupRet(CleanupPadInst *CleanupPad,
1111 BasicBlock *UnwindBB = nullptr) {
1112 return Insert(CleanupReturnInst::Create(CleanupPad, UnwindBB));
1113 }
1114
1115 CatchSwitchInst *CreateCatchSwitch(Value *ParentPad, BasicBlock *UnwindBB,
1116 unsigned NumHandlers,
1117 const Twine &Name = "") {
1118 return Insert(CatchSwitchInst::Create(ParentPad, UnwindBB, NumHandlers),
1119 Name);
1120 }
1121
1122 CatchPadInst *CreateCatchPad(Value *ParentPad, ArrayRef<Value *> Args,
1123 const Twine &Name = "") {
1124 return Insert(CatchPadInst::Create(ParentPad, Args), Name);
1125 }
1126
1127 CleanupPadInst *CreateCleanupPad(Value *ParentPad,
1128 ArrayRef<Value *> Args = None,
1129 const Twine &Name = "") {
1130 return Insert(CleanupPadInst::Create(ParentPad, Args), Name);
1131 }
1132
1133 CatchReturnInst *CreateCatchRet(CatchPadInst *CatchPad, BasicBlock *BB) {
1134 return Insert(CatchReturnInst::Create(CatchPad, BB));
1135 }
1136
1137 UnreachableInst *CreateUnreachable() {
1138 return Insert(new UnreachableInst(Context));
1139 }
1140
1141 //===--------------------------------------------------------------------===//
1142 // Instruction creation methods: Binary Operators
1143 //===--------------------------------------------------------------------===//
1144 private:
1145 BinaryOperator *CreateInsertNUWNSWBinOp(BinaryOperator::BinaryOps Opc,
1146 Value *LHS, Value *RHS,
1147 const Twine &Name,
1148 bool HasNUW, bool HasNSW) {
1149 BinaryOperator *BO = Insert(BinaryOperator::Create(Opc, LHS, RHS), Name);
1150 if (HasNUW) BO->setHasNoUnsignedWrap();
1151 if (HasNSW) BO->setHasNoSignedWrap();
1152 return BO;
1153 }
1154
1155 Instruction *setFPAttrs(Instruction *I, MDNode *FPMD,
1156 FastMathFlags FMF) const {
1157 if (!FPMD)
1158 FPMD = DefaultFPMathTag;
1159 if (FPMD)
1160 I->setMetadata(LLVMContext::MD_fpmath, FPMD);
1161 I->setFastMathFlags(FMF);
1162 return I;
1163 }
1164
1165 Value *foldConstant(Instruction::BinaryOps Opc, Value *L,
1166 Value *R, const Twine &Name) const {
1167 auto *LC = dyn_cast<Constant>(L);
1168 auto *RC = dyn_cast<Constant>(R);
1169 return (LC && RC) ? Insert(Folder.CreateBinOp(Opc, LC, RC), Name) : nullptr;
1170 }
1171
1172 Value *getConstrainedFPRounding(Optional<RoundingMode> Rounding) {
1173 RoundingMode UseRounding = DefaultConstrainedRounding;
1174
1175 if (Rounding.hasValue())
1176 UseRounding = Rounding.getValue();
1177
1178 Optional<StringRef> RoundingStr = convertRoundingModeToStr(UseRounding);
1179 assert(RoundingStr.hasValue() && "Garbage strict rounding mode!");
1180 auto *RoundingMDS = MDString::get(Context, RoundingStr.getValue());
1181
1182 return MetadataAsValue::get(Context, RoundingMDS);
1183 }
1184
1185 Value *getConstrainedFPExcept(Optional<fp::ExceptionBehavior> Except) {
1186 fp::ExceptionBehavior UseExcept = DefaultConstrainedExcept;
1187
1188 if (Except.hasValue())
1189 UseExcept = Except.getValue();
1190
1191 Optional<StringRef> ExceptStr = convertExceptionBehaviorToStr(UseExcept);
1192 assert(ExceptStr.hasValue() && "Garbage strict exception behavior!");
1193 auto *ExceptMDS = MDString::get(Context, ExceptStr.getValue());
1194
1195 return MetadataAsValue::get(Context, ExceptMDS);
1196 }
1197
1198 Value *getConstrainedFPPredicate(CmpInst::Predicate Predicate) {
1199 assert(CmpInst::isFPPredicate(Predicate) &&
1200 Predicate != CmpInst::FCMP_FALSE &&
1201 Predicate != CmpInst::FCMP_TRUE &&
1202 "Invalid constrained FP comparison predicate!");
1203
1204 StringRef PredicateStr = CmpInst::getPredicateName(Predicate);
1205 auto *PredicateMDS = MDString::get(Context, PredicateStr);
1206
1207 return MetadataAsValue::get(Context, PredicateMDS);
1208 }
1209
1210 public:
1211 Value *CreateAdd(Value *LHS, Value *RHS, const Twine &Name = "",
1212 bool HasNUW = false, bool HasNSW = false) {
1213 if (auto *V = Folder.FoldAdd(LHS, RHS, HasNUW, HasNSW))
1214 return V;
1215 return CreateInsertNUWNSWBinOp(Instruction::Add, LHS, RHS, Name,
1216 HasNUW, HasNSW);
1217 }
1218
1219 Value *CreateNSWAdd(Value *LHS, Value *RHS, const Twine &Name = "") {
1220 return CreateAdd(LHS, RHS, Name, false, true);
1221 }
1222
1223 Value *CreateNUWAdd(Value *LHS, Value *RHS, const Twine &Name = "") {
1224 return CreateAdd(LHS, RHS, Name, true, false);
1225 }
1226
1227 Value *CreateSub(Value *LHS, Value *RHS, const Twine &Name = "",
1228 bool HasNUW = false, bool HasNSW = false) {
1229 if (auto *LC = dyn_cast<Constant>(LHS))
1230 if (auto *RC = dyn_cast<Constant>(RHS))
1231 return Insert(Folder.CreateSub(LC, RC, HasNUW, HasNSW), Name);
1232 return CreateInsertNUWNSWBinOp(Instruction::Sub, LHS, RHS, Name,
1233 HasNUW, HasNSW);
1234 }
1235
1236 Value *CreateNSWSub(Value *LHS, Value *RHS, const Twine &Name = "") {
1237 return CreateSub(LHS, RHS, Name, false, true);
1238 }
1239
1240 Value *CreateNUWSub(Value *LHS, Value *RHS, const Twine &Name = "") {
1241 return CreateSub(LHS, RHS, Name, true, false);
1242 }
1243
1244 Value *CreateMul(Value *LHS, Value *RHS, const Twine &Name = "",
1245 bool HasNUW = false, bool HasNSW = false) {
1246 if (auto *LC = dyn_cast<Constant>(LHS))
1247 if (auto *RC = dyn_cast<Constant>(RHS))
1248 return Insert(Folder.CreateMul(LC, RC, HasNUW, HasNSW), Name);
1249 return CreateInsertNUWNSWBinOp(Instruction::Mul, LHS, RHS, Name,
1250 HasNUW, HasNSW);
1251 }
1252
1253 Value *CreateNSWMul(Value *LHS, Value *RHS, const Twine &Name = "") {
1254 return CreateMul(LHS, RHS, Name, false, true);
1255 }
1256
1257 Value *CreateNUWMul(Value *LHS, Value *RHS, const Twine &Name = "") {
1258 return CreateMul(LHS, RHS, Name, true, false);
1259 }
1260
1261 Value *CreateUDiv(Value *LHS, Value *RHS, const Twine &Name = "",
1262 bool isExact = false) {
1263 if (auto *LC = dyn_cast<Constant>(LHS))
1264 if (auto *RC = dyn_cast<Constant>(RHS))
1265 return Insert(Folder.CreateUDiv(LC, RC, isExact), Name);
1266 if (!isExact)
1267 return Insert(BinaryOperator::CreateUDiv(LHS, RHS), Name);
1268 return Insert(BinaryOperator::CreateExactUDiv(LHS, RHS), Name);
1269 }
1270
1271 Value *CreateExactUDiv(Value *LHS, Value *RHS, const Twine &Name = "") {
1272 return CreateUDiv(LHS, RHS, Name, true);
1273 }
1274
1275 Value *CreateSDiv(Value *LHS, Value *RHS, const Twine &Name = "",
1276 bool isExact = false) {
1277 if (auto *LC = dyn_cast<Constant>(LHS))
1278 if (auto *RC = dyn_cast<Constant>(RHS))
1279 return Insert(Folder.CreateSDiv(LC, RC, isExact), Name);
1280 if (!isExact)
1281 return Insert(BinaryOperator::CreateSDiv(LHS, RHS), Name);
1282 return Insert(BinaryOperator::CreateExactSDiv(LHS, RHS), Name);
1283 }
1284
1285 Value *CreateExactSDiv(Value *LHS, Value *RHS, const Twine &Name = "") {
1286 return CreateSDiv(LHS, RHS, Name, true);
1287 }
1288
1289 Value *CreateURem(Value *LHS, Value *RHS, const Twine &Name = "") {
1290 if (Value *V = foldConstant(Instruction::URem, LHS, RHS, Name)) return V;
1291 return Insert(BinaryOperator::CreateURem(LHS, RHS), Name);
1292 }
1293
1294 Value *CreateSRem(Value *LHS, Value *RHS, const Twine &Name = "") {
1295 if (Value *V = foldConstant(Instruction::SRem, LHS, RHS, Name)) return V;
1296 return Insert(BinaryOperator::CreateSRem(LHS, RHS), Name);
1297 }
1298
1299 Value *CreateShl(Value *LHS, Value *RHS, const Twine &Name = "",
1300 bool HasNUW = false, bool HasNSW = false) {
1301 if (auto *LC = dyn_cast<Constant>(LHS))
1302 if (auto *RC = dyn_cast<Constant>(RHS))
1303 return Insert(Folder.CreateShl(LC, RC, HasNUW, HasNSW), Name);
1304 return CreateInsertNUWNSWBinOp(Instruction::Shl, LHS, RHS, Name,
1305 HasNUW, HasNSW);
1306 }
1307
1308 Value *CreateShl(Value *LHS, const APInt &RHS, const Twine &Name = "",
1309 bool HasNUW = false, bool HasNSW = false) {
1310 return CreateShl(LHS, ConstantInt::get(LHS->getType(), RHS), Name,
1311 HasNUW, HasNSW);
1312 }
1313
1314 Value *CreateShl(Value *LHS, uint64_t RHS, const Twine &Name = "",
1315 bool HasNUW = false, bool HasNSW = false) {
1316 return CreateShl(LHS, ConstantInt::get(LHS->getType(), RHS), Name,
1317 HasNUW, HasNSW);
1318 }
1319
1320 Value *CreateLShr(Value *LHS, Value *RHS, const Twine &Name = "",
1321 bool isExact = false) {
1322 if (auto *LC = dyn_cast<Constant>(LHS))
1323 if (auto *RC = dyn_cast<Constant>(RHS))
1324 return Insert(Folder.CreateLShr(LC, RC, isExact), Name);
1325 if (!isExact)
1326 return Insert(BinaryOperator::CreateLShr(LHS, RHS), Name);
1327 return Insert(BinaryOperator::CreateExactLShr(LHS, RHS), Name);
1328 }
1329
1330 Value *CreateLShr(Value *LHS, const APInt &RHS, const Twine &Name = "",
1331 bool isExact = false) {
1332 return CreateLShr(LHS, ConstantInt::get(LHS->getType(), RHS), Name,isExact);
1333 }
1334
1335 Value *CreateLShr(Value *LHS, uint64_t RHS, const Twine &Name = "",
1336 bool isExact = false) {
1337 return CreateLShr(LHS, ConstantInt::get(LHS->getType(), RHS), Name,isExact);
1338 }
1339
1340 Value *CreateAShr(Value *LHS, Value *RHS, const Twine &Name = "",
1341 bool isExact = false) {
1342 if (auto *LC = dyn_cast<Constant>(LHS))
1343 if (auto *RC = dyn_cast<Constant>(RHS))
1344 return Insert(Folder.CreateAShr(LC, RC, isExact), Name);
1345 if (!isExact)
1346 return Insert(BinaryOperator::CreateAShr(LHS, RHS), Name);
1347 return Insert(BinaryOperator::CreateExactAShr(LHS, RHS), Name);
1348 }
1349
1350 Value *CreateAShr(Value *LHS, const APInt &RHS, const Twine &Name = "",
1351 bool isExact = false) {
1352 return CreateAShr(LHS, ConstantInt::get(LHS->getType(), RHS), Name,isExact);
1353 }
1354
1355 Value *CreateAShr(Value *LHS, uint64_t RHS, const Twine &Name = "",
1356 bool isExact = false) {
1357 return CreateAShr(LHS, ConstantInt::get(LHS->getType(), RHS), Name,isExact);
1358 }
1359
1360 Value *CreateAnd(Value *LHS, Value *RHS, const Twine &Name = "") {
1361 if (auto *V = Folder.FoldAnd(LHS, RHS))
1362 return V;
1363 return Insert(BinaryOperator::CreateAnd(LHS, RHS), Name);
1364 }
1365
1366 Value *CreateAnd(Value *LHS, const APInt &RHS, const Twine &Name = "") {
1367 return CreateAnd(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
1368 }
1369
1370 Value *CreateAnd(Value *LHS, uint64_t RHS, const Twine &Name = "") {
1371 return CreateAnd(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
1372 }
1373
1374 Value *CreateAnd(ArrayRef<Value*> Ops) {
1375 assert(!Ops.empty());
1376 Value *Accum = Ops[0];
1377 for (unsigned i = 1; i < Ops.size(); i++)
1378 Accum = CreateAnd(Accum, Ops[i]);
1379 return Accum;
1380 }
1381
1382 Value *CreateOr(Value *LHS, Value *RHS, const Twine &Name = "") {
1383 if (auto *V = Folder.FoldOr(LHS, RHS))
1384 return V;
1385 return Insert(BinaryOperator::CreateOr(LHS, RHS), Name);
1386 }
1387
1388 Value *CreateOr(Value *LHS, const APInt &RHS, const Twine &Name = "") {
1389 return CreateOr(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
1390 }
1391
1392 Value *CreateOr(Value *LHS, uint64_t RHS, const Twine &Name = "") {
1393 return CreateOr(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
1394 }
1395
1396 Value *CreateOr(ArrayRef<Value*> Ops) {
1397 assert(!Ops.empty());
1398 Value *Accum = Ops[0];
1399 for (unsigned i = 1; i < Ops.size(); i++)
1400 Accum = CreateOr(Accum, Ops[i]);
1401 return Accum;
1402 }
1403
1404 Value *CreateXor(Value *LHS, Value *RHS, const Twine &Name = "") {
1405 if (Value *V = foldConstant(Instruction::Xor, LHS, RHS, Name)) return V;
1406 return Insert(BinaryOperator::CreateXor(LHS, RHS), Name);
1407 }
1408
1409 Value *CreateXor(Value *LHS, const APInt &RHS, const Twine &Name = "") {
1410 return CreateXor(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
1411 }
1412
1413 Value *CreateXor(Value *LHS, uint64_t RHS, const Twine &Name = "") {
1414 return CreateXor(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
1415 }
1416
1417 Value *CreateFAdd(Value *L, Value *R, const Twine &Name = "",
1418 MDNode *FPMD = nullptr) {
1419 if (IsFPConstrained)
1420 return CreateConstrainedFPBinOp(Intrinsic::experimental_constrained_fadd,
1421 L, R, nullptr, Name, FPMD);
1422
1423 if (Value *V = foldConstant(Instruction::FAdd, L, R, Name)) return V;
1424 Instruction *I = setFPAttrs(BinaryOperator::CreateFAdd(L, R), FPMD, FMF);
1425 return Insert(I, Name);
1426 }
1427
1428 /// Copy fast-math-flags from an instruction rather than using the builder's
1429 /// default FMF.
1430 Value *CreateFAddFMF(Value *L, Value *R, Instruction *FMFSource,
1431 const Twine &Name = "") {
1432 if (IsFPConstrained)
1433 return CreateConstrainedFPBinOp(Intrinsic::experimental_constrained_fadd,
1434 L, R, FMFSource, Name);
1435
1436 if (Value *V = foldConstant(Instruction::FAdd, L, R, Name)) return V;
1437 Instruction *I = setFPAttrs(BinaryOperator::CreateFAdd(L, R), nullptr,
1438 FMFSource->getFastMathFlags());
1439 return Insert(I, Name);
1440 }
1441
1442 Value *CreateFSub(Value *L, Value *R, const Twine &Name = "",
1443 MDNode *FPMD = nullptr) {
1444 if (IsFPConstrained)
1445 return CreateConstrainedFPBinOp(Intrinsic::experimental_constrained_fsub,
1446 L, R, nullptr, Name, FPMD);
1447
1448 if (Value *V = foldConstant(Instruction::FSub, L, R, Name)) return V;
1449 Instruction *I = setFPAttrs(BinaryOperator::CreateFSub(L, R), FPMD, FMF);
1450 return Insert(I, Name);
1451 }
1452
1453 /// Copy fast-math-flags from an instruction rather than using the builder's
1454 /// default FMF.
1455 Value *CreateFSubFMF(Value *L, Value *R, Instruction *FMFSource,
1456 const Twine &Name = "") {
1457 if (IsFPConstrained)
1458 return CreateConstrainedFPBinOp(Intrinsic::experimental_constrained_fsub,
1459 L, R, FMFSource, Name);
1460
1461 if (Value *V = foldConstant(Instruction::FSub, L, R, Name)) return V;
1462 Instruction *I = setFPAttrs(BinaryOperator::CreateFSub(L, R), nullptr,
1463 FMFSource->getFastMathFlags());
1464 return Insert(I, Name);
1465 }
1466
1467 Value *CreateFMul(Value *L, Value *R, const Twine &Name = "",
1468 MDNode *FPMD = nullptr) {
1469 if (IsFPConstrained)
1470 return CreateConstrainedFPBinOp(Intrinsic::experimental_constrained_fmul,
1471 L, R, nullptr, Name, FPMD);
1472
1473 if (Value *V = foldConstant(Instruction::FMul, L, R, Name)) return V;
1474 Instruction *I = setFPAttrs(BinaryOperator::CreateFMul(L, R), FPMD, FMF);
1475 return Insert(I, Name);
1476 }
1477
1478 /// Copy fast-math-flags from an instruction rather than using the builder's
1479 /// default FMF.
1480 Value *CreateFMulFMF(Value *L, Value *R, Instruction *FMFSource,
1481 const Twine &Name = "") {
1482 if (IsFPConstrained)
1483 return CreateConstrainedFPBinOp(Intrinsic::experimental_constrained_fmul,
1484 L, R, FMFSource, Name);
1485
1486 if (Value *V = foldConstant(Instruction::FMul, L, R, Name)) return V;
1487 Instruction *I = setFPAttrs(BinaryOperator::CreateFMul(L, R), nullptr,
1488 FMFSource->getFastMathFlags());
1489 return Insert(I, Name);
1490 }
1491
1492 Value *CreateFDiv(Value *L, Value *R, const Twine &Name = "",
1493 MDNode *FPMD = nullptr) {
1494 if (IsFPConstrained)
1495 return CreateConstrainedFPBinOp(Intrinsic::experimental_constrained_fdiv,
1496 L, R, nullptr, Name, FPMD);
1497
1498 if (Value *V = foldConstant(Instruction::FDiv, L, R, Name)) return V;
1499 Instruction *I = setFPAttrs(BinaryOperator::CreateFDiv(L, R), FPMD, FMF);
1500 return Insert(I, Name);
1501 }
1502
1503 /// Copy fast-math-flags from an instruction rather than using the builder's
1504 /// default FMF.
1505 Value *CreateFDivFMF(Value *L, Value *R, Instruction *FMFSource,
1506 const Twine &Name = "") {
1507 if (IsFPConstrained)
1508 return CreateConstrainedFPBinOp(Intrinsic::experimental_constrained_fdiv,
1509 L, R, FMFSource, Name);
1510
1511 if (Value *V = foldConstant(Instruction::FDiv, L, R, Name)) return V;
1512 Instruction *I = setFPAttrs(BinaryOperator::CreateFDiv(L, R), nullptr,
1513 FMFSource->getFastMathFlags());
1514 return Insert(I, Name);
1515 }
1516
1517 Value *CreateFRem(Value *L, Value *R, const Twine &Name = "",
1518 MDNode *FPMD = nullptr) {
1519 if (IsFPConstrained)
1520 return CreateConstrainedFPBinOp(Intrinsic::experimental_constrained_frem,
1521 L, R, nullptr, Name, FPMD);
1522
1523 if (Value *V = foldConstant(Instruction::FRem, L, R, Name)) return V;
1524 Instruction *I = setFPAttrs(BinaryOperator::CreateFRem(L, R), FPMD, FMF);
1525 return Insert(I, Name);
1526 }
1527
1528 /// Copy fast-math-flags from an instruction rather than using the builder's
1529 /// default FMF.
1530 Value *CreateFRemFMF(Value *L, Value *R, Instruction *FMFSource,
1531 const Twine &Name = "") {
1532 if (IsFPConstrained)
1533 return CreateConstrainedFPBinOp(Intrinsic::experimental_constrained_frem,
1534 L, R, FMFSource, Name);
1535
1536 if (Value *V = foldConstant(Instruction::FRem, L, R, Name)) return V;
1537 Instruction *I = setFPAttrs(BinaryOperator::CreateFRem(L, R), nullptr,
1538 FMFSource->getFastMathFlags());
1539 return Insert(I, Name);
1540 }
1541
1542 Value *CreateBinOp(Instruction::BinaryOps Opc,
1543 Value *LHS, Value *RHS, const Twine &Name = "",
1544 MDNode *FPMathTag = nullptr) {
1545 if (Value *V = foldConstant(Opc, LHS, RHS, Name)) return V;
1546 Instruction *BinOp = BinaryOperator::Create(Opc, LHS, RHS);
1547 if (isa<FPMathOperator>(BinOp))
1548 setFPAttrs(BinOp, FPMathTag, FMF);
1549 return Insert(BinOp, Name);
1550 }
1551
1552 Value *CreateLogicalAnd(Value *Cond1, Value *Cond2, const Twine &Name = "") {
1553 assert(Cond2->getType()->isIntOrIntVectorTy(1));
1554 return CreateSelect(Cond1, Cond2,
1555 ConstantInt::getNullValue(Cond2->getType()), Name);
1556 }
1557
1558 Value *CreateLogicalOr(Value *Cond1, Value *Cond2, const Twine &Name = "") {
1559 assert(Cond2->getType()->isIntOrIntVectorTy(1));
1560 return CreateSelect(Cond1, ConstantInt::getAllOnesValue(Cond2->getType()),
1561 Cond2, Name);
1562 }
1563
1564 // NOTE: this is sequential, non-commutative, ordered reduction!
1565 Value *CreateLogicalOr(ArrayRef<Value *> Ops) {
1566 assert(!Ops.empty());
1567 Value *Accum = Ops[0];
1568 for (unsigned i = 1; i < Ops.size(); i++)
1569 Accum = CreateLogicalOr(Accum, Ops[i]);
1570 return Accum;
1571 }
1572
1573 CallInst *CreateConstrainedFPBinOp(
1574 Intrinsic::ID ID, Value *L, Value *R, Instruction *FMFSource = nullptr,
1575 const Twine &Name = "", MDNode *FPMathTag = nullptr,
1576 Optional<RoundingMode> Rounding = None,
1577 Optional<fp::ExceptionBehavior> Except = None);
1578
1579 Value *CreateNeg(Value *V, const Twine &Name = "",
1580 bool HasNUW = false, bool HasNSW = false) {
1581 if (auto *VC = dyn_cast<Constant>(V))
1582 return Insert(Folder.CreateNeg(VC, HasNUW, HasNSW), Name);
1583 BinaryOperator *BO = Insert(BinaryOperator::CreateNeg(V), Name);
1584 if (HasNUW) BO->setHasNoUnsignedWrap();
1585 if (HasNSW) BO->setHasNoSignedWrap();
1586 return BO;
1587 }
1588
1589 Value *CreateNSWNeg(Value *V, const Twine &Name = "") {
1590 return CreateNeg(V, Name, false, true);
1591 }
1592
1593 Value *CreateNUWNeg(Value *V, const Twine &Name = "") {
1594 return CreateNeg(V, Name, true, false);
1595 }
1596
1597 Value *CreateFNeg(Value *V, const Twine &Name = "",
1598 MDNode *FPMathTag = nullptr) {
1599 if (auto *VC = dyn_cast<Constant>(V))
1600 return Insert(Folder.CreateFNeg(VC), Name);
1601 return Insert(setFPAttrs(UnaryOperator::CreateFNeg(V), FPMathTag, FMF),
1602 Name);
1603 }
1604
1605 /// Copy fast-math-flags from an instruction rather than using the builder's
1606 /// default FMF.
1607 Value *CreateFNegFMF(Value *V, Instruction *FMFSource,
1608 const Twine &Name = "") {
1609 if (auto *VC = dyn_cast<Constant>(V))
1610 return Insert(Folder.CreateFNeg(VC), Name);
1611 return Insert(setFPAttrs(UnaryOperator::CreateFNeg(V), nullptr,
1612 FMFSource->getFastMathFlags()),
1613 Name);
1614 }
1615
1616 Value *CreateNot(Value *V, const Twine &Name = "") {
1617 if (auto *VC = dyn_cast<Constant>(V))
1618 return Insert(Folder.CreateNot(VC), Name);
1619 return Insert(BinaryOperator::CreateNot(V), Name);
1620 }
1621
1622 Value *CreateUnOp(Instruction::UnaryOps Opc,
1623 Value *V, const Twine &Name = "",
1624 MDNode *FPMathTag = nullptr) {
1625 if (auto *VC = dyn_cast<Constant>(V))
1626 return Insert(Folder.CreateUnOp(Opc, VC), Name);
1627 Instruction *UnOp = UnaryOperator::Create(Opc, V);
1628 if (isa<FPMathOperator>(UnOp))
1629 setFPAttrs(UnOp, FPMathTag, FMF);
1630 return Insert(UnOp, Name);
1631 }
1632
1633 /// Create either a UnaryOperator or BinaryOperator depending on \p Opc.
1634 /// Correct number of operands must be passed accordingly.
1635 Value *CreateNAryOp(unsigned Opc, ArrayRef<Value *> Ops,
1636 const Twine &Name = "", MDNode *FPMathTag = nullptr);
1637
1638 //===--------------------------------------------------------------------===//
1639 // Instruction creation methods: Memory Instructions
1640 //===--------------------------------------------------------------------===//
1641
1642 AllocaInst *CreateAlloca(Type *Ty, unsigned AddrSpace,
1643 Value *ArraySize = nullptr, const Twine &Name = "") {
1644 const DataLayout &DL = BB->getModule()->getDataLayout();
1645 Align AllocaAlign = DL.getPrefTypeAlign(Ty);
1646 return Insert(new AllocaInst(Ty, AddrSpace, ArraySize, AllocaAlign), Name);
1647 }
1648
1649 AllocaInst *CreateAlloca(Type *Ty, Value *ArraySize = nullptr,
1650 const Twine &Name = "") {
1651 const DataLayout &DL = BB->getModule()->getDataLayout();
1652 Align AllocaAlign = DL.getPrefTypeAlign(Ty);
1653 unsigned AddrSpace = DL.getAllocaAddrSpace();
1654 return Insert(new AllocaInst(Ty, AddrSpace, ArraySize, AllocaAlign), Name);
1655 }
1656
1657 /// Provided to resolve 'CreateLoad(Ty, Ptr, "...")' correctly, instead of
1658 /// converting the string to 'bool' for the isVolatile parameter.
1659 LoadInst *CreateLoad(Type *Ty, Value *Ptr, const char *Name) {
1660 return CreateAlignedLoad(Ty, Ptr, MaybeAlign(), Name);
1661 }
1662
1663 LoadInst *CreateLoad(Type *Ty, Value *Ptr, const Twine &Name = "") {
1664 return CreateAlignedLoad(Ty, Ptr, MaybeAlign(), Name);
1665 }
1666
1667 LoadInst *CreateLoad(Type *Ty, Value *Ptr, bool isVolatile,
1668 const Twine &Name = "") {
1669 return CreateAlignedLoad(Ty, Ptr, MaybeAlign(), isVolatile, Name);
1670 }
1671
1672 StoreInst *CreateStore(Value *Val, Value *Ptr, bool isVolatile = false) {
1673 return CreateAlignedStore(Val, Ptr, MaybeAlign(), isVolatile);
1674 }
1675
1676 LoadInst *CreateAlignedLoad(Type *Ty, Value *Ptr, MaybeAlign Align,
1677 const char *Name) {
1678 return CreateAlignedLoad(Ty, Ptr, Align, /*isVolatile*/false, Name);
1679 }
1680
1681 LoadInst *CreateAlignedLoad(Type *Ty, Value *Ptr, MaybeAlign Align,
1682 const Twine &Name = "") {
1683 return CreateAlignedLoad(Ty, Ptr, Align, /*isVolatile*/false, Name);
1684 }
1685
1686 LoadInst *CreateAlignedLoad(Type *Ty, Value *Ptr, MaybeAlign Align,
1687 bool isVolatile, const Twine &Name = "") {
1688 if (!Align) {
1689 const DataLayout &DL = BB->getModule()->getDataLayout();
1690 Align = DL.getABITypeAlign(Ty);
1691 }
1692 return Insert(new LoadInst(Ty, Ptr, Twine(), isVolatile, *Align), Name);
1693 }
1694
1695 StoreInst *CreateAlignedStore(Value *Val, Value *Ptr, MaybeAlign Align,
1696 bool isVolatile = false) {
1697 if (!Align) {
1698 const DataLayout &DL = BB->getModule()->getDataLayout();
1699 Align = DL.getABITypeAlign(Val->getType());
1700 }
1701 return Insert(new StoreInst(Val, Ptr, isVolatile, *Align));
1702 }
1703 FenceInst *CreateFence(AtomicOrdering Ordering,
1704 SyncScope::ID SSID = SyncScope::System,
1705 const Twine &Name = "") {
1706 return Insert(new FenceInst(Context, Ordering, SSID), Name);
1707 }
1708
1709 AtomicCmpXchgInst *
1710 CreateAtomicCmpXchg(Value *Ptr, Value *Cmp, Value *New, MaybeAlign Align,
1711 AtomicOrdering SuccessOrdering,
1712 AtomicOrdering FailureOrdering,
1713 SyncScope::ID SSID = SyncScope::System) {
1714 if (!Align) {
1715 const DataLayout &DL = BB->getModule()->getDataLayout();
1716 Align = llvm::Align(DL.getTypeStoreSize(New->getType()));
1717 }
1718
1719 return Insert(new AtomicCmpXchgInst(Ptr, Cmp, New, *Align, SuccessOrdering,
1720 FailureOrdering, SSID));
1721 }
1722
1723 AtomicRMWInst *CreateAtomicRMW(AtomicRMWInst::BinOp Op, Value *Ptr,
1724 Value *Val, MaybeAlign Align,
1725 AtomicOrdering Ordering,
1726 SyncScope::ID SSID = SyncScope::System) {
1727 if (!Align) {
1728 const DataLayout &DL = BB->getModule()->getDataLayout();
1729 Align = llvm::Align(DL.getTypeStoreSize(Val->getType()));
1730 }
1731
1732 return Insert(new AtomicRMWInst(Op, Ptr, Val, *Align, Ordering, SSID));
1733 }
1734
1735 Value *CreateGEP(Type *Ty, Value *Ptr, ArrayRef<Value *> IdxList,
1736 const Twine &Name = "") {
1737 if (auto *V = Folder.FoldGEP(Ty, Ptr, IdxList, /*IsInBounds=*/false))
1738 return V;
1739 return Insert(GetElementPtrInst::Create(Ty, Ptr, IdxList), Name);
1740 }
1741
1742 Value *CreateInBoundsGEP(Type *Ty, Value *Ptr, ArrayRef<Value *> IdxList,
1743 const Twine &Name = "") {
1744 if (auto *V = Folder.FoldGEP(Ty, Ptr, IdxList, /*IsInBounds=*/true))
1745 return V;
1746 return Insert(GetElementPtrInst::CreateInBounds(Ty, Ptr, IdxList), Name);
1747 }
1748
1749 Value *CreateGEP(Type *Ty, Value *Ptr, Value *Idx, const Twine &Name = "") {
1750 if (auto *V = Folder.FoldGEP(Ty, Ptr, {Idx}, /*IsInBounds=*/false))
1751 return V;
1752 return Insert(GetElementPtrInst::Create(Ty, Ptr, Idx), Name);
1753 }
1754
1755 Value *CreateInBoundsGEP(Type *Ty, Value *Ptr, Value *Idx,
1756 const Twine &Name = "") {
1757 if (auto *V = Folder.FoldGEP(Ty, Ptr, {Idx}, /*IsInBounds=*/true))
1758 return V;
1759 return Insert(GetElementPtrInst::CreateInBounds(Ty, Ptr, Idx), Name);
1760 }
1761
1762 Value *CreateConstGEP1_32(Type *Ty, Value *Ptr, unsigned Idx0,
1763 const Twine &Name = "") {
1764 Value *Idx = ConstantInt::get(Type::getInt32Ty(Context), Idx0);
1765
1766 if (auto *V = Folder.FoldGEP(Ty, Ptr, Idx, /*IsInBounds=*/false))
1767 return V;
1768
1769 return Insert(GetElementPtrInst::Create(Ty, Ptr, Idx), Name);
1770 }
1771
1772 Value *CreateConstInBoundsGEP1_32(Type *Ty, Value *Ptr, unsigned Idx0,
1773 const Twine &Name = "") {
1774 Value *Idx = ConstantInt::get(Type::getInt32Ty(Context), Idx0);
1775
1776 if (auto *V = Folder.FoldGEP(Ty, Ptr, Idx, /*IsInBounds=*/true))
1777 return V;
1778
1779 return Insert(GetElementPtrInst::CreateInBounds(Ty, Ptr, Idx), Name);
1780 }
1781
1782 Value *CreateConstGEP2_32(Type *Ty, Value *Ptr, unsigned Idx0, unsigned Idx1,
1783 const Twine &Name = "") {
1784 Value *Idxs[] = {
1785 ConstantInt::get(Type::getInt32Ty(Context), Idx0),
1786 ConstantInt::get(Type::getInt32Ty(Context), Idx1)
1787 };
1788
1789 if (auto *V = Folder.FoldGEP(Ty, Ptr, Idxs, /*IsInBounds=*/false))
1790 return V;
1791
1792 return Insert(GetElementPtrInst::Create(Ty, Ptr, Idxs), Name);
1793 }
1794
1795 Value *CreateConstInBoundsGEP2_32(Type *Ty, Value *Ptr, unsigned Idx0,
1796 unsigned Idx1, const Twine &Name = "") {
1797 Value *Idxs[] = {
1798 ConstantInt::get(Type::getInt32Ty(Context), Idx0),
1799 ConstantInt::get(Type::getInt32Ty(Context), Idx1)
1800 };
1801
1802 if (auto *V = Folder.FoldGEP(Ty, Ptr, Idxs, /*IsInBounds=*/true))
1803 return V;
1804
1805 return Insert(GetElementPtrInst::CreateInBounds(Ty, Ptr, Idxs), Name);
1806 }
1807
1808 Value *CreateConstGEP1_64(Type *Ty, Value *Ptr, uint64_t Idx0,
1809 const Twine &Name = "") {
1810 Value *Idx = ConstantInt::get(Type::getInt64Ty(Context), Idx0);
1811
1812 if (auto *V = Folder.FoldGEP(Ty, Ptr, Idx, /*IsInBounds=*/false))
1813 return V;
1814
1815 return Insert(GetElementPtrInst::Create(Ty, Ptr, Idx), Name);
1816 }
1817
1818 Value *CreateConstInBoundsGEP1_64(Type *Ty, Value *Ptr, uint64_t Idx0,
1819 const Twine &Name = "") {
1820 Value *Idx = ConstantInt::get(Type::getInt64Ty(Context), Idx0);
1821
1822 if (auto *V = Folder.FoldGEP(Ty, Ptr, Idx, /*IsInBounds=*/true))
1823 return V;
1824
1825 return Insert(GetElementPtrInst::CreateInBounds(Ty, Ptr, Idx), Name);
1826 }
1827
1828 Value *CreateConstGEP2_64(Type *Ty, Value *Ptr, uint64_t Idx0, uint64_t Idx1,
1829 const Twine &Name = "") {
1830 Value *Idxs[] = {
1831 ConstantInt::get(Type::getInt64Ty(Context), Idx0),
1832 ConstantInt::get(Type::getInt64Ty(Context), Idx1)
1833 };
1834
1835 if (auto *V = Folder.FoldGEP(Ty, Ptr, Idxs, /*IsInBounds=*/false))
1836 return V;
1837
1838 return Insert(GetElementPtrInst::Create(Ty, Ptr, Idxs), Name);
1839 }
1840
1841 Value *CreateConstInBoundsGEP2_64(Type *Ty, Value *Ptr, uint64_t Idx0,
1842 uint64_t Idx1, const Twine &Name = "") {
1843 Value *Idxs[] = {
1844 ConstantInt::get(Type::getInt64Ty(Context), Idx0),
1845 ConstantInt::get(Type::getInt64Ty(Context), Idx1)
1846 };
1847
1848 if (auto *V = Folder.FoldGEP(Ty, Ptr, Idxs, /*IsInBounds=*/true))
1849 return V;
1850
1851 return Insert(GetElementPtrInst::CreateInBounds(Ty, Ptr, Idxs), Name);
1852 }
1853
1854 Value *CreateStructGEP(Type *Ty, Value *Ptr, unsigned Idx,
1855 const Twine &Name = "") {
1856 return CreateConstInBoundsGEP2_32(Ty, Ptr, 0, Idx, Name);
1857 }
1858
1859 /// Same as CreateGlobalString, but return a pointer with "i8*" type
1860 /// instead of a pointer to array of i8.
1861 ///
1862 /// If no module is given via \p M, it is take from the insertion point basic
1863 /// block.
1864 Constant *CreateGlobalStringPtr(StringRef Str, const Twine &Name = "",
1865 unsigned AddressSpace = 0,
1866 Module *M = nullptr) {
1867 GlobalVariable *GV = CreateGlobalString(Str, Name, AddressSpace, M);
1868 Constant *Zero = ConstantInt::get(Type::getInt32Ty(Context), 0);
1869 Constant *Indices[] = {Zero, Zero};
1870 return ConstantExpr::getInBoundsGetElementPtr(GV->getValueType(), GV,
1871 Indices);
1872 }
1873
1874 //===--------------------------------------------------------------------===//
1875 // Instruction creation methods: Cast/Conversion Operators
1876 //===--------------------------------------------------------------------===//
1877
1878 Value *CreateTrunc(Value *V, Type *DestTy, const Twine &Name = "") {
1879 return CreateCast(Instruction::Trunc, V, DestTy, Name);
1880 }
1881
1882 Value *CreateZExt(Value *V, Type *DestTy, const Twine &Name = "") {
1883 return CreateCast(Instruction::ZExt, V, DestTy, Name);
1884 }
1885
1886 Value *CreateSExt(Value *V, Type *DestTy, const Twine &Name = "") {
1887 return CreateCast(Instruction::SExt, V, DestTy, Name);
1888 }
1889
1890 /// Create a ZExt or Trunc from the integer value V to DestTy. Return
1891 /// the value untouched if the type of V is already DestTy.
1892 Value *CreateZExtOrTrunc(Value *V, Type *DestTy,
1893 const Twine &Name = "") {
1894 assert(V->getType()->isIntOrIntVectorTy() &&
1895 DestTy->isIntOrIntVectorTy() &&
1896 "Can only zero extend/truncate integers!");
1897 Type *VTy = V->getType();
1898 if (VTy->getScalarSizeInBits() < DestTy->getScalarSizeInBits())
1899 return CreateZExt(V, DestTy, Name);
1900 if (VTy->getScalarSizeInBits() > DestTy->getScalarSizeInBits())
1901 return CreateTrunc(V, DestTy, Name);
1902 return V;
1903 }
1904
1905 /// Create a SExt or Trunc from the integer value V to DestTy. Return
1906 /// the value untouched if the type of V is already DestTy.
1907 Value *CreateSExtOrTrunc(Value *V, Type *DestTy,
1908 const Twine &Name = "") {
1909 assert(V->getType()->isIntOrIntVectorTy() &&
1910 DestTy->isIntOrIntVectorTy() &&
1911 "Can only sign extend/truncate integers!");
1912 Type *VTy = V->getType();
1913 if (VTy->getScalarSizeInBits() < DestTy->getScalarSizeInBits())
1914 return CreateSExt(V, DestTy, Name);
1915 if (VTy->getScalarSizeInBits() > DestTy->getScalarSizeInBits())
1916 return CreateTrunc(V, DestTy, Name);
1917 return V;
1918 }
1919
1920 Value *CreateFPToUI(Value *V, Type *DestTy, const Twine &Name = "") {
1921 if (IsFPConstrained)
1922 return CreateConstrainedFPCast(Intrinsic::experimental_constrained_fptoui,
1923 V, DestTy, nullptr, Name);
1924 return CreateCast(Instruction::FPToUI, V, DestTy, Name);
1925 }
1926
1927 Value *CreateFPToSI(Value *V, Type *DestTy, const Twine &Name = "") {
1928 if (IsFPConstrained)
1929 return CreateConstrainedFPCast(Intrinsic::experimental_constrained_fptosi,
1930 V, DestTy, nullptr, Name);
1931 return CreateCast(Instruction::FPToSI, V, DestTy, Name);
1932 }
1933
1934 Value *CreateUIToFP(Value *V, Type *DestTy, const Twine &Name = ""){
1935 if (IsFPConstrained)
1936 return CreateConstrainedFPCast(Intrinsic::experimental_constrained_uitofp,
1937 V, DestTy, nullptr, Name);
1938 return CreateCast(Instruction::UIToFP, V, DestTy, Name);
1939 }
1940
1941 Value *CreateSIToFP(Value *V, Type *DestTy, const Twine &Name = ""){
1942 if (IsFPConstrained)
1943 return CreateConstrainedFPCast(Intrinsic::experimental_constrained_sitofp,
1944 V, DestTy, nullptr, Name);
1945 return CreateCast(Instruction::SIToFP, V, DestTy, Name);
1946 }
1947
1948 Value *CreateFPTrunc(Value *V, Type *DestTy,
1949 const Twine &Name = "") {
1950 if (IsFPConstrained)
1951 return CreateConstrainedFPCast(
1952 Intrinsic::experimental_constrained_fptrunc, V, DestTy, nullptr,
1953 Name);
1954 return CreateCast(Instruction::FPTrunc, V, DestTy, Name);
1955 }
1956
1957 Value *CreateFPExt(Value *V, Type *DestTy, const Twine &Name = "") {
1958 if (IsFPConstrained)
1959 return CreateConstrainedFPCast(Intrinsic::experimental_constrained_fpext,
1960 V, DestTy, nullptr, Name);
1961 return CreateCast(Instruction::FPExt, V, DestTy, Name);
1962 }
1963
1964 Value *CreatePtrToInt(Value *V, Type *DestTy,
1965 const Twine &Name = "") {
1966 return CreateCast(Instruction::PtrToInt, V, DestTy, Name);
1967 }
1968
1969 Value *CreateIntToPtr(Value *V, Type *DestTy,
1970 const Twine &Name = "") {
1971 return CreateCast(Instruction::IntToPtr, V, DestTy, Name);
1972 }
1973
1974 Value *CreateBitCast(Value *V, Type *DestTy,
1975 const Twine &Name = "") {
1976 return CreateCast(Instruction::BitCast, V, DestTy, Name);
1977 }
1978
1979 Value *CreateAddrSpaceCast(Value *V, Type *DestTy,
1980 const Twine &Name = "") {
1981 return CreateCast(Instruction::AddrSpaceCast, V, DestTy, Name);
1982 }
1983
1984 Value *CreateZExtOrBitCast(Value *V, Type *DestTy,
1985 const Twine &Name = "") {
1986 if (V->getType() == DestTy)
1987 return V;
1988 if (auto *VC = dyn_cast<Constant>(V))
1989 return Insert(Folder.CreateZExtOrBitCast(VC, DestTy), Name);
1990 return Insert(CastInst::CreateZExtOrBitCast(V, DestTy), Name);
1991 }
1992
1993 Value *CreateSExtOrBitCast(Value *V, Type *DestTy,
1994 const Twine &Name = "") {
1995 if (V->getType() == DestTy)
1996 return V;
1997 if (auto *VC = dyn_cast<Constant>(V))
1998 return Insert(Folder.CreateSExtOrBitCast(VC, DestTy), Name);
1999 return Insert(CastInst::CreateSExtOrBitCast(V, DestTy), Name);
2000 }
2001
2002 Value *CreateTruncOrBitCast(Value *V, Type *DestTy,
2003 const Twine &Name = "") {
2004 if (V->getType() == DestTy)
2005 return V;
2006 if (auto *VC = dyn_cast<Constant>(V))
2007 return Insert(Folder.CreateTruncOrBitCast(VC, DestTy), Name);
2008 return Insert(CastInst::CreateTruncOrBitCast(V, DestTy), Name);
2009 }
2010
2011 Value *CreateCast(Instruction::CastOps Op, Value *V, Type *DestTy,
2012 const Twine &Name = "") {
2013 if (V->getType() == DestTy)
2014 return V;
2015 if (auto *VC = dyn_cast<Constant>(V))
2016 return Insert(Folder.CreateCast(Op, VC, DestTy), Name);
2017 return Insert(CastInst::Create(Op, V, DestTy), Name);
2018 }
2019
2020 Value *CreatePointerCast(Value *V, Type *DestTy,
2021 const Twine &Name = "") {
2022 if (V->getType() == DestTy)
2023 return V;
2024 if (auto *VC = dyn_cast<Constant>(V))
2025 return Insert(Folder.CreatePointerCast(VC, DestTy), Name);
2026 return Insert(CastInst::CreatePointerCast(V, DestTy), Name);
2027 }
2028
2029 Value *CreatePointerBitCastOrAddrSpaceCast(Value *V, Type *DestTy,
2030 const Twine &Name = "") {
2031 if (V->getType() == DestTy)
2032 return V;
2033
2034 if (auto *VC = dyn_cast<Constant>(V)) {
2035 return Insert(Folder.CreatePointerBitCastOrAddrSpaceCast(VC, DestTy),
2036 Name);
2037 }
2038
2039 return Insert(CastInst::CreatePointerBitCastOrAddrSpaceCast(V, DestTy),
2040 Name);
2041 }
2042
2043 Value *CreateIntCast(Value *V, Type *DestTy, bool isSigned,
2044 const Twine &Name = "") {
2045 if (V->getType() == DestTy)
2046 return V;
2047 if (auto *VC = dyn_cast<Constant>(V))
2048 return Insert(Folder.CreateIntCast(VC, DestTy, isSigned), Name);
2049 return Insert(CastInst::CreateIntegerCast(V, DestTy, isSigned), Name);
2050 }
2051
2052 Value *CreateBitOrPointerCast(Value *V, Type *DestTy,
2053 const Twine &Name = "") {
2054 if (V->getType() == DestTy)
2055 return V;
2056 if (V->getType()->isPtrOrPtrVectorTy() && DestTy->isIntOrIntVectorTy())
2057 return CreatePtrToInt(V, DestTy, Name);
2058 if (V->getType()->isIntOrIntVectorTy() && DestTy->isPtrOrPtrVectorTy())
2059 return CreateIntToPtr(V, DestTy, Name);
2060
2061 return CreateBitCast(V, DestTy, Name);
2062 }
2063
2064 Value *CreateFPCast(Value *V, Type *DestTy, const Twine &Name = "") {
2065 if (V->getType() == DestTy)
2066 return V;
2067 if (auto *VC = dyn_cast<Constant>(V))
2068 return Insert(Folder.CreateFPCast(VC, DestTy), Name);
2069 return Insert(CastInst::CreateFPCast(V, DestTy), Name);
2070 }
2071
2072 CallInst *CreateConstrainedFPCast(
2073 Intrinsic::ID ID, Value *V, Type *DestTy,
2074 Instruction *FMFSource = nullptr, const Twine &Name = "",
2075 MDNode *FPMathTag = nullptr,
2076 Optional<RoundingMode> Rounding = None,
2077 Optional<fp::ExceptionBehavior> Except = None);
2078
2079 // Provided to resolve 'CreateIntCast(Ptr, Ptr, "...")', giving a
2080 // compile time error, instead of converting the string to bool for the
2081 // isSigned parameter.
2082 Value *CreateIntCast(Value *, Type *, const char *) = delete;
2083
2084 //===--------------------------------------------------------------------===//
2085 // Instruction creation methods: Compare Instructions
2086 //===--------------------------------------------------------------------===//
2087
2088 Value *CreateICmpEQ(Value *LHS, Value *RHS, const Twine &Name = "") {
2089 return CreateICmp(ICmpInst::ICMP_EQ, LHS, RHS, Name);
2090 }
2091
2092 Value *CreateICmpNE(Value *LHS, Value *RHS, const Twine &Name = "") {
2093 return CreateICmp(ICmpInst::ICMP_NE, LHS, RHS, Name);
2094 }
2095
2096 Value *CreateICmpUGT(Value *LHS, Value *RHS, const Twine &Name = "") {
2097 return CreateICmp(ICmpInst::ICMP_UGT, LHS, RHS, Name);
2098 }
2099
2100 Value *CreateICmpUGE(Value *LHS, Value *RHS, const Twine &Name = "") {
2101 return CreateICmp(ICmpInst::ICMP_UGE, LHS, RHS, Name);
2102 }
2103
2104 Value *CreateICmpULT(Value *LHS, Value *RHS, const Twine &Name = "") {
2105 return CreateICmp(ICmpInst::ICMP_ULT, LHS, RHS, Name);
2106 }
2107
2108 Value *CreateICmpULE(Value *LHS, Value *RHS, const Twine &Name = "") {
2109 return CreateICmp(ICmpInst::ICMP_ULE, LHS, RHS, Name);
2110 }
2111
2112 Value *CreateICmpSGT(Value *LHS, Value *RHS, const Twine &Name = "") {
2113 return CreateICmp(ICmpInst::ICMP_SGT, LHS, RHS, Name);
2114 }
2115
2116 Value *CreateICmpSGE(Value *LHS, Value *RHS, const Twine &Name = "") {
2117 return CreateICmp(ICmpInst::ICMP_SGE, LHS, RHS, Name);
2118 }
2119
2120 Value *CreateICmpSLT(Value *LHS, Value *RHS, const Twine &Name = "") {
2121 return CreateICmp(ICmpInst::ICMP_SLT, LHS, RHS, Name);
2122 }
2123
2124 Value *CreateICmpSLE(Value *LHS, Value *RHS, const Twine &Name = "") {
2125 return CreateICmp(ICmpInst::ICMP_SLE, LHS, RHS, Name);
2126 }
2127
2128 Value *CreateFCmpOEQ(Value *LHS, Value *RHS, const Twine &Name = "",
2129 MDNode *FPMathTag = nullptr) {
2130 return CreateFCmp(FCmpInst::FCMP_OEQ, LHS, RHS, Name, FPMathTag);
2131 }
2132
2133 Value *CreateFCmpOGT(Value *LHS, Value *RHS, const Twine &Name = "",
2134 MDNode *FPMathTag = nullptr) {
2135 return CreateFCmp(FCmpInst::FCMP_OGT, LHS, RHS, Name, FPMathTag);
2136 }
2137
2138 Value *CreateFCmpOGE(Value *LHS, Value *RHS, const Twine &Name = "",
2139 MDNode *FPMathTag = nullptr) {
2140 return CreateFCmp(FCmpInst::FCMP_OGE, LHS, RHS, Name, FPMathTag);
2141 }
2142
2143 Value *CreateFCmpOLT(Value *LHS, Value *RHS, const Twine &Name = "",
2144 MDNode *FPMathTag = nullptr) {
2145 return CreateFCmp(FCmpInst::FCMP_OLT, LHS, RHS, Name, FPMathTag);
2146 }
2147
2148 Value *CreateFCmpOLE(Value *LHS, Value *RHS, const Twine &Name = "",
2149 MDNode *FPMathTag = nullptr) {
2150 return CreateFCmp(FCmpInst::FCMP_OLE, LHS, RHS, Name, FPMathTag);
2151 }
2152
2153 Value *CreateFCmpONE(Value *LHS, Value *RHS, const Twine &Name = "",
2154 MDNode *FPMathTag = nullptr) {
2155 return CreateFCmp(FCmpInst::FCMP_ONE, LHS, RHS, Name, FPMathTag);
2156 }
2157
2158 Value *CreateFCmpORD(Value *LHS, Value *RHS, const Twine &Name = "",
2159 MDNode *FPMathTag = nullptr) {
2160 return CreateFCmp(FCmpInst::FCMP_ORD, LHS, RHS, Name, FPMathTag);
2161 }
2162
2163 Value *CreateFCmpUNO(Value *LHS, Value *RHS, const Twine &Name = "",
2164 MDNode *FPMathTag = nullptr) {
2165 return CreateFCmp(FCmpInst::FCMP_UNO, LHS, RHS, Name, FPMathTag);
2166 }
2167
2168 Value *CreateFCmpUEQ(Value *LHS, Value *RHS, const Twine &Name = "",
2169 MDNode *FPMathTag = nullptr) {
2170 return CreateFCmp(FCmpInst::FCMP_UEQ, LHS, RHS, Name, FPMathTag);
2171 }
2172
2173 Value *CreateFCmpUGT(Value *LHS, Value *RHS, const Twine &Name = "",
2174 MDNode *FPMathTag = nullptr) {
2175 return CreateFCmp(FCmpInst::FCMP_UGT, LHS, RHS, Name, FPMathTag);
2176 }
2177
2178 Value *CreateFCmpUGE(Value *LHS, Value *RHS, const Twine &Name = "",
2179 MDNode *FPMathTag = nullptr) {
2180 return CreateFCmp(FCmpInst::FCMP_UGE, LHS, RHS, Name, FPMathTag);
2181 }
2182
2183 Value *CreateFCmpULT(Value *LHS, Value *RHS, const Twine &Name = "",
2184 MDNode *FPMathTag = nullptr) {
2185 return CreateFCmp(FCmpInst::FCMP_ULT, LHS, RHS, Name, FPMathTag);
2186 }
2187
2188 Value *CreateFCmpULE(Value *LHS, Value *RHS, const Twine &Name = "",
2189 MDNode *FPMathTag = nullptr) {
2190 return CreateFCmp(FCmpInst::FCMP_ULE, LHS, RHS, Name, FPMathTag);
2191 }
2192
2193 Value *CreateFCmpUNE(Value *LHS, Value *RHS, const Twine &Name = "",
2194 MDNode *FPMathTag = nullptr) {
2195 return CreateFCmp(FCmpInst::FCMP_UNE, LHS, RHS, Name, FPMathTag);
2196 }
2197
2198 Value *CreateICmp(CmpInst::Predicate P, Value *LHS, Value *RHS,
2199 const Twine &Name = "") {
2200 if (auto *V = Folder.FoldICmp(P, LHS, RHS))
2201 return V;
2202 return Insert(new ICmpInst(P, LHS, RHS), Name);
2203 }
2204
2205 // Create a quiet floating-point comparison (i.e. one that raises an FP
2206 // exception only in the case where an input is a signaling NaN).
2207 // Note that this differs from CreateFCmpS only if IsFPConstrained is true.
2208 Value *CreateFCmp(CmpInst::Predicate P, Value *LHS, Value *RHS,
2209 const Twine &Name = "", MDNode *FPMathTag = nullptr) {
2210 return CreateFCmpHelper(P, LHS, RHS, Name, FPMathTag, false);
2211 }
2212
2213 Value *CreateCmp(CmpInst::Predicate Pred, Value *LHS, Value *RHS,
2214 const Twine &Name = "", MDNode *FPMathTag = nullptr) {
2215 return CmpInst::isFPPredicate(Pred)
2216 ? CreateFCmp(Pred, LHS, RHS, Name, FPMathTag)
2217 : CreateICmp(Pred, LHS, RHS, Name);
2218 }
2219
2220 // Create a signaling floating-point comparison (i.e. one that raises an FP
2221 // exception whenever an input is any NaN, signaling or quiet).
2222 // Note that this differs from CreateFCmp only if IsFPConstrained is true.
2223 Value *CreateFCmpS(CmpInst::Predicate P, Value *LHS, Value *RHS,
2224 const Twine &Name = "", MDNode *FPMathTag = nullptr) {
2225 return CreateFCmpHelper(P, LHS, RHS, Name, FPMathTag, true);
2226 }
2227
2228 private:
2229 // Helper routine to create either a signaling or a quiet FP comparison.
2230 Value *CreateFCmpHelper(CmpInst::Predicate P, Value *LHS, Value *RHS,
2231 const Twine &Name, MDNode *FPMathTag,
2232 bool IsSignaling);
2233
2234 public:
2235 CallInst *CreateConstrainedFPCmp(
2236 Intrinsic::ID ID, CmpInst::Predicate P, Value *L, Value *R,
2237 const Twine &Name = "", Optional<fp::ExceptionBehavior> Except = None);
2238
2239 //===--------------------------------------------------------------------===//
2240 // Instruction creation methods: Other Instructions
2241 //===--------------------------------------------------------------------===//
2242
2243 PHINode *CreatePHI(Type *Ty, unsigned NumReservedValues,
2244 const Twine &Name = "") {
2245 PHINode *Phi = PHINode::Create(Ty, NumReservedValues);
2246 if (isa<FPMathOperator>(Phi))
2247 setFPAttrs(Phi, nullptr /* MDNode* */, FMF);
2248 return Insert(Phi, Name);
2249 }
2250
2251 CallInst *CreateCall(FunctionType *FTy, Value *Callee,
2252 ArrayRef<Value *> Args = None, const Twine &Name = "",
2253 MDNode *FPMathTag = nullptr) {
2254 CallInst *CI = CallInst::Create(FTy, Callee, Args, DefaultOperandBundles);
2255 if (IsFPConstrained)
2256 setConstrainedFPCallAttr(CI);
2257 if (isa<FPMathOperator>(CI))
2258 setFPAttrs(CI, FPMathTag, FMF);
2259 return Insert(CI, Name);
2260 }
2261
2262 CallInst *CreateCall(FunctionType *FTy, Value *Callee, ArrayRef<Value *> Args,
2263 ArrayRef<OperandBundleDef> OpBundles,
2264 const Twine &Name = "", MDNode *FPMathTag = nullptr) {
2265 CallInst *CI = CallInst::Create(FTy, Callee, Args, OpBundles);
2266 if (IsFPConstrained)
2267 setConstrainedFPCallAttr(CI);
2268 if (isa<FPMathOperator>(CI))
2269 setFPAttrs(CI, FPMathTag, FMF);
2270 return Insert(CI, Name);
2271 }
2272
2273 CallInst *CreateCall(FunctionCallee Callee, ArrayRef<Value *> Args = None,
2274 const Twine &Name = "", MDNode *FPMathTag = nullptr) {
2275 return CreateCall(Callee.getFunctionType(), Callee.getCallee(), Args, Name,
2276 FPMathTag);
2277 }
2278
2279 CallInst *CreateCall(FunctionCallee Callee, ArrayRef<Value *> Args,
2280 ArrayRef<OperandBundleDef> OpBundles,
2281 const Twine &Name = "", MDNode *FPMathTag = nullptr) {
2282 return CreateCall(Callee.getFunctionType(), Callee.getCallee(), Args,
2283 OpBundles, Name, FPMathTag);
2284 }
2285
2286 CallInst *CreateConstrainedFPCall(
2287 Function *Callee, ArrayRef<Value *> Args, const Twine &Name = "",
2288 Optional<RoundingMode> Rounding = None,
2289 Optional<fp::ExceptionBehavior> Except = None);
2290
2291 Value *CreateSelect(Value *C, Value *True, Value *False,
2292 const Twine &Name = "", Instruction *MDFrom = nullptr);
2293
2294 VAArgInst *CreateVAArg(Value *List, Type *Ty, const Twine &Name = "") {
2295 return Insert(new VAArgInst(List, Ty), Name);
2296 }
2297
2298 Value *CreateExtractElement(Value *Vec, Value *Idx,
2299 const Twine &Name = "") {
2300 if (auto *VC = dyn_cast<Constant>(Vec))
2301 if (auto *IC = dyn_cast<Constant>(Idx))
2302 return Insert(Folder.CreateExtractElement(VC, IC), Name);
2303 return Insert(ExtractElementInst::Create(Vec, Idx), Name);
2304 }
2305
2306 Value *CreateExtractElement(Value *Vec, uint64_t Idx,
2307 const Twine &Name = "") {
2308 return CreateExtractElement(Vec, getInt64(Idx), Name);
2309 }
2310
2311 Value *CreateInsertElement(Type *VecTy, Value *NewElt, Value *Idx,
2312 const Twine &Name = "") {
2313 return CreateInsertElement(PoisonValue::get(VecTy), NewElt, Idx, Name);
2314 }
2315
2316 Value *CreateInsertElement(Type *VecTy, Value *NewElt, uint64_t Idx,
2317 const Twine &Name = "") {
2318 return CreateInsertElement(PoisonValue::get(VecTy), NewElt, Idx, Name);
2319 }
2320
2321 Value *CreateInsertElement(Value *Vec, Value *NewElt, Value *Idx,
2322 const Twine &Name = "") {
2323 if (auto *VC = dyn_cast<Constant>(Vec))
2324 if (auto *NC = dyn_cast<Constant>(NewElt))
2325 if (auto *IC = dyn_cast<Constant>(Idx))
2326 return Insert(Folder.CreateInsertElement(VC, NC, IC), Name);
2327 return Insert(InsertElementInst::Create(Vec, NewElt, Idx), Name);
2328 }
2329
2330 Value *CreateInsertElement(Value *Vec, Value *NewElt, uint64_t Idx,
2331 const Twine &Name = "") {
2332 return CreateInsertElement(Vec, NewElt, getInt64(Idx), Name);
2333 }
2334
2335 Value *CreateShuffleVector(Value *V1, Value *V2, Value *Mask,
2336 const Twine &Name = "") {
2337 SmallVector<int, 16> IntMask;
2338 ShuffleVectorInst::getShuffleMask(cast<Constant>(Mask), IntMask);
2339 return CreateShuffleVector(V1, V2, IntMask, Name);
2340 }
2341
2342 LLVM_ATTRIBUTE_DEPRECATED(Value *CreateShuffleVector(Value *V1, Value *V2,
2343 ArrayRef<uint32_t> Mask,
2344 const Twine &Name = ""),
2345 "Pass indices as 'int' instead") {
2346 SmallVector<int, 16> IntMask;
2347 IntMask.assign(Mask.begin(), Mask.end());
2348 return CreateShuffleVector(V1, V2, IntMask, Name);
2349 }
2350
2351 /// See class ShuffleVectorInst for a description of the mask representation.
2352 Value *CreateShuffleVector(Value *V1, Value *V2, ArrayRef<int> Mask,
2353 const Twine &Name = "") {
2354 if (auto *V1C = dyn_cast<Constant>(V1))
2355 if (auto *V2C = dyn_cast<Constant>(V2))
2356 return Insert(Folder.CreateShuffleVector(V1C, V2C, Mask), Name);
2357 return Insert(new ShuffleVectorInst(V1, V2, Mask), Name);
2358 }
2359
2360 /// Create a unary shuffle. The second vector operand of the IR instruction
2361 /// is poison.
2362 Value *CreateShuffleVector(Value *V, ArrayRef<int> Mask,
2363 const Twine &Name = "") {
2364 return CreateShuffleVector(V, PoisonValue::get(V->getType()), Mask, Name);
2365 }
2366
2367 Value *CreateExtractValue(Value *Agg,
2368 ArrayRef<unsigned> Idxs,
2369 const Twine &Name = "") {
2370 if (auto *AggC = dyn_cast<Constant>(Agg))
2371 return Insert(Folder.CreateExtractValue(AggC, Idxs), Name);
2372 return Insert(ExtractValueInst::Create(Agg, Idxs), Name);
2373 }
2374
2375 Value *CreateInsertValue(Value *Agg, Value *Val,
2376 ArrayRef<unsigned> Idxs,
2377 const Twine &Name = "") {
2378 if (auto *AggC = dyn_cast<Constant>(Agg))
2379 if (auto *ValC = dyn_cast<Constant>(Val))
2380 return Insert(Folder.CreateInsertValue(AggC, ValC, Idxs), Name);
2381 return Insert(InsertValueInst::Create(Agg, Val, Idxs), Name);
2382 }
2383
2384 LandingPadInst *CreateLandingPad(Type *Ty, unsigned NumClauses,
2385 const Twine &Name = "") {
2386 return Insert(LandingPadInst::Create(Ty, NumClauses), Name);
2387 }
2388
2389 Value *CreateFreeze(Value *V, const Twine &Name = "") {
2390 return Insert(new FreezeInst(V), Name);
2391 }
2392
2393 //===--------------------------------------------------------------------===//
2394 // Utility creation methods
2395 //===--------------------------------------------------------------------===//
2396
2397 /// Return an i1 value testing if \p Arg is null.
2398 Value *CreateIsNull(Value *Arg, const Twine &Name = "") {
2399 return CreateICmpEQ(Arg, Constant::getNullValue(Arg->getType()),
2400 Name);
2401 }
2402
2403 /// Return an i1 value testing if \p Arg is not null.
2404 Value *CreateIsNotNull(Value *Arg, const Twine &Name = "") {
2405 return CreateICmpNE(Arg, Constant::getNullValue(Arg->getType()),
2406 Name);
2407 }
2408
2409 /// Return the i64 difference between two pointer values, dividing out
2410 /// the size of the pointed-to objects.
2411 ///
2412 /// This is intended to implement C-style pointer subtraction. As such, the
2413 /// pointers must be appropriately aligned for their element types and
2414 /// pointing into the same object.
2415 Value *CreatePtrDiff(Type *ElemTy, Value *LHS, Value *RHS,
2416 const Twine &Name = "");
2417
2418 /// Create a launder.invariant.group intrinsic call. If Ptr type is
2419 /// different from pointer to i8, it's casted to pointer to i8 in the same
2420 /// address space before call and casted back to Ptr type after call.
2421 Value *CreateLaunderInvariantGroup(Value *Ptr);
2422
2423 /// \brief Create a strip.invariant.group intrinsic call. If Ptr type is
2424 /// different from pointer to i8, it's casted to pointer to i8 in the same
2425 /// address space before call and casted back to Ptr type after call.
2426 Value *CreateStripInvariantGroup(Value *Ptr);
2427
2428 /// Return a vector value that contains the vector V reversed
2429 Value *CreateVectorReverse(Value *V, const Twine &Name = "");
2430
2431 /// Return a vector splice intrinsic if using scalable vectors, otherwise
2432 /// return a shufflevector. If the immediate is positive, a vector is
2433 /// extracted from concat(V1, V2), starting at Imm. If the immediate
2434 /// is negative, we extract -Imm elements from V1 and the remaining
2435 /// elements from V2. Imm is a signed integer in the range
2436 /// -VL <= Imm < VL (where VL is the runtime vector length of the
2437 /// source/result vector)
2438 Value *CreateVectorSplice(Value *V1, Value *V2, int64_t Imm,
2439 const Twine &Name = "");
2440
2441 /// Return a vector value that contains \arg V broadcasted to \p
2442 /// NumElts elements.
2443 Value *CreateVectorSplat(unsigned NumElts, Value *V, const Twine &Name = "");
2444
2445 /// Return a vector value that contains \arg V broadcasted to \p
2446 /// EC elements.
2447 Value *CreateVectorSplat(ElementCount EC, Value *V, const Twine &Name = "");
2448
2449 /// Return a value that has been extracted from a larger integer type.
2450 Value *CreateExtractInteger(const DataLayout &DL, Value *From,
2451 IntegerType *ExtractedTy, uint64_t Offset,
2452 const Twine &Name);
2453
2454 Value *CreatePreserveArrayAccessIndex(Type *ElTy, Value *Base,
2455 unsigned Dimension, unsigned LastIndex,
2456 MDNode *DbgInfo);
2457
2458 Value *CreatePreserveUnionAccessIndex(Value *Base, unsigned FieldIndex,
2459 MDNode *DbgInfo);
2460
2461 Value *CreatePreserveStructAccessIndex(Type *ElTy, Value *Base,
2462 unsigned Index, unsigned FieldIndex,
2463 MDNode *DbgInfo);
2464
2465 private:
2466 /// Helper function that creates an assume intrinsic call that
2467 /// represents an alignment assumption on the provided pointer \p PtrValue
2468 /// with offset \p OffsetValue and alignment value \p AlignValue.
2469 CallInst *CreateAlignmentAssumptionHelper(const DataLayout &DL,
2470 Value *PtrValue, Value *AlignValue,
2471 Value *OffsetValue);
2472
2473 public:
2474 /// Create an assume intrinsic call that represents an alignment
2475 /// assumption on the provided pointer.
2476 ///
2477 /// An optional offset can be provided, and if it is provided, the offset
2478 /// must be subtracted from the provided pointer to get the pointer with the
2479 /// specified alignment.
2480 CallInst *CreateAlignmentAssumption(const DataLayout &DL, Value *PtrValue,
2481 unsigned Alignment,
2482 Value *OffsetValue = nullptr);
2483
2484 /// Create an assume intrinsic call that represents an alignment
2485 /// assumption on the provided pointer.
2486 ///
2487 /// An optional offset can be provided, and if it is provided, the offset
2488 /// must be subtracted from the provided pointer to get the pointer with the
2489 /// specified alignment.
2490 ///
2491 /// This overload handles the condition where the Alignment is dependent
2492 /// on an existing value rather than a static value.
2493 CallInst *CreateAlignmentAssumption(const DataLayout &DL, Value *PtrValue,
2494 Value *Alignment,
2495 Value *OffsetValue = nullptr);
2496 };
2497
2498 /// This provides a uniform API for creating instructions and inserting
2499 /// them into a basic block: either at the end of a BasicBlock, or at a specific
2500 /// iterator location in a block.
2501 ///
2502 /// Note that the builder does not expose the full generality of LLVM
2503 /// instructions. For access to extra instruction properties, use the mutators
2504 /// (e.g. setVolatile) on the instructions after they have been
2505 /// created. Convenience state exists to specify fast-math flags and fp-math
2506 /// tags.
2507 ///
2508 /// The first template argument specifies a class to use for creating constants.
2509 /// This defaults to creating minimally folded constants. The second template
2510 /// argument allows clients to specify custom insertion hooks that are called on
2511 /// every newly created insertion.
2512 template <typename FolderTy = ConstantFolder,
2513 typename InserterTy = IRBuilderDefaultInserter>
2514 class IRBuilder : public IRBuilderBase {
2515 private:
2516 FolderTy Folder;
2517 InserterTy Inserter;
2518
2519 public:
2520 IRBuilder(LLVMContext &C, FolderTy Folder, InserterTy Inserter = InserterTy(),
2521 MDNode *FPMathTag = nullptr,
2522 ArrayRef<OperandBundleDef> OpBundles = None)
2523 : IRBuilderBase(C, this->Folder, this->Inserter, FPMathTag, OpBundles),
2524 Folder(Folder), Inserter(Inserter) {}
2525
2526 explicit IRBuilder(LLVMContext &C, MDNode *FPMathTag = nullptr,
2527 ArrayRef<OperandBundleDef> OpBundles = None)
2528 : IRBuilderBase(C, this->Folder, this->Inserter, FPMathTag, OpBundles) {}
2529
2530 explicit IRBuilder(BasicBlock *TheBB, FolderTy Folder,
2531 MDNode *FPMathTag = nullptr,
2532 ArrayRef<OperandBundleDef> OpBundles = None)
2533 : IRBuilderBase(TheBB->getContext(), this->Folder, this->Inserter,
2534 FPMathTag, OpBundles), Folder(Folder) {
2535 SetInsertPoint(TheBB);
2536 }
2537
2538 explicit IRBuilder(BasicBlock *TheBB, MDNode *FPMathTag = nullptr,
2539 ArrayRef<OperandBundleDef> OpBundles = None)
2540 : IRBuilderBase(TheBB->getContext(), this->Folder, this->Inserter,
2541 FPMathTag, OpBundles) {
2542 SetInsertPoint(TheBB);
2543 }
2544
2545 explicit IRBuilder(Instruction *IP, MDNode *FPMathTag = nullptr,
2546 ArrayRef<OperandBundleDef> OpBundles = None)
2547 : IRBuilderBase(IP->getContext(), this->Folder, this->Inserter,
2548 FPMathTag, OpBundles) {
2549 SetInsertPoint(IP);
2550 }
2551
2552 IRBuilder(BasicBlock *TheBB, BasicBlock::iterator IP, FolderTy Folder,
2553 MDNode *FPMathTag = nullptr,
2554 ArrayRef<OperandBundleDef> OpBundles = None)
2555 : IRBuilderBase(TheBB->getContext(), this->Folder, this->Inserter,
2556 FPMathTag, OpBundles), Folder(Folder) {
2557 SetInsertPoint(TheBB, IP);
2558 }
2559
2560 IRBuilder(BasicBlock *TheBB, BasicBlock::iterator IP,
2561 MDNode *FPMathTag = nullptr,
2562 ArrayRef<OperandBundleDef> OpBundles = None)
2563 : IRBuilderBase(TheBB->getContext(), this->Folder, this->Inserter,
2564 FPMathTag, OpBundles) {
2565 SetInsertPoint(TheBB, IP);
2566 }
2567
2568 /// Avoid copying the full IRBuilder. Prefer using InsertPointGuard
2569 /// or FastMathFlagGuard instead.
2570 IRBuilder(const IRBuilder &) = delete;
2571
2572 InserterTy &getInserter() { return Inserter; }
2573 };
2574
2575 // Create wrappers for C Binding types (see CBindingWrapping.h).
2576 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(IRBuilder<>, LLVMBuilderRef)
2577
2578 } // end namespace llvm
2579
2580 #endif // LLVM_IR_IRBUILDER_H