blob: d2a55f89fac98a55fe11fbaf7729e0342c18927f [file] [log] [blame]
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01001//===-- llvm/Instruction.h - Instruction class definition -------*- C++ -*-===//
2//
Andrew Walbran16937d02019-10-22 13:54:20 +01003// 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
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01006//
7//===----------------------------------------------------------------------===//
8//
9// This file contains the declaration of the Instruction class, which is the
10// base class for all of the LLVM instructions.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_IR_INSTRUCTION_H
15#define LLVM_IR_INSTRUCTION_H
16
17#include "llvm/ADT/ArrayRef.h"
Olivier Deprezf4ef2d02021-04-20 13:36:24 +020018#include "llvm/ADT/Bitfields.h"
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010019#include "llvm/ADT/None.h"
20#include "llvm/ADT/StringRef.h"
21#include "llvm/ADT/ilist_node.h"
22#include "llvm/IR/DebugLoc.h"
23#include "llvm/IR/SymbolTableListTraits.h"
24#include "llvm/IR/User.h"
25#include "llvm/IR/Value.h"
Olivier Deprezf4ef2d02021-04-20 13:36:24 +020026#include "llvm/Support/AtomicOrdering.h"
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010027#include "llvm/Support/Casting.h"
28#include <algorithm>
29#include <cassert>
30#include <cstdint>
31#include <utility>
32
33namespace llvm {
34
35class BasicBlock;
36class FastMathFlags;
37class MDNode;
38class Module;
39struct AAMDNodes;
40
41template <> struct ilist_alloc_traits<Instruction> {
42 static inline void deleteNode(Instruction *V);
43};
44
45class Instruction : public User,
46 public ilist_node_with_parent<Instruction, BasicBlock> {
47 BasicBlock *Parent;
48 DebugLoc DbgLoc; // 'dbg' Metadata cache.
49
Olivier Deprezf4ef2d02021-04-20 13:36:24 +020050 /// Relative order of this instruction in its parent basic block. Used for
51 /// O(1) local dominance checks between instructions.
52 mutable unsigned Order = 0;
53
54protected:
55 // The 15 first bits of `Value::SubclassData` are available for subclasses of
56 // `Instruction` to use.
57 using OpaqueField = Bitfield::Element<uint16_t, 0, 15>;
58
59 // Template alias so that all Instruction storing alignment use the same
60 // definiton.
61 // Valid alignments are powers of two from 2^0 to 2^MaxAlignmentExponent =
62 // 2^29. We store them as Log2(Alignment), so we need 5 bits to encode the 30
63 // possible values.
64 template <unsigned Offset>
65 using AlignmentBitfieldElementT =
66 typename Bitfield::Element<unsigned, Offset, 5,
67 Value::MaxAlignmentExponent>;
68
69 template <unsigned Offset>
70 using BoolBitfieldElementT = typename Bitfield::Element<bool, Offset, 1>;
71
72 template <unsigned Offset>
73 using AtomicOrderingBitfieldElementT =
74 typename Bitfield::Element<AtomicOrdering, Offset, 3,
75 AtomicOrdering::LAST>;
76
77private:
78 // The last bit is used to store whether the instruction has metadata attached
79 // or not.
80 using HasMetadataField = Bitfield::Element<bool, 15, 1>;
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010081
82protected:
83 ~Instruction(); // Use deleteValue() to delete a generic Instruction.
84
85public:
86 Instruction(const Instruction &) = delete;
87 Instruction &operator=(const Instruction &) = delete;
88
89 /// Specialize the methods defined in Value, as we know that an instruction
90 /// can only be used by other instructions.
91 Instruction *user_back() { return cast<Instruction>(*user_begin());}
92 const Instruction *user_back() const { return cast<Instruction>(*user_begin());}
93
94 inline const BasicBlock *getParent() const { return Parent; }
95 inline BasicBlock *getParent() { return Parent; }
96
97 /// Return the module owning the function this instruction belongs to
98 /// or nullptr it the function does not have a module.
99 ///
100 /// Note: this is undefined behavior if the instruction does not have a
101 /// parent, or the parent basic block does not have a parent function.
102 const Module *getModule() const;
103 Module *getModule() {
104 return const_cast<Module *>(
105 static_cast<const Instruction *>(this)->getModule());
106 }
107
108 /// Return the function this instruction belongs to.
109 ///
110 /// Note: it is undefined behavior to call this on an instruction not
111 /// currently inserted into a function.
112 const Function *getFunction() const;
113 Function *getFunction() {
114 return const_cast<Function *>(
115 static_cast<const Instruction *>(this)->getFunction());
116 }
117
118 /// This method unlinks 'this' from the containing basic block, but does not
119 /// delete it.
120 void removeFromParent();
121
122 /// This method unlinks 'this' from the containing basic block and deletes it.
123 ///
124 /// \returns an iterator pointing to the element after the erased one
125 SymbolTableList<Instruction>::iterator eraseFromParent();
126
127 /// Insert an unlinked instruction into a basic block immediately before
128 /// the specified instruction.
129 void insertBefore(Instruction *InsertPos);
130
131 /// Insert an unlinked instruction into a basic block immediately after the
132 /// specified instruction.
133 void insertAfter(Instruction *InsertPos);
134
135 /// Unlink this instruction from its current basic block and insert it into
136 /// the basic block that MovePos lives in, right before MovePos.
137 void moveBefore(Instruction *MovePos);
138
139 /// Unlink this instruction and insert into BB before I.
140 ///
141 /// \pre I is a valid iterator into BB.
142 void moveBefore(BasicBlock &BB, SymbolTableList<Instruction>::iterator I);
143
144 /// Unlink this instruction from its current basic block and insert it into
145 /// the basic block that MovePos lives in, right after MovePos.
146 void moveAfter(Instruction *MovePos);
147
Olivier Deprezf4ef2d02021-04-20 13:36:24 +0200148 /// Given an instruction Other in the same basic block as this instruction,
149 /// return true if this instruction comes before Other. In this worst case,
150 /// this takes linear time in the number of instructions in the block. The
151 /// results are cached, so in common cases when the block remains unmodified,
152 /// it takes constant time.
153 bool comesBefore(const Instruction *Other) const;
154
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100155 //===--------------------------------------------------------------------===//
156 // Subclass classification.
157 //===--------------------------------------------------------------------===//
158
159 /// Returns a member of one of the enums like Instruction::Add.
160 unsigned getOpcode() const { return getValueID() - InstructionVal; }
161
162 const char *getOpcodeName() const { return getOpcodeName(getOpcode()); }
163 bool isTerminator() const { return isTerminator(getOpcode()); }
Andrew Walbran16937d02019-10-22 13:54:20 +0100164 bool isUnaryOp() const { return isUnaryOp(getOpcode()); }
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100165 bool isBinaryOp() const { return isBinaryOp(getOpcode()); }
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100166 bool isIntDivRem() const { return isIntDivRem(getOpcode()); }
Olivier Deprezf4ef2d02021-04-20 13:36:24 +0200167 bool isShift() const { return isShift(getOpcode()); }
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100168 bool isCast() const { return isCast(getOpcode()); }
169 bool isFuncletPad() const { return isFuncletPad(getOpcode()); }
Andrew Scull0372a572018-11-16 15:47:06 +0000170 bool isExceptionalTerminator() const {
171 return isExceptionalTerminator(getOpcode());
172 }
Andrew Walbran16937d02019-10-22 13:54:20 +0100173 bool isIndirectTerminator() const {
174 return isIndirectTerminator(getOpcode());
175 }
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100176
177 static const char* getOpcodeName(unsigned OpCode);
178
179 static inline bool isTerminator(unsigned OpCode) {
180 return OpCode >= TermOpsBegin && OpCode < TermOpsEnd;
181 }
182
Andrew Walbran16937d02019-10-22 13:54:20 +0100183 static inline bool isUnaryOp(unsigned Opcode) {
184 return Opcode >= UnaryOpsBegin && Opcode < UnaryOpsEnd;
185 }
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100186 static inline bool isBinaryOp(unsigned Opcode) {
187 return Opcode >= BinaryOpsBegin && Opcode < BinaryOpsEnd;
188 }
189
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100190 static inline bool isIntDivRem(unsigned Opcode) {
191 return Opcode == UDiv || Opcode == SDiv || Opcode == URem || Opcode == SRem;
192 }
193
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100194 /// Determine if the Opcode is one of the shift instructions.
195 static inline bool isShift(unsigned Opcode) {
196 return Opcode >= Shl && Opcode <= AShr;
197 }
198
199 /// Return true if this is a logical shift left or a logical shift right.
200 inline bool isLogicalShift() const {
201 return getOpcode() == Shl || getOpcode() == LShr;
202 }
203
204 /// Return true if this is an arithmetic shift right.
205 inline bool isArithmeticShift() const {
206 return getOpcode() == AShr;
207 }
208
209 /// Determine if the Opcode is and/or/xor.
210 static inline bool isBitwiseLogicOp(unsigned Opcode) {
211 return Opcode == And || Opcode == Or || Opcode == Xor;
212 }
213
214 /// Return true if this is and/or/xor.
215 inline bool isBitwiseLogicOp() const {
216 return isBitwiseLogicOp(getOpcode());
217 }
218
219 /// Determine if the OpCode is one of the CastInst instructions.
220 static inline bool isCast(unsigned OpCode) {
221 return OpCode >= CastOpsBegin && OpCode < CastOpsEnd;
222 }
223
224 /// Determine if the OpCode is one of the FuncletPadInst instructions.
225 static inline bool isFuncletPad(unsigned OpCode) {
226 return OpCode >= FuncletPadOpsBegin && OpCode < FuncletPadOpsEnd;
227 }
228
Andrew Scull0372a572018-11-16 15:47:06 +0000229 /// Returns true if the OpCode is a terminator related to exception handling.
230 static inline bool isExceptionalTerminator(unsigned OpCode) {
231 switch (OpCode) {
232 case Instruction::CatchSwitch:
233 case Instruction::CatchRet:
234 case Instruction::CleanupRet:
235 case Instruction::Invoke:
236 case Instruction::Resume:
237 return true;
238 default:
239 return false;
240 }
241 }
242
Andrew Walbran16937d02019-10-22 13:54:20 +0100243 /// Returns true if the OpCode is a terminator with indirect targets.
244 static inline bool isIndirectTerminator(unsigned OpCode) {
245 switch (OpCode) {
246 case Instruction::IndirectBr:
247 case Instruction::CallBr:
248 return true;
249 default:
250 return false;
251 }
252 }
253
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100254 //===--------------------------------------------------------------------===//
255 // Metadata manipulation.
256 //===--------------------------------------------------------------------===//
257
258 /// Return true if this instruction has any metadata attached to it.
Olivier Deprezf4ef2d02021-04-20 13:36:24 +0200259 bool hasMetadata() const { return DbgLoc || Value::hasMetadata(); }
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100260
261 /// Return true if this instruction has metadata attached to it other than a
262 /// debug location.
Olivier Deprezf4ef2d02021-04-20 13:36:24 +0200263 bool hasMetadataOtherThanDebugLoc() const { return Value::hasMetadata(); }
264
265 /// Return true if this instruction has the given type of metadata attached.
266 bool hasMetadata(unsigned KindID) const {
267 return getMetadata(KindID) != nullptr;
268 }
269
270 /// Return true if this instruction has the given type of metadata attached.
271 bool hasMetadata(StringRef Kind) const {
272 return getMetadata(Kind) != nullptr;
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100273 }
274
275 /// Get the metadata of given kind attached to this Instruction.
276 /// If the metadata is not found then return null.
277 MDNode *getMetadata(unsigned KindID) const {
278 if (!hasMetadata()) return nullptr;
279 return getMetadataImpl(KindID);
280 }
281
282 /// Get the metadata of given kind attached to this Instruction.
283 /// If the metadata is not found then return null.
284 MDNode *getMetadata(StringRef Kind) const {
285 if (!hasMetadata()) return nullptr;
286 return getMetadataImpl(Kind);
287 }
288
289 /// Get all metadata attached to this Instruction. The first element of each
290 /// pair returned is the KindID, the second element is the metadata value.
291 /// This list is returned sorted by the KindID.
292 void
293 getAllMetadata(SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs) const {
294 if (hasMetadata())
295 getAllMetadataImpl(MDs);
296 }
297
298 /// This does the same thing as getAllMetadata, except that it filters out the
299 /// debug location.
300 void getAllMetadataOtherThanDebugLoc(
301 SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs) const {
Olivier Deprezf4ef2d02021-04-20 13:36:24 +0200302 Value::getAllMetadata(MDs);
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100303 }
304
305 /// Fills the AAMDNodes structure with AA metadata from this instruction.
306 /// When Merge is true, the existing AA metadata is merged with that from this
307 /// instruction providing the most-general result.
308 void getAAMetadata(AAMDNodes &N, bool Merge = false) const;
309
310 /// Set the metadata of the specified kind to the specified node. This updates
311 /// or replaces metadata if already present, or removes it if Node is null.
312 void setMetadata(unsigned KindID, MDNode *Node);
313 void setMetadata(StringRef Kind, MDNode *Node);
314
315 /// Copy metadata from \p SrcInst to this instruction. \p WL, if not empty,
316 /// specifies the list of meta data that needs to be copied. If \p WL is
317 /// empty, all meta data will be copied.
318 void copyMetadata(const Instruction &SrcInst,
319 ArrayRef<unsigned> WL = ArrayRef<unsigned>());
320
321 /// If the instruction has "branch_weights" MD_prof metadata and the MDNode
322 /// has three operands (including name string), swap the order of the
323 /// metadata.
324 void swapProfMetadata();
325
326 /// Drop all unknown metadata except for debug locations.
327 /// @{
328 /// Passes are required to drop metadata they don't understand. This is a
329 /// convenience method for passes to do so.
330 void dropUnknownNonDebugMetadata(ArrayRef<unsigned> KnownIDs);
331 void dropUnknownNonDebugMetadata() {
332 return dropUnknownNonDebugMetadata(None);
333 }
334 void dropUnknownNonDebugMetadata(unsigned ID1) {
335 return dropUnknownNonDebugMetadata(makeArrayRef(ID1));
336 }
337 void dropUnknownNonDebugMetadata(unsigned ID1, unsigned ID2) {
338 unsigned IDs[] = {ID1, ID2};
339 return dropUnknownNonDebugMetadata(IDs);
340 }
341 /// @}
342
Olivier Deprezf4ef2d02021-04-20 13:36:24 +0200343 /// Adds an !annotation metadata node with \p Annotation to this instruction.
344 /// If this instruction already has !annotation metadata, append \p Annotation
345 /// to the existing node.
346 void addAnnotationMetadata(StringRef Annotation);
347
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100348 /// Sets the metadata on this instruction from the AAMDNodes structure.
349 void setAAMetadata(const AAMDNodes &N);
350
351 /// Retrieve the raw weight values of a conditional branch or select.
352 /// Returns true on success with profile weights filled in.
353 /// Returns false if no metadata or invalid metadata was found.
354 bool extractProfMetadata(uint64_t &TrueVal, uint64_t &FalseVal) const;
355
356 /// Retrieve total raw weight values of a branch.
357 /// Returns true on success with profile total weights filled in.
358 /// Returns false if no metadata was found.
359 bool extractProfTotalWeight(uint64_t &TotalVal) const;
360
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100361 /// Set the debug location information for this instruction.
362 void setDebugLoc(DebugLoc Loc) { DbgLoc = std::move(Loc); }
363
364 /// Return the debug location for this node as a DebugLoc.
365 const DebugLoc &getDebugLoc() const { return DbgLoc; }
366
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100367 /// Set or clear the nuw flag on this instruction, which must be an operator
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100368 /// which supports this flag. See LangRef.html for the meaning of this flag.
369 void setHasNoUnsignedWrap(bool b = true);
370
371 /// Set or clear the nsw flag on this instruction, which must be an operator
372 /// which supports this flag. See LangRef.html for the meaning of this flag.
373 void setHasNoSignedWrap(bool b = true);
374
375 /// Set or clear the exact flag on this instruction, which must be an operator
376 /// which supports this flag. See LangRef.html for the meaning of this flag.
377 void setIsExact(bool b = true);
378
379 /// Determine whether the no unsigned wrap flag is set.
380 bool hasNoUnsignedWrap() const;
381
382 /// Determine whether the no signed wrap flag is set.
383 bool hasNoSignedWrap() const;
384
385 /// Drops flags that may cause this instruction to evaluate to poison despite
386 /// having non-poison inputs.
387 void dropPoisonGeneratingFlags();
388
389 /// Determine whether the exact flag is set.
390 bool isExact() const;
391
392 /// Set or clear all fast-math-flags on this instruction, which must be an
393 /// operator which supports this flag. See LangRef.html for the meaning of
394 /// this flag.
395 void setFast(bool B);
396
397 /// Set or clear the reassociation flag on this instruction, which must be
398 /// an operator which supports this flag. See LangRef.html for the meaning of
399 /// this flag.
400 void setHasAllowReassoc(bool B);
401
402 /// Set or clear the no-nans flag on this instruction, which must be an
403 /// operator which supports this flag. See LangRef.html for the meaning of
404 /// this flag.
405 void setHasNoNaNs(bool B);
406
407 /// Set or clear the no-infs flag on this instruction, which must be an
408 /// operator which supports this flag. See LangRef.html for the meaning of
409 /// this flag.
410 void setHasNoInfs(bool B);
411
412 /// Set or clear the no-signed-zeros flag on this instruction, which must be
413 /// an operator which supports this flag. See LangRef.html for the meaning of
414 /// this flag.
415 void setHasNoSignedZeros(bool B);
416
417 /// Set or clear the allow-reciprocal flag on this instruction, which must be
418 /// an operator which supports this flag. See LangRef.html for the meaning of
419 /// this flag.
420 void setHasAllowReciprocal(bool B);
421
Olivier Deprezf4ef2d02021-04-20 13:36:24 +0200422 /// Set or clear the allow-contract flag on this instruction, which must be
423 /// an operator which supports this flag. See LangRef.html for the meaning of
424 /// this flag.
425 void setHasAllowContract(bool B);
426
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100427 /// Set or clear the approximate-math-functions flag on this instruction,
428 /// which must be an operator which supports this flag. See LangRef.html for
429 /// the meaning of this flag.
430 void setHasApproxFunc(bool B);
431
432 /// Convenience function for setting multiple fast-math flags on this
433 /// instruction, which must be an operator which supports these flags. See
434 /// LangRef.html for the meaning of these flags.
435 void setFastMathFlags(FastMathFlags FMF);
436
437 /// Convenience function for transferring all fast-math flag values to this
438 /// instruction, which must be an operator which supports these flags. See
439 /// LangRef.html for the meaning of these flags.
440 void copyFastMathFlags(FastMathFlags FMF);
441
442 /// Determine whether all fast-math-flags are set.
443 bool isFast() const;
444
445 /// Determine whether the allow-reassociation flag is set.
446 bool hasAllowReassoc() const;
447
448 /// Determine whether the no-NaNs flag is set.
449 bool hasNoNaNs() const;
450
451 /// Determine whether the no-infs flag is set.
452 bool hasNoInfs() const;
453
454 /// Determine whether the no-signed-zeros flag is set.
455 bool hasNoSignedZeros() const;
456
457 /// Determine whether the allow-reciprocal flag is set.
458 bool hasAllowReciprocal() const;
459
460 /// Determine whether the allow-contract flag is set.
461 bool hasAllowContract() const;
462
463 /// Determine whether the approximate-math-functions flag is set.
464 bool hasApproxFunc() const;
465
466 /// Convenience function for getting all the fast-math flags, which must be an
467 /// operator which supports these flags. See LangRef.html for the meaning of
468 /// these flags.
469 FastMathFlags getFastMathFlags() const;
470
471 /// Copy I's fast-math flags
472 void copyFastMathFlags(const Instruction *I);
473
474 /// Convenience method to copy supported exact, fast-math, and (optionally)
475 /// wrapping flags from V to this instruction.
476 void copyIRFlags(const Value *V, bool IncludeWrapFlags = true);
477
478 /// Logical 'and' of any supported wrapping, exact, and fast-math flags of
479 /// V and this instruction.
480 void andIRFlags(const Value *V);
481
482 /// Merge 2 debug locations and apply it to the Instruction. If the
483 /// instruction is a CallIns, we need to traverse the inline chain to find
484 /// the common scope. This is not efficient for N-way merging as each time
485 /// you merge 2 iterations, you need to rebuild the hashmap to find the
486 /// common scope. However, we still choose this API because:
487 /// 1) Simplicity: it takes 2 locations instead of a list of locations.
488 /// 2) In worst case, it increases the complexity from O(N*I) to
489 /// O(2*N*I), where N is # of Instructions to merge, and I is the
490 /// maximum level of inline stack. So it is still linear.
491 /// 3) Merging of call instructions should be extremely rare in real
492 /// applications, thus the N-way merging should be in code path.
493 /// The DebugLoc attached to this instruction will be overwritten by the
494 /// merged DebugLoc.
495 void applyMergedLocation(const DILocation *LocA, const DILocation *LocB);
496
Olivier Deprezf4ef2d02021-04-20 13:36:24 +0200497 /// Updates the debug location given that the instruction has been hoisted
498 /// from a block to a predecessor of that block.
499 /// Note: it is undefined behavior to call this on an instruction not
500 /// currently inserted into a function.
501 void updateLocationAfterHoist();
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100502
Olivier Deprezf4ef2d02021-04-20 13:36:24 +0200503 /// Drop the instruction's debug location. This does not guarantee removal
504 /// of the !dbg source location attachment, as it must set a line 0 location
505 /// with scope information attached on call instructions. To guarantee
506 /// removal of the !dbg attachment, use the \ref setDebugLoc() API.
507 /// Note: it is undefined behavior to call this on an instruction not
508 /// currently inserted into a function.
509 void dropLocation();
510
511private:
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100512 // These are all implemented in Metadata.cpp.
513 MDNode *getMetadataImpl(unsigned KindID) const;
514 MDNode *getMetadataImpl(StringRef Kind) const;
515 void
516 getAllMetadataImpl(SmallVectorImpl<std::pair<unsigned, MDNode *>> &) const;
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100517
518public:
519 //===--------------------------------------------------------------------===//
520 // Predicates and helper methods.
521 //===--------------------------------------------------------------------===//
522
523 /// Return true if the instruction is associative:
524 ///
525 /// Associative operators satisfy: x op (y op z) === (x op y) op z
526 ///
527 /// In LLVM, the Add, Mul, And, Or, and Xor operators are associative.
528 ///
529 bool isAssociative() const LLVM_READONLY;
530 static bool isAssociative(unsigned Opcode) {
531 return Opcode == And || Opcode == Or || Opcode == Xor ||
532 Opcode == Add || Opcode == Mul;
533 }
534
535 /// Return true if the instruction is commutative:
536 ///
537 /// Commutative operators satisfy: (x op y) === (y op x)
538 ///
539 /// In LLVM, these are the commutative operators, plus SetEQ and SetNE, when
540 /// applied to any type.
541 ///
Olivier Deprezf4ef2d02021-04-20 13:36:24 +0200542 bool isCommutative() const LLVM_READONLY;
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100543 static bool isCommutative(unsigned Opcode) {
544 switch (Opcode) {
545 case Add: case FAdd:
546 case Mul: case FMul:
547 case And: case Or: case Xor:
548 return true;
549 default:
550 return false;
551 }
552 }
553
554 /// Return true if the instruction is idempotent:
555 ///
556 /// Idempotent operators satisfy: x op x === x
557 ///
558 /// In LLVM, the And and Or operators are idempotent.
559 ///
560 bool isIdempotent() const { return isIdempotent(getOpcode()); }
561 static bool isIdempotent(unsigned Opcode) {
562 return Opcode == And || Opcode == Or;
563 }
564
565 /// Return true if the instruction is nilpotent:
566 ///
567 /// Nilpotent operators satisfy: x op x === Id,
568 ///
569 /// where Id is the identity for the operator, i.e. a constant such that
570 /// x op Id === x and Id op x === x for all x.
571 ///
572 /// In LLVM, the Xor operator is nilpotent.
573 ///
574 bool isNilpotent() const { return isNilpotent(getOpcode()); }
575 static bool isNilpotent(unsigned Opcode) {
576 return Opcode == Xor;
577 }
578
579 /// Return true if this instruction may modify memory.
580 bool mayWriteToMemory() const;
581
582 /// Return true if this instruction may read memory.
583 bool mayReadFromMemory() const;
584
585 /// Return true if this instruction may read or write memory.
586 bool mayReadOrWriteMemory() const {
587 return mayReadFromMemory() || mayWriteToMemory();
588 }
589
590 /// Return true if this instruction has an AtomicOrdering of unordered or
591 /// higher.
592 bool isAtomic() const;
593
594 /// Return true if this atomic instruction loads from memory.
595 bool hasAtomicLoad() const;
596
597 /// Return true if this atomic instruction stores to memory.
598 bool hasAtomicStore() const;
599
600 /// Return true if this instruction may throw an exception.
601 bool mayThrow() const;
602
603 /// Return true if this instruction behaves like a memory fence: it can load
604 /// or store to memory location without being given a memory location.
605 bool isFenceLike() const {
606 switch (getOpcode()) {
607 default:
608 return false;
609 // This list should be kept in sync with the list in mayWriteToMemory for
610 // all opcodes which don't have a memory location.
611 case Instruction::Fence:
612 case Instruction::CatchPad:
613 case Instruction::CatchRet:
614 case Instruction::Call:
615 case Instruction::Invoke:
616 return true;
617 }
618 }
619
620 /// Return true if the instruction may have side effects.
621 ///
622 /// Note that this does not consider malloc and alloca to have side
623 /// effects because the newly allocated memory is completely invisible to
624 /// instructions which don't use the returned value. For cases where this
625 /// matters, isSafeToSpeculativelyExecute may be more appropriate.
626 bool mayHaveSideEffects() const { return mayWriteToMemory() || mayThrow(); }
627
628 /// Return true if the instruction can be removed if the result is unused.
629 ///
630 /// When constant folding some instructions cannot be removed even if their
631 /// results are unused. Specifically terminator instructions and calls that
632 /// may have side effects cannot be removed without semantically changing the
633 /// generated program.
634 bool isSafeToRemove() const;
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100635
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100636 /// Return true if the instruction is a variety of EH-block.
637 bool isEHPad() const {
638 switch (getOpcode()) {
639 case Instruction::CatchSwitch:
640 case Instruction::CatchPad:
641 case Instruction::CleanupPad:
642 case Instruction::LandingPad:
643 return true;
644 default:
645 return false;
646 }
647 }
648
Andrew Walbran16937d02019-10-22 13:54:20 +0100649 /// Return true if the instruction is a llvm.lifetime.start or
650 /// llvm.lifetime.end marker.
651 bool isLifetimeStartOrEnd() const;
652
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100653 /// Return a pointer to the next non-debug instruction in the same basic
Olivier Deprezf4ef2d02021-04-20 13:36:24 +0200654 /// block as 'this', or nullptr if no such instruction exists. Skip any pseudo
655 /// operations if \c SkipPseudoOp is true.
656 const Instruction *
657 getNextNonDebugInstruction(bool SkipPseudoOp = false) const;
658 Instruction *getNextNonDebugInstruction(bool SkipPseudoOp = false) {
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100659 return const_cast<Instruction *>(
Olivier Deprezf4ef2d02021-04-20 13:36:24 +0200660 static_cast<const Instruction *>(this)->getNextNonDebugInstruction(
661 SkipPseudoOp));
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100662 }
663
Andrew Walbran16937d02019-10-22 13:54:20 +0100664 /// Return a pointer to the previous non-debug instruction in the same basic
Olivier Deprezf4ef2d02021-04-20 13:36:24 +0200665 /// block as 'this', or nullptr if no such instruction exists. Skip any pseudo
666 /// operations if \c SkipPseudoOp is true.
667 const Instruction *
668 getPrevNonDebugInstruction(bool SkipPseudoOp = false) const;
669 Instruction *getPrevNonDebugInstruction(bool SkipPseudoOp = false) {
Andrew Walbran16937d02019-10-22 13:54:20 +0100670 return const_cast<Instruction *>(
Olivier Deprezf4ef2d02021-04-20 13:36:24 +0200671 static_cast<const Instruction *>(this)->getPrevNonDebugInstruction(
672 SkipPseudoOp));
Andrew Walbran16937d02019-10-22 13:54:20 +0100673 }
674
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100675 /// Create a copy of 'this' instruction that is identical in all ways except
676 /// the following:
677 /// * The instruction has no parent
678 /// * The instruction has no name
679 ///
680 Instruction *clone() const;
681
682 /// Return true if the specified instruction is exactly identical to the
683 /// current one. This means that all operands match and any extra information
684 /// (e.g. load is volatile) agree.
685 bool isIdenticalTo(const Instruction *I) const;
686
687 /// This is like isIdenticalTo, except that it ignores the
688 /// SubclassOptionalData flags, which may specify conditions under which the
689 /// instruction's result is undefined.
690 bool isIdenticalToWhenDefined(const Instruction *I) const;
691
692 /// When checking for operation equivalence (using isSameOperationAs) it is
693 /// sometimes useful to ignore certain attributes.
694 enum OperationEquivalenceFlags {
695 /// Check for equivalence ignoring load/store alignment.
696 CompareIgnoringAlignment = 1<<0,
697 /// Check for equivalence treating a type and a vector of that type
698 /// as equivalent.
699 CompareUsingScalarTypes = 1<<1
700 };
701
702 /// This function determines if the specified instruction executes the same
703 /// operation as the current one. This means that the opcodes, type, operand
704 /// types and any other factors affecting the operation must be the same. This
705 /// is similar to isIdenticalTo except the operands themselves don't have to
706 /// be identical.
707 /// @returns true if the specified instruction is the same operation as
708 /// the current one.
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100709 /// Determine if one instruction is the same operation as another.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100710 bool isSameOperationAs(const Instruction *I, unsigned flags = 0) const;
711
712 /// Return true if there are any uses of this instruction in blocks other than
713 /// the specified block. Note that PHI nodes are considered to evaluate their
714 /// operands in the corresponding predecessor block.
715 bool isUsedOutsideOfBlock(const BasicBlock *BB) const;
716
Andrew Scull0372a572018-11-16 15:47:06 +0000717 /// Return the number of successors that this instruction has. The instruction
718 /// must be a terminator.
719 unsigned getNumSuccessors() const;
720
721 /// Return the specified successor. This instruction must be a terminator.
722 BasicBlock *getSuccessor(unsigned Idx) const;
723
724 /// Update the specified successor to point at the provided block. This
725 /// instruction must be a terminator.
726 void setSuccessor(unsigned Idx, BasicBlock *BB);
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100727
Andrew Walbran3d2c1972020-04-07 12:24:26 +0100728 /// Replace specified successor OldBB to point at the provided block.
729 /// This instruction must be a terminator.
730 void replaceSuccessorWith(BasicBlock *OldBB, BasicBlock *NewBB);
731
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100732 /// Methods for support type inquiry through isa, cast, and dyn_cast:
733 static bool classof(const Value *V) {
734 return V->getValueID() >= Value::InstructionVal;
735 }
736
737 //----------------------------------------------------------------------
738 // Exported enumerations.
739 //
740 enum TermOps { // These terminate basic blocks
741#define FIRST_TERM_INST(N) TermOpsBegin = N,
742#define HANDLE_TERM_INST(N, OPC, CLASS) OPC = N,
743#define LAST_TERM_INST(N) TermOpsEnd = N+1
744#include "llvm/IR/Instruction.def"
745 };
746
Andrew Walbran16937d02019-10-22 13:54:20 +0100747 enum UnaryOps {
748#define FIRST_UNARY_INST(N) UnaryOpsBegin = N,
749#define HANDLE_UNARY_INST(N, OPC, CLASS) OPC = N,
750#define LAST_UNARY_INST(N) UnaryOpsEnd = N+1
751#include "llvm/IR/Instruction.def"
752 };
753
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100754 enum BinaryOps {
755#define FIRST_BINARY_INST(N) BinaryOpsBegin = N,
756#define HANDLE_BINARY_INST(N, OPC, CLASS) OPC = N,
757#define LAST_BINARY_INST(N) BinaryOpsEnd = N+1
758#include "llvm/IR/Instruction.def"
759 };
760
761 enum MemoryOps {
762#define FIRST_MEMORY_INST(N) MemoryOpsBegin = N,
763#define HANDLE_MEMORY_INST(N, OPC, CLASS) OPC = N,
764#define LAST_MEMORY_INST(N) MemoryOpsEnd = N+1
765#include "llvm/IR/Instruction.def"
766 };
767
768 enum CastOps {
769#define FIRST_CAST_INST(N) CastOpsBegin = N,
770#define HANDLE_CAST_INST(N, OPC, CLASS) OPC = N,
771#define LAST_CAST_INST(N) CastOpsEnd = N+1
772#include "llvm/IR/Instruction.def"
773 };
774
775 enum FuncletPadOps {
776#define FIRST_FUNCLETPAD_INST(N) FuncletPadOpsBegin = N,
777#define HANDLE_FUNCLETPAD_INST(N, OPC, CLASS) OPC = N,
778#define LAST_FUNCLETPAD_INST(N) FuncletPadOpsEnd = N+1
779#include "llvm/IR/Instruction.def"
780 };
781
782 enum OtherOps {
783#define FIRST_OTHER_INST(N) OtherOpsBegin = N,
784#define HANDLE_OTHER_INST(N, OPC, CLASS) OPC = N,
785#define LAST_OTHER_INST(N) OtherOpsEnd = N+1
786#include "llvm/IR/Instruction.def"
787 };
788
789private:
790 friend class SymbolTableListTraits<Instruction>;
Olivier Deprezf4ef2d02021-04-20 13:36:24 +0200791 friend class BasicBlock; // For renumbering.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100792
793 // Shadow Value::setValueSubclassData with a private forwarding method so that
794 // subclasses cannot accidentally use it.
795 void setValueSubclassData(unsigned short D) {
796 Value::setValueSubclassData(D);
797 }
798
799 unsigned short getSubclassDataFromValue() const {
800 return Value::getSubclassDataFromValue();
801 }
802
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100803 void setParent(BasicBlock *P);
804
805protected:
806 // Instruction subclasses can stick up to 15 bits of stuff into the
807 // SubclassData field of instruction with these members.
808
Olivier Deprezf4ef2d02021-04-20 13:36:24 +0200809 template <typename BitfieldElement>
810 typename BitfieldElement::Type getSubclassData() const {
811 static_assert(
812 std::is_same<BitfieldElement, HasMetadataField>::value ||
813 !Bitfield::isOverlapping<BitfieldElement, HasMetadataField>(),
814 "Must not overlap with the metadata bit");
815 return Bitfield::get<BitfieldElement>(getSubclassDataFromValue());
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100816 }
817
Olivier Deprezf4ef2d02021-04-20 13:36:24 +0200818 template <typename BitfieldElement>
819 void setSubclassData(typename BitfieldElement::Type Value) {
820 static_assert(
821 std::is_same<BitfieldElement, HasMetadataField>::value ||
822 !Bitfield::isOverlapping<BitfieldElement, HasMetadataField>(),
823 "Must not overlap with the metadata bit");
824 auto Storage = getSubclassDataFromValue();
825 Bitfield::set<BitfieldElement>(Storage, Value);
826 setValueSubclassData(Storage);
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100827 }
828
829 Instruction(Type *Ty, unsigned iType, Use *Ops, unsigned NumOps,
830 Instruction *InsertBefore = nullptr);
831 Instruction(Type *Ty, unsigned iType, Use *Ops, unsigned NumOps,
832 BasicBlock *InsertAtEnd);
833
834private:
835 /// Create a copy of this instruction.
836 Instruction *cloneImpl() const;
837};
838
839inline void ilist_alloc_traits<Instruction>::deleteNode(Instruction *V) {
840 V->deleteValue();
841}
842
843} // end namespace llvm
844
845#endif // LLVM_IR_INSTRUCTION_H