LLVM 20.0.0git
SandboxIR.h
Go to the documentation of this file.
1//===- SandboxIR.h ----------------------------------------------*- 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// Sandbox IR is a lightweight overlay transactional IR on top of LLVM IR.
10// Features:
11// - You can save/rollback the state of the IR at any time.
12// - Any changes made to Sandbox IR will automatically update the underlying
13// LLVM IR so both IRs are always in sync.
14// - Feels like LLVM IR, similar API.
15//
16// SandboxIR forms a class hierarchy that resembles that of LLVM IR
17// but is in the `sandboxir` namespace:
18//
19// namespace sandboxir {
20//
21// Value -+- Argument
22// |
23// +- BasicBlock
24// |
25// +- User ------+- Constant ------ Function
26// |
27// +- Instruction -+- BinaryOperator
28// |
29// +- BranchInst
30// |
31// +- CastInst --------+- AddrSpaceCastInst
32// | |
33// | +- BitCastInst
34// | |
35// | +- FPExtInst
36// | |
37// | +- FPToSIInst
38// | |
39// | +- FPToUIInst
40// | |
41// | +- FPTruncInst
42// | |
43// | +- IntToPtrInst
44// | |
45// | +- PtrToIntInst
46// | |
47// | +- SExtInst
48// | |
49// | +- SIToFPInst
50// | |
51// | +- TruncInst
52// | |
53// | +- UIToFPInst
54// | |
55// | +- ZExtInst
56// |
57// +- CallBase -----------+- CallBrInst
58// | |
59// +- CmpInst +- CallInst
60// | |
61// +- ExtractElementInst +- InvokeInst
62// |
63// +- GetElementPtrInst
64// |
65// +- InsertElementInst
66// |
67// +- OpaqueInst
68// |
69// +- PHINode
70// |
71// +- ReturnInst
72// |
73// +- SelectInst
74// |
75// +- ShuffleVectorInst
76// |
77// +- StoreInst
78// |
79// +- UnaryInstruction -+- LoadInst
80// | |
81// | +- CastInst
82// |
83// +- UnaryOperator
84// |
85// +- UnreachableInst
86//
87// Use
88//
89// } // namespace sandboxir
90//
91
92#ifndef LLVM_SANDBOXIR_SANDBOXIR_H
93#define LLVM_SANDBOXIR_SANDBOXIR_H
94
95#include "llvm/IR/Function.h"
96#include "llvm/IR/IRBuilder.h"
97#include "llvm/IR/Instruction.h"
98#include "llvm/IR/User.h"
99#include "llvm/IR/Value.h"
101#include "llvm/SandboxIR/Use.h"
103#include <iterator>
104
105namespace llvm {
106
107namespace sandboxir {
108
109class BasicBlock;
110class ConstantInt;
111class Context;
112class Function;
113class Instruction;
114class SelectInst;
118class BranchInst;
119class UnaryInstruction;
120class LoadInst;
121class ReturnInst;
122class StoreInst;
123class User;
124class UnreachableInst;
125class Value;
126class CallBase;
127class CallInst;
128class InvokeInst;
129class CallBrInst;
130class FuncletPadInst;
131class CatchPadInst;
132class CleanupPadInst;
134class CastInst;
135class PtrToIntInst;
136class BitCastInst;
137class AllocaInst;
138class CatchSwitchInst;
139class SwitchInst;
140class UnaryOperator;
141class BinaryOperator;
142class AtomicRMWInst;
144
145/// Iterator for the `Use` edges of a User's operands.
146/// \Returns the operand `Use` when dereferenced.
149 /// Don't let the user create a non-empty OperandUseIterator.
150 OperandUseIterator(const class Use &Use) : Use(Use) {}
151 friend class User; // For constructor
152#define DEF_INSTR(ID, OPC, CLASS) friend class CLASS; // For constructor
153#include "llvm/SandboxIR/SandboxIRValues.def"
154
155public:
156 using difference_type = std::ptrdiff_t;
160 using iterator_category = std::input_iterator_tag;
161
163 value_type operator*() const;
166 auto Copy = *this;
167 this->operator++();
168 return Copy;
169 }
171 return Use == Other.Use;
172 }
174 return !(*this == Other);
175 }
176 OperandUseIterator operator+(unsigned Num) const;
177 OperandUseIterator operator-(unsigned Num) const;
178 int operator-(const OperandUseIterator &Other) const;
179};
180
181/// Iterator for the `Use` edges of a Value's users.
182/// \Returns a `Use` when dereferenced.
185 /// Don't let the user create a non-empty UserUseIterator.
186 UserUseIterator(const class Use &Use) : Use(Use) {}
187 friend class Value; // For constructor
188
189public:
190 using difference_type = std::ptrdiff_t;
194 using iterator_category = std::input_iterator_tag;
195
196 UserUseIterator() = default;
197 value_type operator*() const { return Use; }
199 bool operator==(const UserUseIterator &Other) const {
200 return Use == Other.Use;
201 }
202 bool operator!=(const UserUseIterator &Other) const {
203 return !(*this == Other);
204 }
205 const sandboxir::Use &getUse() const { return Use; }
206};
207
208/// A SandboxIR Value has users. This is the base class.
209class Value {
210public:
211 enum class ClassID : unsigned {
212#define DEF_VALUE(ID, CLASS) ID,
213#define DEF_USER(ID, CLASS) ID,
214#define DEF_INSTR(ID, OPC, CLASS) ID,
215#include "llvm/SandboxIR/SandboxIRValues.def"
216 };
217
218protected:
219 static const char *getSubclassIDStr(ClassID ID) {
220 switch (ID) {
221#define DEF_VALUE(ID, CLASS) \
222 case ClassID::ID: \
223 return #ID;
224#define DEF_USER(ID, CLASS) \
225 case ClassID::ID: \
226 return #ID;
227#define DEF_INSTR(ID, OPC, CLASS) \
228 case ClassID::ID: \
229 return #ID;
230#include "llvm/SandboxIR/SandboxIRValues.def"
231 }
232 llvm_unreachable("Unimplemented ID");
233 }
234
235 /// For isa/dyn_cast.
237#ifndef NDEBUG
238 /// A unique ID used for forming the name (used for debugging).
239 unsigned UID;
240#endif
241 /// The LLVM Value that corresponds to this SandboxIR Value.
242 /// NOTE: Some sandboxir Instructions, like Packs, may include more than one
243 /// value and in these cases `Val` points to the last instruction in program
244 /// order.
245 llvm::Value *Val = nullptr;
246
247 friend class Context; // For getting `Val`.
248 friend class User; // For getting `Val`.
249 friend class Use; // For getting `Val`.
250 friend class SelectInst; // For getting `Val`.
251 friend class ExtractElementInst; // For getting `Val`.
252 friend class InsertElementInst; // For getting `Val`.
253 friend class ShuffleVectorInst; // For getting `Val`.
254 friend class BranchInst; // For getting `Val`.
255 friend class LoadInst; // For getting `Val`.
256 friend class StoreInst; // For getting `Val`.
257 friend class ReturnInst; // For getting `Val`.
258 friend class CallBase; // For getting `Val`.
259 friend class CallInst; // For getting `Val`.
260 friend class InvokeInst; // For getting `Val`.
261 friend class CallBrInst; // For getting `Val`.
262 friend class FuncletPadInst; // For getting `Val`.
263 friend class CatchPadInst; // For getting `Val`.
264 friend class CleanupPadInst; // For getting `Val`.
265 friend class GetElementPtrInst; // For getting `Val`.
266 friend class CatchSwitchInst; // For getting `Val`.
267 friend class SwitchInst; // For getting `Val`.
268 friend class UnaryOperator; // For getting `Val`.
269 friend class BinaryOperator; // For getting `Val`.
270 friend class AtomicRMWInst; // For getting `Val`.
271 friend class AtomicCmpXchgInst; // For getting `Val`.
272 friend class AllocaInst; // For getting `Val`.
273 friend class CastInst; // For getting `Val`.
274 friend class PHINode; // For getting `Val`.
275 friend class UnreachableInst; // For getting `Val`.
276 friend class CatchSwitchAddHandler; // For `Val`.
277
278 /// All values point to the context.
280 // This is used by eraseFromParent().
281 void clearValue() { Val = nullptr; }
282 template <typename ItTy, typename SBTy> friend class LLVMOpUserItToSBTy;
283
285 /// Disable copies.
286 Value(const Value &) = delete;
287 Value &operator=(const Value &) = delete;
288
289public:
290 virtual ~Value() = default;
291 ClassID getSubclassID() const { return SubclassID; }
292
295
298 return const_cast<Value *>(this)->use_begin();
299 }
300 use_iterator use_end() { return use_iterator(Use(nullptr, nullptr, Ctx)); }
302 return const_cast<Value *>(this)->use_end();
303 }
304
306 return make_range<use_iterator>(use_begin(), use_end());
307 }
309 return make_range<const_use_iterator>(use_begin(), use_end());
310 }
311
312 /// Helper for mapped_iterator.
313 struct UseToUser {
314 User *operator()(const Use &Use) const { return &*Use.getUser(); }
315 };
316
319
322 return user_iterator(Use(nullptr, nullptr, Ctx), UseToUser());
323 }
325 return const_cast<Value *>(this)->user_begin();
326 }
328 return const_cast<Value *>(this)->user_end();
329 }
330
332 return make_range<user_iterator>(user_begin(), user_end());
333 }
335 return make_range<const_user_iterator>(user_begin(), user_end());
336 }
337 /// \Returns the number of user edges (not necessarily to unique users).
338 /// WARNING: This is a linear-time operation.
339 unsigned getNumUses() const;
340 /// Return true if this value has N uses or more.
341 /// This is logically equivalent to getNumUses() >= N.
342 /// WARNING: This can be expensive, as it is linear to the number of users.
343 bool hasNUsesOrMore(unsigned Num) const {
344 unsigned Cnt = 0;
345 for (auto It = use_begin(), ItE = use_end(); It != ItE; ++It) {
346 if (++Cnt >= Num)
347 return true;
348 }
349 return false;
350 }
351 /// Return true if this Value has exactly N uses.
352 bool hasNUses(unsigned Num) const {
353 unsigned Cnt = 0;
354 for (auto It = use_begin(), ItE = use_end(); It != ItE; ++It) {
355 if (++Cnt > Num)
356 return false;
357 }
358 return Cnt == Num;
359 }
360
361 Type *getType() const { return Val->getType(); }
362
363 Context &getContext() const { return Ctx; }
364
365 void replaceUsesWithIf(Value *OtherV,
366 llvm::function_ref<bool(const Use &)> ShouldReplace);
368
369 /// \Returns the LLVM IR name of the bottom-most LLVM value.
370 StringRef getName() const { return Val->getName(); }
371
372#ifndef NDEBUG
373 /// Should crash if there is something wrong with the instruction.
374 virtual void verify() const = 0;
375 /// Returns the unique id in the form 'SB<number>.' like 'SB1.'
376 std::string getUid() const;
377 virtual void dumpCommonHeader(raw_ostream &OS) const;
378 void dumpCommonFooter(raw_ostream &OS) const;
379 void dumpCommonPrefix(raw_ostream &OS) const;
380 void dumpCommonSuffix(raw_ostream &OS) const;
383 V.dumpOS(OS);
384 return OS;
385 }
386 virtual void dumpOS(raw_ostream &OS) const = 0;
387 LLVM_DUMP_METHOD void dump() const;
388#endif
389};
390
391/// Argument of a sandboxir::Function.
394 : sandboxir::Value(ClassID::Argument, Arg, Ctx) {}
395 friend class Context; // For constructor.
396
397public:
398 static bool classof(const sandboxir::Value *From) {
399 return From->getSubclassID() == ClassID::Argument;
400 }
401#ifndef NDEBUG
402 void verify() const final {
403 assert(isa<llvm::Argument>(Val) && "Expected Argument!");
404 }
405 void printAsOperand(raw_ostream &OS) const;
406 void dumpOS(raw_ostream &OS) const final;
407#endif
408};
409
410/// A sandboxir::User has operands.
411class User : public Value {
412protected:
414
415 /// \Returns the Use edge that corresponds to \p OpIdx.
416 /// Note: This is the default implementation that works for instructions that
417 /// match the underlying LLVM instruction. All others should use a different
418 /// implementation.
419 Use getOperandUseDefault(unsigned OpIdx, bool Verify) const;
420 /// \Returns the Use for the \p OpIdx'th operand. This is virtual to allow
421 /// instructions to deviate from the LLVM IR operands, which is a requirement
422 /// for sandboxir Instructions that consist of more than one LLVM Instruction.
423 virtual Use getOperandUseInternal(unsigned OpIdx, bool Verify) const = 0;
424 friend class OperandUseIterator; // for getOperandUseInternal()
425
426 /// The default implementation works only for single-LLVMIR-instruction
427 /// Users and only if they match exactly the LLVM instruction.
428 unsigned getUseOperandNoDefault(const Use &Use) const {
429 return Use.LLVMUse->getOperandNo();
430 }
431 /// \Returns the operand index of \p Use.
432 virtual unsigned getUseOperandNo(const Use &Use) const = 0;
433 friend unsigned Use::getOperandNo() const; // For getUseOperandNo()
434
435 void swapOperandsInternal(unsigned OpIdxA, unsigned OpIdxB) {
436 assert(OpIdxA < getNumOperands() && "OpIdxA out of bounds!");
437 assert(OpIdxB < getNumOperands() && "OpIdxB out of bounds!");
438 auto UseA = getOperandUse(OpIdxA);
439 auto UseB = getOperandUse(OpIdxB);
440 UseA.swap(UseB);
441 }
442
443#ifndef NDEBUG
444 void verifyUserOfLLVMUse(const llvm::Use &Use) const;
445#endif // NDEBUG
446
447public:
448 /// For isa/dyn_cast.
449 static bool classof(const Value *From);
454
456 assert(isa<llvm::User>(Val) && "Expect User value!");
457 return op_iterator(getOperandUseInternal(0, /*Verify=*/false));
458 }
459 virtual op_iterator op_end() {
460 assert(isa<llvm::User>(Val) && "Expect User value!");
461 return op_iterator(
462 getOperandUseInternal(getNumOperands(), /*Verify=*/false));
463 }
464 virtual const_op_iterator op_begin() const {
465 return const_cast<User *>(this)->op_begin();
466 }
467 virtual const_op_iterator op_end() const {
468 return const_cast<User *>(this)->op_end();
469 }
470
471 op_range operands() { return make_range<op_iterator>(op_begin(), op_end()); }
473 return make_range<const_op_iterator>(op_begin(), op_end());
474 }
475 Value *getOperand(unsigned OpIdx) const { return getOperandUse(OpIdx).get(); }
476 /// \Returns the operand edge for \p OpIdx. NOTE: This should also work for
477 /// OpIdx == getNumOperands(), which is used for op_end().
478 Use getOperandUse(unsigned OpIdx) const {
479 return getOperandUseInternal(OpIdx, /*Verify=*/true);
480 }
481 virtual unsigned getNumOperands() const {
482 return isa<llvm::User>(Val) ? cast<llvm::User>(Val)->getNumOperands() : 0;
483 }
484
485 virtual void setOperand(unsigned OperandIdx, Value *Operand);
486 /// Replaces any operands that match \p FromV with \p ToV. Returns whether any
487 /// operands were replaced.
488 bool replaceUsesOfWith(Value *FromV, Value *ToV);
489
490#ifndef NDEBUG
491 void verify() const override {
492 assert(isa<llvm::User>(Val) && "Expected User!");
493 }
494 void dumpCommonHeader(raw_ostream &OS) const final;
495 void dumpOS(raw_ostream &OS) const override {
496 // TODO: Remove this tmp implementation once we get the Instruction classes.
497 }
498#endif
499};
500
501class Constant : public sandboxir::User {
503 : sandboxir::User(ClassID::Constant, C, SBCtx) {}
505 : sandboxir::User(ID, C, SBCtx) {}
506 friend class ConstantInt; // For constructor.
507 friend class Function; // For constructor
508 friend class Context; // For constructor.
509 Use getOperandUseInternal(unsigned OpIdx, bool Verify) const override {
510 return getOperandUseDefault(OpIdx, Verify);
511 }
512
513public:
514 /// For isa/dyn_cast.
515 static bool classof(const sandboxir::Value *From) {
516 return From->getSubclassID() == ClassID::Constant ||
517 From->getSubclassID() == ClassID::ConstantInt ||
518 From->getSubclassID() == ClassID::Function;
519 }
521 unsigned getUseOperandNo(const Use &Use) const override {
523 }
524#ifndef NDEBUG
525 void verify() const override {
526 assert(isa<llvm::Constant>(Val) && "Expected Constant!");
527 }
528 void dumpOS(raw_ostream &OS) const override;
529#endif
530};
531
532class ConstantInt : public Constant {
534 : Constant(ClassID::ConstantInt, C, Ctx) {}
535 friend class Context; // For constructor.
536
537 Use getOperandUseInternal(unsigned OpIdx, bool Verify) const final {
538 llvm_unreachable("ConstantInt has no operands!");
539 }
540
541public:
542 /// If Ty is a vector type, return a Constant with a splat of the given
543 /// value. Otherwise return a ConstantInt for the given value.
544 static ConstantInt *get(Type *Ty, uint64_t V, Context &Ctx,
545 bool IsSigned = false);
546
547 // TODO: Implement missing functions.
548
549 /// For isa/dyn_cast.
550 static bool classof(const sandboxir::Value *From) {
551 return From->getSubclassID() == ClassID::ConstantInt;
552 }
553 unsigned getUseOperandNo(const Use &Use) const override {
554 llvm_unreachable("ConstantInt has no operands!");
555 }
556#ifndef NDEBUG
557 void verify() const override {
558 assert(isa<llvm::ConstantInt>(Val) && "Expected a ConstantInst!");
559 }
560 void dumpOS(raw_ostream &OS) const override {
563 }
564#endif
565};
566
567/// Iterator for `Instruction`s in a `BasicBlock.
568/// \Returns an sandboxir::Instruction & when derereferenced.
570public:
571 using difference_type = std::ptrdiff_t;
575 using iterator_category = std::bidirectional_iterator_tag;
576
577private:
580 Context *Ctx;
581 pointer getInstr(llvm::BasicBlock::iterator It) const;
582
583public:
584 BBIterator() : BB(nullptr), Ctx(nullptr) {}
586 : BB(BB), It(It), Ctx(Ctx) {}
587 reference operator*() const { return *getInstr(It); }
590 auto Copy = *this;
591 ++*this;
592 return Copy;
593 }
596 auto Copy = *this;
597 --*this;
598 return Copy;
599 }
600 bool operator==(const BBIterator &Other) const {
601 assert(Ctx == Other.Ctx && "BBIterators in different context!");
602 return It == Other.It;
603 }
604 bool operator!=(const BBIterator &Other) const { return !(*this == Other); }
605 /// \Returns the SBInstruction that corresponds to this iterator, or null if
606 /// the instruction is not found in the IR-to-SandboxIR tables.
607 pointer get() const { return getInstr(It); }
608};
609
610/// Contains a list of sandboxir::Instruction's.
611class BasicBlock : public Value {
612 /// Builds a graph that contains all values in \p BB in their original form
613 /// i.e., no vectorization is taking place here.
614 void buildBasicBlockFromLLVMIR(llvm::BasicBlock *LLVMBB);
615 friend class Context; // For `buildBasicBlockFromIR`
616 friend class Instruction; // For LLVM Val.
617
619 : Value(ClassID::Block, BB, SBCtx) {
620 buildBasicBlockFromLLVMIR(BB);
621 }
622
623public:
624 ~BasicBlock() = default;
625 /// For isa/dyn_cast.
626 static bool classof(const Value *From) {
627 return From->getSubclassID() == Value::ClassID::Block;
628 }
629 Function *getParent() const;
631 iterator begin() const;
632 iterator end() const {
633 auto *BB = cast<llvm::BasicBlock>(Val);
634 return iterator(BB, BB->end(), &Ctx);
635 }
636 std::reverse_iterator<iterator> rbegin() const {
637 return std::make_reverse_iterator(end());
638 }
639 std::reverse_iterator<iterator> rend() const {
640 return std::make_reverse_iterator(begin());
641 }
642 Context &getContext() const { return Ctx; }
643 Instruction *getTerminator() const;
644 bool empty() const { return begin() == end(); }
645 Instruction &front() const;
646 Instruction &back() const;
647
648#ifndef NDEBUG
649 void verify() const final {
650 assert(isa<llvm::BasicBlock>(Val) && "Expected BasicBlock!");
651 }
652 void dumpOS(raw_ostream &OS) const final;
653#endif
654};
655
656/// A sandboxir::User with operands, opcode and linked with previous/next
657/// instructions in an instruction list.
659public:
660 enum class Opcode {
661#define OP(OPC) OPC,
662#define OPCODES(...) __VA_ARGS__
663#define DEF_INSTR(ID, OPC, CLASS) OPC
664#include "llvm/SandboxIR/SandboxIRValues.def"
665 };
666
667protected:
669 sandboxir::Context &SBCtx)
670 : sandboxir::User(ID, I, SBCtx), Opc(Opc) {}
671
673
674 /// A SandboxIR Instruction may map to multiple LLVM IR Instruction. This
675 /// returns its topmost LLVM IR instruction.
677 friend class SelectInst; // For getTopmostLLVMInstruction().
678 friend class ExtractElementInst; // For getTopmostLLVMInstruction().
679 friend class InsertElementInst; // For getTopmostLLVMInstruction().
680 friend class ShuffleVectorInst; // For getTopmostLLVMInstruction().
681 friend class BranchInst; // For getTopmostLLVMInstruction().
682 friend class LoadInst; // For getTopmostLLVMInstruction().
683 friend class StoreInst; // For getTopmostLLVMInstruction().
684 friend class ReturnInst; // For getTopmostLLVMInstruction().
685 friend class CallInst; // For getTopmostLLVMInstruction().
686 friend class InvokeInst; // For getTopmostLLVMInstruction().
687 friend class CallBrInst; // For getTopmostLLVMInstruction().
688 friend class CatchPadInst; // For getTopmostLLVMInstruction().
689 friend class CleanupPadInst; // For getTopmostLLVMInstruction().
690 friend class GetElementPtrInst; // For getTopmostLLVMInstruction().
691 friend class CatchSwitchInst; // For getTopmostLLVMInstruction().
692 friend class SwitchInst; // For getTopmostLLVMInstruction().
693 friend class UnaryOperator; // For getTopmostLLVMInstruction().
694 friend class BinaryOperator; // For getTopmostLLVMInstruction().
695 friend class AtomicRMWInst; // For getTopmostLLVMInstruction().
696 friend class AtomicCmpXchgInst; // For getTopmostLLVMInstruction().
697 friend class AllocaInst; // For getTopmostLLVMInstruction().
698 friend class CastInst; // For getTopmostLLVMInstruction().
699 friend class PHINode; // For getTopmostLLVMInstruction().
700 friend class UnreachableInst; // For getTopmostLLVMInstruction().
701
702 /// \Returns the LLVM IR Instructions that this SandboxIR maps to in program
703 /// order.
705 friend class EraseFromParent; // For getLLVMInstrs().
706
707public:
708 static const char *getOpcodeName(Opcode Opc);
709 /// This is used by BasicBlock::iterator.
710 virtual unsigned getNumOfIRInstrs() const = 0;
711 /// \Returns a BasicBlock::iterator for this Instruction.
712 BBIterator getIterator() const;
713 /// \Returns the next sandboxir::Instruction in the block, or nullptr if at
714 /// the end of the block.
715 Instruction *getNextNode() const;
716 /// \Returns the previous sandboxir::Instruction in the block, or nullptr if
717 /// at the beginning of the block.
718 Instruction *getPrevNode() const;
719 /// \Returns this Instruction's opcode. Note that SandboxIR has its own opcode
720 /// state to allow for new SandboxIR-specific instructions.
721 Opcode getOpcode() const { return Opc; }
722 /// Detach this from its parent BasicBlock without deleting it.
723 void removeFromParent();
724 /// Detach this Value from its parent and delete it.
725 void eraseFromParent();
726 /// Insert this detached instruction before \p BeforeI.
727 void insertBefore(Instruction *BeforeI);
728 /// Insert this detached instruction after \p AfterI.
729 void insertAfter(Instruction *AfterI);
730 /// Insert this detached instruction into \p BB at \p WhereIt.
731 void insertInto(BasicBlock *BB, const BBIterator &WhereIt);
732 /// Move this instruction to \p WhereIt.
733 void moveBefore(BasicBlock &BB, const BBIterator &WhereIt);
734 /// Move this instruction before \p Before.
736 moveBefore(*Before->getParent(), Before->getIterator());
737 }
738 /// Move this instruction after \p After.
740 moveBefore(*After->getParent(), std::next(After->getIterator()));
741 }
742 /// \Returns the BasicBlock containing this Instruction, or null if it is
743 /// detached.
744 BasicBlock *getParent() const;
745 /// For isa/dyn_cast.
746 static bool classof(const sandboxir::Value *From);
747
748 /// Determine whether the no signed wrap flag is set.
749 bool hasNoUnsignedWrap() const {
750 return cast<llvm::Instruction>(Val)->hasNoUnsignedWrap();
751 }
752 /// Set or clear the nuw flag on this instruction, which must be an operator
753 /// which supports this flag. See LangRef.html for the meaning of this flag.
754 void setHasNoUnsignedWrap(bool B = true);
755 /// Determine whether the no signed wrap flag is set.
756 bool hasNoSignedWrap() const {
757 return cast<llvm::Instruction>(Val)->hasNoSignedWrap();
758 }
759 /// Set or clear the nsw flag on this instruction, which must be an operator
760 /// which supports this flag. See LangRef.html for the meaning of this flag.
761 void setHasNoSignedWrap(bool B = true);
762 /// Determine whether all fast-math-flags are set.
763 bool isFast() const { return cast<llvm::Instruction>(Val)->isFast(); }
764 /// Set or clear all fast-math-flags on this instruction, which must be an
765 /// operator which supports this flag. See LangRef.html for the meaning of
766 /// this flag.
767 void setFast(bool B);
768 /// Determine whether the allow-reassociation flag is set.
769 bool hasAllowReassoc() const {
770 return cast<llvm::Instruction>(Val)->hasAllowReassoc();
771 }
772 /// Set or clear the reassociation flag on this instruction, which must be
773 /// an operator which supports this flag. See LangRef.html for the meaning of
774 /// this flag.
775 void setHasAllowReassoc(bool B);
776 /// Determine whether the exact flag is set.
777 bool isExact() const { return cast<llvm::Instruction>(Val)->isExact(); }
778 /// Set or clear the exact flag on this instruction, which must be an operator
779 /// which supports this flag. See LangRef.html for the meaning of this flag.
780 void setIsExact(bool B = true);
781 /// Determine whether the no-NaNs flag is set.
782 bool hasNoNaNs() const { return cast<llvm::Instruction>(Val)->hasNoNaNs(); }
783 /// Set or clear the no-nans flag on this instruction, which must be an
784 /// operator which supports this flag. See LangRef.html for the meaning of
785 /// this flag.
786 void setHasNoNaNs(bool B);
787 /// Determine whether the no-infs flag is set.
788 bool hasNoInfs() const { return cast<llvm::Instruction>(Val)->hasNoInfs(); }
789 /// Set or clear the no-infs flag on this instruction, which must be an
790 /// operator which supports this flag. See LangRef.html for the meaning of
791 /// this flag.
792 void setHasNoInfs(bool B);
793 /// Determine whether the no-signed-zeros flag is set.
794 bool hasNoSignedZeros() const {
795 return cast<llvm::Instruction>(Val)->hasNoSignedZeros();
796 }
797 /// Set or clear the no-signed-zeros flag on this instruction, which must be
798 /// an operator which supports this flag. See LangRef.html for the meaning of
799 /// this flag.
800 void setHasNoSignedZeros(bool B);
801 /// Determine whether the allow-reciprocal flag is set.
802 bool hasAllowReciprocal() const {
803 return cast<llvm::Instruction>(Val)->hasAllowReciprocal();
804 }
805 /// Set or clear the allow-reciprocal flag on this instruction, which must be
806 /// an operator which supports this flag. See LangRef.html for the meaning of
807 /// this flag.
808 void setHasAllowReciprocal(bool B);
809 /// Determine whether the allow-contract flag is set.
810 bool hasAllowContract() const {
811 return cast<llvm::Instruction>(Val)->hasAllowContract();
812 }
813 /// Set or clear the allow-contract flag on this instruction, which must be
814 /// an operator which supports this flag. See LangRef.html for the meaning of
815 /// this flag.
816 void setHasAllowContract(bool B);
817 /// Determine whether the approximate-math-functions flag is set.
818 bool hasApproxFunc() const {
819 return cast<llvm::Instruction>(Val)->hasApproxFunc();
820 }
821 /// Set or clear the approximate-math-functions flag on this instruction,
822 /// which must be an operator which supports this flag. See LangRef.html for
823 /// the meaning of this flag.
824 void setHasApproxFunc(bool B);
825 /// Convenience function for getting all the fast-math flags, which must be an
826 /// operator which supports these flags. See LangRef.html for the meaning of
827 /// these flags.
829 return cast<llvm::Instruction>(Val)->getFastMathFlags();
830 }
831 /// Convenience function for setting multiple fast-math flags on this
832 /// instruction, which must be an operator which supports these flags. See
833 /// LangRef.html for the meaning of these flags.
835 /// Convenience function for transferring all fast-math flag values to this
836 /// instruction, which must be an operator which supports these flags. See
837 /// LangRef.html for the meaning of these flags.
839
840#ifndef NDEBUG
841 void dumpOS(raw_ostream &OS) const override;
842#endif
843};
844
845/// Instructions that contain a single LLVM Instruction can inherit from this.
846template <typename LLVMT> class SingleLLVMInstructionImpl : public Instruction {
848 sandboxir::Context &SBCtx)
849 : Instruction(ID, Opc, I, SBCtx) {}
850
851 // All instructions are friends with this so they can call the constructor.
852#define DEF_INSTR(ID, OPC, CLASS) friend class CLASS;
853#include "llvm/SandboxIR/SandboxIRValues.def"
854 friend class UnaryInstruction;
855 friend class CallBase;
856 friend class FuncletPadInst;
857
858 Use getOperandUseInternal(unsigned OpIdx, bool Verify) const final {
859 return getOperandUseDefault(OpIdx, Verify);
860 }
861 SmallVector<llvm::Instruction *, 1> getLLVMInstrs() const final {
862 return {cast<llvm::Instruction>(Val)};
863 }
864
865public:
866 unsigned getUseOperandNo(const Use &Use) const final {
868 }
869 unsigned getNumOfIRInstrs() const final { return 1u; }
870#ifndef NDEBUG
871 void verify() const final { assert(isa<LLVMT>(Val) && "Expected LLVMT!"); }
872 void dumpOS(raw_ostream &OS) const override {
875 }
876#endif
877};
878
879class SelectInst : public SingleLLVMInstructionImpl<llvm::SelectInst> {
880 /// Use Context::createSelectInst(). Don't call the
881 /// constructor directly.
883 : SingleLLVMInstructionImpl(ClassID::Select, Opcode::Select, CI, Ctx) {}
884 friend Context; // for SelectInst()
885 static Value *createCommon(Value *Cond, Value *True, Value *False,
886 const Twine &Name, IRBuilder<> &Builder,
887 Context &Ctx);
888
889public:
890 static Value *create(Value *Cond, Value *True, Value *False,
891 Instruction *InsertBefore, Context &Ctx,
892 const Twine &Name = "");
893 static Value *create(Value *Cond, Value *True, Value *False,
894 BasicBlock *InsertAtEnd, Context &Ctx,
895 const Twine &Name = "");
896 Value *getCondition() { return getOperand(0); }
897 Value *getTrueValue() { return getOperand(1); }
899
900 void setCondition(Value *New) { setOperand(0, New); }
901 void setTrueValue(Value *New) { setOperand(1, New); }
902 void setFalseValue(Value *New) { setOperand(2, New); }
903 void swapValues() { cast<llvm::SelectInst>(Val)->swapValues(); }
904 /// For isa/dyn_cast.
905 static bool classof(const Value *From);
906};
907
909 : public SingleLLVMInstructionImpl<llvm::InsertElementInst> {
910 /// Use Context::createInsertElementInst() instead.
912 : SingleLLVMInstructionImpl(ClassID::InsertElement, Opcode::InsertElement,
913 I, Ctx) {}
914 friend class Context; // For accessing the constructor in create*()
915
916public:
917 static Value *create(Value *Vec, Value *NewElt, Value *Idx,
918 Instruction *InsertBefore, Context &Ctx,
919 const Twine &Name = "");
920 static Value *create(Value *Vec, Value *NewElt, Value *Idx,
921 BasicBlock *InsertAtEnd, Context &Ctx,
922 const Twine &Name = "");
923 static bool classof(const Value *From) {
924 return From->getSubclassID() == ClassID::InsertElement;
925 }
926 static bool isValidOperands(const Value *Vec, const Value *NewElt,
927 const Value *Idx) {
929 Idx->Val);
930 }
931};
932
934 : public SingleLLVMInstructionImpl<llvm::ExtractElementInst> {
935 /// Use Context::createExtractElementInst() instead.
937 : SingleLLVMInstructionImpl(ClassID::ExtractElement,
938 Opcode::ExtractElement, I, Ctx) {}
939 friend class Context; // For accessing the constructor in
940 // create*()
941
942public:
943 static Value *create(Value *Vec, Value *Idx, Instruction *InsertBefore,
944 Context &Ctx, const Twine &Name = "");
945 static Value *create(Value *Vec, Value *Idx, BasicBlock *InsertAtEnd,
946 Context &Ctx, const Twine &Name = "");
947 static bool classof(const Value *From) {
948 return From->getSubclassID() == ClassID::ExtractElement;
949 }
950
951 static bool isValidOperands(const Value *Vec, const Value *Idx) {
953 }
956 const Value *getVectorOperand() const { return getOperand(0); }
957 const Value *getIndexOperand() const { return getOperand(1); }
958
960 return cast<VectorType>(getVectorOperand()->getType());
961 }
962};
963
965 : public SingleLLVMInstructionImpl<llvm::ShuffleVectorInst> {
966 /// Use Context::createShuffleVectorInst() instead.
968 : SingleLLVMInstructionImpl(ClassID::ShuffleVector, Opcode::ShuffleVector,
969 I, Ctx) {}
970 friend class Context; // For accessing the constructor in create*()
971
972public:
973 static Value *create(Value *V1, Value *V2, Value *Mask,
974 Instruction *InsertBefore, Context &Ctx,
975 const Twine &Name = "");
976 static Value *create(Value *V1, Value *V2, Value *Mask,
977 BasicBlock *InsertAtEnd, Context &Ctx,
978 const Twine &Name = "");
979 static Value *create(Value *V1, Value *V2, ArrayRef<int> Mask,
980 Instruction *InsertBefore, Context &Ctx,
981 const Twine &Name = "");
982 static Value *create(Value *V1, Value *V2, ArrayRef<int> Mask,
983 BasicBlock *InsertAtEnd, Context &Ctx,
984 const Twine &Name = "");
985 static bool classof(const Value *From) {
986 return From->getSubclassID() == ClassID::ShuffleVector;
987 }
988
989 /// Swap the operands and adjust the mask to preserve the semantics of the
990 /// instruction.
991 void commute() { cast<llvm::ShuffleVectorInst>(Val)->commute(); }
992
993 /// Return true if a shufflevector instruction can be formed with the
994 /// specified operands.
995 static bool isValidOperands(const Value *V1, const Value *V2,
996 const Value *Mask) {
998 Mask->Val);
999 }
1000 static bool isValidOperands(const Value *V1, const Value *V2,
1001 ArrayRef<int> Mask) {
1002 return llvm::ShuffleVectorInst::isValidOperands(V1->Val, V2->Val, Mask);
1003 }
1004
1005 /// Overload to return most specific vector type.
1007 return cast<llvm::ShuffleVectorInst>(Val)->getType();
1008 }
1009
1010 /// Return the shuffle mask value of this instruction for the given element
1011 /// index. Return PoisonMaskElem if the element is undef.
1012 int getMaskValue(unsigned Elt) const {
1013 return cast<llvm::ShuffleVectorInst>(Val)->getMaskValue(Elt);
1014 }
1015
1016 /// Convert the input shuffle mask operand to a vector of integers. Undefined
1017 /// elements of the mask are returned as PoisonMaskElem.
1018 static void getShuffleMask(const Constant *Mask,
1019 SmallVectorImpl<int> &Result) {
1020 llvm::ShuffleVectorInst::getShuffleMask(cast<llvm::Constant>(Mask->Val),
1021 Result);
1022 }
1023
1024 /// Return the mask for this instruction as a vector of integers. Undefined
1025 /// elements of the mask are returned as PoisonMaskElem.
1027 cast<llvm::ShuffleVectorInst>(Val)->getShuffleMask(Result);
1028 }
1029
1030 /// Return the mask for this instruction, for use in bitcode.
1032
1034 Type *ResultTy, Context &Ctx);
1035
1036 void setShuffleMask(ArrayRef<int> Mask);
1037
1039 return cast<llvm::ShuffleVectorInst>(Val)->getShuffleMask();
1040 }
1041
1042 /// Return true if this shuffle returns a vector with a different number of
1043 /// elements than its source vectors.
1044 /// Examples: shufflevector <4 x n> A, <4 x n> B, <1,2,3>
1045 /// shufflevector <4 x n> A, <4 x n> B, <1,2,3,4,5>
1046 bool changesLength() const {
1047 return cast<llvm::ShuffleVectorInst>(Val)->changesLength();
1048 }
1049
1050 /// Return true if this shuffle returns a vector with a greater number of
1051 /// elements than its source vectors.
1052 /// Example: shufflevector <2 x n> A, <2 x n> B, <1,2,3>
1053 bool increasesLength() const {
1054 return cast<llvm::ShuffleVectorInst>(Val)->increasesLength();
1055 }
1056
1057 /// Return true if this shuffle mask chooses elements from exactly one source
1058 /// vector.
1059 /// Example: <7,5,undef,7>
1060 /// This assumes that vector operands (of length \p NumSrcElts) are the same
1061 /// length as the mask.
1062 static bool isSingleSourceMask(ArrayRef<int> Mask, int NumSrcElts) {
1063 return llvm::ShuffleVectorInst::isSingleSourceMask(Mask, NumSrcElts);
1064 }
1065 static bool isSingleSourceMask(const Constant *Mask, int NumSrcElts) {
1067 cast<llvm::Constant>(Mask->Val), NumSrcElts);
1068 }
1069
1070 /// Return true if this shuffle chooses elements from exactly one source
1071 /// vector without changing the length of that vector.
1072 /// Example: shufflevector <4 x n> A, <4 x n> B, <3,0,undef,3>
1073 bool isSingleSource() const {
1074 return cast<llvm::ShuffleVectorInst>(Val)->isSingleSource();
1075 }
1076
1077 /// Return true if this shuffle mask chooses elements from exactly one source
1078 /// vector without lane crossings. A shuffle using this mask is not
1079 /// necessarily a no-op because it may change the number of elements from its
1080 /// input vectors or it may provide demanded bits knowledge via undef lanes.
1081 /// Example: <undef,undef,2,3>
1082 static bool isIdentityMask(ArrayRef<int> Mask, int NumSrcElts) {
1083 return llvm::ShuffleVectorInst::isIdentityMask(Mask, NumSrcElts);
1084 }
1085 static bool isIdentityMask(const Constant *Mask, int NumSrcElts) {
1087 cast<llvm::Constant>(Mask->Val), NumSrcElts);
1088 }
1089
1090 /// Return true if this shuffle chooses elements from exactly one source
1091 /// vector without lane crossings and does not change the number of elements
1092 /// from its input vectors.
1093 /// Example: shufflevector <4 x n> A, <4 x n> B, <4,undef,6,undef>
1094 bool isIdentity() const {
1095 return cast<llvm::ShuffleVectorInst>(Val)->isIdentity();
1096 }
1097
1098 /// Return true if this shuffle lengthens exactly one source vector with
1099 /// undefs in the high elements.
1101 return cast<llvm::ShuffleVectorInst>(Val)->isIdentityWithPadding();
1102 }
1103
1104 /// Return true if this shuffle extracts the first N elements of exactly one
1105 /// source vector.
1107 return cast<llvm::ShuffleVectorInst>(Val)->isIdentityWithExtract();
1108 }
1109
1110 /// Return true if this shuffle concatenates its 2 source vectors. This
1111 /// returns false if either input is undefined. In that case, the shuffle is
1112 /// is better classified as an identity with padding operation.
1113 bool isConcat() const {
1114 return cast<llvm::ShuffleVectorInst>(Val)->isConcat();
1115 }
1116
1117 /// Return true if this shuffle mask chooses elements from its source vectors
1118 /// without lane crossings. A shuffle using this mask would be
1119 /// equivalent to a vector select with a constant condition operand.
1120 /// Example: <4,1,6,undef>
1121 /// This returns false if the mask does not choose from both input vectors.
1122 /// In that case, the shuffle is better classified as an identity shuffle.
1123 /// This assumes that vector operands are the same length as the mask
1124 /// (a length-changing shuffle can never be equivalent to a vector select).
1125 static bool isSelectMask(ArrayRef<int> Mask, int NumSrcElts) {
1126 return llvm::ShuffleVectorInst::isSelectMask(Mask, NumSrcElts);
1127 }
1128 static bool isSelectMask(const Constant *Mask, int NumSrcElts) {
1130 cast<llvm::Constant>(Mask->Val), NumSrcElts);
1131 }
1132
1133 /// Return true if this shuffle chooses elements from its source vectors
1134 /// without lane crossings and all operands have the same number of elements.
1135 /// In other words, this shuffle is equivalent to a vector select with a
1136 /// constant condition operand.
1137 /// Example: shufflevector <4 x n> A, <4 x n> B, <undef,1,6,3>
1138 /// This returns false if the mask does not choose from both input vectors.
1139 /// In that case, the shuffle is better classified as an identity shuffle.
1140 bool isSelect() const {
1141 return cast<llvm::ShuffleVectorInst>(Val)->isSelect();
1142 }
1143
1144 /// Return true if this shuffle mask swaps the order of elements from exactly
1145 /// one source vector.
1146 /// Example: <7,6,undef,4>
1147 /// This assumes that vector operands (of length \p NumSrcElts) are the same
1148 /// length as the mask.
1149 static bool isReverseMask(ArrayRef<int> Mask, int NumSrcElts) {
1150 return llvm::ShuffleVectorInst::isReverseMask(Mask, NumSrcElts);
1151 }
1152 static bool isReverseMask(const Constant *Mask, int NumSrcElts) {
1154 cast<llvm::Constant>(Mask->Val), NumSrcElts);
1155 }
1156
1157 /// Return true if this shuffle swaps the order of elements from exactly
1158 /// one source vector.
1159 /// Example: shufflevector <4 x n> A, <4 x n> B, <3,undef,1,undef>
1160 bool isReverse() const {
1161 return cast<llvm::ShuffleVectorInst>(Val)->isReverse();
1162 }
1163
1164 /// Return true if this shuffle mask chooses all elements with the same value
1165 /// as the first element of exactly one source vector.
1166 /// Example: <4,undef,undef,4>
1167 /// This assumes that vector operands (of length \p NumSrcElts) are the same
1168 /// length as the mask.
1169 static bool isZeroEltSplatMask(ArrayRef<int> Mask, int NumSrcElts) {
1170 return llvm::ShuffleVectorInst::isZeroEltSplatMask(Mask, NumSrcElts);
1171 }
1172 static bool isZeroEltSplatMask(const Constant *Mask, int NumSrcElts) {
1174 cast<llvm::Constant>(Mask->Val), NumSrcElts);
1175 }
1176
1177 /// Return true if all elements of this shuffle are the same value as the
1178 /// first element of exactly one source vector without changing the length
1179 /// of that vector.
1180 /// Example: shufflevector <4 x n> A, <4 x n> B, <undef,0,undef,0>
1181 bool isZeroEltSplat() const {
1182 return cast<llvm::ShuffleVectorInst>(Val)->isZeroEltSplat();
1183 }
1184
1185 /// Return true if this shuffle mask is a transpose mask.
1186 /// Transpose vector masks transpose a 2xn matrix. They read corresponding
1187 /// even- or odd-numbered vector elements from two n-dimensional source
1188 /// vectors and write each result into consecutive elements of an
1189 /// n-dimensional destination vector. Two shuffles are necessary to complete
1190 /// the transpose, one for the even elements and another for the odd elements.
1191 /// This description closely follows how the TRN1 and TRN2 AArch64
1192 /// instructions operate.
1193 ///
1194 /// For example, a simple 2x2 matrix can be transposed with:
1195 ///
1196 /// ; Original matrix
1197 /// m0 = < a, b >
1198 /// m1 = < c, d >
1199 ///
1200 /// ; Transposed matrix
1201 /// t0 = < a, c > = shufflevector m0, m1, < 0, 2 >
1202 /// t1 = < b, d > = shufflevector m0, m1, < 1, 3 >
1203 ///
1204 /// For matrices having greater than n columns, the resulting nx2 transposed
1205 /// matrix is stored in two result vectors such that one vector contains
1206 /// interleaved elements from all the even-numbered rows and the other vector
1207 /// contains interleaved elements from all the odd-numbered rows. For example,
1208 /// a 2x4 matrix can be transposed with:
1209 ///
1210 /// ; Original matrix
1211 /// m0 = < a, b, c, d >
1212 /// m1 = < e, f, g, h >
1213 ///
1214 /// ; Transposed matrix
1215 /// t0 = < a, e, c, g > = shufflevector m0, m1 < 0, 4, 2, 6 >
1216 /// t1 = < b, f, d, h > = shufflevector m0, m1 < 1, 5, 3, 7 >
1217 static bool isTransposeMask(ArrayRef<int> Mask, int NumSrcElts) {
1218 return llvm::ShuffleVectorInst::isTransposeMask(Mask, NumSrcElts);
1219 }
1220 static bool isTransposeMask(const Constant *Mask, int NumSrcElts) {
1222 cast<llvm::Constant>(Mask->Val), NumSrcElts);
1223 }
1224
1225 /// Return true if this shuffle transposes the elements of its inputs without
1226 /// changing the length of the vectors. This operation may also be known as a
1227 /// merge or interleave. See the description for isTransposeMask() for the
1228 /// exact specification.
1229 /// Example: shufflevector <4 x n> A, <4 x n> B, <0,4,2,6>
1230 bool isTranspose() const {
1231 return cast<llvm::ShuffleVectorInst>(Val)->isTranspose();
1232 }
1233
1234 /// Return true if this shuffle mask is a splice mask, concatenating the two
1235 /// inputs together and then extracts an original width vector starting from
1236 /// the splice index.
1237 /// Example: shufflevector <4 x n> A, <4 x n> B, <1,2,3,4>
1238 /// This assumes that vector operands (of length \p NumSrcElts) are the same
1239 /// length as the mask.
1240 static bool isSpliceMask(ArrayRef<int> Mask, int NumSrcElts, int &Index) {
1241 return llvm::ShuffleVectorInst::isSpliceMask(Mask, NumSrcElts, Index);
1242 }
1243 static bool isSpliceMask(const Constant *Mask, int NumSrcElts, int &Index) {
1245 cast<llvm::Constant>(Mask->Val), NumSrcElts, Index);
1246 }
1247
1248 /// Return true if this shuffle splices two inputs without changing the length
1249 /// of the vectors. This operation concatenates the two inputs together and
1250 /// then extracts an original width vector starting from the splice index.
1251 /// Example: shufflevector <4 x n> A, <4 x n> B, <1,2,3,4>
1252 bool isSplice(int &Index) const {
1253 return cast<llvm::ShuffleVectorInst>(Val)->isSplice(Index);
1254 }
1255
1256 /// Return true if this shuffle mask is an extract subvector mask.
1257 /// A valid extract subvector mask returns a smaller vector from a single
1258 /// source operand. The base extraction index is returned as well.
1259 static bool isExtractSubvectorMask(ArrayRef<int> Mask, int NumSrcElts,
1260 int &Index) {
1262 Index);
1263 }
1264 static bool isExtractSubvectorMask(const Constant *Mask, int NumSrcElts,
1265 int &Index) {
1267 cast<llvm::Constant>(Mask->Val), NumSrcElts, Index);
1268 }
1269
1270 /// Return true if this shuffle mask is an extract subvector mask.
1272 return cast<llvm::ShuffleVectorInst>(Val)->isExtractSubvectorMask(Index);
1273 }
1274
1275 /// Return true if this shuffle mask is an insert subvector mask.
1276 /// A valid insert subvector mask inserts the lowest elements of a second
1277 /// source operand into an in-place first source operand.
1278 /// Both the sub vector width and the insertion index is returned.
1279 static bool isInsertSubvectorMask(ArrayRef<int> Mask, int NumSrcElts,
1280 int &NumSubElts, int &Index) {
1281 return llvm::ShuffleVectorInst::isInsertSubvectorMask(Mask, NumSrcElts,
1282 NumSubElts, Index);
1283 }
1284 static bool isInsertSubvectorMask(const Constant *Mask, int NumSrcElts,
1285 int &NumSubElts, int &Index) {
1287 cast<llvm::Constant>(Mask->Val), NumSrcElts, NumSubElts, Index);
1288 }
1289
1290 /// Return true if this shuffle mask is an insert subvector mask.
1291 bool isInsertSubvectorMask(int &NumSubElts, int &Index) const {
1292 return cast<llvm::ShuffleVectorInst>(Val)->isInsertSubvectorMask(NumSubElts,
1293 Index);
1294 }
1295
1296 /// Return true if this shuffle mask replicates each of the \p VF elements
1297 /// in a vector \p ReplicationFactor times.
1298 /// For example, the mask for \p ReplicationFactor=3 and \p VF=4 is:
1299 /// <0,0,0,1,1,1,2,2,2,3,3,3>
1300 static bool isReplicationMask(ArrayRef<int> Mask, int &ReplicationFactor,
1301 int &VF) {
1302 return llvm::ShuffleVectorInst::isReplicationMask(Mask, ReplicationFactor,
1303 VF);
1304 }
1305 static bool isReplicationMask(const Constant *Mask, int &ReplicationFactor,
1306 int &VF) {
1308 cast<llvm::Constant>(Mask->Val), ReplicationFactor, VF);
1309 }
1310
1311 /// Return true if this shuffle mask is a replication mask.
1312 bool isReplicationMask(int &ReplicationFactor, int &VF) const {
1313 return cast<llvm::ShuffleVectorInst>(Val)->isReplicationMask(
1314 ReplicationFactor, VF);
1315 }
1316
1317 /// Return true if this shuffle mask represents "clustered" mask of size VF,
1318 /// i.e. each index between [0..VF) is used exactly once in each submask of
1319 /// size VF.
1320 /// For example, the mask for \p VF=4 is:
1321 /// 0, 1, 2, 3, 3, 2, 0, 1 - "clustered", because each submask of size 4
1322 /// (0,1,2,3 and 3,2,0,1) uses indices [0..VF) exactly one time.
1323 /// 0, 1, 2, 3, 3, 3, 1, 0 - not "clustered", because
1324 /// element 3 is used twice in the second submask
1325 /// (3,3,1,0) and index 2 is not used at all.
1326 static bool isOneUseSingleSourceMask(ArrayRef<int> Mask, int VF) {
1328 }
1329
1330 /// Return true if this shuffle mask is a one-use-single-source("clustered")
1331 /// mask.
1332 bool isOneUseSingleSourceMask(int VF) const {
1333 return cast<llvm::ShuffleVectorInst>(Val)->isOneUseSingleSourceMask(VF);
1334 }
1335
1336 /// Change values in a shuffle permute mask assuming the two vector operands
1337 /// of length InVecNumElts have swapped position.
1339 unsigned InVecNumElts) {
1341 }
1342
1343 /// Return if this shuffle interleaves its two input vectors together.
1344 bool isInterleave(unsigned Factor) const {
1345 return cast<llvm::ShuffleVectorInst>(Val)->isInterleave(Factor);
1346 }
1347
1348 /// Return true if the mask interleaves one or more input vectors together.
1349 ///
1350 /// I.e. <0, LaneLen, ... , LaneLen*(Factor - 1), 1, LaneLen + 1, ...>
1351 /// E.g. For a Factor of 2 (LaneLen=4):
1352 /// <0, 4, 1, 5, 2, 6, 3, 7>
1353 /// E.g. For a Factor of 3 (LaneLen=4):
1354 /// <4, 0, 9, 5, 1, 10, 6, 2, 11, 7, 3, 12>
1355 /// E.g. For a Factor of 4 (LaneLen=2):
1356 /// <0, 2, 6, 4, 1, 3, 7, 5>
1357 ///
1358 /// NumInputElts is the total number of elements in the input vectors.
1359 ///
1360 /// StartIndexes are the first indexes of each vector being interleaved,
1361 /// substituting any indexes that were undef
1362 /// E.g. <4, -1, 2, 5, 1, 3> (Factor=3): StartIndexes=<4, 0, 2>
1363 ///
1364 /// Note that this does not check if the input vectors are consecutive:
1365 /// It will return true for masks such as
1366 /// <0, 4, 6, 1, 5, 7> (Factor=3, LaneLen=2)
1367 static bool isInterleaveMask(ArrayRef<int> Mask, unsigned Factor,
1368 unsigned NumInputElts,
1369 SmallVectorImpl<unsigned> &StartIndexes) {
1370 return llvm::ShuffleVectorInst::isInterleaveMask(Mask, Factor, NumInputElts,
1371 StartIndexes);
1372 }
1373 static bool isInterleaveMask(ArrayRef<int> Mask, unsigned Factor,
1374 unsigned NumInputElts) {
1376 NumInputElts);
1377 }
1378
1379 /// Check if the mask is a DE-interleave mask of the given factor
1380 /// \p Factor like:
1381 /// <Index, Index+Factor, ..., Index+(NumElts-1)*Factor>
1382 static bool isDeInterleaveMaskOfFactor(ArrayRef<int> Mask, unsigned Factor,
1383 unsigned &Index) {
1385 Index);
1386 }
1387 static bool isDeInterleaveMaskOfFactor(ArrayRef<int> Mask, unsigned Factor) {
1389 }
1390
1391 /// Checks if the shuffle is a bit rotation of the first operand across
1392 /// multiple subelements, e.g:
1393 ///
1394 /// shuffle <8 x i8> %a, <8 x i8> poison, <8 x i32> <1, 0, 3, 2, 5, 4, 7, 6>
1395 ///
1396 /// could be expressed as
1397 ///
1398 /// rotl <4 x i16> %a, 8
1399 ///
1400 /// If it can be expressed as a rotation, returns the number of subelements to
1401 /// group by in NumSubElts and the number of bits to rotate left in RotateAmt.
1402 static bool isBitRotateMask(ArrayRef<int> Mask, unsigned EltSizeInBits,
1403 unsigned MinSubElts, unsigned MaxSubElts,
1404 unsigned &NumSubElts, unsigned &RotateAmt) {
1406 Mask, EltSizeInBits, MinSubElts, MaxSubElts, NumSubElts, RotateAmt);
1407 }
1408};
1409
1410class BranchInst : public SingleLLVMInstructionImpl<llvm::BranchInst> {
1411 /// Use Context::createBranchInst(). Don't call the constructor directly.
1413 : SingleLLVMInstructionImpl(ClassID::Br, Opcode::Br, BI, Ctx) {}
1414 friend Context; // for BranchInst()
1415
1416public:
1417 static BranchInst *create(BasicBlock *IfTrue, Instruction *InsertBefore,
1418 Context &Ctx);
1419 static BranchInst *create(BasicBlock *IfTrue, BasicBlock *InsertAtEnd,
1420 Context &Ctx);
1421 static BranchInst *create(BasicBlock *IfTrue, BasicBlock *IfFalse,
1422 Value *Cond, Instruction *InsertBefore,
1423 Context &Ctx);
1424 static BranchInst *create(BasicBlock *IfTrue, BasicBlock *IfFalse,
1425 Value *Cond, BasicBlock *InsertAtEnd, Context &Ctx);
1426 /// For isa/dyn_cast.
1427 static bool classof(const Value *From);
1428 bool isUnconditional() const {
1429 return cast<llvm::BranchInst>(Val)->isUnconditional();
1430 }
1431 bool isConditional() const {
1432 return cast<llvm::BranchInst>(Val)->isConditional();
1433 }
1434 Value *getCondition() const;
1435 void setCondition(Value *V) { setOperand(0, V); }
1436 unsigned getNumSuccessors() const { return 1 + isConditional(); }
1437 BasicBlock *getSuccessor(unsigned SuccIdx) const;
1438 void setSuccessor(unsigned Idx, BasicBlock *NewSucc);
1440
1441private:
1442 struct LLVMBBToSBBB {
1443 Context &Ctx;
1444 LLVMBBToSBBB(Context &Ctx) : Ctx(Ctx) {}
1445 BasicBlock *operator()(llvm::BasicBlock *BB) const;
1446 };
1447
1448 struct ConstLLVMBBToSBBB {
1449 Context &Ctx;
1450 ConstLLVMBBToSBBB(Context &Ctx) : Ctx(Ctx) {}
1451 const BasicBlock *operator()(const llvm::BasicBlock *BB) const;
1452 };
1453
1454public:
1459 cast<llvm::BranchInst>(Val)->successors();
1460 LLVMBBToSBBB BBMap(Ctx);
1461 sb_succ_op_iterator MappedBegin = map_iterator(LLVMRange.begin(), BBMap);
1462 sb_succ_op_iterator MappedEnd = map_iterator(LLVMRange.end(), BBMap);
1463 return make_range(MappedBegin, MappedEnd);
1464 }
1465
1468 ConstLLVMBBToSBBB>;
1471 static_cast<const llvm::BranchInst *>(cast<llvm::BranchInst>(Val))
1472 ->successors();
1473 ConstLLVMBBToSBBB ConstBBMap(Ctx);
1474 const_sb_succ_op_iterator ConstMappedBegin =
1475 map_iterator(ConstLLVMRange.begin(), ConstBBMap);
1476 const_sb_succ_op_iterator ConstMappedEnd =
1477 map_iterator(ConstLLVMRange.end(), ConstBBMap);
1478 return make_range(ConstMappedBegin, ConstMappedEnd);
1479 }
1480};
1481
1482/// An abstract class, parent of unary instructions.
1484 : public SingleLLVMInstructionImpl<llvm::UnaryInstruction> {
1485protected:
1487 Context &Ctx)
1488 : SingleLLVMInstructionImpl(ID, Opc, LLVMI, Ctx) {}
1489
1490public:
1491 static bool classof(const Instruction *I) {
1492 return isa<LoadInst>(I) || isa<CastInst>(I);
1493 }
1494 static bool classof(const Value *V) {
1495 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1496 }
1497};
1498
1499class LoadInst final : public UnaryInstruction {
1500 /// Use LoadInst::create() instead of calling the constructor.
1502 : UnaryInstruction(ClassID::Load, Opcode::Load, LI, Ctx) {}
1503 friend Context; // for LoadInst()
1504
1505public:
1506 /// Return true if this is a load from a volatile memory location.
1507 bool isVolatile() const { return cast<llvm::LoadInst>(Val)->isVolatile(); }
1508 /// Specify whether this is a volatile load or not.
1509 void setVolatile(bool V);
1510
1511 static LoadInst *create(Type *Ty, Value *Ptr, MaybeAlign Align,
1512 Instruction *InsertBefore, Context &Ctx,
1513 const Twine &Name = "");
1514 static LoadInst *create(Type *Ty, Value *Ptr, MaybeAlign Align,
1515 Instruction *InsertBefore, bool IsVolatile,
1516 Context &Ctx, const Twine &Name = "");
1517 static LoadInst *create(Type *Ty, Value *Ptr, MaybeAlign Align,
1518 BasicBlock *InsertAtEnd, Context &Ctx,
1519 const Twine &Name = "");
1520 static LoadInst *create(Type *Ty, Value *Ptr, MaybeAlign Align,
1521 BasicBlock *InsertAtEnd, bool IsVolatile,
1522 Context &Ctx, const Twine &Name = "");
1523
1524 /// For isa/dyn_cast.
1525 static bool classof(const Value *From);
1526 Value *getPointerOperand() const;
1527 Align getAlign() const { return cast<llvm::LoadInst>(Val)->getAlign(); }
1528 bool isUnordered() const { return cast<llvm::LoadInst>(Val)->isUnordered(); }
1529 bool isSimple() const { return cast<llvm::LoadInst>(Val)->isSimple(); }
1530};
1531
1532class StoreInst final : public SingleLLVMInstructionImpl<llvm::StoreInst> {
1533 /// Use StoreInst::create().
1535 : SingleLLVMInstructionImpl(ClassID::Store, Opcode::Store, SI, Ctx) {}
1536 friend Context; // for StoreInst()
1537
1538public:
1539 /// Return true if this is a store from a volatile memory location.
1540 bool isVolatile() const { return cast<llvm::StoreInst>(Val)->isVolatile(); }
1541 /// Specify whether this is a volatile store or not.
1542 void setVolatile(bool V);
1543
1545 Instruction *InsertBefore, Context &Ctx);
1547 Instruction *InsertBefore, bool IsVolatile,
1548 Context &Ctx);
1550 BasicBlock *InsertAtEnd, Context &Ctx);
1552 BasicBlock *InsertAtEnd, bool IsVolatile,
1553 Context &Ctx);
1554 /// For isa/dyn_cast.
1555 static bool classof(const Value *From);
1556 Value *getValueOperand() const;
1557 Value *getPointerOperand() const;
1558 Align getAlign() const { return cast<llvm::StoreInst>(Val)->getAlign(); }
1559 bool isSimple() const { return cast<llvm::StoreInst>(Val)->isSimple(); }
1560 bool isUnordered() const { return cast<llvm::StoreInst>(Val)->isUnordered(); }
1561};
1562
1563class UnreachableInst final : public Instruction {
1564 /// Use UnreachableInst::create() instead of calling the constructor.
1566 : Instruction(ClassID::Unreachable, Opcode::Unreachable, I, Ctx) {}
1567 friend Context;
1568 Use getOperandUseInternal(unsigned OpIdx, bool Verify) const final {
1569 return getOperandUseDefault(OpIdx, Verify);
1570 }
1571 SmallVector<llvm::Instruction *, 1> getLLVMInstrs() const final {
1572 return {cast<llvm::Instruction>(Val)};
1573 }
1574
1575public:
1576 static UnreachableInst *create(Instruction *InsertBefore, Context &Ctx);
1577 static UnreachableInst *create(BasicBlock *InsertAtEnd, Context &Ctx);
1578 static bool classof(const Value *From);
1579 unsigned getNumSuccessors() const { return 0; }
1580 unsigned getUseOperandNo(const Use &Use) const final {
1581 llvm_unreachable("UnreachableInst has no operands!");
1582 }
1583 unsigned getNumOfIRInstrs() const final { return 1u; }
1584};
1585
1586class ReturnInst final : public SingleLLVMInstructionImpl<llvm::ReturnInst> {
1587 /// Use ReturnInst::create() instead of calling the constructor.
1589 : SingleLLVMInstructionImpl(ClassID::Ret, Opcode::Ret, I, Ctx) {}
1591 : SingleLLVMInstructionImpl(SubclassID, Opcode::Ret, I, Ctx) {}
1592 friend class Context; // For accessing the constructor in create*()
1593 static ReturnInst *createCommon(Value *RetVal, IRBuilder<> &Builder,
1594 Context &Ctx);
1595
1596public:
1597 static ReturnInst *create(Value *RetVal, Instruction *InsertBefore,
1598 Context &Ctx);
1599 static ReturnInst *create(Value *RetVal, BasicBlock *InsertAtEnd,
1600 Context &Ctx);
1601 static bool classof(const Value *From) {
1602 return From->getSubclassID() == ClassID::Ret;
1603 }
1604 /// \Returns null if there is no return value.
1605 Value *getReturnValue() const;
1606};
1607
1608class CallBase : public SingleLLVMInstructionImpl<llvm::CallBase> {
1611 friend class CallInst; // For constructor.
1612 friend class InvokeInst; // For constructor.
1613 friend class CallBrInst; // For constructor.
1614
1615public:
1616 static bool classof(const Value *From) {
1617 auto Opc = From->getSubclassID();
1618 return Opc == Instruction::ClassID::Call ||
1619 Opc == Instruction::ClassID::Invoke ||
1620 Opc == Instruction::ClassID::CallBr;
1621 }
1622
1624 return cast<llvm::CallBase>(Val)->getFunctionType();
1625 }
1626
1629 return const_cast<CallBase *>(this)->data_operands_begin();
1630 }
1632 auto *LLVMCB = cast<llvm::CallBase>(Val);
1633 auto Dist = LLVMCB->data_operands_end() - LLVMCB->data_operands_begin();
1634 return op_begin() + Dist;
1635 }
1637 auto *LLVMCB = cast<llvm::CallBase>(Val);
1638 auto Dist = LLVMCB->data_operands_end() - LLVMCB->data_operands_begin();
1639 return op_begin() + Dist;
1640 }
1643 }
1646 }
1647 bool data_operands_empty() const {
1649 }
1650 unsigned data_operands_size() const {
1651 return std::distance(data_operands_begin(), data_operands_end());
1652 }
1653 bool isDataOperand(Use U) const {
1654 assert(this == U.getUser() &&
1655 "Only valid to query with a use of this instruction!");
1656 return cast<llvm::CallBase>(Val)->isDataOperand(U.LLVMUse);
1657 }
1658 unsigned getDataOperandNo(Use U) const {
1659 assert(isDataOperand(U) && "Data operand # out of range!");
1660 return cast<llvm::CallBase>(Val)->getDataOperandNo(U.LLVMUse);
1661 }
1662
1663 /// Return the total number operands (not operand bundles) used by
1664 /// every operand bundle in this OperandBundleUser.
1665 unsigned getNumTotalBundleOperands() const {
1666 return cast<llvm::CallBase>(Val)->getNumTotalBundleOperands();
1667 }
1668
1673 }
1675 return const_cast<CallBase *>(this)->arg_end();
1676 }
1678 return make_range(arg_begin(), arg_end());
1679 }
1681 return make_range(arg_begin(), arg_end());
1682 }
1683 bool arg_empty() const { return arg_end() == arg_begin(); }
1684 unsigned arg_size() const { return arg_end() - arg_begin(); }
1685
1686 Value *getArgOperand(unsigned OpIdx) const {
1687 assert(OpIdx < arg_size() && "Out of bounds!");
1688 return getOperand(OpIdx);
1689 }
1690 void setArgOperand(unsigned OpIdx, Value *NewOp) {
1691 assert(OpIdx < arg_size() && "Out of bounds!");
1692 setOperand(OpIdx, NewOp);
1693 }
1694
1695 Use getArgOperandUse(unsigned Idx) const {
1696 assert(Idx < arg_size() && "Out of bounds!");
1697 return getOperandUse(Idx);
1698 }
1700 assert(Idx < arg_size() && "Out of bounds!");
1701 return getOperandUse(Idx);
1702 }
1703
1704 bool isArgOperand(Use U) const {
1705 return cast<llvm::CallBase>(Val)->isArgOperand(U.LLVMUse);
1706 }
1707 unsigned getArgOperandNo(Use U) const {
1708 return cast<llvm::CallBase>(Val)->getArgOperandNo(U.LLVMUse);
1709 }
1710 bool hasArgument(const Value *V) const { return is_contained(args(), V); }
1711
1712 Value *getCalledOperand() const;
1713 Use getCalledOperandUse() const;
1714
1715 Function *getCalledFunction() const;
1716 bool isIndirectCall() const {
1717 return cast<llvm::CallBase>(Val)->isIndirectCall();
1718 }
1719 bool isCallee(Use U) const {
1720 return cast<llvm::CallBase>(Val)->isCallee(U.LLVMUse);
1721 }
1723 const Function *getCaller() const {
1724 return const_cast<CallBase *>(this)->getCaller();
1725 }
1726 bool isMustTailCall() const {
1727 return cast<llvm::CallBase>(Val)->isMustTailCall();
1728 }
1729 bool isTailCall() const { return cast<llvm::CallBase>(Val)->isTailCall(); }
1731 return cast<llvm::CallBase>(Val)->getIntrinsicID();
1732 }
1736 return cast<llvm::CallBase>(Val)->getCallingConv();
1737 }
1738 bool isInlineAsm() const { return cast<llvm::CallBase>(Val)->isInlineAsm(); }
1739};
1740
1741class CallInst final : public CallBase {
1742 /// Use Context::createCallInst(). Don't call the
1743 /// constructor directly.
1745 : CallBase(ClassID::Call, Opcode::Call, I, Ctx) {}
1746 friend class Context; // For accessing the constructor in
1747 // create*()
1748
1749public:
1750 static CallInst *create(FunctionType *FTy, Value *Func,
1751 ArrayRef<Value *> Args, BBIterator WhereIt,
1752 BasicBlock *WhereBB, Context &Ctx,
1753 const Twine &NameStr = "");
1754 static CallInst *create(FunctionType *FTy, Value *Func,
1755 ArrayRef<Value *> Args, Instruction *InsertBefore,
1756 Context &Ctx, const Twine &NameStr = "");
1757 static CallInst *create(FunctionType *FTy, Value *Func,
1758 ArrayRef<Value *> Args, BasicBlock *InsertAtEnd,
1759 Context &Ctx, const Twine &NameStr = "");
1760
1761 static bool classof(const Value *From) {
1762 return From->getSubclassID() == ClassID::Call;
1763 }
1764};
1765
1766class InvokeInst final : public CallBase {
1767 /// Use Context::createInvokeInst(). Don't call the
1768 /// constructor directly.
1770 : CallBase(ClassID::Invoke, Opcode::Invoke, I, Ctx) {}
1771 friend class Context; // For accessing the constructor in
1772 // create*()
1773
1774public:
1775 static InvokeInst *create(FunctionType *FTy, Value *Func,
1776 BasicBlock *IfNormal, BasicBlock *IfException,
1777 ArrayRef<Value *> Args, BBIterator WhereIt,
1778 BasicBlock *WhereBB, Context &Ctx,
1779 const Twine &NameStr = "");
1780 static InvokeInst *create(FunctionType *FTy, Value *Func,
1781 BasicBlock *IfNormal, BasicBlock *IfException,
1782 ArrayRef<Value *> Args, Instruction *InsertBefore,
1783 Context &Ctx, const Twine &NameStr = "");
1784 static InvokeInst *create(FunctionType *FTy, Value *Func,
1785 BasicBlock *IfNormal, BasicBlock *IfException,
1786 ArrayRef<Value *> Args, BasicBlock *InsertAtEnd,
1787 Context &Ctx, const Twine &NameStr = "");
1788
1789 static bool classof(const Value *From) {
1790 return From->getSubclassID() == ClassID::Invoke;
1791 }
1792 BasicBlock *getNormalDest() const;
1793 BasicBlock *getUnwindDest() const;
1794 void setNormalDest(BasicBlock *BB);
1795 void setUnwindDest(BasicBlock *BB);
1796 // TODO: Return a `LandingPadInst` once implemented.
1798 BasicBlock *getSuccessor(unsigned SuccIdx) const;
1799 void setSuccessor(unsigned SuccIdx, BasicBlock *NewSucc) {
1800 assert(SuccIdx < 2 && "Successor # out of range for invoke!");
1801 if (SuccIdx == 0)
1802 setNormalDest(NewSucc);
1803 else
1804 setUnwindDest(NewSucc);
1805 }
1806 unsigned getNumSuccessors() const {
1807 return cast<llvm::InvokeInst>(Val)->getNumSuccessors();
1808 }
1809};
1810
1811class CallBrInst final : public CallBase {
1812 /// Use Context::createCallBrInst(). Don't call the
1813 /// constructor directly.
1815 : CallBase(ClassID::CallBr, Opcode::CallBr, I, Ctx) {}
1816 friend class Context; // For accessing the constructor in
1817 // create*()
1818
1819public:
1820 static CallBrInst *create(FunctionType *FTy, Value *Func,
1821 BasicBlock *DefaultDest,
1822 ArrayRef<BasicBlock *> IndirectDests,
1823 ArrayRef<Value *> Args, BBIterator WhereIt,
1824 BasicBlock *WhereBB, Context &Ctx,
1825 const Twine &NameStr = "");
1826 static CallBrInst *create(FunctionType *FTy, Value *Func,
1827 BasicBlock *DefaultDest,
1828 ArrayRef<BasicBlock *> IndirectDests,
1829 ArrayRef<Value *> Args, Instruction *InsertBefore,
1830 Context &Ctx, const Twine &NameStr = "");
1831 static CallBrInst *create(FunctionType *FTy, Value *Func,
1832 BasicBlock *DefaultDest,
1833 ArrayRef<BasicBlock *> IndirectDests,
1834 ArrayRef<Value *> Args, BasicBlock *InsertAtEnd,
1835 Context &Ctx, const Twine &NameStr = "");
1836 static bool classof(const Value *From) {
1837 return From->getSubclassID() == ClassID::CallBr;
1838 }
1839 unsigned getNumIndirectDests() const {
1840 return cast<llvm::CallBrInst>(Val)->getNumIndirectDests();
1841 }
1842 Value *getIndirectDestLabel(unsigned Idx) const;
1843 Value *getIndirectDestLabelUse(unsigned Idx) const;
1844 BasicBlock *getDefaultDest() const;
1845 BasicBlock *getIndirectDest(unsigned Idx) const;
1847 void setDefaultDest(BasicBlock *BB);
1848 void setIndirectDest(unsigned Idx, BasicBlock *BB);
1849 BasicBlock *getSuccessor(unsigned Idx) const;
1850 unsigned getNumSuccessors() const {
1851 return cast<llvm::CallBrInst>(Val)->getNumSuccessors();
1852 }
1853};
1854
1855class FuncletPadInst : public SingleLLVMInstructionImpl<llvm::FuncletPadInst> {
1857 Context &Ctx)
1859 friend class CatchPadInst; // For constructor.
1860 friend class CleanupPadInst; // For constructor.
1861
1862public:
1863 /// Return the number of funcletpad arguments.
1864 unsigned arg_size() const {
1865 return cast<llvm::FuncletPadInst>(Val)->arg_size();
1866 }
1867 /// Return the outer EH-pad this funclet is nested within.
1868 ///
1869 /// Note: This returns the associated CatchSwitchInst if this FuncletPadInst
1870 /// is a CatchPadInst.
1871 Value *getParentPad() const;
1872 void setParentPad(Value *ParentPad);
1873 /// Return the Idx-th funcletpad argument.
1874 Value *getArgOperand(unsigned Idx) const;
1875 /// Set the Idx-th funcletpad argument.
1876 void setArgOperand(unsigned Idx, Value *V);
1877
1878 // TODO: Implement missing functions: arg_operands().
1879 static bool classof(const Value *From) {
1880 return From->getSubclassID() == ClassID::CatchPad ||
1881 From->getSubclassID() == ClassID::CleanupPad;
1882 }
1883};
1884
1887 : FuncletPadInst(ClassID::CatchPad, Opcode::CatchPad, CPI, Ctx) {}
1888 friend class Context; // For constructor.
1889
1890public:
1892 // TODO: We have not implemented setCatchSwitch() because we can't revert it
1893 // for now, as there is no CatchPadInst member function that can undo it.
1894
1895 static CatchPadInst *create(Value *ParentPad, ArrayRef<Value *> Args,
1896 BBIterator WhereIt, BasicBlock *WhereBB,
1897 Context &Ctx, const Twine &Name = "");
1898 static bool classof(const Value *From) {
1899 return From->getSubclassID() == ClassID::CatchPad;
1900 }
1901};
1902
1905 : FuncletPadInst(ClassID::CleanupPad, Opcode::CleanupPad, CPI, Ctx) {}
1906 friend class Context; // For constructor.
1907
1908public:
1909 static CleanupPadInst *create(Value *ParentPad, ArrayRef<Value *> Args,
1910 BBIterator WhereIt, BasicBlock *WhereBB,
1911 Context &Ctx, const Twine &Name = "");
1912 static bool classof(const Value *From) {
1913 return From->getSubclassID() == ClassID::CleanupPad;
1914 }
1915};
1916
1918 : public SingleLLVMInstructionImpl<llvm::GetElementPtrInst> {
1919 /// Use Context::createGetElementPtrInst(). Don't call
1920 /// the constructor directly.
1922 : SingleLLVMInstructionImpl(ClassID::GetElementPtr, Opcode::GetElementPtr,
1923 I, Ctx) {}
1925 : SingleLLVMInstructionImpl(SubclassID, Opcode::GetElementPtr, I, Ctx) {}
1926 friend class Context; // For accessing the constructor in
1927 // create*()
1928
1929public:
1930 static Value *create(Type *Ty, Value *Ptr, ArrayRef<Value *> IdxList,
1931 BBIterator WhereIt, BasicBlock *WhereBB, Context &Ctx,
1932 const Twine &NameStr = "");
1933 static Value *create(Type *Ty, Value *Ptr, ArrayRef<Value *> IdxList,
1934 Instruction *InsertBefore, Context &Ctx,
1935 const Twine &NameStr = "");
1936 static Value *create(Type *Ty, Value *Ptr, ArrayRef<Value *> IdxList,
1937 BasicBlock *InsertAtEnd, Context &Ctx,
1938 const Twine &NameStr = "");
1939
1940 static bool classof(const Value *From) {
1941 return From->getSubclassID() == ClassID::GetElementPtr;
1942 }
1943
1945 return cast<llvm::GetElementPtrInst>(Val)->getSourceElementType();
1946 }
1948 return cast<llvm::GetElementPtrInst>(Val)->getResultElementType();
1949 }
1950 unsigned getAddressSpace() const {
1951 return cast<llvm::GetElementPtrInst>(Val)->getAddressSpace();
1952 }
1953
1954 inline op_iterator idx_begin() { return op_begin() + 1; }
1956 return const_cast<GetElementPtrInst *>(this)->idx_begin();
1957 }
1958 inline op_iterator idx_end() { return op_end(); }
1960 return const_cast<GetElementPtrInst *>(this)->idx_end();
1961 }
1963 return make_range(idx_begin(), idx_end());
1964 }
1966 return const_cast<GetElementPtrInst *>(this)->indices();
1967 }
1968
1969 Value *getPointerOperand() const;
1970 static unsigned getPointerOperandIndex() {
1972 }
1974 return cast<llvm::GetElementPtrInst>(Val)->getPointerOperandType();
1975 }
1976 unsigned getPointerAddressSpace() const {
1977 return cast<llvm::GetElementPtrInst>(Val)->getPointerAddressSpace();
1978 }
1979 unsigned getNumIndices() const {
1980 return cast<llvm::GetElementPtrInst>(Val)->getNumIndices();
1981 }
1982 bool hasIndices() const {
1983 return cast<llvm::GetElementPtrInst>(Val)->hasIndices();
1984 }
1986 return cast<llvm::GetElementPtrInst>(Val)->hasAllConstantIndices();
1987 }
1989 return cast<llvm::GetElementPtrInst>(Val)->getNoWrapFlags();
1990 }
1991 bool isInBounds() const {
1992 return cast<llvm::GetElementPtrInst>(Val)->isInBounds();
1993 }
1995 return cast<llvm::GetElementPtrInst>(Val)->hasNoUnsignedSignedWrap();
1996 }
1997 bool hasNoUnsignedWrap() const {
1998 return cast<llvm::GetElementPtrInst>(Val)->hasNoUnsignedWrap();
1999 }
2001 return cast<llvm::GetElementPtrInst>(Val)->accumulateConstantOffset(DL,
2002 Offset);
2003 }
2004 // TODO: Add missing member functions.
2005};
2006
2008 : public SingleLLVMInstructionImpl<llvm::CatchSwitchInst> {
2009public:
2011 : SingleLLVMInstructionImpl(ClassID::CatchSwitch, Opcode::CatchSwitch,
2012 CSI, Ctx) {}
2013
2014 static CatchSwitchInst *create(Value *ParentPad, BasicBlock *UnwindBB,
2015 unsigned NumHandlers, BBIterator WhereIt,
2016 BasicBlock *WhereBB, Context &Ctx,
2017 const Twine &Name = "");
2018
2019 Value *getParentPad() const;
2020 void setParentPad(Value *ParentPad);
2021
2022 bool hasUnwindDest() const {
2023 return cast<llvm::CatchSwitchInst>(Val)->hasUnwindDest();
2024 }
2025 bool unwindsToCaller() const {
2026 return cast<llvm::CatchSwitchInst>(Val)->unwindsToCaller();
2027 }
2028 BasicBlock *getUnwindDest() const;
2029 void setUnwindDest(BasicBlock *UnwindDest);
2030
2031 unsigned getNumHandlers() const {
2032 return cast<llvm::CatchSwitchInst>(Val)->getNumHandlers();
2033 }
2034
2035private:
2036 static BasicBlock *handler_helper(Value *V) { return cast<BasicBlock>(V); }
2037 static const BasicBlock *handler_helper(const Value *V) {
2038 return cast<BasicBlock>(V);
2039 }
2040
2041public:
2042 using DerefFnTy = BasicBlock *(*)(Value *);
2045 using ConstDerefFnTy = const BasicBlock *(*)(const Value *);
2049
2051 op_iterator It = op_begin() + 1;
2052 if (hasUnwindDest())
2053 ++It;
2054 return handler_iterator(It, DerefFnTy(handler_helper));
2055 }
2057 const_op_iterator It = op_begin() + 1;
2058 if (hasUnwindDest())
2059 ++It;
2060 return const_handler_iterator(It, ConstDerefFnTy(handler_helper));
2061 }
2063 return handler_iterator(op_end(), DerefFnTy(handler_helper));
2064 }
2066 return const_handler_iterator(op_end(), ConstDerefFnTy(handler_helper));
2067 }
2070 }
2073 }
2074
2075 void addHandler(BasicBlock *Dest);
2076
2077 // TODO: removeHandler() cannot be reverted because there is no equivalent
2078 // addHandler() with a handler_iterator to specify the position. So we can't
2079 // implement it for now.
2080
2081 unsigned getNumSuccessors() const { return getNumOperands() - 1; }
2082 BasicBlock *getSuccessor(unsigned Idx) const {
2084 "Successor # out of range for catchswitch!");
2085 return cast<BasicBlock>(getOperand(Idx + 1));
2086 }
2087 void setSuccessor(unsigned Idx, BasicBlock *NewSucc) {
2089 "Successor # out of range for catchswitch!");
2090 setOperand(Idx + 1, NewSucc);
2091 }
2092
2093 static bool classof(const Value *From) {
2094 return From->getSubclassID() == ClassID::CatchSwitch;
2095 }
2096};
2097
2098class SwitchInst : public SingleLLVMInstructionImpl<llvm::SwitchInst> {
2099public:
2101 : SingleLLVMInstructionImpl(ClassID::Switch, Opcode::Switch, SI, Ctx) {}
2102
2103 static constexpr const unsigned DefaultPseudoIndex =
2105
2106 static SwitchInst *create(Value *V, BasicBlock *Dest, unsigned NumCases,
2107 BasicBlock::iterator WhereIt, BasicBlock *WhereBB,
2108 Context &Ctx, const Twine &Name = "");
2109
2110 Value *getCondition() const;
2111 void setCondition(Value *V);
2112 BasicBlock *getDefaultDest() const;
2114 return cast<llvm::SwitchInst>(Val)->defaultDestUndefined();
2115 }
2116 void setDefaultDest(BasicBlock *DefaultCase);
2117 unsigned getNumCases() const {
2118 return cast<llvm::SwitchInst>(Val)->getNumCases();
2119 }
2120
2125 const BasicBlock>;
2128
2129 /// Returns a read/write iterator that points to the first case in the
2130 /// SwitchInst.
2131 CaseIt case_begin() { return CaseIt(this, 0); }
2132 ConstCaseIt case_begin() const { return ConstCaseIt(this, 0); }
2133 /// Returns a read/write iterator that points one past the last in the
2134 /// SwitchInst.
2135 CaseIt case_end() { return CaseIt(this, getNumCases()); }
2136 ConstCaseIt case_end() const { return ConstCaseIt(this, getNumCases()); }
2137 /// Iteration adapter for range-for loops.
2139 return make_range(case_begin(), case_end());
2140 }
2142 return make_range(case_begin(), case_end());
2143 }
2146 return ConstCaseIt(this, DefaultPseudoIndex);
2147 }
2149 return CaseIt(
2150 this,
2151 const_cast<const SwitchInst *>(this)->findCaseValue(C)->getCaseIndex());
2152 }
2154 ConstCaseIt I = llvm::find_if(cases(), [C](const ConstCaseHandle &Case) {
2155 return Case.getCaseValue() == C;
2156 });
2157 if (I != case_end())
2158 return I;
2159 return case_default();
2160 }
2162
2163 void addCase(ConstantInt *OnVal, BasicBlock *Dest);
2164 /// This method removes the specified case and its successor from the switch
2165 /// instruction. Note that this operation may reorder the remaining cases at
2166 /// index idx and above.
2167 /// Note:
2168 /// This action invalidates iterators for all cases following the one removed,
2169 /// including the case_end() iterator. It returns an iterator for the next
2170 /// case.
2172
2173 unsigned getNumSuccessors() const {
2174 return cast<llvm::SwitchInst>(Val)->getNumSuccessors();
2175 }
2176 BasicBlock *getSuccessor(unsigned Idx) const;
2177 void setSuccessor(unsigned Idx, BasicBlock *NewSucc);
2178 static bool classof(const Value *From) {
2179 return From->getSubclassID() == ClassID::Switch;
2180 }
2181};
2182
2184 static Opcode getUnaryOpcode(llvm::Instruction::UnaryOps UnOp) {
2185 switch (UnOp) {
2186 case llvm::Instruction::FNeg:
2187 return Opcode::FNeg;
2188 case llvm::Instruction::UnaryOpsEnd:
2189 llvm_unreachable("Bad UnOp!");
2190 }
2191 llvm_unreachable("Unhandled UnOp!");
2192 }
2194 : UnaryInstruction(ClassID::UnOp, getUnaryOpcode(UO->getOpcode()), UO,
2195 Ctx) {}
2196 friend Context; // for constructor.
2197public:
2198 static Value *create(Instruction::Opcode Op, Value *OpV, BBIterator WhereIt,
2199 BasicBlock *WhereBB, Context &Ctx,
2200 const Twine &Name = "");
2201 static Value *create(Instruction::Opcode Op, Value *OpV,
2202 Instruction *InsertBefore, Context &Ctx,
2203 const Twine &Name = "");
2204 static Value *create(Instruction::Opcode Op, Value *OpV,
2205 BasicBlock *InsertAtEnd, Context &Ctx,
2206 const Twine &Name = "");
2208 Value *CopyFrom, BBIterator WhereIt,
2209 BasicBlock *WhereBB, Context &Ctx,
2210 const Twine &Name = "");
2212 Value *CopyFrom,
2213 Instruction *InsertBefore, Context &Ctx,
2214 const Twine &Name = "");
2216 Value *CopyFrom, BasicBlock *InsertAtEnd,
2217 Context &Ctx, const Twine &Name = "");
2218 /// For isa/dyn_cast.
2219 static bool classof(const Value *From) {
2220 return From->getSubclassID() == ClassID::UnOp;
2221 }
2222};
2223
2224class BinaryOperator : public SingleLLVMInstructionImpl<llvm::BinaryOperator> {
2225 static Opcode getBinOpOpcode(llvm::Instruction::BinaryOps BinOp) {
2226 switch (BinOp) {
2227 case llvm::Instruction::Add:
2228 return Opcode::Add;
2229 case llvm::Instruction::FAdd:
2230 return Opcode::FAdd;
2231 case llvm::Instruction::Sub:
2232 return Opcode::Sub;
2233 case llvm::Instruction::FSub:
2234 return Opcode::FSub;
2235 case llvm::Instruction::Mul:
2236 return Opcode::Mul;
2237 case llvm::Instruction::FMul:
2238 return Opcode::FMul;
2239 case llvm::Instruction::UDiv:
2240 return Opcode::UDiv;
2241 case llvm::Instruction::SDiv:
2242 return Opcode::SDiv;
2243 case llvm::Instruction::FDiv:
2244 return Opcode::FDiv;
2245 case llvm::Instruction::URem:
2246 return Opcode::URem;
2247 case llvm::Instruction::SRem:
2248 return Opcode::SRem;
2249 case llvm::Instruction::FRem:
2250 return Opcode::FRem;
2251 case llvm::Instruction::Shl:
2252 return Opcode::Shl;
2253 case llvm::Instruction::LShr:
2254 return Opcode::LShr;
2255 case llvm::Instruction::AShr:
2256 return Opcode::AShr;
2257 case llvm::Instruction::And:
2258 return Opcode::And;
2259 case llvm::Instruction::Or:
2260 return Opcode::Or;
2261 case llvm::Instruction::Xor:
2262 return Opcode::Xor;
2263 case llvm::Instruction::BinaryOpsEnd:
2264 llvm_unreachable("Bad BinOp!");
2265 }
2266 llvm_unreachable("Unhandled BinOp!");
2267 }
2269 : SingleLLVMInstructionImpl(ClassID::BinaryOperator,
2270 getBinOpOpcode(BinOp->getOpcode()), BinOp,
2271 Ctx) {}
2272 friend class Context; // For constructor.
2273
2274public:
2276 BBIterator WhereIt, BasicBlock *WhereBB, Context &Ctx,
2277 const Twine &Name = "");
2279 Instruction *InsertBefore, Context &Ctx,
2280 const Twine &Name = "");
2282 BasicBlock *InsertAtEnd, Context &Ctx,
2283 const Twine &Name = "");
2284
2286 Value *RHS, Value *CopyFrom,
2287 BBIterator WhereIt, BasicBlock *WhereBB,
2288 Context &Ctx, const Twine &Name = "");
2290 Value *RHS, Value *CopyFrom,
2291 Instruction *InsertBefore, Context &Ctx,
2292 const Twine &Name = "");
2294 Value *RHS, Value *CopyFrom,
2295 BasicBlock *InsertAtEnd, Context &Ctx,
2296 const Twine &Name = "");
2297 /// For isa/dyn_cast.
2298 static bool classof(const Value *From) {
2299 return From->getSubclassID() == ClassID::BinaryOperator;
2300 }
2302};
2303
2304class AtomicRMWInst : public SingleLLVMInstructionImpl<llvm::AtomicRMWInst> {
2306 : SingleLLVMInstructionImpl(ClassID::AtomicRMW,
2307 Instruction::Opcode::AtomicRMW, Atomic, Ctx) {
2308 }
2309 friend class Context; // For constructor.
2310
2311public:
2314 return cast<llvm::AtomicRMWInst>(Val)->getOperation();
2315 }
2318 }
2319 static bool isFPOperation(BinOp Op) {
2321 }
2323 cast<llvm::AtomicRMWInst>(Val)->setOperation(Op);
2324 }
2325 Align getAlign() const { return cast<llvm::AtomicRMWInst>(Val)->getAlign(); }
2326 void setAlignment(Align Align);
2327 bool isVolatile() const {
2328 return cast<llvm::AtomicRMWInst>(Val)->isVolatile();
2329 }
2330 void setVolatile(bool V);
2332 return cast<llvm::AtomicRMWInst>(Val)->getOrdering();
2333 }
2334 void setOrdering(AtomicOrdering Ordering);
2336 return cast<llvm::AtomicRMWInst>(Val)->getSyncScopeID();
2337 }
2338 void setSyncScopeID(SyncScope::ID SSID);
2340 const Value *getPointerOperand() const {
2341 return const_cast<AtomicRMWInst *>(this)->getPointerOperand();
2342 }
2344 const Value *getValOperand() const {
2345 return const_cast<AtomicRMWInst *>(this)->getValOperand();
2346 }
2347 unsigned getPointerAddressSpace() const {
2348 return cast<llvm::AtomicRMWInst>(Val)->getPointerAddressSpace();
2349 }
2351 return cast<llvm::AtomicRMWInst>(Val)->isFloatingPointOperation();
2352 }
2353 static bool classof(const Value *From) {
2354 return From->getSubclassID() == ClassID::AtomicRMW;
2355 }
2356
2359 BBIterator WhereIt, BasicBlock *WhereBB,
2360 Context &Ctx,
2362 const Twine &Name = "");
2365 Instruction *InsertBefore, Context &Ctx,
2367 const Twine &Name = "");
2370 BasicBlock *InsertAtEnd, Context &Ctx,
2372 const Twine &Name = "");
2373};
2374
2376 : public SingleLLVMInstructionImpl<llvm::AtomicCmpXchgInst> {
2378 : SingleLLVMInstructionImpl(ClassID::AtomicCmpXchg,
2379 Instruction::Opcode::AtomicCmpXchg, Atomic,
2380 Ctx) {}
2381 friend class Context; // For constructor.
2382
2383public:
2384 /// Return the alignment of the memory that is being allocated by the
2385 /// instruction.
2386 Align getAlign() const {
2387 return cast<llvm::AtomicCmpXchgInst>(Val)->getAlign();
2388 }
2389
2390 void setAlignment(Align Align);
2391 /// Return true if this is a cmpxchg from a volatile memory
2392 /// location.
2393 bool isVolatile() const {
2394 return cast<llvm::AtomicCmpXchgInst>(Val)->isVolatile();
2395 }
2396 /// Specify whether this is a volatile cmpxchg.
2397 void setVolatile(bool V);
2398 /// Return true if this cmpxchg may spuriously fail.
2399 bool isWeak() const { return cast<llvm::AtomicCmpXchgInst>(Val)->isWeak(); }
2400 void setWeak(bool IsWeak);
2403 }
2406 }
2408 return cast<llvm::AtomicCmpXchgInst>(Val)->getSuccessOrdering();
2409 }
2410 void setSuccessOrdering(AtomicOrdering Ordering);
2411
2413 return cast<llvm::AtomicCmpXchgInst>(Val)->getFailureOrdering();
2414 }
2415 void setFailureOrdering(AtomicOrdering Ordering);
2417 return cast<llvm::AtomicCmpXchgInst>(Val)->getMergedOrdering();
2418 }
2420 return cast<llvm::AtomicCmpXchgInst>(Val)->getSyncScopeID();
2421 }
2422 void setSyncScopeID(SyncScope::ID SSID);
2424 const Value *getPointerOperand() const {
2425 return const_cast<AtomicCmpXchgInst *>(this)->getPointerOperand();
2426 }
2427
2429 const Value *getCompareOperand() const {
2430 return const_cast<AtomicCmpXchgInst *>(this)->getCompareOperand();
2431 }
2432
2434 const Value *getNewValOperand() const {
2435 return const_cast<AtomicCmpXchgInst *>(this)->getNewValOperand();
2436 }
2437
2438 /// Returns the address space of the pointer operand.
2439 unsigned getPointerAddressSpace() const {
2440 return cast<llvm::AtomicCmpXchgInst>(Val)->getPointerAddressSpace();
2441 }
2442
2443 static AtomicCmpXchgInst *
2444 create(Value *Ptr, Value *Cmp, Value *New, MaybeAlign Align,
2445 AtomicOrdering SuccessOrdering, AtomicOrdering FailureOrdering,
2446 BBIterator WhereIt, BasicBlock *WhereBB, Context &Ctx,
2447 SyncScope::ID SSID = SyncScope::System, const Twine &Name = "");
2448 static AtomicCmpXchgInst *
2449 create(Value *Ptr, Value *Cmp, Value *New, MaybeAlign Align,
2450 AtomicOrdering SuccessOrdering, AtomicOrdering FailureOrdering,
2451 Instruction *InsertBefore, Context &Ctx,
2452 SyncScope::ID SSID = SyncScope::System, const Twine &Name = "");
2453 static AtomicCmpXchgInst *
2454 create(Value *Ptr, Value *Cmp, Value *New, MaybeAlign Align,
2455 AtomicOrdering SuccessOrdering, AtomicOrdering FailureOrdering,
2456 BasicBlock *InsertAtEnd, Context &Ctx,
2457 SyncScope::ID SSID = SyncScope::System, const Twine &Name = "");
2458};
2459
2460class AllocaInst final : public UnaryInstruction {
2462 : UnaryInstruction(ClassID::Alloca, Instruction::Opcode::Alloca, AI,
2463 Ctx) {}
2464 friend class Context; // For constructor.
2465
2466public:
2467 static AllocaInst *create(Type *Ty, unsigned AddrSpace, BBIterator WhereIt,
2468 BasicBlock *WhereBB, Context &Ctx,
2469 Value *ArraySize = nullptr, const Twine &Name = "");
2470 static AllocaInst *create(Type *Ty, unsigned AddrSpace,
2471 Instruction *InsertBefore, Context &Ctx,
2472 Value *ArraySize = nullptr, const Twine &Name = "");
2473 static AllocaInst *create(Type *Ty, unsigned AddrSpace,
2474 BasicBlock *InsertAtEnd, Context &Ctx,
2475 Value *ArraySize = nullptr, const Twine &Name = "");
2476
2477 /// Return true if there is an allocation size parameter to the allocation
2478 /// instruction that is not 1.
2479 bool isArrayAllocation() const {
2480 return cast<llvm::AllocaInst>(Val)->isArrayAllocation();
2481 }
2482 /// Get the number of elements allocated. For a simple allocation of a single
2483 /// element, this will return a constant 1 value.
2485 const Value *getArraySize() const {
2486 return const_cast<AllocaInst *>(this)->getArraySize();
2487 }
2488 /// Overload to return most specific pointer type.
2490 return cast<llvm::AllocaInst>(Val)->getType();
2491 }
2492 /// Return the address space for the allocation.
2493 unsigned getAddressSpace() const {
2494 return cast<llvm::AllocaInst>(Val)->getAddressSpace();
2495 }
2496 /// Get allocation size in bytes. Returns std::nullopt if size can't be
2497 /// determined, e.g. in case of a VLA.
2498 std::optional<TypeSize> getAllocationSize(const DataLayout &DL) const {
2499 return cast<llvm::AllocaInst>(Val)->getAllocationSize(DL);
2500 }
2501 /// Get allocation size in bits. Returns std::nullopt if size can't be
2502 /// determined, e.g. in case of a VLA.
2503 std::optional<TypeSize> getAllocationSizeInBits(const DataLayout &DL) const {
2504 return cast<llvm::AllocaInst>(Val)->getAllocationSizeInBits(DL);
2505 }
2506 /// Return the type that is being allocated by the instruction.
2508 return cast<llvm::AllocaInst>(Val)->getAllocatedType();
2509 }
2510 /// for use only in special circumstances that need to generically
2511 /// transform a whole instruction (eg: IR linking and vectorization).
2512 void setAllocatedType(Type *Ty);
2513 /// Return the alignment of the memory that is being allocated by the
2514 /// instruction.
2515 Align getAlign() const { return cast<llvm::AllocaInst>(Val)->getAlign(); }
2516 void setAlignment(Align Align);
2517 /// Return true if this alloca is in the entry block of the function and is a
2518 /// constant size. If so, the code generator will fold it into the
2519 /// prolog/epilog code, so it is basically free.
2520 bool isStaticAlloca() const {
2521 return cast<llvm::AllocaInst>(Val)->isStaticAlloca();
2522 }
2523 /// Return true if this alloca is used as an inalloca argument to a call. Such
2524 /// allocas are never considered static even if they are in the entry block.
2525 bool isUsedWithInAlloca() const {
2526 return cast<llvm::AllocaInst>(Val)->isUsedWithInAlloca();
2527 }
2528 /// Specify whether this alloca is used to represent the arguments to a call.
2529 void setUsedWithInAlloca(bool V);
2530
2531 static bool classof(const Value *From) {
2532 if (auto *I = dyn_cast<Instruction>(From))
2533 return I->getSubclassID() == Instruction::ClassID::Alloca;
2534 return false;
2535 }
2536};
2537
2539 static Opcode getCastOpcode(llvm::Instruction::CastOps CastOp) {
2540 switch (CastOp) {
2541 case llvm::Instruction::ZExt:
2542 return Opcode::ZExt;
2543 case llvm::Instruction::SExt:
2544 return Opcode::SExt;
2545 case llvm::Instruction::FPToUI:
2546 return Opcode::FPToUI;
2547 case llvm::Instruction::FPToSI:
2548 return Opcode::FPToSI;
2549 case llvm::Instruction::FPExt:
2550 return Opcode::FPExt;
2551 case llvm::Instruction::PtrToInt:
2552 return Opcode::PtrToInt;
2553 case llvm::Instruction::IntToPtr:
2554 return Opcode::IntToPtr;
2555 case llvm::Instruction::SIToFP:
2556 return Opcode::SIToFP;
2557 case llvm::Instruction::UIToFP:
2558 return Opcode::UIToFP;
2559 case llvm::Instruction::Trunc:
2560 return Opcode::Trunc;
2561 case llvm::Instruction::FPTrunc:
2562 return Opcode::FPTrunc;
2563 case llvm::Instruction::BitCast:
2564 return Opcode::BitCast;
2565 case llvm::Instruction::AddrSpaceCast:
2566 return Opcode::AddrSpaceCast;
2567 case llvm::Instruction::CastOpsEnd:
2568 llvm_unreachable("Bad CastOp!");
2569 }
2570 llvm_unreachable("Unhandled CastOp!");
2571 }
2572 /// Use Context::createCastInst(). Don't call the
2573 /// constructor directly.
2575 : UnaryInstruction(ClassID::Cast, getCastOpcode(CI->getOpcode()), CI,
2576 Ctx) {}
2577 friend Context; // for SBCastInstruction()
2578
2579public:
2580 static Value *create(Type *DestTy, Opcode Op, Value *Operand,
2581 BBIterator WhereIt, BasicBlock *WhereBB, Context &Ctx,
2582 const Twine &Name = "");
2583 static Value *create(Type *DestTy, Opcode Op, Value *Operand,
2584 Instruction *InsertBefore, Context &Ctx,
2585 const Twine &Name = "");
2586 static Value *create(Type *DestTy, Opcode Op, Value *Operand,
2587 BasicBlock *InsertAtEnd, Context &Ctx,
2588 const Twine &Name = "");
2589 /// For isa/dyn_cast.
2590 static bool classof(const Value *From);
2591 Type *getSrcTy() const { return cast<llvm::CastInst>(Val)->getSrcTy(); }
2592 Type *getDestTy() const { return cast<llvm::CastInst>(Val)->getDestTy(); }
2593};
2594
2595// Helper class to simplify stamping out CastInst subclasses.
2596template <Instruction::Opcode Op> class CastInstImpl : public CastInst {
2597public:
2598 static Value *create(Value *Src, Type *DestTy, BBIterator WhereIt,
2599 BasicBlock *WhereBB, Context &Ctx,
2600 const Twine &Name = "") {
2601 return CastInst::create(DestTy, Op, Src, WhereIt, WhereBB, Ctx, Name);
2602 }
2603 static Value *create(Value *Src, Type *DestTy, Instruction *InsertBefore,
2604 Context &Ctx, const Twine &Name = "") {
2605 return create(Src, DestTy, InsertBefore->getIterator(),
2606 InsertBefore->getParent(), Ctx, Name);
2607 }
2608 static Value *create(Value *Src, Type *DestTy, BasicBlock *InsertAtEnd,
2609 Context &Ctx, const Twine &Name = "") {
2610 return create(Src, DestTy, InsertAtEnd->end(), InsertAtEnd, Ctx, Name);
2611 }
2612
2613 static bool classof(const Value *From) {
2614 if (auto *I = dyn_cast<Instruction>(From))
2615 return I->getOpcode() == Op;
2616 return false;
2617 }
2618};
2619
2620class TruncInst final : public CastInstImpl<Instruction::Opcode::Trunc> {};
2621class ZExtInst final : public CastInstImpl<Instruction::Opcode::ZExt> {};
2622class SExtInst final : public CastInstImpl<Instruction::Opcode::SExt> {};
2623class FPTruncInst final : public CastInstImpl<Instruction::Opcode::FPTrunc> {};
2624class FPExtInst final : public CastInstImpl<Instruction::Opcode::FPExt> {};
2625class UIToFPInst final : public CastInstImpl<Instruction::Opcode::UIToFP> {};
2626class SIToFPInst final : public CastInstImpl<Instruction::Opcode::SIToFP> {};
2627class FPToUIInst final : public CastInstImpl<Instruction::Opcode::FPToUI> {};
2628class FPToSIInst final : public CastInstImpl<Instruction::Opcode::FPToSI> {};
2629class IntToPtrInst final : public CastInstImpl<Instruction::Opcode::IntToPtr> {
2630};
2631class PtrToIntInst final : public CastInstImpl<Instruction::Opcode::PtrToInt> {
2632};
2633class BitCastInst final : public CastInstImpl<Instruction::Opcode::BitCast> {};
2635 : public CastInstImpl<Instruction::Opcode::AddrSpaceCast> {
2636public:
2637 /// \Returns the pointer operand.
2639 /// \Returns the pointer operand.
2640 const Value *getPointerOperand() const {
2641 return const_cast<AddrSpaceCastInst *>(this)->getPointerOperand();
2642 }
2643 /// \Returns the operand index of the pointer operand.
2644 static unsigned getPointerOperandIndex() { return 0u; }
2645 /// \Returns the address space of the pointer operand.
2646 unsigned getSrcAddressSpace() const {
2648 }
2649 /// \Returns the address space of the result.
2650 unsigned getDestAddressSpace() const {
2651 return getType()->getPointerAddressSpace();
2652 }
2653};
2654
2655class PHINode final : public SingleLLVMInstructionImpl<llvm::PHINode> {
2656 /// Use Context::createPHINode(). Don't call the constructor directly.
2658 : SingleLLVMInstructionImpl(ClassID::PHI, Opcode::PHI, PHI, Ctx) {}
2659 friend Context; // for PHINode()
2660 /// Helper for mapped_iterator.
2661 struct LLVMBBToBB {
2662 Context &Ctx;
2663 LLVMBBToBB(Context &Ctx) : Ctx(Ctx) {}
2664 BasicBlock *operator()(llvm::BasicBlock *LLVMBB) const;
2665 };
2666
2667public:
2668 static PHINode *create(Type *Ty, unsigned NumReservedValues,
2669 Instruction *InsertBefore, Context &Ctx,
2670 const Twine &Name = "");
2671 /// For isa/dyn_cast.
2672 static bool classof(const Value *From);
2673
2676
2678 LLVMBBToBB BBGetter(Ctx);
2679 return const_block_iterator(cast<llvm::PHINode>(Val)->block_begin(),
2680 BBGetter);
2681 }
2683 LLVMBBToBB BBGetter(Ctx);
2684 return const_block_iterator(cast<llvm::PHINode>(Val)->block_end(),
2685 BBGetter);
2686 }
2688 return make_range(block_begin(), block_end());
2689 }
2690
2692
2694
2695 unsigned getNumIncomingValues() const {
2696 return cast<llvm::PHINode>(Val)->getNumIncomingValues();
2697 }
2698 Value *getIncomingValue(unsigned Idx) const;
2699 void setIncomingValue(unsigned Idx, Value *V);
2700 static unsigned getOperandNumForIncomingValue(unsigned Idx) {
2702 }
2703 static unsigned getIncomingValueNumForOperand(unsigned Idx) {
2705 }
2706 BasicBlock *getIncomingBlock(unsigned Idx) const;
2707 BasicBlock *getIncomingBlock(const Use &U) const;
2708
2709 void setIncomingBlock(unsigned Idx, BasicBlock *BB);
2710
2711 void addIncoming(Value *V, BasicBlock *BB);
2712
2713 Value *removeIncomingValue(unsigned Idx);
2715
2716 int getBasicBlockIndex(const BasicBlock *BB) const;
2717 Value *getIncomingValueForBlock(const BasicBlock *BB) const;
2718
2719 Value *hasConstantValue() const;
2720
2722 return cast<llvm::PHINode>(Val)->hasConstantOrUndefValue();
2723 }
2724 bool isComplete() const { return cast<llvm::PHINode>(Val)->isComplete(); }
2725 void replaceIncomingBlockWith(const BasicBlock *Old, BasicBlock *New);
2726 void removeIncomingValueIf(function_ref<bool(unsigned)> Predicate);
2727 // TODO: Implement
2728 // void copyIncomingBlocks(iterator_range<const_block_iterator> BBRange,
2729 // uint32_t ToIdx = 0)
2730};
2731
2732/// An LLLVM Instruction that has no SandboxIR equivalent class gets mapped to
2733/// an OpaqueInstr.
2734class OpaqueInst : public SingleLLVMInstructionImpl<llvm::Instruction> {
2736 : SingleLLVMInstructionImpl(ClassID::Opaque, Opcode::Opaque, I, Ctx) {}
2738 : SingleLLVMInstructionImpl(SubclassID, Opcode::Opaque, I, Ctx) {}
2739 friend class Context; // For constructor.
2740
2741public:
2742 static bool classof(const sandboxir::Value *From) {
2743 return From->getSubclassID() == ClassID::Opaque;
2744 }
2745};
2746
2747class Context {
2748protected:
2751
2752 /// Maps LLVM Value to the corresponding sandboxir::Value. Owns all
2753 /// SandboxIR objects.
2756
2757 /// Remove \p V from the maps and returns the unique_ptr.
2758 std::unique_ptr<Value> detachLLVMValue(llvm::Value *V);
2759 /// Remove \p SBV from all SandboxIR maps and stop owning it. This effectively
2760 /// detaches \p V from the underlying IR.
2761 std::unique_ptr<Value> detach(Value *V);
2762 friend void Instruction::eraseFromParent(); // For detach().
2763 /// Take ownership of VPtr and store it in `LLVMValueToValueMap`.
2764 Value *registerValue(std::unique_ptr<Value> &&VPtr);
2765 friend class EraseFromParent; // For registerValue().
2766 /// This is the actual function that creates sandboxir values for \p V,
2767 /// and among others handles all instruction types.
2769 /// Get or create a sandboxir::Argument for an existing LLVM IR \p LLVMArg.
2771 auto Pair = LLVMValueToValueMap.insert({LLVMArg, nullptr});
2772 auto It = Pair.first;
2773 if (Pair.second) {
2774 It->second = std::unique_ptr<Argument>(new Argument(LLVMArg, *this));
2775 return cast<Argument>(It->second.get());
2776 }
2777 return cast<Argument>(It->second.get());
2778 }
2779 /// Get or create a sandboxir::Value for an existing LLVM IR \p LLVMV.
2781 return getOrCreateValueInternal(LLVMV, 0);
2782 }
2783 /// Get or create a sandboxir::Constant from an existing LLVM IR \p LLVMC.
2785 return cast<Constant>(getOrCreateValueInternal(LLVMC, 0));
2786 }
2787 friend class ConstantInt; // For getOrCreateConstant().
2788 /// Create a sandboxir::BasicBlock for an existing LLVM IR \p BB. This will
2789 /// also create all contents of the block.
2791
2792 friend class BasicBlock; // For getOrCreateValue().
2793
2796
2798 friend SelectInst; // For createSelectInst()
2800 friend InsertElementInst; // For createInsertElementInst()
2802 friend ExtractElementInst; // For createExtractElementInst()
2804 friend ShuffleVectorInst; // For createShuffleVectorInst()
2806 friend BranchInst; // For createBranchInst()
2808 friend LoadInst; // For createLoadInst()
2810 friend StoreInst; // For createStoreInst()
2812 friend ReturnInst; // For createReturnInst()
2814 friend CallInst; // For createCallInst()
2816 friend InvokeInst; // For createInvokeInst()
2818 friend CallBrInst; // For createCallBrInst()
2820 friend CatchPadInst; // For createCatchPadInst()
2822 friend CleanupPadInst; // For createCleanupPadInst()
2824 friend GetElementPtrInst; // For createGetElementPtrInst()
2826 friend CatchSwitchInst; // For createCatchSwitchInst()
2828 friend SwitchInst; // For createSwitchInst()
2830 friend UnaryOperator; // For createUnaryOperator()
2832 friend BinaryOperator; // For createBinaryOperator()
2834 friend AtomicRMWInst; // For createAtomicRMWInst()
2836 friend AtomicCmpXchgInst; // For createAtomicCmpXchgInst()
2838 friend AllocaInst; // For createAllocaInst()
2840 friend CastInst; // For createCastInst()
2842 friend PHINode; // For createPHINode()
2844 friend UnreachableInst; // For createUnreachableInst()
2845
2846public:
2848 : LLVMCtx(LLVMCtx), IRTracker(*this),
2850
2852 /// Convenience function for `getTracker().save()`
2853 void save() { IRTracker.save(); }
2854 /// Convenience function for `getTracker().revert()`
2856 /// Convenience function for `getTracker().accept()`
2858
2860 const sandboxir::Value *getValue(const llvm::Value *V) const {
2861 return getValue(const_cast<llvm::Value *>(V));
2862 }
2863 /// Create a sandboxir::Function for an existing LLVM IR \p F, including all
2864 /// blocks and instructions.
2865 /// This is the main API function for creating Sandbox IR.
2867
2868 /// \Returns the number of values registered with Context.
2869 size_t getNumValues() const { return LLVMValueToValueMap.size(); }
2870};
2871
2872class Function : public Constant {
2873 /// Helper for mapped_iterator.
2874 struct LLVMBBToBB {
2875 Context &Ctx;
2876 LLVMBBToBB(Context &Ctx) : Ctx(Ctx) {}
2877 BasicBlock &operator()(llvm::BasicBlock &LLVMBB) const {
2878 return *cast<BasicBlock>(Ctx.getValue(&LLVMBB));
2879 }
2880 };
2881 /// Use Context::createFunction() instead.
2883 : Constant(ClassID::Function, F, Ctx) {}
2884 friend class Context; // For constructor.
2885
2886public:
2887 /// For isa/dyn_cast.
2888 static bool classof(const sandboxir::Value *From) {
2889 return From->getSubclassID() == ClassID::Function;
2890 }
2891
2892 Argument *getArg(unsigned Idx) const {
2893 llvm::Argument *Arg = cast<llvm::Function>(Val)->getArg(Idx);
2894 return cast<Argument>(Ctx.getValue(Arg));
2895 }
2896
2897 size_t arg_size() const { return cast<llvm::Function>(Val)->arg_size(); }
2898 bool arg_empty() const { return cast<llvm::Function>(Val)->arg_empty(); }
2899
2901 iterator begin() const {
2902 LLVMBBToBB BBGetter(Ctx);
2903 return iterator(cast<llvm::Function>(Val)->begin(), BBGetter);
2904 }
2905 iterator end() const {
2906 LLVMBBToBB BBGetter(Ctx);
2907 return iterator(cast<llvm::Function>(Val)->end(), BBGetter);
2908 }
2910 return cast<llvm::Function>(Val)->getFunctionType();
2911 }
2912
2913#ifndef NDEBUG
2914 void verify() const final {
2915 assert(isa<llvm::Function>(Val) && "Expected Function!");
2916 }
2917 void dumpNameAndArgs(raw_ostream &OS) const;
2918 void dumpOS(raw_ostream &OS) const final;
2919#endif
2920};
2921
2922} // namespace sandboxir
2923} // namespace llvm
2924
2925#endif // LLVM_SANDBOXIR_SANDBOXIR_H
aarch64 promote const
Rewrite undef for PHI
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
BlockVerifier::State From
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
Definition: Compiler.h:533
Returns the sub type a function will return at a given Idx Should correspond to the result type of an ExtractValue instruction executed with just that one unsigned Idx
std::string Name
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
ppc ctr loops PowerPC CTR Loops Verify
StandardInstrumentations SI(Mod->getContext(), Debug, VerifyEach)
const SmallVectorImpl< MachineOperand > & Cond
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
raw_pwrite_stream & OS
Value * RHS
Value * LHS
Class for arbitrary precision integers.
Definition: APInt.h:77
an instruction to allocate memory on the stack
Definition: Instructions.h:61
This class represents an incoming formal argument to a Function.
Definition: Argument.h:31
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
An instruction that atomically checks whether a specified value is in a memory location,...
Definition: Instructions.h:495
static bool isValidFailureOrdering(AtomicOrdering Ordering)
Definition: Instructions.h:566
static bool isValidSuccessOrdering(AtomicOrdering Ordering)
Definition: Instructions.h:561
an instruction that atomically reads a memory location, combines it with another value,...
Definition: Instructions.h:696
static bool isFPOperation(BinOp Op)
Definition: Instructions.h:791
BinOp
This enumeration lists the possible modifications atomicrmw can make.
Definition: Instructions.h:708
static StringRef getOperationName(BinOp Op)
LLVM Basic Block Representation.
Definition: BasicBlock.h:61
InstListType::iterator iterator
Instruction iterators...
Definition: BasicBlock.h:177
Conditional or Unconditional Branch instruction.
CallBr instruction, tracking function calls that may not return control but instead transfer it to a ...
This class represents a function call, abstracting a target machine's calling convention.
This is the base class for all instructions that perform data casts.
Definition: InstrTypes.h:530
Instruction::CastOps getOpcode() const
Return the opcode of this CastInst.
Definition: InstrTypes.h:694
ConstantFolder - Create constants with minimum, target independent, folding.
This is the shared class of boolean and integer constants.
Definition: Constants.h:81
This is an important base class in LLVM.
Definition: Constant.h:42
This class represents an Operation in the Expression.
A parsed version of the target data layout string in and methods for querying it.
Definition: DataLayout.h:63
This instruction extracts a single (scalar) element from a VectorType value.
static bool isValidOperands(const Value *Vec, const Value *Idx)
Return true if an extractelement instruction can be formed with the specified operands.
Convenience struct for specifying and reasoning about fast-math flags.
Definition: FMF.h:20
Class to represent function types.
Definition: DerivedTypes.h:103
Represents flags for the getelementptr instruction/expression.
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
Definition: Instructions.h:915
static unsigned getPointerOperandIndex()
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition: IRBuilder.h:2686
This instruction inserts a single (scalar) element into a VectorType value.
static bool isValidOperands(const Value *Vec, const Value *NewElt, const Value *Idx)
Return true if an insertelement instruction can be formed with the specified operands.
Invoke instruction.
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:67
An instruction for reading from memory.
Definition: Instructions.h:174
MutableArrayRef - Represent a mutable reference to an array (0 or more elements consecutively in memo...
Definition: ArrayRef.h:307
static unsigned getOperandNumForIncomingValue(unsigned i)
static unsigned getIncomingValueNumForOperand(unsigned i)
Class to represent pointers.
Definition: DerivedTypes.h:646
Return a value (possibly void), from a function.
This class represents the LLVM 'select' instruction.
This instruction constructs a fixed permutation of two input vectors.
static bool isZeroEltSplatMask(ArrayRef< int > Mask, int NumSrcElts)
Return true if this shuffle mask chooses all elements with the same value as the first element of exa...
ArrayRef< int > getShuffleMask() const
static bool isSpliceMask(ArrayRef< int > Mask, int NumSrcElts, int &Index)
Return true if this shuffle mask is a splice mask, concatenating the two inputs together and then ext...
static bool isValidOperands(const Value *V1, const Value *V2, const Value *Mask)
Return true if a shufflevector instruction can be formed with the specified operands.
static bool isSelectMask(ArrayRef< int > Mask, int NumSrcElts)
Return true if this shuffle mask chooses elements from its source vectors without lane crossings.
static bool isBitRotateMask(ArrayRef< int > Mask, unsigned EltSizeInBits, unsigned MinSubElts, unsigned MaxSubElts, unsigned &NumSubElts, unsigned &RotateAmt)
Checks if the shuffle is a bit rotation of the first operand across multiple subelements,...
static bool isOneUseSingleSourceMask(ArrayRef< int > Mask, int VF)
Return true if this shuffle mask represents "clustered" mask of size VF, i.e.
static bool isSingleSourceMask(ArrayRef< int > Mask, int NumSrcElts)
Return true if this shuffle mask chooses elements from exactly one source vector.
static bool isDeInterleaveMaskOfFactor(ArrayRef< int > Mask, unsigned Factor, unsigned &Index)
Check if the mask is a DE-interleave mask of the given factor Factor like: <Index,...
static bool isIdentityMask(ArrayRef< int > Mask, int NumSrcElts)
Return true if this shuffle mask chooses elements from exactly one source vector without lane crossin...
static bool isExtractSubvectorMask(ArrayRef< int > Mask, int NumSrcElts, int &Index)
Return true if this shuffle mask is an extract subvector mask.
static bool isReverseMask(ArrayRef< int > Mask, int NumSrcElts)
Return true if this shuffle mask swaps the order of elements from exactly one source vector.
static void commuteShuffleMask(MutableArrayRef< int > Mask, unsigned InVecNumElts)
Change values in a shuffle permute mask assuming the two vector operands of length InVecNumElts have ...
static bool isTransposeMask(ArrayRef< int > Mask, int NumSrcElts)
Return true if this shuffle mask is a transpose mask.
static bool isInsertSubvectorMask(ArrayRef< int > Mask, int NumSrcElts, int &NumSubElts, int &Index)
Return true if this shuffle mask is an insert subvector mask.
static bool isReplicationMask(ArrayRef< int > Mask, int &ReplicationFactor, int &VF)
Return true if this shuffle mask replicates each of the VF elements in a vector ReplicationFactor tim...
static bool isInterleaveMask(ArrayRef< int > Mask, unsigned Factor, unsigned NumInputElts, SmallVectorImpl< unsigned > &StartIndexes)
Return true if the mask interleaves one or more input vectors together.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: SmallVector.h:586
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1209
An instruction for storing to memory.
Definition: Instructions.h:290
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
ConstantIntT * getCaseValue() const
Resolves case value for current case.
Multiway switch.
static const unsigned DefaultPseudoIndex
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
UnaryOps getOpcode() const
Definition: InstrTypes.h:171
This function has undefined behavior.
A Use represents the edge between a Value definition and its users.
Definition: Use.h:43
LLVM Value Representation.
Definition: Value.h:74
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:255
StringRef getName() const
Return a constant reference to the value's name.
Definition: Value.cpp:309
Base class of all SIMD vector types.
Definition: DerivedTypes.h:403
An efficient, type-erasing, non-owning reference to a callable.
A range adaptor for a pair of iterators.
IteratorT end() const
IteratorT begin() const
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:52
unsigned getSrcAddressSpace() const
\Returns the address space of the pointer operand.
Definition: SandboxIR.h:2646
Value * getPointerOperand()
\Returns the pointer operand.
Definition: SandboxIR.h:2638
unsigned getDestAddressSpace() const
\Returns the address space of the result.
Definition: SandboxIR.h:2650
const Value * getPointerOperand() const
\Returns the pointer operand.
Definition: SandboxIR.h:2640
static unsigned getPointerOperandIndex()
\Returns the operand index of the pointer operand.
Definition: SandboxIR.h:2644
bool isUsedWithInAlloca() const
Return true if this alloca is used as an inalloca argument to a call.
Definition: SandboxIR.h:2525
Value * getArraySize()
Get the number of elements allocated.
Definition: SandboxIR.cpp:1794
Type * getAllocatedType() const
Return the type that is being allocated by the instruction.
Definition: SandboxIR.h:2507
bool isStaticAlloca() const
Return true if this alloca is in the entry block of the function and is a constant size.
Definition: SandboxIR.h:2520
bool isArrayAllocation() const
Return true if there is an allocation size parameter to the allocation instruction that is not 1.
Definition: SandboxIR.h:2479
std::optional< TypeSize > getAllocationSizeInBits(const DataLayout &DL) const
Get allocation size in bits.
Definition: SandboxIR.h:2503
void setAlignment(Align Align)
Definition: SandboxIR.cpp:1779
unsigned getAddressSpace() const
Return the address space for the allocation.
Definition: SandboxIR.h:2493
Align getAlign() const
Return the alignment of the memory that is being allocated by the instruction.
Definition: SandboxIR.h:2515
PointerType * getType() const
Overload to return most specific pointer type.
Definition: SandboxIR.h:2489
void setUsedWithInAlloca(bool V)
Specify whether this alloca is used to represent the arguments to a call.
Definition: SandboxIR.cpp:1787
static AllocaInst * create(Type *Ty, unsigned AddrSpace, BBIterator WhereIt, BasicBlock *WhereBB, Context &Ctx, Value *ArraySize=nullptr, const Twine &Name="")
Definition: SandboxIR.cpp:1746
static bool classof(const Value *From)
Definition: SandboxIR.h:2531
std::optional< TypeSize > getAllocationSize(const DataLayout &DL) const
Get allocation size in bytes.
Definition: SandboxIR.h:2498
const Value * getArraySize() const
Definition: SandboxIR.h:2485
void setAllocatedType(Type *Ty)
for use only in special circumstances that need to generically transform a whole instruction (eg: IR ...
Definition: SandboxIR.cpp:1772
Argument of a sandboxir::Function.
Definition: SandboxIR.h:392
void dumpOS(raw_ostream &OS) const final
Definition: SandboxIR.cpp:214
void printAsOperand(raw_ostream &OS) const
Definition: SandboxIR.cpp:211
void verify() const final
Should crash if there is something wrong with the instruction.
Definition: SandboxIR.h:402
static bool classof(const sandboxir::Value *From)
Definition: SandboxIR.h:398
void setSyncScopeID(SyncScope::ID SSID)
Definition: SandboxIR.cpp:1648
void setVolatile(bool V)
Specify whether this is a volatile cmpxchg.
Definition: SandboxIR.cpp:1716
const Value * getNewValOperand() const
Definition: SandboxIR.h:2434
void setSuccessOrdering(AtomicOrdering Ordering)
Definition: SandboxIR.cpp:1730
unsigned getPointerAddressSpace() const
Returns the address space of the pointer operand.
Definition: SandboxIR.h:2439
AtomicOrdering getMergedOrdering() const
Definition: SandboxIR.h:2416
const Value * getCompareOperand() const
Definition: SandboxIR.h:2429
static AtomicCmpXchgInst * create(Value *Ptr, Value *Cmp, Value *New, MaybeAlign Align, AtomicOrdering SuccessOrdering, AtomicOrdering FailureOrdering, BBIterator WhereIt, BasicBlock *WhereBB, Context &Ctx, SyncScope::ID SSID=SyncScope::System, const Twine &Name="")
Definition: SandboxIR.cpp:1669
const Value * getPointerOperand() const
Definition: SandboxIR.h:2424
AtomicOrdering getFailureOrdering() const
Definition: SandboxIR.h:2412
static bool isValidFailureOrdering(AtomicOrdering Ordering)
Definition: SandboxIR.h:2404
bool isVolatile() const
Return true if this is a cmpxchg from a volatile memory location.
Definition: SandboxIR.h:2393
static bool isValidSuccessOrdering(AtomicOrdering Ordering)
Definition: SandboxIR.h:2401
AtomicOrdering getSuccessOrdering() const
Definition: SandboxIR.h:2407
void setFailureOrdering(AtomicOrdering Ordering)
Definition: SandboxIR.cpp:1738
SyncScope::ID getSyncScopeID() const
Definition: SandboxIR.h:2419
Align getAlign() const
Return the alignment of the memory that is being allocated by the instruction.
Definition: SandboxIR.h:2386
bool isWeak() const
Return true if this cmpxchg may spuriously fail.
Definition: SandboxIR.h:2399
static AtomicRMWInst * create(BinOp Op, Value *Ptr, Value *Val, MaybeAlign Align, AtomicOrdering Ordering, BBIterator WhereIt, BasicBlock *WhereBB, Context &Ctx, SyncScope::ID SSID=SyncScope::System, const Twine &Name="")
Definition: SandboxIR.cpp:1616
const Value * getPointerOperand() const
Definition: SandboxIR.h:2340
unsigned getPointerAddressSpace() const
Definition: SandboxIR.h:2347
llvm::AtomicRMWInst::BinOp BinOp
Definition: SandboxIR.h:2312
SyncScope::ID getSyncScopeID() const
Definition: SandboxIR.h:2335
void setAlignment(Align Align)
Definition: SandboxIR.cpp:1580
const Value * getValOperand() const
Definition: SandboxIR.h:2344
void setSyncScopeID(SyncScope::ID SSID)
Definition: SandboxIR.cpp:1601
static StringRef getOperationName(BinOp Op)
Definition: SandboxIR.h:2316
void setOrdering(AtomicOrdering Ordering)
Definition: SandboxIR.cpp:1594
AtomicOrdering getOrdering() const
Definition: SandboxIR.h:2331
static bool classof(const Value *From)
Definition: SandboxIR.h:2353
bool isFloatingPointOperation() const
Definition: SandboxIR.h:2350
static bool isFPOperation(BinOp Op)
Definition: SandboxIR.h:2319
Iterator for Instructions in a `BasicBlock.
Definition: SandboxIR.h:569
BBIterator operator++(int)
Definition: SandboxIR.h:589
bool operator!=(const BBIterator &Other) const
Definition: SandboxIR.h:604
BBIterator operator--(int)
Definition: SandboxIR.h:595
pointer get() const
\Returns the SBInstruction that corresponds to this iterator, or null if the instruction is not found...
Definition: SandboxIR.h:607
reference operator*() const
Definition: SandboxIR.h:587
std::bidirectional_iterator_tag iterator_category
Definition: SandboxIR.h:575
std::ptrdiff_t difference_type
Definition: SandboxIR.h:571
BBIterator(llvm::BasicBlock *BB, llvm::BasicBlock::iterator It, Context *Ctx)
Definition: SandboxIR.h:585
bool operator==(const BBIterator &Other) const
Definition: SandboxIR.h:600
Contains a list of sandboxir::Instruction's.
Definition: SandboxIR.h:611
void dumpOS(raw_ostream &OS) const final
Definition: SandboxIR.cpp:2458
std::reverse_iterator< iterator > rbegin() const
Definition: SandboxIR.h:636
static bool classof(const Value *From)
For isa/dyn_cast.
Definition: SandboxIR.h:626
void verify() const final
Should crash if there is something wrong with the instruction.
Definition: SandboxIR.h:649
std::reverse_iterator< iterator > rend() const
Definition: SandboxIR.h:639
Function * getParent() const
Definition: SandboxIR.cpp:2390
Instruction & front() const
Definition: SandboxIR.cpp:2441
Instruction * getTerminator() const
Definition: SandboxIR.cpp:2435
Context & getContext() const
Definition: SandboxIR.h:642
Instruction & back() const
Definition: SandboxIR.cpp:2449
iterator end() const
Definition: SandboxIR.h:632
static Value * create(Instruction::Opcode Op, Value *LHS, Value *RHS, BBIterator WhereIt, BasicBlock *WhereBB, Context &Ctx, const Twine &Name="")
Definition: SandboxIR.cpp:1522
static bool classof(const Value *From)
For isa/dyn_cast.
Definition: SandboxIR.h:2298
static Value * createWithCopiedFlags(Instruction::Opcode Op, Value *LHS, Value *RHS, Value *CopyFrom, BBIterator WhereIt, BasicBlock *WhereBB, Context &Ctx, const Twine &Name="")
Definition: SandboxIR.cpp:1551
unsigned getNumSuccessors() const
Definition: SandboxIR.h:1436
iterator_range< sb_succ_op_iterator > successors()
Definition: SandboxIR.h:1457
iterator_range< const_sb_succ_op_iterator > successors() const
Definition: SandboxIR.h:1469
static bool classof(const Value *From)
For isa/dyn_cast.
Definition: SandboxIR.cpp:653
void setCondition(Value *V)
Definition: SandboxIR.h:1435
void setSuccessor(unsigned Idx, BasicBlock *NewSucc)
Definition: SandboxIR.cpp:669
bool isUnconditional() const
Definition: SandboxIR.h:1428
BasicBlock * getSuccessor(unsigned SuccIdx) const
Definition: SandboxIR.cpp:662
static BranchInst * create(BasicBlock *IfTrue, Instruction *InsertBefore, Context &Ctx)
Definition: SandboxIR.cpp:611
Value * getCondition() const
Definition: SandboxIR.cpp:657
iterator_range< const_op_iterator > args() const
Definition: SandboxIR.h:1680
CallingConv::ID getCallingConv() const
Definition: SandboxIR.h:1735
bool isMustTailCall() const
Definition: SandboxIR.h:1726
const Function * getCaller() const
Definition: SandboxIR.h:1723
FunctionType * getFunctionType() const
Definition: SandboxIR.h:1623
void setCalledFunction(Function *F)
Definition: SandboxIR.cpp:851
op_iterator arg_begin()
Definition: SandboxIR.h:1669
const_op_iterator arg_end() const
Definition: SandboxIR.h:1674
iterator_range< op_iterator > args()
Definition: SandboxIR.h:1677
static bool classof(const Value *From)
Definition: SandboxIR.h:1616
Value * getArgOperand(unsigned OpIdx) const
Definition: SandboxIR.h:1686
bool isInlineAsm() const
Definition: SandboxIR.h:1738
Function * getCalledFunction() const
Definition: SandboxIR.cpp:843
Use getArgOperandUse(unsigned Idx)
Definition: SandboxIR.h:1699
bool isDataOperand(Use U) const
Definition: SandboxIR.h:1653
unsigned getArgOperandNo(Use U) const
Definition: SandboxIR.h:1707
const_op_iterator data_operands_end() const
Definition: SandboxIR.h:1636
op_iterator data_operands_end()
Definition: SandboxIR.h:1631
unsigned getDataOperandNo(Use U) const
Definition: SandboxIR.h:1658
unsigned getNumTotalBundleOperands() const
Return the total number operands (not operand bundles) used by every operand bundle in this OperandBu...
Definition: SandboxIR.h:1665
iterator_range< op_iterator > data_ops()
Definition: SandboxIR.h:1641
const_op_iterator data_operands_begin() const
Definition: SandboxIR.h:1628
bool data_operands_empty() const
Definition: SandboxIR.h:1647
bool hasArgument(const Value *V) const
Definition: SandboxIR.h:1710
void setCalledOperand(Value *V)
Definition: SandboxIR.h:1733
unsigned arg_size() const
Definition: SandboxIR.h:1684
unsigned data_operands_size() const
Definition: SandboxIR.h:1650
const_op_iterator arg_begin() const
Definition: SandboxIR.h:1670
Intrinsic::ID getIntrinsicID() const
Definition: SandboxIR.h:1730
Use getArgOperandUse(unsigned Idx) const
Definition: SandboxIR.h:1695
Value * getCalledOperand() const
Definition: SandboxIR.cpp:834
op_iterator data_operands_begin()
Definition: SandboxIR.h:1627
bool isArgOperand(Use U) const
Definition: SandboxIR.h:1704
void setArgOperand(unsigned OpIdx, Value *NewOp)
Definition: SandboxIR.h:1690
iterator_range< const_op_iterator > data_ops() const
Definition: SandboxIR.h:1644
Use getCalledOperandUse() const
Definition: SandboxIR.cpp:838
bool isCallee(Use U) const
Definition: SandboxIR.h:1719
bool isIndirectCall() const
Definition: SandboxIR.h:1716
static CallBrInst * create(FunctionType *FTy, Value *Func, BasicBlock *DefaultDest, ArrayRef< BasicBlock * > IndirectDests, ArrayRef< Value * > Args, BBIterator WhereIt, BasicBlock *WhereBB, Context &Ctx, const Twine &NameStr="")
Definition: SandboxIR.cpp:958
BasicBlock * getIndirectDest(unsigned Idx) const
Definition: SandboxIR.cpp:1016
static bool classof(const Value *From)
Definition: SandboxIR.h:1836
void setDefaultDest(BasicBlock *BB)
Definition: SandboxIR.cpp:1027
Value * getIndirectDestLabel(unsigned Idx) const
Definition: SandboxIR.cpp:1005
Value * getIndirectDestLabelUse(unsigned Idx) const
Definition: SandboxIR.cpp:1008
unsigned getNumIndirectDests() const
Definition: SandboxIR.h:1839
SmallVector< BasicBlock *, 16 > getIndirectDests() const
Definition: SandboxIR.cpp:1020
BasicBlock * getDefaultDest() const
Definition: SandboxIR.cpp:1012
BasicBlock * getSuccessor(unsigned Idx) const
Definition: SandboxIR.cpp:1041
void setIndirectDest(unsigned Idx, BasicBlock *BB)
Definition: SandboxIR.cpp:1033
unsigned getNumSuccessors() const
Definition: SandboxIR.h:1850
static CallInst * create(FunctionType *FTy, Value *Func, ArrayRef< Value * > Args, BBIterator WhereIt, BasicBlock *WhereBB, Context &Ctx, const Twine &NameStr="")
static bool classof(const Value *From)
Definition: SandboxIR.h:1761
static Value * create(Value *Src, Type *DestTy, Instruction *InsertBefore, Context &Ctx, const Twine &Name="")
Definition: SandboxIR.h:2603
static bool classof(const Value *From)
Definition: SandboxIR.h:2613
static Value * create(Value *Src, Type *DestTy, BBIterator WhereIt, BasicBlock *WhereBB, Context &Ctx, const Twine &Name="")
Definition: SandboxIR.h:2598
static Value * create(Value *Src, Type *DestTy, BasicBlock *InsertAtEnd, Context &Ctx, const Twine &Name="")
Definition: SandboxIR.h:2608
static Value * create(Type *DestTy, Opcode Op, Value *Operand, BBIterator WhereIt, BasicBlock *WhereBB, Context &Ctx, const Twine &Name="")
Definition: SandboxIR.cpp:1798
Type * getSrcTy() const
Definition: SandboxIR.h:2591
static bool classof(const Value *From)
For isa/dyn_cast.
Definition: SandboxIR.cpp:1829
Type * getDestTy() const
Definition: SandboxIR.h:2592
static bool classof(const Value *From)
Definition: SandboxIR.h:1898
CatchSwitchInst * getCatchSwitch() const
Definition: SandboxIR.cpp:1069
static CatchPadInst * create(Value *ParentPad, ArrayRef< Value * > Args, BBIterator WhereIt, BasicBlock *WhereBB, Context &Ctx, const Twine &Name="")
Definition: SandboxIR.cpp:1074
const_handler_iterator handler_begin() const
Definition: SandboxIR.h:2056
void setParentPad(Value *ParentPad)
Definition: SandboxIR.cpp:1320
const_handler_iterator handler_end() const
Definition: SandboxIR.h:2065
static CatchSwitchInst * create(Value *ParentPad, BasicBlock *UnwindBB, unsigned NumHandlers, BBIterator WhereIt, BasicBlock *WhereBB, Context &Ctx, const Twine &Name="")
Definition: SandboxIR.cpp:1301
const BasicBlock *(*)(const Value *) ConstDerefFnTy
Definition: SandboxIR.h:2045
BasicBlock *(*)(Value *) DerefFnTy
Definition: SandboxIR.h:2042
unsigned getNumSuccessors() const
Definition: SandboxIR.h:2081
void addHandler(BasicBlock *Dest)
Definition: SandboxIR.cpp:1340
handler_iterator handler_begin()
Definition: SandboxIR.h:2050
mapped_iterator< const_op_iterator, ConstDerefFnTy > const_handler_iterator
Definition: SandboxIR.h:2047
void setUnwindDest(BasicBlock *UnwindDest)
Definition: SandboxIR.cpp:1332
mapped_iterator< op_iterator, DerefFnTy > handler_iterator
Definition: SandboxIR.h:2043
static bool classof(const Value *From)
Definition: SandboxIR.h:2093
BasicBlock * getUnwindDest() const
Definition: SandboxIR.cpp:1327
CatchSwitchInst(llvm::CatchSwitchInst *CSI, Context &Ctx)
Definition: SandboxIR.h:2010
handler_iterator handler_end()
Definition: SandboxIR.h:2062
unsigned getNumHandlers() const
Definition: SandboxIR.h:2031
void setSuccessor(unsigned Idx, BasicBlock *NewSucc)
Definition: SandboxIR.h:2087
BasicBlock * getSuccessor(unsigned Idx) const
Definition: SandboxIR.h:2082
const_handler_range handlers() const
Definition: SandboxIR.h:2071
static CleanupPadInst * create(Value *ParentPad, ArrayRef< Value * > Args, BBIterator WhereIt, BasicBlock *WhereBB, Context &Ctx, const Twine &Name="")
Definition: SandboxIR.cpp:1091
static bool classof(const Value *From)
Definition: SandboxIR.h:1912
static ConstantInt * get(Type *Ty, uint64_t V, Context &Ctx, bool IsSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
Definition: SandboxIR.cpp:1956
void verify() const override
Should crash if there is something wrong with the instruction.
Definition: SandboxIR.h:557
unsigned getUseOperandNo(const Use &Use) const override
\Returns the operand index of Use.
Definition: SandboxIR.h:553
void dumpOS(raw_ostream &OS) const override
Definition: SandboxIR.h:560
static bool classof(const sandboxir::Value *From)
For isa/dyn_cast.
Definition: SandboxIR.h:550
sandboxir::Context & getParent() const
Definition: SandboxIR.h:520
void verify() const override
Should crash if there is something wrong with the instruction.
Definition: SandboxIR.h:525
static bool classof(const sandboxir::Value *From)
For isa/dyn_cast.
Definition: SandboxIR.h:515
void dumpOS(raw_ostream &OS) const override
Definition: SandboxIR.cpp:1950
unsigned getUseOperandNo(const Use &Use) const override
\Returns the operand index of Use.
Definition: SandboxIR.h:521
friend class ConstantInt
Definition: SandboxIR.h:506
CallBrInst * createCallBrInst(llvm::CallBrInst *I)
Definition: SandboxIR.cpp:2307
GetElementPtrInst * createGetElementPtrInst(llvm::GetElementPtrInst *I)
Definition: SandboxIR.cpp:2326
DenseMap< llvm::Value *, std::unique_ptr< sandboxir::Value > > LLVMValueToValueMap
Maps LLVM Value to the corresponding sandboxir::Value.
Definition: SandboxIR.h:2755
Value * registerValue(std::unique_ptr< Value > &&VPtr)
Take ownership of VPtr and store it in LLVMValueToValueMap.
Definition: SandboxIR.cpp:2019
CatchPadInst * createCatchPadInst(llvm::CatchPadInst *I)
Definition: SandboxIR.cpp:2317
sandboxir::Value * getValue(llvm::Value *V) const
Definition: SandboxIR.cpp:2370
IRBuilder< ConstantFolder > LLVMIRBuilder
Definition: SandboxIR.h:2794
Argument * getOrCreateArgument(llvm::Argument *LLVMArg)
Get or create a sandboxir::Argument for an existing LLVM IR LLVMArg.
Definition: SandboxIR.h:2770
Function * createFunction(llvm::Function *F)
Create a sandboxir::Function for an existing LLVM IR F, including all blocks and instructions.
Definition: SandboxIR.cpp:2377
Value * getOrCreateValueInternal(llvm::Value *V, llvm::User *U=nullptr)
This is the actual function that creates sandboxir values for V, and among others handles all instruc...
Definition: SandboxIR.cpp:2037
std::unique_ptr< Value > detach(Value *V)
Remove SBV from all SandboxIR maps and stop owning it.
Definition: SandboxIR.cpp:2012
SwitchInst * createSwitchInst(llvm::SwitchInst *I)
Definition: SandboxIR.cpp:2335
UnreachableInst * createUnreachableInst(llvm::UnreachableInst *UI)
Definition: SandboxIR.cpp:2312
const sandboxir::Value * getValue(const llvm::Value *V) const
Definition: SandboxIR.h:2860
void accept()
Convenience function for getTracker().accept()
Definition: SandboxIR.h:2857
ShuffleVectorInst * createShuffleVectorInst(llvm::ShuffleVectorInst *SVI)
Definition: SandboxIR.cpp:2271
BranchInst * createBranchInst(llvm::BranchInst *I)
Definition: SandboxIR.cpp:2277
Constant * getOrCreateConstant(llvm::Constant *LLVMC)
Get or create a sandboxir::Constant from an existing LLVM IR LLVMC.
Definition: SandboxIR.h:2784
BasicBlock * createBasicBlock(llvm::BasicBlock *BB)
Create a sandboxir::BasicBlock for an existing LLVM IR BB.
Definition: SandboxIR.cpp:2242
UnaryOperator * createUnaryOperator(llvm::UnaryOperator *I)
Definition: SandboxIR.cpp:2339
ExtractElementInst * createExtractElementInst(llvm::ExtractElementInst *EEI)
Definition: SandboxIR.cpp:2257
LoadInst * createLoadInst(llvm::LoadInst *LI)
Definition: SandboxIR.cpp:2282
AllocaInst * createAllocaInst(llvm::AllocaInst *I)
Definition: SandboxIR.cpp:2357
Context(LLVMContext &LLVMCtx)
Definition: SandboxIR.h:2847
void revert()
Convenience function for getTracker().revert()
Definition: SandboxIR.h:2855
CallInst * createCallInst(llvm::CallInst *I)
Definition: SandboxIR.cpp:2297
AtomicRMWInst * createAtomicRMWInst(llvm::AtomicRMWInst *I)
Definition: SandboxIR.cpp:2347
std::unique_ptr< Value > detachLLVMValue(llvm::Value *V)
Remove V from the maps and returns the unique_ptr.
Definition: SandboxIR.cpp:2001
StoreInst * createStoreInst(llvm::StoreInst *SI)
Definition: SandboxIR.cpp:2287
void save()
Convenience function for getTracker().save()
Definition: SandboxIR.h:2853
Value * getOrCreateValue(llvm::Value *LLVMV)
Get or create a sandboxir::Value for an existing LLVM IR LLVMV.
Definition: SandboxIR.h:2780
InsertElementInst * createInsertElementInst(llvm::InsertElementInst *IEI)
Definition: SandboxIR.cpp:2264
AtomicCmpXchgInst * createAtomicCmpXchgInst(llvm::AtomicCmpXchgInst *I)
Definition: SandboxIR.cpp:2352
CatchSwitchInst * createCatchSwitchInst(llvm::CatchSwitchInst *I)
Definition: SandboxIR.cpp:2331
ReturnInst * createReturnInst(llvm::ReturnInst *I)
Definition: SandboxIR.cpp:2292
CleanupPadInst * createCleanupPadInst(llvm::CleanupPadInst *I)
Definition: SandboxIR.cpp:2321
PHINode * createPHINode(llvm::PHINode *I)
Definition: SandboxIR.cpp:2365
SelectInst * createSelectInst(llvm::SelectInst *SI)
Definition: SandboxIR.cpp:2251
CastInst * createCastInst(llvm::CastInst *I)
Definition: SandboxIR.cpp:2361