LLVM 24.0.0git
Instructions.cpp
Go to the documentation of this file.
1//===- Instructions.cpp - Implement the LLVM instructions -----------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements all of the non-inline methods for the LLVM instruction
10// classes.
11//
12//===----------------------------------------------------------------------===//
13
15#include "IROptions.h"
16#include "LLVMContextImpl.h"
19#include "llvm/ADT/Twine.h"
20#include "llvm/IR/Attributes.h"
21#include "llvm/IR/BasicBlock.h"
22#include "llvm/IR/Constant.h"
24#include "llvm/IR/Constants.h"
25#include "llvm/IR/DataLayout.h"
27#include "llvm/IR/Function.h"
28#include "llvm/IR/InstrTypes.h"
29#include "llvm/IR/Instruction.h"
30#include "llvm/IR/Intrinsics.h"
31#include "llvm/IR/LLVMContext.h"
32#include "llvm/IR/MDBuilder.h"
33#include "llvm/IR/Metadata.h"
34#include "llvm/IR/Module.h"
35#include "llvm/IR/Operator.h"
38#include "llvm/IR/Type.h"
39#include "llvm/IR/Value.h"
47#include "llvm/Support/ModRef.h"
49#include <algorithm>
50#include <cassert>
51#include <cstdint>
52#include <optional>
53#include <vector>
54
55using namespace llvm;
56
57//===----------------------------------------------------------------------===//
58// AllocaInst Class
59//===----------------------------------------------------------------------===//
60
62 return DL.getTypeAllocSize(getAllocatedType());
63}
64
65std::optional<TypeSize>
68 // Zero-sized types can return early since 0 * N = 0 for any array size N.
69 if (Size.isZero())
70 return Size;
71 if (isArrayAllocation()) {
73 if (!C)
74 return std::nullopt;
75 std::optional<uint64_t> NumElements = C->getValue().tryZExtValue();
76 if (!NumElements)
77 return std::nullopt;
78 assert(!Size.isScalable() && "Array elements cannot have a scalable size");
79 auto CheckedProd =
80 checkedMulUnsigned(Size.getKnownMinValue(), *NumElements);
81 if (!CheckedProd)
82 return std::nullopt;
83 return TypeSize::getFixed(*CheckedProd);
84 }
85 return Size;
86}
87
88std::optional<TypeSize>
90 std::optional<TypeSize> Size = getAllocationSize(DL);
91 if (!Size)
92 return std::nullopt;
93 auto CheckedProd = checkedMulUnsigned(Size->getKnownMinValue(),
94 static_cast<TypeSize::ScalarTy>(8));
95 if (!CheckedProd)
96 return std::nullopt;
97 return TypeSize::get(*CheckedProd, Size->isScalable());
98}
99
100//===----------------------------------------------------------------------===//
101// SelectInst Class
102//===----------------------------------------------------------------------===//
103
104/// areInvalidOperands - Return a string if the specified operands are invalid
105/// for a select operation, otherwise return null.
106const char *SelectInst::areInvalidOperands(Value *Op0, Value *Op1, Value *Op2) {
107 if (Op1->getType() != Op2->getType())
108 return "both values to select must have same type";
109
110 if (Op1->getType()->isTokenTy())
111 return "select values cannot have token type";
112
113 if (VectorType *VT = dyn_cast<VectorType>(Op0->getType())) {
114 // Vector select.
115 if (VT->getElementType() != Type::getInt1Ty(Op0->getContext()))
116 return "vector select condition element type must be i1";
118 if (!ET)
119 return "selected values for vector select must be vectors";
120 if (ET->getElementCount() != VT->getElementCount())
121 return "vector select requires selected vectors to have "
122 "the same vector length as select condition";
123 } else if (Op0->getType() != Type::getInt1Ty(Op0->getContext())) {
124 return "select condition must be i1 or <n x i1>";
125 }
126 return nullptr;
127}
128
129//===----------------------------------------------------------------------===//
130// PHINode Class
131//===----------------------------------------------------------------------===//
132
133PHINode::PHINode(const PHINode &PN)
134 : Instruction(PN.getType(), Instruction::PHI, AllocMarker),
135 ReservedSpace(PN.getNumOperands()) {
138 std::copy(PN.op_begin(), PN.op_end(), op_begin());
139 copyIncomingBlocks(make_range(PN.block_begin(), PN.block_end()));
140 FMF = PN.FMF;
141}
142
143// removeIncomingValue - Remove an incoming value. This is useful if a
144// predecessor basic block is deleted.
145Value *PHINode::removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty) {
146 Value *Removed = getIncomingValue(Idx);
147 // Swap with the end of the list.
148 unsigned Last = getNumOperands() - 1;
149 if (Idx != Last) {
152 }
153
154 // Nuke the last value.
155 Op<-1>().set(nullptr);
157
158 // If the PHI node is dead, because it has zero entries, nuke it now.
159 if (getNumOperands() == 0 && DeletePHIIfEmpty) {
160 // If anyone is using this PHI, make them use a dummy value instead...
163 }
164 return Removed;
165}
166
167void PHINode::removeIncomingValueIf(function_ref<bool(unsigned)> Predicate,
168 bool DeletePHIIfEmpty) {
169 unsigned NumOps = getNumIncomingValues();
170
171 // Loop backwards in case the predicate is purely index based.
172 for (unsigned Idx = NumOps; Idx-- > 0;) {
173 if (Predicate(Idx)) {
174 unsigned LastIdx = NumOps - 1;
175 if (Idx != LastIdx) {
176 setIncomingValue(Idx, getIncomingValue(LastIdx));
177 setIncomingBlock(Idx, getIncomingBlock(LastIdx));
178 }
179 getOperandUse(LastIdx).set(nullptr);
180 NumOps--;
181 }
182 }
183
185
186 // If the PHI node is dead, because it has zero entries, nuke it now.
187 if (getNumOperands() == 0 && DeletePHIIfEmpty) {
188 // If anyone is using this PHI, make them use a dummy value instead...
191 }
192}
193
194/// growOperands - grow operands - This grows the operand list in response
195/// to a push_back style of operation. This grows the number of ops by 1.5
196/// times.
197///
198void PHINode::growOperands() {
199 unsigned e = getNumOperands();
200 unsigned NumOps = e + e / 2;
201 if (NumOps < 2) NumOps = 2; // 2 op PHI nodes are VERY common.
202
203 ReservedSpace = NumOps;
204 growHungoffUses(ReservedSpace, /*WithExtraValues=*/true);
205}
206
207/// hasConstantValue - If the specified PHI node always merges together the same
208/// value, return the value, otherwise return null.
210 // Exploit the fact that phi nodes always have at least one entry.
211 Value *ConstantValue = getIncomingValue(0);
212 for (unsigned i = 1, e = getNumIncomingValues(); i != e; ++i)
213 if (getIncomingValue(i) != ConstantValue && getIncomingValue(i) != this) {
214 if (ConstantValue != this)
215 return nullptr; // Incoming values not all the same.
216 // The case where the first value is this PHI.
217 ConstantValue = getIncomingValue(i);
218 }
219 if (ConstantValue == this)
220 return PoisonValue::get(getType());
221 return ConstantValue;
222}
223
224/// hasConstantOrUndefValue - Whether the specified PHI node always merges
225/// together the same value, assuming that undefs result in the same value as
226/// non-undefs.
227/// Unlike \ref hasConstantValue, this does not return a value because the
228/// unique non-undef incoming value need not dominate the PHI node.
230 Value *ConstantValue = nullptr;
231 for (unsigned i = 0, e = getNumIncomingValues(); i != e; ++i) {
232 Value *Incoming = getIncomingValue(i);
233 if (Incoming != this && !isa<UndefValue>(Incoming)) {
234 if (ConstantValue && ConstantValue != Incoming)
235 return false;
236 ConstantValue = Incoming;
237 }
238 }
239 return true;
240}
241
242//===----------------------------------------------------------------------===//
243// LandingPadInst Implementation
244//===----------------------------------------------------------------------===//
245
246LandingPadInst::LandingPadInst(Type *RetTy, unsigned NumReservedValues,
247 const Twine &NameStr,
248 InsertPosition InsertBefore)
249 : Instruction(RetTy, Instruction::LandingPad, AllocMarker, InsertBefore) {
250 init(NumReservedValues, NameStr);
251}
252
253LandingPadInst::LandingPadInst(const LandingPadInst &LP)
254 : Instruction(LP.getType(), Instruction::LandingPad, AllocMarker),
255 ReservedSpace(LP.getNumOperands()) {
258 Use *OL = getOperandList();
259 const Use *InOL = LP.getOperandList();
260 for (unsigned I = 0, E = ReservedSpace; I != E; ++I)
261 OL[I] = InOL[I];
262
263 setCleanup(LP.isCleanup());
264}
265
266LandingPadInst *LandingPadInst::Create(Type *RetTy, unsigned NumReservedClauses,
267 const Twine &NameStr,
268 InsertPosition InsertBefore) {
269 return new LandingPadInst(RetTy, NumReservedClauses, NameStr, InsertBefore);
270}
271
272void LandingPadInst::init(unsigned NumReservedValues, const Twine &NameStr) {
273 ReservedSpace = NumReservedValues;
274 allocHungoffUses(ReservedSpace);
276 setName(NameStr);
277 setCleanup(false);
278}
279
280/// growOperands - grow operands - This grows the operand list in response to a
281/// push_back style of operation. This grows the number of ops by 2 times.
282void LandingPadInst::growOperands(unsigned Size) {
283 unsigned e = getNumOperands();
284 if (ReservedSpace >= e + Size) return;
285 ReservedSpace = (std::max(e, 1U) + Size / 2) * 2;
286 growHungoffUses(ReservedSpace);
287}
288
290 unsigned OpNo = getNumOperands();
291 growOperands(1);
292 assert(OpNo < ReservedSpace && "Growing didn't work!");
294 getOperandList()[OpNo] = Val;
295}
296
297//===----------------------------------------------------------------------===//
298// CallBase Implementation
299//===----------------------------------------------------------------------===//
300
302 InsertPosition InsertPt) {
303 switch (CB->getOpcode()) {
304 case Instruction::Call:
305 return CallInst::Create(cast<CallInst>(CB), Bundles, InsertPt);
306 case Instruction::Invoke:
307 return InvokeInst::Create(cast<InvokeInst>(CB), Bundles, InsertPt);
308 case Instruction::CallBr:
309 return CallBrInst::Create(cast<CallBrInst>(CB), Bundles, InsertPt);
310 default:
311 llvm_unreachable("Unknown CallBase sub-class!");
312 }
313}
314
316 InsertPosition InsertPt) {
318 for (unsigned i = 0, e = CI->getNumOperandBundles(); i < e; ++i) {
319 auto ChildOB = CI->getOperandBundleAt(i);
320 if (ChildOB.getTagName() != OpB.getTag())
321 OpDefs.emplace_back(ChildOB);
322 }
323 OpDefs.emplace_back(OpB);
324 return CallBase::Create(CI, OpDefs, InsertPt);
325}
326
328
330 assert(getOpcode() == Instruction::CallBr && "Unexpected opcode!");
331 return cast<CallBrInst>(this)->getNumIndirectDests() + 1;
332}
333
335 const Value *V = getCalledOperand();
336 if (isa<Function>(V) || isa<Constant>(V))
337 return false;
338 return !isInlineAsm();
339}
340
341/// Tests if this call site must be tail call optimized. Only a CallInst can
342/// be tail call optimized.
344 if (auto *CI = dyn_cast<CallInst>(this))
345 return CI->isMustTailCall();
346 return false;
347}
348
349/// Tests if this call site is marked as a tail call.
351 if (auto *CI = dyn_cast<CallInst>(this))
352 return CI->isTailCall();
353 return false;
354}
355
358 return F->getIntrinsicID();
360}
361
363 FPClassTest Mask = Attrs.getRetNoFPClass();
364
365 if (const Function *F = getCalledFunction())
366 Mask |= F->getAttributes().getRetNoFPClass();
367 return Mask;
368}
369
371 FPClassTest Mask = Attrs.getParamNoFPClass(i);
372
373 if (const Function *F = getCalledFunction())
374 Mask |= F->getAttributes().getParamNoFPClass(i);
375 return Mask;
376}
377
378std::optional<ConstantRange> CallBase::getRange() const {
379 Attribute CallAttr = Attrs.getRetAttr(Attribute::Range);
381 if (const Function *F = getCalledFunction())
382 FnAttr = F->getRetAttribute(Attribute::Range);
383
384 if (CallAttr.isValid() && FnAttr.isValid())
385 return CallAttr.getRange().intersectWith(FnAttr.getRange());
386 if (CallAttr.isValid())
387 return CallAttr.getRange();
388 if (FnAttr.isValid())
389 return FnAttr.getRange();
390 return std::nullopt;
391}
392
394 if (hasRetAttr(Attribute::NonNull))
395 return true;
396
397 if (getRetDereferenceableBytes() > 0 &&
399 return true;
400
401 return false;
402}
403
405 unsigned Index;
406
407 if (Attrs.hasAttrSomewhere(Kind, &Index))
408 return getArgOperand(Index - AttributeList::FirstArgIndex);
409 if (const Function *F = getCalledFunction())
410 if (F->getAttributes().hasAttrSomewhere(Kind, &Index))
411 return getArgOperand(Index - AttributeList::FirstArgIndex);
412
413 return nullptr;
414}
415
416/// Determine whether the argument or parameter has the given attribute.
417bool CallBase::paramHasAttr(unsigned ArgNo, Attribute::AttrKind Kind) const {
418 assert(ArgNo < arg_size() && "Param index out of bounds!");
419
420 if (Attrs.hasParamAttr(ArgNo, Kind))
421 return true;
422
423 const Function *F = getCalledFunction();
424 if (!F)
425 return false;
426
427 if (!F->getAttributes().hasParamAttr(ArgNo, Kind))
428 return false;
429
430 // Take into account mod/ref by operand bundles.
431 switch (Kind) {
432 case Attribute::ReadNone:
434 case Attribute::ReadOnly:
436 case Attribute::WriteOnly:
437 return !hasReadingOperandBundles();
438 default:
439 return true;
440 }
441}
442
444 bool AllowUndefOrPoison) const {
446 "Argument must be a pointer");
447 if (paramHasAttr(ArgNo, Attribute::NonNull) &&
448 (AllowUndefOrPoison || paramHasAttr(ArgNo, Attribute::NoUndef)))
449 return true;
450
451 if (paramHasAttr(ArgNo, Attribute::Dereferenceable) &&
453 getCaller(),
455 return true;
456
457 return false;
458}
459
460bool CallBase::hasFnAttrOnCalledFunction(Attribute::AttrKind Kind) const {
462 return F->getAttributes().hasFnAttr(Kind);
463
464 return false;
465}
466
467bool CallBase::hasFnAttrOnCalledFunction(StringRef Kind) const {
469 return F->getAttributes().hasFnAttr(Kind);
470
471 return false;
472}
473
474template <typename AK>
475Attribute CallBase::getFnAttrOnCalledFunction(AK Kind) const {
476 if constexpr (std::is_same_v<AK, Attribute::AttrKind>) {
477 // getMemoryEffects() correctly combines memory effects from the call-site,
478 // operand bundles and function.
479 assert(Kind != Attribute::Memory && "Use getMemoryEffects() instead");
480 }
481
483 return F->getAttributes().getFnAttr(Kind);
484
485 return Attribute();
486}
487
488template LLVM_ABI Attribute
489CallBase::getFnAttrOnCalledFunction(Attribute::AttrKind Kind) const;
490template LLVM_ABI Attribute
491CallBase::getFnAttrOnCalledFunction(StringRef Kind) const;
492
493template <typename AK>
494Attribute CallBase::getParamAttrOnCalledFunction(unsigned ArgNo,
495 AK Kind) const {
497
498 if (auto *F = dyn_cast<Function>(V))
499 return F->getAttributes().getParamAttr(ArgNo, Kind);
500
501 return Attribute();
502}
503template LLVM_ABI Attribute CallBase::getParamAttrOnCalledFunction(
504 unsigned ArgNo, Attribute::AttrKind Kind) const;
505template LLVM_ABI Attribute
506CallBase::getParamAttrOnCalledFunction(unsigned ArgNo, StringRef Kind) const;
507
510 for (unsigned i = 0, e = getNumOperandBundles(); i != e; ++i)
512}
513
516 const unsigned BeginIndex) {
517 auto It = op_begin() + BeginIndex;
518 for (auto &B : Bundles)
519 It = std::copy(B.input_begin(), B.input_end(), It);
520
521 auto *ContextImpl = getContext().pImpl;
522 auto BI = Bundles.begin();
523 unsigned CurrentIndex = BeginIndex;
524
525 for (auto &BOI : bundle_op_infos()) {
526 assert(BI != Bundles.end() && "Incorrect allocation?");
527
528 BOI.Tag = ContextImpl->getOrInsertBundleTag(BI->getTag());
529 BOI.Begin = CurrentIndex;
530 BOI.End = CurrentIndex + BI->input_size();
531 CurrentIndex = BOI.End;
532 BI++;
533 }
534
535 assert(BI == Bundles.end() && "Incorrect allocation?");
536
537 return It;
538}
539
541 /// When there isn't many bundles, we do a simple linear search.
542 /// Else fallback to a binary-search that use the fact that bundles usually
543 /// have similar number of argument to get faster convergence.
545 for (auto &BOI : bundle_op_infos())
546 if (BOI.Begin <= OpIdx && OpIdx < BOI.End)
547 return BOI;
548
549 llvm_unreachable("Did not find operand bundle for operand!");
550 }
551
552 assert(OpIdx >= arg_size() && "the Idx is not in the operand bundles");
554 OpIdx < std::prev(bundle_op_info_end())->End &&
555 "The Idx isn't in the operand bundle");
556
557 /// We need a decimal number below and to prevent using floating point numbers
558 /// we use an intergal value multiplied by this constant.
559 constexpr unsigned NumberScaling = 1024;
560
563 bundle_op_iterator Current = Begin;
564
565 while (Begin != End) {
566 unsigned ScaledOperandPerBundle =
567 NumberScaling * (std::prev(End)->End - Begin->Begin) / (End - Begin);
568 Current = Begin + (((OpIdx - Begin->Begin) * NumberScaling) /
569 ScaledOperandPerBundle);
570 if (Current >= End)
571 Current = std::prev(End);
572 assert(Current < End && Current >= Begin &&
573 "the operand bundle doesn't cover every value in the range");
574 if (OpIdx >= Current->Begin && OpIdx < Current->End)
575 break;
576 if (OpIdx >= Current->End)
577 Begin = Current + 1;
578 else
579 End = Current;
580 }
581
582 assert(OpIdx >= Current->Begin && OpIdx < Current->End &&
583 "the operand bundle doesn't cover every value in the range");
584 return *Current;
585}
586
589 InsertPosition InsertPt) {
590 if (CB->getOperandBundle(ID))
591 return CB;
592
594 CB->getOperandBundlesAsDefs(Bundles);
595 Bundles.push_back(OB);
596 return Create(CB, Bundles, InsertPt);
597}
598
600 InsertPosition InsertPt) {
602 bool CreateNew = false;
603
604 for (unsigned I = 0, E = CB->getNumOperandBundles(); I != E; ++I) {
605 auto Bundle = CB->getOperandBundleAt(I);
606 if (Bundle.getTagID() == ID) {
607 CreateNew = true;
608 continue;
609 }
610 Bundles.emplace_back(Bundle);
611 }
612
613 return CreateNew ? Create(CB, Bundles, InsertPt) : CB;
614}
615
617 InsertPosition InsertPt) {
618 auto OpBundleCount = CB->getNumOperandBundles();
619 assert(Offset < OpBundleCount &&
620 "Trying to remove non-existant operand bundle");
622 Bundles.reserve(OpBundleCount - 1);
623 size_t I = 0;
624 for (; I != Offset; ++I)
625 Bundles.emplace_back(CB->getOperandBundleAt(I));
626 ++I;
627 for (; I != OpBundleCount; ++I)
628 Bundles.emplace_back(CB->getOperandBundleAt(I));
629 return Create(CB, Bundles, InsertPt);
630}
631
633 // Implementation note: this is a conservative implementation of operand
634 // bundle semantics, where *any* non-assume operand bundle (other than
635 // ptrauth) forces a callsite to be at least readonly.
640 getIntrinsicID() != Intrinsic::assume;
641}
642
651
653 MemoryEffects ME = getAttributes().getMemoryEffects();
654 if (auto *Fn = dyn_cast<Function>(getCalledOperand())) {
655 MemoryEffects FnME = Fn->getMemoryEffects();
656 if (hasOperandBundles()) {
657 // TODO: Add a method to get memory effects for operand bundles instead.
659 FnME |= MemoryEffects::readOnly();
661 FnME |= MemoryEffects::writeOnly();
662 }
663 if (isVolatile()) {
664 // Volatile operations also access inaccessible memory.
666 }
667 ME &= FnME;
668 }
669 return ME;
670}
674
675/// Determine if the function does not access memory.
682
683/// Determine if the function does not access or only reads memory.
690
691/// Determine if the function does not access or only writes memory.
698
699/// Determine if the call can access memmory only using pointers based
700/// on its arguments.
707
708/// Determine if the function may only access memory that is
709/// inaccessible from the IR.
716
717/// Determine if the function may only access memory that is
718/// either inaccessible from the IR or pointed to by its arguments.
726
728 if (OpNo < arg_size()) {
729 // If the argument is passed byval, the callee does not have access to the
730 // original pointer and thus cannot capture it.
731 if (isByValArgument(OpNo))
732 return CaptureInfo::none();
733
735 if (auto *Fn = dyn_cast<Function>(getCalledOperand()))
736 CI &= Fn->getAttributes().getParamAttrs(OpNo).getCaptureInfo();
737 return CI;
738 }
739
740 // Bundles on assumes are captures(none).
741 if (getIntrinsicID() == Intrinsic::assume)
742 return CaptureInfo::none();
743
744 // deopt operand bundles are captures(none)
745 auto &BOI = getBundleOpInfoForOperand(OpNo);
746 auto OBU = operandBundleFromBundleOpInfo(BOI);
747 return OBU.isDeoptOperandBundle() ? CaptureInfo::none() : CaptureInfo::all();
748}
749
751 for (unsigned I = 0, E = arg_size(); I < E; ++I) {
753 continue;
754
756 if (auto *Fn = dyn_cast<Function>(getCalledOperand()))
757 CI &= Fn->getAttributes().getParamAttrs(I).getCaptureInfo();
759 return true;
760 }
761 return false;
762}
763
764//===----------------------------------------------------------------------===//
765// CallInst Implementation
766//===----------------------------------------------------------------------===//
767
768void CallInst::init(FunctionType *FTy, Value *Func, ArrayRef<Value *> Args,
769 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr) {
770 this->FTy = FTy;
771 assert(getNumOperands() == Args.size() + CountBundleInputs(Bundles) + 1 &&
772 "NumOperands not set up?");
773
774#ifndef NDEBUG
775 assert((Args.size() == FTy->getNumParams() ||
776 (FTy->isVarArg() && Args.size() > FTy->getNumParams())) &&
777 "Calling a function with bad signature!");
778
779 for (unsigned i = 0; i != Args.size(); ++i)
780 assert((i >= FTy->getNumParams() ||
781 FTy->getParamType(i) == Args[i]->getType()) &&
782 "Calling a function with a bad signature!");
783#endif
784
785 // Set operands in order of their index to match use-list-order
786 // prediction.
787 llvm::copy(Args, op_begin());
788 setCalledOperand(Func);
789
790 auto It = populateBundleOperandInfos(Bundles, Args.size());
791 (void)It;
792 assert(It + 1 == op_end() && "Should add up!");
793
794 setName(NameStr);
795}
796
797void CallInst::init(FunctionType *FTy, Value *Func, const Twine &NameStr) {
798 this->FTy = FTy;
799 assert(getNumOperands() == 1 && "NumOperands not set up?");
800 setCalledOperand(Func);
801
802 assert(FTy->getNumParams() == 0 && "Calling a function with bad signature");
803
804 setName(NameStr);
805}
806
807CallInst::CallInst(FunctionType *Ty, Value *Func, const Twine &Name,
808 AllocInfo AllocInfo, InsertPosition InsertBefore)
809 : CallBase(Ty->getReturnType(), Instruction::Call, AllocInfo,
810 InsertBefore) {
811 init(Ty, Func, Name);
812}
813
814CallInst::CallInst(const CallInst &CI, AllocInfo AllocInfo)
815 : CallBase(CI.Attrs, CI.FTy, CI.getType(), Instruction::Call, AllocInfo) {
817 "Wrong number of operands allocated");
818 setTailCallKind(CI.getTailCallKind());
820
821 std::copy(CI.op_begin(), CI.op_end(), op_begin());
822 std::copy(CI.bundle_op_info_begin(), CI.bundle_op_info_end(),
824 FMF = CI.FMF;
825}
826
828 InsertPosition InsertPt) {
829 std::vector<Value *> Args(CI->arg_begin(), CI->arg_end());
830
831 auto *NewCI = CallInst::Create(CI->getFunctionType(), CI->getCalledOperand(),
832 Args, OpB, CI->getName(), InsertPt);
833 NewCI->setTailCallKind(CI->getTailCallKind());
834 NewCI->setCallingConv(CI->getCallingConv());
835 NewCI->FMF = CI->FMF;
836 NewCI->setAttributes(CI->getAttributes());
837 NewCI->setDebugLoc(CI->getDebugLoc());
838 return NewCI;
839}
840
841// Update profile weight for call instruction by scaling it using the ratio
842// of S/T. The meaning of "branch_weights" meta data for call instruction is
843// transfered to represent call count.
844void CallInst::updateProfWeight(uint64_t S, uint64_t T) {
845 if (T == 0) {
846 LLVM_DEBUG(dbgs() << "Attempting to update profile weights will result in "
847 "div by 0. Ignoring. Likely the function "
848 << getParent()->getParent()->getName()
849 << " has 0 entry count, and contains call instructions "
850 "with non-zero prof info.");
851 return;
852 }
853 scaleProfData(*this, S, T);
854}
855
856//===----------------------------------------------------------------------===//
857// InvokeInst Implementation
858//===----------------------------------------------------------------------===//
859
860void InvokeInst::init(FunctionType *FTy, Value *Fn, BasicBlock *IfNormal,
861 BasicBlock *IfException, ArrayRef<Value *> Args,
863 const Twine &NameStr) {
864 this->FTy = FTy;
865
867 ComputeNumOperands(Args.size(), CountBundleInputs(Bundles)) &&
868 "NumOperands not set up?");
869
870#ifndef NDEBUG
871 assert(((Args.size() == FTy->getNumParams()) ||
872 (FTy->isVarArg() && Args.size() > FTy->getNumParams())) &&
873 "Invoking a function with bad signature");
874
875 for (unsigned i = 0, e = Args.size(); i != e; i++)
876 assert((i >= FTy->getNumParams() ||
877 FTy->getParamType(i) == Args[i]->getType()) &&
878 "Invoking a function with a bad signature!");
879#endif
880
881 // Set operands in order of their index to match use-list-order
882 // prediction.
883 llvm::copy(Args, op_begin());
884 setNormalDest(IfNormal);
885 setUnwindDest(IfException);
887
888 auto It = populateBundleOperandInfos(Bundles, Args.size());
889 (void)It;
890 assert(It + 3 == op_end() && "Should add up!");
891
892 setName(NameStr);
893}
894
895InvokeInst::InvokeInst(const InvokeInst &II, AllocInfo AllocInfo)
896 : CallBase(II.Attrs, II.FTy, II.getType(), Instruction::Invoke, AllocInfo) {
897 assert(getNumOperands() == II.getNumOperands() &&
898 "Wrong number of operands allocated");
899 setCallingConv(II.getCallingConv());
900 std::copy(II.op_begin(), II.op_end(), op_begin());
901 std::copy(II.bundle_op_info_begin(), II.bundle_op_info_end(),
903 SubclassOptionalData = II.SubclassOptionalData;
904}
905
907 InsertPosition InsertPt) {
908 std::vector<Value *> Args(II->arg_begin(), II->arg_end());
909
910 auto *NewII = InvokeInst::Create(
911 II->getFunctionType(), II->getCalledOperand(), II->getNormalDest(),
912 II->getUnwindDest(), Args, OpB, II->getName(), InsertPt);
913 NewII->setCallingConv(II->getCallingConv());
914 NewII->SubclassOptionalData = II->SubclassOptionalData;
915 NewII->setAttributes(II->getAttributes());
916 NewII->setDebugLoc(II->getDebugLoc());
917 return NewII;
918}
919
921 return cast<LandingPadInst>(getUnwindDest()->getFirstNonPHIIt());
922}
923
924void InvokeInst::updateProfWeight(uint64_t S, uint64_t T) {
925 if (T == 0) {
926 LLVM_DEBUG(dbgs() << "Attempting to update profile weights will result in "
927 "div by 0. Ignoring. Likely the function "
928 << getParent()->getParent()->getName()
929 << " has 0 entry count, and contains call instructions "
930 "with non-zero prof info.");
931 return;
932 }
933 scaleProfData(*this, S, T);
934}
935
936//===----------------------------------------------------------------------===//
937// CallBrInst Implementation
938//===----------------------------------------------------------------------===//
939
940void CallBrInst::init(FunctionType *FTy, Value *Fn, BasicBlock *Fallthrough,
941 ArrayRef<BasicBlock *> IndirectDests,
944 const Twine &NameStr) {
945 this->FTy = FTy;
946
947 assert(getNumOperands() == ComputeNumOperands(Args.size(),
948 IndirectDests.size(),
949 CountBundleInputs(Bundles)) &&
950 "NumOperands not set up?");
951
952#ifndef NDEBUG
953 assert(((Args.size() == FTy->getNumParams()) ||
954 (FTy->isVarArg() && Args.size() > FTy->getNumParams())) &&
955 "Calling a function with bad signature");
956
957 for (unsigned i = 0, e = Args.size(); i != e; i++)
958 assert((i >= FTy->getNumParams() ||
959 FTy->getParamType(i) == Args[i]->getType()) &&
960 "Calling a function with a bad signature!");
961#endif
962
963 // Set operands in order of their index to match use-list-order
964 // prediction.
965 llvm::copy(Args, op_begin());
966 NumIndirectDests = IndirectDests.size();
967 setDefaultDest(Fallthrough);
968 for (unsigned i = 0; i != NumIndirectDests; ++i)
969 setIndirectDest(i, IndirectDests[i]);
971
972 auto It = populateBundleOperandInfos(Bundles, Args.size());
973 (void)It;
974 assert(It + 2 + IndirectDests.size() == op_end() && "Should add up!");
975
976 setName(NameStr);
977}
978
979CallBrInst::CallBrInst(const CallBrInst &CBI, AllocInfo AllocInfo)
980 : CallBase(CBI.Attrs, CBI.FTy, CBI.getType(), Instruction::CallBr,
981 AllocInfo) {
983 "Wrong number of operands allocated");
985 std::copy(CBI.op_begin(), CBI.op_end(), op_begin());
986 std::copy(CBI.bundle_op_info_begin(), CBI.bundle_op_info_end(),
989 NumIndirectDests = CBI.NumIndirectDests;
990}
991
992CallBrInst *CallBrInst::Create(CallBrInst *CBI, ArrayRef<OperandBundleDef> OpB,
993 InsertPosition InsertPt) {
994 std::vector<Value *> Args(CBI->arg_begin(), CBI->arg_end());
995
996 auto *NewCBI = CallBrInst::Create(
997 CBI->getFunctionType(), CBI->getCalledOperand(), CBI->getDefaultDest(),
998 CBI->getIndirectDests(), Args, OpB, CBI->getName(), InsertPt);
999 NewCBI->setCallingConv(CBI->getCallingConv());
1000 NewCBI->SubclassOptionalData = CBI->SubclassOptionalData;
1001 NewCBI->setAttributes(CBI->getAttributes());
1002 NewCBI->setDebugLoc(CBI->getDebugLoc());
1003 NewCBI->NumIndirectDests = CBI->NumIndirectDests;
1004 return NewCBI;
1005}
1006
1007//===----------------------------------------------------------------------===//
1008// ReturnInst Implementation
1009//===----------------------------------------------------------------------===//
1010
1011ReturnInst::ReturnInst(const ReturnInst &RI, AllocInfo AllocInfo)
1012 : Instruction(Type::getVoidTy(RI.getContext()), Instruction::Ret,
1013 AllocInfo) {
1015 "Wrong number of operands allocated");
1016 if (RI.getNumOperands())
1017 Op<0>() = RI.Op<0>();
1019}
1020
1021ReturnInst::ReturnInst(LLVMContext &C, Value *retVal, AllocInfo AllocInfo,
1022 InsertPosition InsertBefore)
1023 : Instruction(Type::getVoidTy(C), Instruction::Ret, AllocInfo,
1024 InsertBefore) {
1025 if (retVal)
1026 Op<0>() = retVal;
1027}
1028
1029//===----------------------------------------------------------------------===//
1030// ResumeInst Implementation
1031//===----------------------------------------------------------------------===//
1032
1033ResumeInst::ResumeInst(const ResumeInst &RI)
1034 : Instruction(Type::getVoidTy(RI.getContext()), Instruction::Resume,
1035 AllocMarker) {
1036 Op<0>() = RI.Op<0>();
1037}
1038
1039ResumeInst::ResumeInst(Value *Exn, InsertPosition InsertBefore)
1040 : Instruction(Type::getVoidTy(Exn->getContext()), Instruction::Resume,
1041 AllocMarker, InsertBefore) {
1042 Op<0>() = Exn;
1043}
1044
1045//===----------------------------------------------------------------------===//
1046// CleanupReturnInst Implementation
1047//===----------------------------------------------------------------------===//
1048
1049CleanupReturnInst::CleanupReturnInst(const CleanupReturnInst &CRI,
1051 : Instruction(CRI.getType(), Instruction::CleanupRet, AllocInfo) {
1053 "Wrong number of operands allocated");
1054 setSubclassData<Instruction::OpaqueField>(
1056 Op<0>() = CRI.Op<0>();
1057 if (CRI.hasUnwindDest())
1058 Op<1>() = CRI.Op<1>();
1059}
1060
1061void CleanupReturnInst::init(Value *CleanupPad, BasicBlock *UnwindBB) {
1062 if (UnwindBB)
1063 setSubclassData<UnwindDestField>(true);
1064
1065 Op<0>() = CleanupPad;
1066 if (UnwindBB)
1067 Op<1>() = UnwindBB;
1068}
1069
1070CleanupReturnInst::CleanupReturnInst(Value *CleanupPad, BasicBlock *UnwindBB,
1072 InsertPosition InsertBefore)
1073 : Instruction(Type::getVoidTy(CleanupPad->getContext()),
1074 Instruction::CleanupRet, AllocInfo, InsertBefore) {
1075 init(CleanupPad, UnwindBB);
1076}
1077
1078//===----------------------------------------------------------------------===//
1079// CatchReturnInst Implementation
1080//===----------------------------------------------------------------------===//
1081void CatchReturnInst::init(Value *CatchPad, BasicBlock *BB) {
1082 Op<0>() = CatchPad;
1083 Op<1>() = BB;
1084}
1085
1086CatchReturnInst::CatchReturnInst(const CatchReturnInst &CRI)
1087 : Instruction(Type::getVoidTy(CRI.getContext()), Instruction::CatchRet,
1088 AllocMarker) {
1089 Op<0>() = CRI.Op<0>();
1090 Op<1>() = CRI.Op<1>();
1091}
1092
1093CatchReturnInst::CatchReturnInst(Value *CatchPad, BasicBlock *BB,
1094 InsertPosition InsertBefore)
1095 : Instruction(Type::getVoidTy(BB->getContext()), Instruction::CatchRet,
1096 AllocMarker, InsertBefore) {
1097 init(CatchPad, BB);
1098}
1099
1100//===----------------------------------------------------------------------===//
1101// CatchSwitchInst Implementation
1102//===----------------------------------------------------------------------===//
1103
1104CatchSwitchInst::CatchSwitchInst(Value *ParentPad, BasicBlock *UnwindDest,
1105 unsigned NumReservedValues,
1106 const Twine &NameStr,
1107 InsertPosition InsertBefore)
1108 : Instruction(ParentPad->getType(), Instruction::CatchSwitch, AllocMarker,
1109 InsertBefore) {
1110 if (UnwindDest)
1111 ++NumReservedValues;
1112 init(ParentPad, UnwindDest, NumReservedValues + 1);
1113 setName(NameStr);
1114}
1115
1116CatchSwitchInst::CatchSwitchInst(const CatchSwitchInst &CSI)
1117 : Instruction(CSI.getType(), Instruction::CatchSwitch, AllocMarker) {
1119 init(CSI.getParentPad(), CSI.getUnwindDest(), CSI.getNumOperands());
1120 setNumHungOffUseOperands(ReservedSpace);
1121 Use *OL = getOperandList();
1122 const Use *InOL = CSI.getOperandList();
1123 for (unsigned I = 1, E = ReservedSpace; I != E; ++I)
1124 OL[I] = InOL[I];
1125}
1126
1127void CatchSwitchInst::init(Value *ParentPad, BasicBlock *UnwindDest,
1128 unsigned NumReservedValues) {
1129 assert(ParentPad && NumReservedValues);
1130
1131 ReservedSpace = NumReservedValues;
1132 allocHungoffUses(ReservedSpace);
1133 setNumHungOffUseOperands(UnwindDest ? 2 : 1);
1134
1135 Op<0>() = ParentPad;
1136 if (UnwindDest) {
1138 setUnwindDest(UnwindDest);
1139 }
1140}
1141
1142/// growOperands - grow operands - This grows the operand list in response to a
1143/// push_back style of operation. This grows the number of ops by 2 times.
1144void CatchSwitchInst::growOperands(unsigned Size) {
1145 unsigned NumOperands = getNumOperands();
1146 assert(NumOperands >= 1);
1147 if (ReservedSpace >= NumOperands + Size)
1148 return;
1149 ReservedSpace = (NumOperands + Size / 2) * 2;
1150 growHungoffUses(ReservedSpace);
1151}
1152
1154 unsigned OpNo = getNumOperands();
1155 growOperands(1);
1156 assert(OpNo < ReservedSpace && "Growing didn't work!");
1158 getOperandList()[OpNo] = Handler;
1159}
1160
1162 // Move all subsequent handlers up one.
1163 Use *EndDst = op_end() - 1;
1164 for (Use *CurDst = HI.getCurrent(); CurDst != EndDst; ++CurDst)
1165 *CurDst = *(CurDst + 1);
1166 // Null out the last handler use.
1167 *EndDst = nullptr;
1168
1170}
1171
1172//===----------------------------------------------------------------------===//
1173// FuncletPadInst Implementation
1174//===----------------------------------------------------------------------===//
1175void FuncletPadInst::init(Value *ParentPad, ArrayRef<Value *> Args,
1176 const Twine &NameStr) {
1177 assert(getNumOperands() == 1 + Args.size() && "NumOperands not set up?");
1178 llvm::copy(Args, op_begin());
1179 setParentPad(ParentPad);
1180 setName(NameStr);
1181}
1182
1183FuncletPadInst::FuncletPadInst(const FuncletPadInst &FPI, AllocInfo AllocInfo)
1184 : Instruction(FPI.getType(), FPI.getOpcode(), AllocInfo) {
1186 "Wrong number of operands allocated");
1187 std::copy(FPI.op_begin(), FPI.op_end(), op_begin());
1189}
1190
1191FuncletPadInst::FuncletPadInst(Instruction::FuncletPadOps Op, Value *ParentPad,
1193 const Twine &NameStr,
1194 InsertPosition InsertBefore)
1195 : Instruction(ParentPad->getType(), Op, AllocInfo, InsertBefore) {
1196 init(ParentPad, Args, NameStr);
1197}
1198
1199//===----------------------------------------------------------------------===//
1200// UnreachableInst Implementation
1201//===----------------------------------------------------------------------===//
1202
1204 InsertPosition InsertBefore)
1205 : Instruction(Type::getVoidTy(Context), Instruction::Unreachable,
1206 AllocMarker, InsertBefore) {}
1207
1208//===----------------------------------------------------------------------===//
1209// UncondBrInst Implementation
1210//===----------------------------------------------------------------------===//
1211
1212UncondBrInst::UncondBrInst(BasicBlock *Target, InsertPosition InsertBefore)
1213 : Instruction(Type::getVoidTy(Target->getContext()), Instruction::UncondBr,
1214 AllocMarker, InsertBefore) {
1215 Op<-1>() = Target;
1216}
1217
1218UncondBrInst::UncondBrInst(const UncondBrInst &BI)
1219 : Instruction(Type::getVoidTy(BI.getContext()), Instruction::UncondBr,
1220 AllocMarker) {
1221 Op<-1>() = BI.Op<-1>();
1223}
1224
1225//===----------------------------------------------------------------------===//
1226// CondBrInst Implementation
1227//===----------------------------------------------------------------------===//
1228
1229void CondBrInst::AssertOK() {
1230 assert(getCondition()->getType()->isIntegerTy(1) &&
1231 "May only branch on boolean predicates!");
1232}
1233
1234CondBrInst::CondBrInst(Value *Cond, BasicBlock *IfTrue, BasicBlock *IfFalse,
1235 InsertPosition InsertBefore)
1236 : Instruction(Type::getVoidTy(IfTrue->getContext()), Instruction::CondBr,
1237 AllocMarker, InsertBefore) {
1238 // Assign in order of operand index to make use-list order predictable.
1239 Op<-3>() = Cond;
1240 Op<-2>() = IfTrue;
1241 Op<-1>() = IfFalse;
1242#ifndef NDEBUG
1243 AssertOK();
1244#endif
1245}
1246
1247CondBrInst::CondBrInst(const CondBrInst &BI)
1248 : Instruction(Type::getVoidTy(BI.getContext()), Instruction::CondBr,
1249 AllocMarker) {
1250 // Assign in order of operand index to make use-list order predictable.
1251 Op<-3>() = BI.Op<-3>();
1252 Op<-2>() = BI.Op<-2>();
1253 Op<-1>() = BI.Op<-1>();
1255}
1256
1258 Op<-1>().swap(Op<-2>());
1259
1260 // Update profile metadata if present and it matches our structural
1261 // expectations.
1263}
1264
1265//===----------------------------------------------------------------------===//
1266// AllocaInst Implementation
1267//===----------------------------------------------------------------------===//
1268
1269static Value *getAISize(LLVMContext &Context, Value *Amt) {
1270 if (!Amt)
1271 Amt = ConstantInt::get(Type::getInt32Ty(Context), 1);
1272 else {
1273 assert(!isa<BasicBlock>(Amt) &&
1274 "Passed basic block into allocation size parameter! Use other ctor");
1275 assert(Amt->getType()->isIntegerTy() &&
1276 "Allocation array size is not an integer!");
1277 }
1278 return Amt;
1279}
1280
1282 assert(Pos.isValid() &&
1283 "Insertion position cannot be null when alignment not provided!");
1284 BasicBlock *BB = Pos.getBasicBlock();
1285 assert(BB->getParent() &&
1286 "BB must be in a Function when alignment not provided!");
1287 const DataLayout &DL = BB->getDataLayout();
1288 return DL.getPrefTypeAlign(Ty);
1289}
1290
1291AllocaInst::AllocaInst(Type *Ty, unsigned AddrSpace, const Twine &Name,
1292 InsertPosition InsertBefore)
1293 : AllocaInst(Ty, AddrSpace, /*ArraySize=*/nullptr, Name, InsertBefore) {}
1294
1295AllocaInst::AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize,
1296 const Twine &Name, InsertPosition InsertBefore)
1297 : AllocaInst(Ty, AddrSpace, ArraySize,
1298 computeAllocaDefaultAlign(Ty, InsertBefore), Name,
1299 InsertBefore) {}
1300
1301AllocaInst::AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize,
1302 Align Align, const Twine &Name,
1303 InsertPosition InsertBefore)
1304 : UnaryInstruction(PointerType::get(Ty->getContext(), AddrSpace), Alloca,
1305 getAISize(Ty->getContext(), ArraySize), InsertBefore),
1306 AllocatedType(Ty) {
1308 assert(!Ty->isVoidTy() && "Cannot allocate void!");
1309 setName(Name);
1310}
1311
1314 return !CI->isOne();
1315 return true;
1316}
1317
1318/// isStaticAlloca - Return true if this alloca is in the entry block of the
1319/// function and is a constant size. If so, the code generator will fold it
1320/// into the prolog/epilog code, so it is basically free.
1322 // Must be constant size.
1323 if (!isa<ConstantInt>(getArraySize())) return false;
1324
1325 // Must be in the entry block.
1326 const BasicBlock *Parent = getParent();
1327 return Parent->isEntryBlock() && !isUsedWithInAlloca();
1328}
1329
1330//===----------------------------------------------------------------------===//
1331// LoadInst Implementation
1332//===----------------------------------------------------------------------===//
1333
1334void LoadInst::AssertOK() {
1336 "Ptr must have pointer type.");
1337}
1338
1340 assert(Pos.isValid() &&
1341 "Insertion position cannot be null when alignment not provided!");
1342 BasicBlock *BB = Pos.getBasicBlock();
1343 assert(BB->getParent() &&
1344 "BB must be in a Function when alignment not provided!");
1345 const DataLayout &DL = BB->getDataLayout();
1346 return DL.getABITypeAlign(Ty);
1347}
1348
1349LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name,
1350 InsertPosition InsertBef)
1351 : LoadInst(Ty, Ptr, Name, /*isVolatile=*/false, InsertBef) {}
1352
1353LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile,
1354 InsertPosition InsertBef)
1355 : LoadInst(Ty, Ptr, Name, isVolatile,
1356 computeLoadStoreDefaultAlign(Ty, InsertBef), InsertBef) {}
1357
1358LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile,
1359 Align Align, InsertPosition InsertBef)
1360 : LoadInst(Ty, Ptr, Name, isVolatile, Align, AtomicOrdering::NotAtomic,
1361 SyncScope::System, InsertBef) {}
1362
1363LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name,
1364 const LoadStoreInstProperties &Props,
1365 InsertPosition InsertBef)
1366 : LoadInst(Ty, Ptr, Name, Props.IsVolatile, Props.Alignment, Props.Ordering,
1367 Props.SSID, InsertBef) {
1369}
1370
1371LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile,
1373 InsertPosition InsertBef)
1374 : UnaryInstruction(Ty, Load, Ptr, InsertBef) {
1377 setAtomic(Order, SSID);
1378 AssertOK();
1379 setName(Name);
1380}
1381
1382//===----------------------------------------------------------------------===//
1383// StoreInst Implementation
1384//===----------------------------------------------------------------------===//
1385
1386void StoreInst::AssertOK() {
1387 assert(getOperand(0) && getOperand(1) && "Both operands must be non-null!");
1389 "Ptr must have pointer type!");
1390}
1391
1393 : StoreInst(val, addr, /*isVolatile=*/false, InsertBefore) {}
1394
1396 InsertPosition InsertBefore)
1397 : StoreInst(val, addr, isVolatile,
1398 computeLoadStoreDefaultAlign(val->getType(), InsertBefore),
1399 InsertBefore) {}
1400
1402 InsertPosition InsertBefore)
1404 SyncScope::System, InsertBefore) {}
1405
1407 const LoadStoreInstProperties &Props,
1408 InsertPosition InsertBefore)
1409 : StoreInst(Val, Ptr, Props.IsVolatile, Props.Alignment, Props.Ordering,
1410 Props.SSID, InsertBefore) {
1412}
1413
1415 AtomicOrdering Order, SyncScope::ID SSID,
1416 InsertPosition InsertBefore)
1417 : Instruction(Type::getVoidTy(val->getContext()), Store, AllocMarker,
1418 InsertBefore) {
1419 Op<0>() = val;
1420 Op<1>() = addr;
1423 setAtomic(Order, SSID);
1424 AssertOK();
1425}
1426
1427//===----------------------------------------------------------------------===//
1428// AtomicCmpXchgInst Implementation
1429//===----------------------------------------------------------------------===//
1430
1431void AtomicCmpXchgInst::Init(Value *Ptr, Value *Cmp, Value *NewVal,
1432 Align Alignment, AtomicOrdering SuccessOrdering,
1433 AtomicOrdering FailureOrdering,
1434 SyncScope::ID SSID) {
1435 Op<0>() = Ptr;
1436 Op<1>() = Cmp;
1437 Op<2>() = NewVal;
1438 setSuccessOrdering(SuccessOrdering);
1439 setFailureOrdering(FailureOrdering);
1440 setSyncScopeID(SSID);
1441 setAlignment(Alignment);
1442
1443 assert(getOperand(0) && getOperand(1) && getOperand(2) &&
1444 "All operands must be non-null!");
1446 "Ptr must have pointer type!");
1447 assert(getOperand(1)->getType() == getOperand(2)->getType() &&
1448 "Cmp type and NewVal type must be same!");
1449}
1450
1452 Align Alignment,
1453 AtomicOrdering SuccessOrdering,
1454 AtomicOrdering FailureOrdering,
1455 SyncScope::ID SSID,
1456 InsertPosition InsertBefore)
1457 : Instruction(
1458 StructType::get(Cmp->getType(), Type::getInt1Ty(Cmp->getContext())),
1459 AtomicCmpXchg, AllocMarker, InsertBefore) {
1460 Init(Ptr, Cmp, NewVal, Alignment, SuccessOrdering, FailureOrdering, SSID);
1461}
1462
1463//===----------------------------------------------------------------------===//
1464// AtomicRMWInst Implementation
1465//===----------------------------------------------------------------------===//
1466
1467void AtomicRMWInst::Init(BinOp Operation, Value *Ptr, Value *Val,
1468 Align Alignment, AtomicOrdering Ordering,
1469 SyncScope::ID SSID, bool Elementwise) {
1470 assert(Ordering != AtomicOrdering::NotAtomic &&
1471 "atomicrmw instructions can only be atomic.");
1472 assert(Ordering != AtomicOrdering::Unordered &&
1473 "atomicrmw instructions cannot be unordered.");
1474 Op<0>() = Ptr;
1475 Op<1>() = Val;
1476 setOperation(Operation);
1477 setOrdering(Ordering);
1478 setSyncScopeID(SSID);
1479 setElementwise(Elementwise);
1480 setAlignment(Alignment);
1481
1482 assert(getOperand(0) && getOperand(1) && "All operands must be non-null!");
1484 "Ptr must have pointer type!");
1485 assert(Ordering != AtomicOrdering::NotAtomic &&
1486 "AtomicRMW instructions must be atomic!");
1487}
1488
1490 Align Alignment, AtomicOrdering Ordering,
1491 SyncScope::ID SSID, bool Elementwise,
1492 InsertPosition InsertBefore)
1493 : Instruction(Val->getType(), AtomicRMW, AllocMarker, InsertBefore) {
1494 Init(Operation, Ptr, Val, Alignment, Ordering, SSID, Elementwise);
1495}
1496
1498 switch (Op) {
1500 return "xchg";
1501 case AtomicRMWInst::Add:
1502 return "add";
1503 case AtomicRMWInst::Sub:
1504 return "sub";
1505 case AtomicRMWInst::And:
1506 return "and";
1508 return "nand";
1509 case AtomicRMWInst::Or:
1510 return "or";
1511 case AtomicRMWInst::Xor:
1512 return "xor";
1513 case AtomicRMWInst::Max:
1514 return "max";
1515 case AtomicRMWInst::Min:
1516 return "min";
1518 return "umax";
1520 return "umin";
1522 return "fadd";
1524 return "fsub";
1526 return "fmax";
1528 return "fmin";
1530 return "fmaximum";
1532 return "fminimum";
1534 return "fmaximumnum";
1536 return "fminimumnum";
1538 return "uinc_wrap";
1540 return "udec_wrap";
1542 return "usub_cond";
1544 return "usub_sat";
1546 return "<invalid operation>";
1547 }
1548
1549 llvm_unreachable("invalid atomicrmw operation");
1550}
1551
1552//===----------------------------------------------------------------------===//
1553// FenceInst Implementation
1554//===----------------------------------------------------------------------===//
1555
1557 SyncScope::ID SSID, InsertPosition InsertBefore)
1558 : Instruction(Type::getVoidTy(C), Fence, AllocMarker, InsertBefore) {
1559 setOrdering(Ordering);
1560 setSyncScopeID(SSID);
1561}
1562
1563//===----------------------------------------------------------------------===//
1564// GetElementPtrInst Implementation
1565//===----------------------------------------------------------------------===//
1566
1567void GetElementPtrInst::init(Value *Ptr, ArrayRef<Value *> IdxList,
1568 const Twine &Name) {
1569 assert(getNumOperands() == 1 + IdxList.size() &&
1570 "NumOperands not initialized?");
1571 Op<0>() = Ptr;
1572 llvm::copy(IdxList, op_begin() + 1);
1573 setName(Name);
1574}
1575
1576GetElementPtrInst::GetElementPtrInst(const GetElementPtrInst &GEPI,
1578 : Instruction(GEPI.getType(), GetElementPtr, AllocInfo),
1579 SourceElementType(GEPI.SourceElementType),
1580 ResultElementType(GEPI.ResultElementType) {
1581 assert(getNumOperands() == GEPI.getNumOperands() &&
1582 "Wrong number of operands allocated");
1583 std::copy(GEPI.op_begin(), GEPI.op_end(), op_begin());
1585}
1586
1588 if (auto *Struct = dyn_cast<StructType>(Ty)) {
1589 if (!Struct->indexValid(Idx))
1590 return nullptr;
1591 return Struct->getTypeAtIndex(Idx);
1592 }
1593 if (!Idx->getType()->isIntOrIntVectorTy())
1594 return nullptr;
1595 if (auto *Array = dyn_cast<ArrayType>(Ty))
1596 return Array->getElementType();
1597 if (auto *Vector = dyn_cast<VectorType>(Ty))
1598 return Vector->getElementType();
1599 return nullptr;
1600}
1601
1603 if (auto *Struct = dyn_cast<StructType>(Ty)) {
1604 if (Idx >= Struct->getNumElements())
1605 return nullptr;
1606 return Struct->getElementType(Idx);
1607 }
1608 if (auto *Array = dyn_cast<ArrayType>(Ty))
1609 return Array->getElementType();
1610 if (auto *Vector = dyn_cast<VectorType>(Ty))
1611 return Vector->getElementType();
1612 return nullptr;
1613}
1614
1615template <typename IndexTy>
1617 if (IdxList.empty())
1618 return Ty;
1619 for (IndexTy V : IdxList.slice(1)) {
1621 if (!Ty)
1622 return Ty;
1623 }
1624 return Ty;
1625}
1626
1630
1632 ArrayRef<Constant *> IdxList) {
1633 return getIndexedTypeInternal(Ty, IdxList);
1634}
1635
1639
1640/// hasAllZeroIndices - Return true if all of the indices of this GEP are
1641/// zeros. If so, the result pointer and the first operand have the same
1642/// value, just potentially different types.
1644 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1646 if (!CI->isZero()) return false;
1647 } else {
1648 return false;
1649 }
1650 }
1651 return true;
1652}
1653
1654/// hasAllConstantIndices - Return true if all of the indices of this GEP are
1655/// constant integers. If so, the result pointer and the first operand have
1656/// a constant offset between them.
1658 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1660 return false;
1661 }
1662 return true;
1663}
1664
1668
1670 GEPNoWrapFlags NW = cast<GEPOperator>(this)->getNoWrapFlags();
1671 if (B)
1673 else
1674 NW = NW.withoutInBounds();
1675 setNoWrapFlags(NW);
1676}
1677
1679 return cast<GEPOperator>(this)->getNoWrapFlags();
1680}
1681
1683 return cast<GEPOperator>(this)->isInBounds();
1684}
1685
1687 return cast<GEPOperator>(this)->hasNoUnsignedSignedWrap();
1688}
1689
1691 return cast<GEPOperator>(this)->hasNoUnsignedWrap();
1692}
1693
1695 APInt &Offset) const {
1696 // Delegate to the generic GEPOperator implementation.
1697 return cast<GEPOperator>(this)->accumulateConstantOffset(DL, Offset);
1698}
1699
1701 const DataLayout &DL, unsigned BitWidth,
1702 SmallMapVector<Value *, APInt, 4> &VariableOffsets,
1703 APInt &ConstantOffset) const {
1704 // Delegate to the generic GEPOperator implementation.
1705 return cast<GEPOperator>(this)->collectOffset(DL, BitWidth, VariableOffsets,
1706 ConstantOffset);
1707}
1708
1709//===----------------------------------------------------------------------===//
1710// ExtractElementInst Implementation
1711//===----------------------------------------------------------------------===//
1712
1713ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1714 const Twine &Name,
1715 InsertPosition InsertBef)
1716 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1717 ExtractElement, AllocMarker, InsertBef) {
1718 assert(isValidOperands(Val, Index) &&
1719 "Invalid extractelement instruction operands!");
1720 Op<0>() = Val;
1721 Op<1>() = Index;
1722 setName(Name);
1723}
1724
1725bool ExtractElementInst::isValidOperands(const Value *Val, const Value *Index) {
1726 if (!Val->getType()->isVectorTy() || !Index->getType()->isIntegerTy())
1727 return false;
1728 return true;
1729}
1730
1731//===----------------------------------------------------------------------===//
1732// InsertElementInst Implementation
1733//===----------------------------------------------------------------------===//
1734
1735InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1736 const Twine &Name,
1737 InsertPosition InsertBef)
1738 : Instruction(Vec->getType(), InsertElement, AllocMarker, InsertBef) {
1739 assert(isValidOperands(Vec, Elt, Index) &&
1740 "Invalid insertelement instruction operands!");
1741 Op<0>() = Vec;
1742 Op<1>() = Elt;
1743 Op<2>() = Index;
1744 setName(Name);
1745}
1746
1748 const Value *Index) {
1749 if (!Vec->getType()->isVectorTy())
1750 return false; // First operand of insertelement must be vector type.
1751
1752 if (Elt->getType() != cast<VectorType>(Vec->getType())->getElementType())
1753 return false;// Second operand of insertelement must be vector element type.
1754
1755 if (!Index->getType()->isIntegerTy())
1756 return false; // Third operand of insertelement must be an integer.
1757 return true;
1758}
1759
1760//===----------------------------------------------------------------------===//
1761// ShuffleVectorInst Implementation
1762//===----------------------------------------------------------------------===//
1763
1765 assert(V && "Cannot create placeholder of nullptr V");
1766 return PoisonValue::get(V->getType());
1767}
1768
1770 InsertPosition InsertBefore)
1772 InsertBefore) {}
1773
1775 const Twine &Name,
1776 InsertPosition InsertBefore)
1778 InsertBefore) {}
1779
1781 const Twine &Name,
1782 InsertPosition InsertBefore)
1783 : Instruction(
1784 VectorType::get(cast<VectorType>(V1->getType())->getElementType(),
1785 cast<VectorType>(Mask->getType())->getElementCount()),
1786 ShuffleVector, AllocMarker, InsertBefore) {
1787 assert(isValidOperands(V1, V2, Mask) &&
1788 "Invalid shuffle vector instruction operands!");
1789
1790 Op<0>() = V1;
1791 Op<1>() = V2;
1792 SmallVector<int, 16> MaskArr;
1793 getShuffleMask(cast<Constant>(Mask), MaskArr);
1794 setShuffleMask(MaskArr);
1795 setName(Name);
1796}
1797
1799 const Twine &Name,
1800 InsertPosition InsertBefore)
1801 : Instruction(
1802 VectorType::get(cast<VectorType>(V1->getType())->getElementType(),
1803 Mask.size(), isa<ScalableVectorType>(V1->getType())),
1804 ShuffleVector, AllocMarker, InsertBefore) {
1805 assert(isValidOperands(V1, V2, Mask) &&
1806 "Invalid shuffle vector instruction operands!");
1807 Op<0>() = V1;
1808 Op<1>() = V2;
1809 setShuffleMask(Mask);
1810 setName(Name);
1811}
1812
1814 int NumOpElts = cast<FixedVectorType>(Op<0>()->getType())->getNumElements();
1815 int NumMaskElts = ShuffleMask.size();
1816 SmallVector<int, 16> NewMask(NumMaskElts);
1817 for (int i = 0; i != NumMaskElts; ++i) {
1818 int MaskElt = getMaskValue(i);
1819 if (MaskElt == PoisonMaskElem) {
1820 NewMask[i] = PoisonMaskElem;
1821 continue;
1822 }
1823 assert(MaskElt >= 0 && MaskElt < 2 * NumOpElts && "Out-of-range mask");
1824 MaskElt = (MaskElt < NumOpElts) ? MaskElt + NumOpElts : MaskElt - NumOpElts;
1825 NewMask[i] = MaskElt;
1826 }
1827 setShuffleMask(NewMask);
1828 Op<0>().swap(Op<1>());
1829}
1830
1832 ArrayRef<int> Mask) {
1833 // V1 and V2 must be vectors of the same type.
1834 if (!isa<VectorType>(V1->getType()) || V1->getType() != V2->getType())
1835 return false;
1836
1837 if (isa<ScalableVectorType>(V1->getType()))
1838 return (Mask[0] == 0 || Mask[0] == PoisonMaskElem) && all_equal(Mask);
1839
1840 // Make sure the mask elements make sense.
1841 int64_t MaxMaskSz =
1842 cast<FixedVectorType>(V1->getType())->getNumElements() * 2LL;
1843 for (int Elem : Mask)
1844 if (Elem != PoisonMaskElem && Elem >= MaxMaskSz)
1845 return false;
1846 return true;
1847}
1848
1850 const Value *Mask) {
1851 // V1 and V2 must be vectors of the same type.
1852 if (!V1->getType()->isVectorTy() || V1->getType() != V2->getType())
1853 return false;
1854
1855 // Mask must be vector of i32, and must be the same kind of vector as the
1856 // input vectors
1857 auto *MaskTy = dyn_cast<VectorType>(Mask->getType());
1858 if (!MaskTy || !MaskTy->getElementType()->isIntegerTy(32) ||
1859 isa<ScalableVectorType>(MaskTy) != isa<ScalableVectorType>(V1->getType()))
1860 return false;
1861
1862 // Check to see if Mask is valid.
1864 return true;
1865
1866 // NOTE: Through vector ConstantInt we have the potential to support more
1867 // than just zero splat masks but that requires a LangRef change.
1868 if (isa<ScalableVectorType>(MaskTy))
1869 return false;
1870
1871 unsigned V1Size = cast<FixedVectorType>(V1->getType())->getNumElements();
1872
1873 if (const auto *CI = dyn_cast<ConstantInt>(Mask))
1874 return !CI->uge(V1Size * 2);
1875
1876 if (const auto *MV = dyn_cast<ConstantVector>(Mask)) {
1877 for (Value *Op : MV->operands()) {
1878 if (auto *CI = dyn_cast<ConstantInt>(Op)) {
1879 if (CI->uge(V1Size*2))
1880 return false;
1881 } else if (!isa<UndefValue>(Op)) {
1882 return false;
1883 }
1884 }
1885 return true;
1886 }
1887
1888 if (const auto *CDS = dyn_cast<ConstantDataSequential>(Mask)) {
1889 for (unsigned i = 0, e = cast<FixedVectorType>(MaskTy)->getNumElements();
1890 i != e; ++i)
1891 if (CDS->getElementAsInteger(i) >= V1Size*2)
1892 return false;
1893 return true;
1894 }
1895
1896 return false;
1897}
1898
1900 SmallVectorImpl<int> &Result) {
1901 ElementCount EC = cast<VectorType>(Mask->getType())->getElementCount();
1902
1903 if (isa<ConstantAggregateZero>(Mask) || isa<UndefValue>(Mask)) {
1904 int MaskVal = isa<UndefValue>(Mask) ? -1 : 0;
1905 Result.append(EC.getKnownMinValue(), MaskVal);
1906 return;
1907 }
1908
1909 assert(!EC.isScalable() &&
1910 "Scalable vector shuffle mask must be undef or zeroinitializer");
1911
1912 unsigned NumElts = EC.getFixedValue();
1913
1914 Result.reserve(NumElts);
1915
1916 if (auto *CDS = dyn_cast<ConstantDataSequential>(Mask)) {
1917 for (unsigned i = 0; i != NumElts; ++i)
1918 Result.push_back(CDS->getElementAsInteger(i));
1919 return;
1920 }
1921 for (unsigned i = 0; i != NumElts; ++i) {
1922 Constant *C = Mask->getAggregateElement(i);
1923 Result.push_back(isa<UndefValue>(C) ? -1 :
1924 cast<ConstantInt>(C)->getZExtValue());
1925 }
1926}
1927
1929 ShuffleMask.assign(Mask.begin(), Mask.end());
1930 ShuffleMaskForBitcode = convertShuffleMaskForBitcode(Mask, getType());
1931}
1932
1934 Type *ResultTy) {
1935 Type *Int32Ty = Type::getInt32Ty(ResultTy->getContext());
1936 if (isa<ScalableVectorType>(ResultTy)) {
1937 assert(all_equal(Mask) && "Unexpected shuffle");
1938 Type *VecTy = VectorType::get(Int32Ty, Mask.size(), true);
1939 if (Mask[0] == 0)
1940 return Constant::getNullValue(VecTy);
1941 return PoisonValue::get(VecTy);
1942 }
1944 for (int Elem : Mask) {
1945 if (Elem == PoisonMaskElem)
1946 MaskConst.push_back(PoisonValue::get(Int32Ty));
1947 else
1948 MaskConst.push_back(ConstantInt::get(Int32Ty, Elem));
1949 }
1950 return ConstantVector::get(MaskConst);
1951}
1952
1953static bool isSingleSourceMaskImpl(ArrayRef<int> Mask, int64_t NumOpElts) {
1954 assert(!Mask.empty() && "Shuffle mask must contain elements");
1955 bool UsesLHS = false;
1956 bool UsesRHS = false;
1957 for (int I : Mask) {
1958 if (I == -1)
1959 continue;
1960 assert(I >= 0 && I < (NumOpElts * 2) &&
1961 "Out-of-bounds shuffle mask element");
1962 UsesLHS |= (I < NumOpElts);
1963 UsesRHS |= (I >= NumOpElts);
1964 if (UsesLHS && UsesRHS)
1965 return false;
1966 }
1967 // Allow for degenerate case: completely undef mask means neither source is used.
1968 return UsesLHS || UsesRHS;
1969}
1970
1972 // We don't have vector operand size information, so assume operands are the
1973 // same size as the mask.
1974 return isSingleSourceMaskImpl(Mask, NumSrcElts);
1975}
1976
1977static bool isIdentityMaskImpl(ArrayRef<int> Mask, int NumOpElts) {
1978 if (!isSingleSourceMaskImpl(Mask, NumOpElts))
1979 return false;
1980 for (int i = 0, NumMaskElts = Mask.size(); i < NumMaskElts; ++i) {
1981 if (Mask[i] == -1)
1982 continue;
1983 if (Mask[i] != i && Mask[i] != (NumOpElts + i))
1984 return false;
1985 }
1986 return true;
1987}
1988
1990 if (Mask.size() != static_cast<unsigned>(NumSrcElts))
1991 return false;
1992 // We don't have vector operand size information, so assume operands are the
1993 // same size as the mask.
1994 return isIdentityMaskImpl(Mask, NumSrcElts);
1995}
1996
1998 if (Mask.size() != static_cast<unsigned>(NumSrcElts))
1999 return false;
2000 if (!isSingleSourceMask(Mask, NumSrcElts))
2001 return false;
2002
2003 // The number of elements in the mask must be at least 2.
2004 if (NumSrcElts < 2)
2005 return false;
2006
2007 for (int I = 0, E = Mask.size(); I < E; ++I) {
2008 if (Mask[I] == -1)
2009 continue;
2010 if (Mask[I] != (NumSrcElts - 1 - I) &&
2011 Mask[I] != (NumSrcElts + NumSrcElts - 1 - I))
2012 return false;
2013 }
2014 return true;
2015}
2016
2018 if (Mask.size() != static_cast<unsigned>(NumSrcElts))
2019 return false;
2020 if (!isSingleSourceMask(Mask, NumSrcElts))
2021 return false;
2022 for (int I = 0, E = Mask.size(); I < E; ++I) {
2023 if (Mask[I] == -1)
2024 continue;
2025 if (Mask[I] != 0 && Mask[I] != NumSrcElts)
2026 return false;
2027 }
2028 return true;
2029}
2030
2032 if (Mask.size() != static_cast<unsigned>(NumSrcElts))
2033 return false;
2034 // Select is differentiated from identity. It requires using both sources.
2035 if (isSingleSourceMask(Mask, NumSrcElts))
2036 return false;
2037 for (int I = 0, E = Mask.size(); I < E; ++I) {
2038 if (Mask[I] == -1)
2039 continue;
2040 if (Mask[I] != I && Mask[I] != (NumSrcElts + I))
2041 return false;
2042 }
2043 return true;
2044}
2045
2047 // Example masks that will return true:
2048 // v1 = <a, b, c, d>
2049 // v2 = <e, f, g, h>
2050 // trn1 = shufflevector v1, v2 <0, 4, 2, 6> = <a, e, c, g>
2051 // trn2 = shufflevector v1, v2 <1, 5, 3, 7> = <b, f, d, h>
2052
2053 if (Mask.size() != static_cast<unsigned>(NumSrcElts))
2054 return false;
2055 // 1. The number of elements in the mask must be a power-of-2 and at least 2.
2056 int Sz = Mask.size();
2057 if (Sz < 2 || !isPowerOf2_32(Sz))
2058 return false;
2059
2060 // 2. The first element of the mask must be either a 0 or a 1.
2061 if (Mask[0] != 0 && Mask[0] != 1)
2062 return false;
2063
2064 // 3. The difference between the first 2 elements must be equal to the
2065 // number of elements in the mask.
2066 if ((Mask[1] - Mask[0]) != NumSrcElts)
2067 return false;
2068
2069 // 4. The difference between consecutive even-numbered and odd-numbered
2070 // elements must be equal to 2.
2071 for (int I = 2; I < Sz; ++I) {
2072 int MaskEltVal = Mask[I];
2073 if (MaskEltVal == -1)
2074 return false;
2075 int MaskEltPrevVal = Mask[I - 2];
2076 if (MaskEltVal - MaskEltPrevVal != 2)
2077 return false;
2078 }
2079 return true;
2080}
2081
2083 int &Index) {
2084 if (Mask.size() != static_cast<unsigned>(NumSrcElts))
2085 return false;
2086 // Example: shufflevector <4 x n> A, <4 x n> B, <1,2,3,4>
2087 int StartIndex = -1;
2088 for (int I = 0, E = Mask.size(); I != E; ++I) {
2089 int MaskEltVal = Mask[I];
2090 if (MaskEltVal == -1)
2091 continue;
2092
2093 if (StartIndex == -1) {
2094 // Don't support a StartIndex that begins in the second input, or if the
2095 // first non-undef index would access below the StartIndex.
2096 if (MaskEltVal < I || NumSrcElts <= (MaskEltVal - I))
2097 return false;
2098
2099 StartIndex = MaskEltVal - I;
2100 continue;
2101 }
2102
2103 // Splice is sequential starting from StartIndex.
2104 if (MaskEltVal != (StartIndex + I))
2105 return false;
2106 }
2107
2108 if (StartIndex == -1)
2109 return false;
2110
2111 // NOTE: This accepts StartIndex == 0 (COPY).
2112 Index = StartIndex;
2113 return true;
2114}
2115
2117 int NumSrcElts, int &Index) {
2118 // Must extract from a single source.
2119 if (!isSingleSourceMaskImpl(Mask, NumSrcElts))
2120 return false;
2121
2122 // Must be smaller (else this is an Identity shuffle).
2123 if (NumSrcElts <= (int)Mask.size())
2124 return false;
2125
2126 // Find start of extraction, accounting that we may start with an UNDEF.
2127 int SubIndex = -1;
2128 for (int i = 0, e = Mask.size(); i != e; ++i) {
2129 int M = Mask[i];
2130 if (M < 0)
2131 continue;
2132 int Offset = (M % NumSrcElts) - i;
2133 if (0 <= SubIndex && SubIndex != Offset)
2134 return false;
2135 SubIndex = Offset;
2136 }
2137
2138 if (0 <= SubIndex && SubIndex + (int)Mask.size() <= NumSrcElts) {
2139 Index = SubIndex;
2140 return true;
2141 }
2142 return false;
2143}
2144
2146 int NumSrcElts, int &NumSubElts,
2147 int &Index) {
2148 int NumMaskElts = Mask.size();
2149
2150 // Don't try to match if we're shuffling to a smaller size.
2151 if (NumMaskElts < NumSrcElts)
2152 return false;
2153
2154 // TODO: We don't recognize self-insertion/widening.
2155 if (isSingleSourceMaskImpl(Mask, NumSrcElts))
2156 return false;
2157
2158 // Determine which mask elements are attributed to which source.
2159 APInt UndefElts = APInt::getZero(NumMaskElts);
2160 APInt Src0Elts = APInt::getZero(NumMaskElts);
2161 APInt Src1Elts = APInt::getZero(NumMaskElts);
2162 bool Src0Identity = true;
2163 bool Src1Identity = true;
2164
2165 for (int i = 0; i != NumMaskElts; ++i) {
2166 int M = Mask[i];
2167 if (M < 0) {
2168 UndefElts.setBit(i);
2169 continue;
2170 }
2171 if (M < NumSrcElts) {
2172 Src0Elts.setBit(i);
2173 Src0Identity &= (M == i);
2174 continue;
2175 }
2176 Src1Elts.setBit(i);
2177 Src1Identity &= (M == (i + NumSrcElts));
2178 }
2179 assert((Src0Elts | Src1Elts | UndefElts).isAllOnes() &&
2180 "unknown shuffle elements");
2181 assert(!Src0Elts.isZero() && !Src1Elts.isZero() &&
2182 "2-source shuffle not found");
2183
2184 // Determine lo/hi span ranges.
2185 // TODO: How should we handle undefs at the start of subvector insertions?
2186 int Src0Lo = Src0Elts.countr_zero();
2187 int Src1Lo = Src1Elts.countr_zero();
2188 int Src0Hi = NumMaskElts - Src0Elts.countl_zero();
2189 int Src1Hi = NumMaskElts - Src1Elts.countl_zero();
2190
2191 // If src0 is in place, see if the src1 elements is inplace within its own
2192 // span.
2193 if (Src0Identity) {
2194 int NumSub1Elts = Src1Hi - Src1Lo;
2195 ArrayRef<int> Sub1Mask = Mask.slice(Src1Lo, NumSub1Elts);
2196 if (isIdentityMaskImpl(Sub1Mask, NumSrcElts)) {
2197 NumSubElts = NumSub1Elts;
2198 Index = Src1Lo;
2199 return true;
2200 }
2201 }
2202
2203 // If src1 is in place, see if the src0 elements is inplace within its own
2204 // span.
2205 if (Src1Identity) {
2206 int NumSub0Elts = Src0Hi - Src0Lo;
2207 ArrayRef<int> Sub0Mask = Mask.slice(Src0Lo, NumSub0Elts);
2208 if (isIdentityMaskImpl(Sub0Mask, NumSrcElts)) {
2209 NumSubElts = NumSub0Elts;
2210 Index = Src0Lo;
2211 return true;
2212 }
2213 }
2214
2215 return false;
2216}
2217
2219 // FIXME: Not currently possible to express a shuffle mask for a scalable
2220 // vector for this case.
2222 return false;
2223
2224 int NumOpElts = cast<FixedVectorType>(Op<0>()->getType())->getNumElements();
2225 int NumMaskElts = cast<FixedVectorType>(getType())->getNumElements();
2226 if (NumMaskElts <= NumOpElts)
2227 return false;
2228
2229 // The first part of the mask must choose elements from exactly 1 source op.
2231 if (!isIdentityMaskImpl(Mask, NumOpElts))
2232 return false;
2233
2234 // All extending must be with undef elements.
2235 for (int i = NumOpElts; i < NumMaskElts; ++i)
2236 if (Mask[i] != -1)
2237 return false;
2238
2239 return true;
2240}
2241
2243 // FIXME: Not currently possible to express a shuffle mask for a scalable
2244 // vector for this case.
2246 return false;
2247
2248 int NumOpElts = cast<FixedVectorType>(Op<0>()->getType())->getNumElements();
2249 int NumMaskElts = cast<FixedVectorType>(getType())->getNumElements();
2250 if (NumMaskElts >= NumOpElts)
2251 return false;
2252
2253 return isIdentityMaskImpl(getShuffleMask(), NumOpElts);
2254}
2255
2257 // Vector concatenation is differentiated from identity with padding.
2259 return false;
2260
2261 // FIXME: Not currently possible to express a shuffle mask for a scalable
2262 // vector for this case.
2264 return false;
2265
2266 int NumOpElts = cast<FixedVectorType>(Op<0>()->getType())->getNumElements();
2267 int NumMaskElts = cast<FixedVectorType>(getType())->getNumElements();
2268 if (NumMaskElts != NumOpElts * 2)
2269 return false;
2270
2271 // Use the mask length rather than the operands' vector lengths here. We
2272 // already know that the shuffle returns a vector twice as long as the inputs,
2273 // and neither of the inputs are undef vectors. If the mask picks consecutive
2274 // elements from both inputs, then this is a concatenation of the inputs.
2275 return isIdentityMaskImpl(getShuffleMask(), NumMaskElts);
2276}
2277
2279 int ReplicationFactor, int VF) {
2280 assert(Mask.size() == (unsigned)ReplicationFactor * VF &&
2281 "Unexpected mask size.");
2282
2283 for (int CurrElt : seq(VF)) {
2284 ArrayRef<int> CurrSubMask = Mask.take_front(ReplicationFactor);
2285 assert(CurrSubMask.size() == (unsigned)ReplicationFactor &&
2286 "Run out of mask?");
2287 Mask = Mask.drop_front(ReplicationFactor);
2288 if (!all_of(CurrSubMask, [CurrElt](int MaskElt) {
2289 return MaskElt == PoisonMaskElem || MaskElt == CurrElt;
2290 }))
2291 return false;
2292 }
2293 assert(Mask.empty() && "Did not consume the whole mask?");
2294
2295 return true;
2296}
2297
2299 int &ReplicationFactor, int &VF) {
2300 // undef-less case is trivial.
2301 if (!llvm::is_contained(Mask, PoisonMaskElem)) {
2302 ReplicationFactor =
2303 Mask.take_while([](int MaskElt) { return MaskElt == 0; }).size();
2304 if (ReplicationFactor == 0 || Mask.size() % ReplicationFactor != 0)
2305 return false;
2306 VF = Mask.size() / ReplicationFactor;
2307 return isReplicationMaskWithParams(Mask, ReplicationFactor, VF);
2308 }
2309
2310 // However, if the mask contains undef's, we have to enumerate possible tuples
2311 // and pick one. There are bounds on replication factor: [1, mask size]
2312 // (where RF=1 is an identity shuffle, RF=mask size is a broadcast shuffle)
2313 // Additionally, mask size is a replication factor multiplied by vector size,
2314 // which further significantly reduces the search space.
2315
2316 // Before doing that, let's perform basic correctness checking first.
2317 int Largest = -1;
2318 for (int MaskElt : Mask) {
2319 if (MaskElt == PoisonMaskElem)
2320 continue;
2321 // Elements must be in non-decreasing order.
2322 if (MaskElt < Largest)
2323 return false;
2324 Largest = std::max(Largest, MaskElt);
2325 }
2326
2327 // Prefer larger replication factor if all else equal.
2328 for (int PossibleReplicationFactor :
2329 reverse(seq_inclusive<unsigned>(1, Mask.size()))) {
2330 if (Mask.size() % PossibleReplicationFactor != 0)
2331 continue;
2332 int PossibleVF = Mask.size() / PossibleReplicationFactor;
2333 if (!isReplicationMaskWithParams(Mask, PossibleReplicationFactor,
2334 PossibleVF))
2335 continue;
2336 ReplicationFactor = PossibleReplicationFactor;
2337 VF = PossibleVF;
2338 return true;
2339 }
2340
2341 return false;
2342}
2343
2344bool ShuffleVectorInst::isReplicationMask(int &ReplicationFactor,
2345 int &VF) const {
2346 // Not possible to express a shuffle mask for a scalable vector for this
2347 // case.
2349 return false;
2350
2351 VF = cast<FixedVectorType>(Op<0>()->getType())->getNumElements();
2352 if (ShuffleMask.size() % VF != 0)
2353 return false;
2354 ReplicationFactor = ShuffleMask.size() / VF;
2355
2356 return isReplicationMaskWithParams(ShuffleMask, ReplicationFactor, VF);
2357}
2358
2360 if (VF <= 0 || Mask.size() < static_cast<unsigned>(VF) ||
2361 Mask.size() % VF != 0)
2362 return false;
2363 for (unsigned K = 0, Sz = Mask.size(); K < Sz; K += VF) {
2364 ArrayRef<int> SubMask = Mask.slice(K, VF);
2365 if (all_of(SubMask, equal_to(PoisonMaskElem)))
2366 continue;
2367 SmallBitVector Used(VF, false);
2368 for (int Idx : SubMask) {
2369 if (Idx != PoisonMaskElem && Idx < VF)
2370 Used.set(Idx);
2371 }
2372 if (!Used.all())
2373 return false;
2374 }
2375 return true;
2376}
2377
2378/// Return true if this shuffle mask is a replication mask.
2380 // Not possible to express a shuffle mask for a scalable vector for this
2381 // case.
2383 return false;
2384 if (!isSingleSourceMask(ShuffleMask, VF))
2385 return false;
2386
2387 return isOneUseSingleSourceMask(ShuffleMask, VF);
2388}
2389
2390bool ShuffleVectorInst::isInterleave(unsigned Factor) {
2392 // shuffle_vector can only interleave fixed length vectors - for scalable
2393 // vectors, see the @llvm.vector.interleave2 intrinsic
2394 if (!OpTy)
2395 return false;
2396 unsigned OpNumElts = OpTy->getNumElements();
2397
2398 return isInterleaveMask(ShuffleMask, Factor, OpNumElts * 2);
2399}
2400
2402 ArrayRef<int> Mask, unsigned Factor, unsigned NumInputElts,
2403 SmallVectorImpl<unsigned> &StartIndexes) {
2404 unsigned NumElts = Mask.size();
2405 if (NumElts % Factor)
2406 return false;
2407
2408 unsigned LaneLen = NumElts / Factor;
2409 if (!isPowerOf2_32(LaneLen))
2410 return false;
2411
2412 StartIndexes.resize(Factor);
2413
2414 // Check whether each element matches the general interleaved rule.
2415 // Ignore undef elements, as long as the defined elements match the rule.
2416 // Outer loop processes all factors (x, y, z in the above example)
2417 unsigned I = 0, J;
2418 for (; I < Factor; I++) {
2419 unsigned SavedLaneValue;
2420 unsigned SavedNoUndefs = 0;
2421
2422 // Inner loop processes consecutive accesses (x, x+1... in the example)
2423 for (J = 0; J < LaneLen - 1; J++) {
2424 // Lane computes x's position in the Mask
2425 unsigned Lane = J * Factor + I;
2426 unsigned NextLane = Lane + Factor;
2427 int LaneValue = Mask[Lane];
2428 int NextLaneValue = Mask[NextLane];
2429
2430 // If both are defined, values must be sequential
2431 if (LaneValue >= 0 && NextLaneValue >= 0 &&
2432 LaneValue + 1 != NextLaneValue)
2433 break;
2434
2435 // If the next value is undef, save the current one as reference
2436 if (LaneValue >= 0 && NextLaneValue < 0) {
2437 SavedLaneValue = LaneValue;
2438 SavedNoUndefs = 1;
2439 }
2440
2441 // Undefs are allowed, but defined elements must still be consecutive:
2442 // i.e.: x,..., undef,..., x + 2,..., undef,..., undef,..., x + 5, ....
2443 // Verify this by storing the last non-undef followed by an undef
2444 // Check that following non-undef masks are incremented with the
2445 // corresponding distance.
2446 if (SavedNoUndefs > 0 && LaneValue < 0) {
2447 SavedNoUndefs++;
2448 if (NextLaneValue >= 0 &&
2449 SavedLaneValue + SavedNoUndefs != (unsigned)NextLaneValue)
2450 break;
2451 }
2452 }
2453
2454 if (J < LaneLen - 1)
2455 return false;
2456
2457 int StartMask = 0;
2458 if (Mask[I] >= 0) {
2459 // Check that the start of the I range (J=0) is greater than 0
2460 StartMask = Mask[I];
2461 } else if (Mask[(LaneLen - 1) * Factor + I] >= 0) {
2462 // StartMask defined by the last value in lane
2463 StartMask = Mask[(LaneLen - 1) * Factor + I] - J;
2464 } else if (SavedNoUndefs > 0) {
2465 // StartMask defined by some non-zero value in the j loop
2466 StartMask = SavedLaneValue - (LaneLen - 1 - SavedNoUndefs);
2467 }
2468 // else StartMask remains set to 0, i.e. all elements are undefs
2469
2470 if (StartMask < 0)
2471 return false;
2472 // We must stay within the vectors; This case can happen with undefs.
2473 if (StartMask + LaneLen > NumInputElts)
2474 return false;
2475
2476 StartIndexes[I] = StartMask;
2477 }
2478
2479 return true;
2480}
2481
2482/// Check if the mask is a DE-interleave mask of the given factor
2483/// \p Factor like:
2484/// <Index, Index+Factor, ..., Index+(NumElts-1)*Factor>
2486 unsigned Factor,
2487 unsigned &Index) {
2488 // Check all potential start indices from 0 to (Factor - 1).
2489 for (unsigned Idx = 0; Idx < Factor; Idx++) {
2490 unsigned I = 0;
2491
2492 // Check that elements are in ascending order by Factor. Ignore undef
2493 // elements.
2494 for (; I < Mask.size(); I++)
2495 if (Mask[I] >= 0 && static_cast<unsigned>(Mask[I]) != Idx + I * Factor)
2496 break;
2497
2498 if (I == Mask.size()) {
2499 Index = Idx;
2500 return true;
2501 }
2502 }
2503
2504 return false;
2505}
2506
2507/// Try to lower a vector shuffle as a bit rotation.
2508///
2509/// Look for a repeated rotation pattern in each sub group.
2510/// Returns an element-wise left bit rotation amount or -1 if failed.
2511static int matchShuffleAsBitRotate(ArrayRef<int> Mask, int NumSubElts) {
2512 int NumElts = Mask.size();
2513 assert((NumElts % NumSubElts) == 0 && "Illegal shuffle mask");
2514
2515 int RotateAmt = -1;
2516 for (int i = 0; i != NumElts; i += NumSubElts) {
2517 for (int j = 0; j != NumSubElts; ++j) {
2518 int M = Mask[i + j];
2519 if (M < 0)
2520 continue;
2521 if (M < i || M >= i + NumSubElts)
2522 return -1;
2523 int Offset = (NumSubElts - (M - (i + j))) % NumSubElts;
2524 if (0 <= RotateAmt && Offset != RotateAmt)
2525 return -1;
2526 RotateAmt = Offset;
2527 }
2528 }
2529 return RotateAmt;
2530}
2531
2533 ArrayRef<int> Mask, unsigned EltSizeInBits, unsigned MinSubElts,
2534 unsigned MaxSubElts, unsigned &NumSubElts, unsigned &RotateAmt) {
2535 for (NumSubElts = MinSubElts; NumSubElts <= MaxSubElts; NumSubElts *= 2) {
2536 int EltRotateAmt = matchShuffleAsBitRotate(Mask, NumSubElts);
2537 if (EltRotateAmt < 0)
2538 continue;
2539 RotateAmt = EltRotateAmt * EltSizeInBits;
2540 return true;
2541 }
2542
2543 return false;
2544}
2545
2546//===----------------------------------------------------------------------===//
2547// InsertValueInst Class
2548//===----------------------------------------------------------------------===//
2549
2550void InsertValueInst::init(Value *Agg, Value *Val, ArrayRef<unsigned> Idxs,
2551 const Twine &Name) {
2552 assert(getNumOperands() == 2 && "NumOperands not initialized?");
2553
2554 // There's no fundamental reason why we require at least one index
2555 // (other than weirdness with &*IdxBegin being invalid; see
2556 // getelementptr's init routine for example). But there's no
2557 // present need to support it.
2558 assert(!Idxs.empty() && "InsertValueInst must have at least one index");
2559
2561 Val->getType() && "Inserted value must match indexed type!");
2562 Op<0>() = Agg;
2563 Op<1>() = Val;
2564
2565 Indices.append(Idxs.begin(), Idxs.end());
2566 setName(Name);
2567}
2568
2569InsertValueInst::InsertValueInst(const InsertValueInst &IVI)
2570 : Instruction(IVI.getType(), InsertValue, AllocMarker),
2571 Indices(IVI.Indices) {
2572 Op<0>() = IVI.getOperand(0);
2573 Op<1>() = IVI.getOperand(1);
2575}
2576
2577//===----------------------------------------------------------------------===//
2578// ExtractValueInst Class
2579//===----------------------------------------------------------------------===//
2580
2581void ExtractValueInst::init(ArrayRef<unsigned> Idxs, const Twine &Name) {
2582 assert(getNumOperands() == 1 && "NumOperands not initialized?");
2583
2584 // There's no fundamental reason why we require at least one index.
2585 // But there's no present need to support it.
2586 assert(!Idxs.empty() && "ExtractValueInst must have at least one index");
2587
2588 Indices.append(Idxs.begin(), Idxs.end());
2589 setName(Name);
2590}
2591
2592ExtractValueInst::ExtractValueInst(const ExtractValueInst &EVI)
2593 : UnaryInstruction(EVI.getType(), ExtractValue, EVI.getOperand(0),
2594 (BasicBlock *)nullptr),
2595 Indices(EVI.Indices) {
2597}
2598
2599// getIndexedType - Returns the type of the element that would be extracted
2600// with an extractvalue instruction with the specified parameters.
2601//
2602// A null type is returned if the indices are invalid for the specified
2603// pointer type.
2604//
2606 ArrayRef<unsigned> Idxs) {
2607 for (unsigned Index : Idxs) {
2608 // We can't use CompositeType::indexValid(Index) here.
2609 // indexValid() always returns true for arrays because getelementptr allows
2610 // out-of-bounds indices. Since we don't allow those for extractvalue and
2611 // insertvalue we need to check array indexing manually.
2612 // Since the only other types we can index into are struct types it's just
2613 // as easy to check those manually as well.
2614 if (ArrayType *AT = dyn_cast<ArrayType>(Agg)) {
2615 if (Index >= AT->getNumElements())
2616 return nullptr;
2617 Agg = AT->getElementType();
2618 } else if (StructType *ST = dyn_cast<StructType>(Agg)) {
2619 if (Index >= ST->getNumElements())
2620 return nullptr;
2621 Agg = ST->getElementType(Index);
2622 } else {
2623 // Not a valid type to index into.
2624 return nullptr;
2625 }
2626 }
2627 return Agg;
2628}
2629
2630//===----------------------------------------------------------------------===//
2631// BitInsert Class
2632//===----------------------------------------------------------------------===//
2633BitInsertInst::BitInsertInst(Value *Base, Value *Val, Value *Offset,
2634 const Twine &Name, InsertPosition InsertBef)
2635 : Instruction(Base->getType(), BitInsert, AllocMarker, InsertBef) {
2636 assert(!areInvalidOperands(Base, Val, Offset) &&
2637 "Invalid bitinsert instruction operands!");
2638 Op<0>() = Base;
2639 Op<1>() = Val;
2640 Op<2>() = Offset;
2641 setName(Name);
2642}
2643
2645 Value *Offset) {
2646 if (!Base->getType()->isByteTy())
2647 return "bitinsert base must be a byte type";
2648 if (!(Val->getType()->isFloatingPointTy() || Val->getType()->isIntegerTy() ||
2649 Val->getType()->isPointerTy() || Val->getType()->isByteTy()))
2650 return "bitinsert value must be an integer, floating-point, pointer, or "
2651 "byte type";
2652 if (!Offset->getType()->isIntegerTy(32))
2653 return "bitinsert offset must be i32";
2654 return nullptr;
2655}
2656
2657//===----------------------------------------------------------------------===//
2658// BitExtract Class
2659//===----------------------------------------------------------------------===//
2660BitExtractInst::BitExtractInst(Type *Ty, Value *Src, Value *Offset,
2661 const Twine &Name, InsertPosition InsertBef)
2662 : Instruction(Ty, BitExtract, AllocMarker, InsertBef) {
2663 assert(!areInvalidOperands(Ty, Src, Offset) &&
2664 "Invalid bitextract instruction operands!");
2665 Op<0>() = Src;
2666 Op<1>() = Offset;
2667 setName(Name);
2668}
2669
2671 Value *Offset) {
2672 if (!(Ty->isFloatingPointTy() || Ty->isIntegerTy() || Ty->isPointerTy() ||
2673 Ty->isByteTy()))
2674 return "bitextract result must be an integer, floating-point, pointer, or "
2675 "byte type";
2676 if (!Src->getType()->isByteTy())
2677 return "bitextract source must be a byte type";
2678 if (!Offset->getType()->isIntegerTy(32))
2679 return "bitextract offset must be i32";
2680 return nullptr;
2681}
2682
2683//===----------------------------------------------------------------------===//
2684// UnaryOperator Class
2685//===----------------------------------------------------------------------===//
2686
2688 const Twine &Name, InsertPosition InsertBefore)
2689 : UnaryInstruction(Ty, iType, S, InsertBefore) {
2690 Op<0>() = S;
2691 setName(Name);
2692 AssertOK();
2693}
2694
2696 InsertPosition InsertBefore) {
2697 switch (Op) {
2698 case UnaryOps::FNeg:
2699 return new FPUnaryOperator(Op, S, S->getType(), Name, InsertBefore);
2700 default:
2701 return new UnaryOperator(Op, S, S->getType(), Name, InsertBefore);
2702 }
2703}
2704
2705void UnaryOperator::AssertOK() {
2706 Value *LHS = getOperand(0);
2707 (void)LHS; // Silence warnings.
2708#ifndef NDEBUG
2709 switch (getOpcode()) {
2710 case FNeg:
2711 assert(getType() == LHS->getType() &&
2712 "Unary operation should return same type as operand!");
2713 assert(getType()->isFPOrFPVectorTy() &&
2714 "Tried to create a floating-point operation on a "
2715 "non-floating-point type!");
2716 break;
2717 default: llvm_unreachable("Invalid opcode provided");
2718 }
2719#endif
2720}
2721
2722//===----------------------------------------------------------------------===//
2723// BinaryOperator Class
2724//===----------------------------------------------------------------------===//
2725
2727 const Twine &Name, InsertPosition InsertBefore)
2728 : Instruction(Ty, iType, AllocMarker, InsertBefore) {
2729 Op<0>() = S1;
2730 Op<1>() = S2;
2731 setName(Name);
2732 AssertOK();
2733}
2734
2735void BinaryOperator::AssertOK() {
2736 Value *LHS = getOperand(0), *RHS = getOperand(1);
2737 (void)LHS; (void)RHS; // Silence warnings.
2738 assert(LHS->getType() == RHS->getType() &&
2739 "Binary operator operand types must match!");
2740#ifndef NDEBUG
2741 switch (getOpcode()) {
2742 case Add: case Sub:
2743 case Mul:
2744 assert(getType() == LHS->getType() &&
2745 "Arithmetic operation should return same type as operands!");
2746 assert(getType()->isIntOrIntVectorTy() &&
2747 "Tried to create an integer operation on a non-integer type!");
2748 break;
2749 case FAdd: case FSub:
2750 case FMul:
2751 assert(getType() == LHS->getType() &&
2752 "Arithmetic operation should return same type as operands!");
2753 assert(getType()->isFPOrFPVectorTy() &&
2754 "Tried to create a floating-point operation on a "
2755 "non-floating-point type!");
2756 break;
2757 case UDiv:
2758 case SDiv:
2759 assert(getType() == LHS->getType() &&
2760 "Arithmetic operation should return same type as operands!");
2761 assert(getType()->isIntOrIntVectorTy() &&
2762 "Incorrect operand type (not integer) for S/UDIV");
2763 break;
2764 case FDiv:
2765 assert(getType() == LHS->getType() &&
2766 "Arithmetic operation should return same type as operands!");
2767 assert(getType()->isFPOrFPVectorTy() &&
2768 "Incorrect operand type (not floating point) for FDIV");
2769 break;
2770 case URem:
2771 case SRem:
2772 assert(getType() == LHS->getType() &&
2773 "Arithmetic operation should return same type as operands!");
2774 assert(getType()->isIntOrIntVectorTy() &&
2775 "Incorrect operand type (not integer) for S/UREM");
2776 break;
2777 case FRem:
2778 assert(getType() == LHS->getType() &&
2779 "Arithmetic operation should return same type as operands!");
2780 assert(getType()->isFPOrFPVectorTy() &&
2781 "Incorrect operand type (not floating point) for FREM");
2782 break;
2783 case Shl:
2784 case LShr:
2785 case AShr:
2786 assert(getType() == LHS->getType() &&
2787 "Shift operation should return same type as operands!");
2788 assert(getType()->isIntOrIntVectorTy() &&
2789 "Tried to create a shift operation on a non-integral type!");
2790 break;
2791 case And: case Or:
2792 case Xor:
2793 assert(getType() == LHS->getType() &&
2794 "Logical operation should return same type as operands!");
2795 assert(getType()->isIntOrIntVectorTy() &&
2796 "Tried to create a logical operation on a non-integral type!");
2797 break;
2798 default: llvm_unreachable("Invalid opcode provided");
2799 }
2800#endif
2801}
2802
2804 const Twine &Name,
2805 InsertPosition InsertBefore) {
2806 assert(S1->getType() == S2->getType() &&
2807 "Cannot create binary operator with two operands of differing type!");
2808 switch (Op) {
2809 case BinaryOps::FAdd:
2810 case BinaryOps::FSub:
2811 case BinaryOps::FMul:
2812 case BinaryOps::FDiv:
2813 case BinaryOps::FRem:
2814 return new FPBinaryOperator(Op, S1, S2, S1->getType(), Name, InsertBefore);
2815 default:
2816 return new BinaryOperator(Op, S1, S2, S1->getType(), Name, InsertBefore);
2817 }
2818}
2819
2821 InsertPosition InsertBefore) {
2822 Value *Zero = ConstantInt::get(Op->getType(), 0);
2823 return new BinaryOperator(Instruction::Sub, Zero, Op, Op->getType(), Name,
2824 InsertBefore);
2825}
2826
2828 InsertPosition InsertBefore) {
2829 Value *Zero = ConstantInt::get(Op->getType(), 0);
2830 return BinaryOperator::CreateNSWSub(Zero, Op, Name, InsertBefore);
2831}
2832
2834 InsertPosition InsertBefore) {
2835 Constant *C = Constant::getAllOnesValue(Op->getType());
2836 return new BinaryOperator(Instruction::Xor, Op, C,
2837 Op->getType(), Name, InsertBefore);
2838}
2839
2840// Exchange the two operands to this instruction. This instruction is safe to
2841// use on any binary instruction and does not modify the semantics of the
2842// instruction.
2844 if (!isCommutative())
2845 return true; // Can't commute operands
2846 Op<0>().swap(Op<1>());
2847 return false;
2848}
2849
2850//===----------------------------------------------------------------------===//
2851// FPMathOperator Class
2852//===----------------------------------------------------------------------===//
2853
2855 const MDNode *MD =
2856 cast<Instruction>(this)->getMetadata(LLVMContext::MD_fpmath);
2857 if (!MD)
2858 return 0.0;
2860 return Accuracy->getValueAPF().convertToFloat();
2861}
2862
2863//===----------------------------------------------------------------------===//
2864// CastInst Class
2865//===----------------------------------------------------------------------===//
2866
2867// Just determine if this cast only deals with integral->integral conversion.
2869 switch (getOpcode()) {
2870 default: return false;
2871 case Instruction::ZExt:
2872 case Instruction::SExt:
2873 case Instruction::Trunc:
2874 return true;
2875 case Instruction::BitCast:
2876 return getOperand(0)->getType()->isIntegerTy() &&
2877 getType()->isIntegerTy();
2878 }
2879}
2880
2881/// This function determines if the CastInst does not require any bits to be
2882/// changed in order to effect the cast. Essentially, it identifies cases where
2883/// no code gen is necessary for the cast, hence the name no-op cast. For
2884/// example, the following are all no-op casts:
2885/// # bitcast i32* %x to i8*
2886/// # bitcast <2 x i32> %x to <4 x i16>
2887/// # ptrtoint i32* %x to i32 ; on 32-bit plaforms only
2888/// Determine if the described cast is a no-op.
2890 Type *SrcTy,
2891 Type *DestTy,
2892 const DataLayout &DL) {
2893 assert(castIsValid(Opcode, SrcTy, DestTy) && "method precondition");
2894 switch (Opcode) {
2895 default: llvm_unreachable("Invalid CastOp");
2896 case Instruction::Trunc:
2897 case Instruction::ZExt:
2898 case Instruction::SExt:
2899 case Instruction::FPTrunc:
2900 case Instruction::FPExt:
2901 case Instruction::UIToFP:
2902 case Instruction::SIToFP:
2903 case Instruction::FPToUI:
2904 case Instruction::FPToSI:
2905 case Instruction::AddrSpaceCast:
2906 // TODO: Target informations may give a more accurate answer here.
2907 return false;
2908 case Instruction::BitCast:
2909 return true; // BitCast never modifies bits.
2910 case Instruction::PtrToAddr:
2911 case Instruction::PtrToInt:
2912 return DL.getIntPtrType(SrcTy)->getScalarSizeInBits() ==
2913 DestTy->getScalarSizeInBits();
2914 case Instruction::IntToPtr:
2915 return DL.getIntPtrType(DestTy)->getScalarSizeInBits() ==
2916 SrcTy->getScalarSizeInBits();
2917 }
2918}
2919
2921 return isNoopCast(getOpcode(), getOperand(0)->getType(), getType(), DL);
2922}
2923
2924/// This function determines if a pair of casts can be eliminated and what
2925/// opcode should be used in the elimination. This assumes that there are two
2926/// instructions like this:
2927/// * %F = firstOpcode SrcTy %x to MidTy
2928/// * %S = secondOpcode MidTy %F to DstTy
2929/// The function returns a resultOpcode so these two casts can be replaced with:
2930/// * %Replacement = resultOpcode %SrcTy %x to DstTy
2931/// If no such cast is permitted, the function returns 0.
2933 Instruction::CastOps secondOp,
2934 Type *SrcTy, Type *MidTy, Type *DstTy,
2935 const DataLayout *DL) {
2936 // Define the 144 possibilities for these two cast instructions. The values
2937 // in this matrix determine what to do in a given situation and select the
2938 // case in the switch below. The rows correspond to firstOp, the columns
2939 // correspond to secondOp. In looking at the table below, keep in mind
2940 // the following cast properties:
2941 //
2942 // Size Compare Source Destination
2943 // Operator Src ? Size Type Sign Type Sign
2944 // -------- ------------ ------------------- ---------------------
2945 // TRUNC > Integer Any Integral Any
2946 // ZEXT < Integral Unsigned Integer Any
2947 // SEXT < Integral Signed Integer Any
2948 // FPTOUI n/a FloatPt n/a Integral Unsigned
2949 // FPTOSI n/a FloatPt n/a Integral Signed
2950 // UITOFP n/a Integral Unsigned FloatPt n/a
2951 // SITOFP n/a Integral Signed FloatPt n/a
2952 // FPTRUNC > FloatPt n/a FloatPt n/a
2953 // FPEXT < FloatPt n/a FloatPt n/a
2954 // PTRTOINT n/a Pointer n/a Integral Unsigned
2955 // PTRTOADDR n/a Pointer n/a Integral Unsigned
2956 // INTTOPTR n/a Integral Unsigned Pointer n/a
2957 // BITCAST = FirstClass n/a FirstClass n/a
2958 // ADDRSPCST n/a Pointer n/a Pointer n/a
2959 //
2960 // NOTE: some transforms are safe, but we consider them to be non-profitable.
2961 // For example, we could merge "fptoui double to i32" + "zext i32 to i64",
2962 // into "fptoui double to i64", but this loses information about the range
2963 // of the produced value (we no longer know the top-part is all zeros).
2964 // Further this conversion is often much more expensive for typical hardware,
2965 // and causes issues when building libgcc. We disallow fptosi+sext for the
2966 // same reason.
2967 const unsigned numCastOps =
2968 Instruction::CastOpsEnd - Instruction::CastOpsBegin;
2969 // clang-format off
2970 static const uint8_t CastResults[numCastOps][numCastOps] = {
2971 // T F F U S F F P P I B A -+
2972 // R Z S P P I I T P 2 2 N T S |
2973 // U E E 2 2 2 2 R E I A T C C +- secondOp
2974 // N X X U S F F N X N D 2 V V |
2975 // C T T I I P P C T T R P T T -+
2976 { 1, 0, 0,99,99, 0, 0,99,99,99,99, 0, 3, 0}, // Trunc -+
2977 { 8, 1, 9,99,99, 2,17,99,99,99,99, 2, 3, 0}, // ZExt |
2978 { 8, 0, 1,99,99, 0, 2,99,99,99,99, 0, 3, 0}, // SExt |
2979 { 0, 0, 0,99,99, 0, 0,99,99,99,99, 0, 3, 0}, // FPToUI |
2980 { 0, 0, 0,99,99, 0, 0,99,99,99,99, 0, 3, 0}, // FPToSI |
2981 { 99,99,99, 0, 0,99,99, 0, 0,99,99,99, 4, 0}, // UIToFP +- firstOp
2982 { 99,99,99, 0, 0,99,99, 0, 0,99,99,99, 4, 0}, // SIToFP |
2983 { 99,99,99, 0, 0,99,99, 0, 0,99,99,99, 4, 0}, // FPTrunc |
2984 { 99,99,99, 2, 2,99,99, 8, 2,99,99,99, 4, 0}, // FPExt |
2985 { 1, 0, 0,99,99, 0, 0,99,99,99,99, 7, 3, 0}, // PtrToInt |
2986 { 0, 0, 0,99,99, 0, 0,99,99,99,99, 0, 3, 0}, // PtrToAddr |
2987 { 99,99,99,99,99,99,99,99,99,11,11,99,15, 0}, // IntToPtr |
2988 { 5, 5, 5, 0, 0, 5, 5, 0, 0,16,16, 5,18,14}, // BitCast |
2989 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,13,12}, // AddrSpaceCast -+
2990 };
2991 // clang-format on
2992
2993 // TODO: This logic could be encoded into the table above and handled in the
2994 // switch below.
2995 // If either of the casts are a bitcast from scalar to vector, disallow the
2996 // merging. However, any pair of bitcasts are allowed.
2997 bool IsFirstBitcast = (firstOp == Instruction::BitCast);
2998 bool IsSecondBitcast = (secondOp == Instruction::BitCast);
2999 bool AreBothBitcasts = IsFirstBitcast && IsSecondBitcast;
3000
3001 // Check if any of the casts convert scalars <-> vectors.
3002 if ((IsFirstBitcast && isa<VectorType>(SrcTy) != isa<VectorType>(MidTy)) ||
3003 (IsSecondBitcast && isa<VectorType>(MidTy) != isa<VectorType>(DstTy)))
3004 if (!AreBothBitcasts)
3005 return 0;
3006
3007 int ElimCase = CastResults[firstOp-Instruction::CastOpsBegin]
3008 [secondOp-Instruction::CastOpsBegin];
3009 switch (ElimCase) {
3010 case 0:
3011 // Categorically disallowed.
3012 return 0;
3013 case 1:
3014 // Allowed, use first cast's opcode.
3015 return firstOp;
3016 case 2:
3017 // Allowed, use second cast's opcode.
3018 return secondOp;
3019 case 3:
3020 // No-op cast in second op implies firstOp as long as the DestTy
3021 // is integer and we are not converting between a vector and a
3022 // non-vector type.
3023 if (!SrcTy->isVectorTy() && DstTy->isIntegerTy())
3024 return firstOp;
3025 return 0;
3026 case 4:
3027 // No-op cast in second op implies firstOp as long as the DestTy
3028 // matches MidTy.
3029 if (DstTy == MidTy)
3030 return firstOp;
3031 return 0;
3032 case 5:
3033 // No-op cast in first op implies secondOp as long as the SrcTy
3034 // is an integer.
3035 if (SrcTy->isIntegerTy())
3036 return secondOp;
3037 return 0;
3038 case 7: {
3039 // Skip the inttoptr/ptrtoint optimization if disabled.
3040 if (!getIROptions(SrcTy->getContext()).i2p_p2i_opt)
3041 return 0;
3042
3043 // Cannot simplify if address spaces are different!
3044 if (SrcTy != DstTy)
3045 return 0;
3046
3047 // Cannot simplify if the intermediate integer size is smaller than the
3048 // pointer size.
3049 unsigned MidSize = MidTy->getScalarSizeInBits();
3050 if (!DL || MidSize < DL->getPointerTypeSizeInBits(SrcTy))
3051 return 0;
3052
3053 return Instruction::BitCast;
3054 }
3055 case 8: {
3056 // ext, trunc -> bitcast, if the SrcTy and DstTy are the same
3057 // ext, trunc -> ext, if sizeof(SrcTy) < sizeof(DstTy)
3058 // ext, trunc -> trunc, if sizeof(SrcTy) > sizeof(DstTy)
3059 unsigned SrcSize = SrcTy->getScalarSizeInBits();
3060 unsigned DstSize = DstTy->getScalarSizeInBits();
3061 if (SrcTy == DstTy)
3062 return Instruction::BitCast;
3063 if (SrcSize < DstSize)
3064 return firstOp;
3065 if (SrcSize > DstSize)
3066 return secondOp;
3067 return 0;
3068 }
3069 case 9:
3070 // zext, sext -> zext, because sext can't sign extend after zext
3071 return Instruction::ZExt;
3072 case 11: {
3073 // inttoptr, ptrtoint/ptrtoaddr -> integer cast
3074 if (!DL)
3075 return 0;
3076 unsigned MidSize = secondOp == Instruction::PtrToAddr
3077 ? DL->getAddressSizeInBits(MidTy)
3078 : DL->getPointerTypeSizeInBits(MidTy);
3079 unsigned SrcSize = SrcTy->getScalarSizeInBits();
3080 unsigned DstSize = DstTy->getScalarSizeInBits();
3081 // If the middle size is smaller than both source and destination,
3082 // an additional masking operation would be required.
3083 if (MidSize < SrcSize && MidSize < DstSize)
3084 return 0;
3085 if (DstSize < SrcSize)
3086 return Instruction::Trunc;
3087 if (DstSize > SrcSize)
3088 return Instruction::ZExt;
3089 return Instruction::BitCast;
3090 }
3091 case 12:
3092 // addrspacecast, addrspacecast -> bitcast, if SrcAS == DstAS
3093 // addrspacecast, addrspacecast -> addrspacecast, if SrcAS != DstAS
3094 if (SrcTy->getPointerAddressSpace() != DstTy->getPointerAddressSpace())
3095 return Instruction::AddrSpaceCast;
3096 return Instruction::BitCast;
3097 case 13:
3098 // FIXME: this state can be merged with (1), but the following assert
3099 // is useful to check the correcteness of the sequence due to semantic
3100 // change of bitcast.
3101 // addrspacecast can only fold through a bitcast if the result remains a
3102 // pointer. A pointer-to-byte bitcast must stay as a separate bitcast.
3103 if (!DstTy->isPtrOrPtrVectorTy())
3104 return 0;
3105 assert(
3106 SrcTy->isPtrOrPtrVectorTy() &&
3107 MidTy->isPtrOrPtrVectorTy() &&
3108 DstTy->isPtrOrPtrVectorTy() &&
3109 SrcTy->getPointerAddressSpace() != MidTy->getPointerAddressSpace() &&
3110 MidTy->getPointerAddressSpace() == DstTy->getPointerAddressSpace() &&
3111 "Illegal addrspacecast, bitcast sequence!");
3112 // Allowed, use first cast's opcode
3113 return firstOp;
3114 case 14:
3115 // bitcast, addrspacecast -> addrspacecast
3116 // addrspacecast can only fold through a bitcast if the source was already
3117 // a pointer. A byte-to-pointer bitcast must stay as a separate bitcast.
3118 if (!SrcTy->isPtrOrPtrVectorTy())
3119 return 0;
3120 return Instruction::AddrSpaceCast;
3121 case 15:
3122 // FIXME: this state can be merged with (1), but the following assert
3123 // is useful to check the correcteness of the sequence due to semantic
3124 // change of bitcast.
3125 // inttoptr can only fold through a bitcast if the result remains a
3126 // pointer. A pointer-to-byte bitcast must stay as a separate bitcast.
3127 if (!DstTy->isPtrOrPtrVectorTy())
3128 return 0;
3129 assert(
3130 SrcTy->isIntOrIntVectorTy() &&
3131 MidTy->isPtrOrPtrVectorTy() &&
3132 DstTy->isPtrOrPtrVectorTy() &&
3133 MidTy->getPointerAddressSpace() == DstTy->getPointerAddressSpace() &&
3134 "Illegal inttoptr, bitcast sequence!");
3135 // Allowed, use first cast's opcode
3136 return firstOp;
3137 case 16:
3138 // FIXME: this state can be merged with (2), but the following assert
3139 // is useful to check the correcteness of the sequence due to semantic
3140 // change of bitcast.
3141 // bitcast, ptrtoaddr -> bitcast, if SrcTy is a byte and the address is
3142 // the whole pointer
3143 // ptrtoint can only fold through a bitcast if the source was already a
3144 // pointer, as ptrtoint exposes the provenance.
3145 if (!SrcTy->isPtrOrPtrVectorTy()) {
3146 // ptrtoaddr yields the address width, so the sizes only match if the
3147 // address is the whole pointer.
3148 if (secondOp == Instruction::PtrToAddr &&
3149 SrcTy->getPrimitiveSizeInBits() == DstTy->getPrimitiveSizeInBits())
3150 return Instruction::BitCast;
3151 return 0;
3152 }
3153 assert(
3154 SrcTy->isPtrOrPtrVectorTy() &&
3155 MidTy->isPtrOrPtrVectorTy() &&
3156 DstTy->isIntOrIntVectorTy() &&
3157 SrcTy->getPointerAddressSpace() == MidTy->getPointerAddressSpace() &&
3158 "Illegal bitcast, ptrtoint sequence!");
3159 // Allowed, use second cast's opcode
3160 return secondOp;
3161 case 17:
3162 // (sitofp (zext x)) -> (uitofp x)
3163 return Instruction::UIToFP;
3164 case 18:
3165 // bitcast, bitcast -> bitcast, if neither SrcTy nor DstTy is a pointer,
3166 // both are pointers in the same addrspace,
3167 // or one is a pointer and the other a byte
3168 // bitcast, bitcast -> ptrtoint, if a pointer goes through a byte to an
3169 // integer of the pointer width
3170 // bitcast, bitcast -> inttoptr, if an integer of the pointer width goes
3171 // through a byte to a pointer
3172 // A pair of bitcasts through a byte must stay separate otherwise.
3173 if (!SrcTy->isPtrOrPtrVectorTy() && !DstTy->isPtrOrPtrVectorTy())
3174 return Instruction::BitCast;
3175 if (SrcTy->isPtrOrPtrVectorTy() && DstTy->isPtrOrPtrVectorTy() &&
3176 SrcTy->getPointerAddressSpace() == DstTy->getPointerAddressSpace())
3177 return Instruction::BitCast;
3178 if (SrcTy->isByteOrByteVectorTy() || DstTy->isByteOrByteVectorTy())
3179 return Instruction::BitCast;
3180 if (SrcTy->isVectorTy() == DstTy->isVectorTy() && DL) {
3181 if (SrcTy->isPtrOrPtrVectorTy() && DstTy->isIntOrIntVectorTy() &&
3182 DL->getPointerTypeSizeInBits(SrcTy) == DstTy->getScalarSizeInBits())
3183 return Instruction::PtrToInt;
3184 if (SrcTy->isIntOrIntVectorTy() && DstTy->isPtrOrPtrVectorTy() &&
3185 SrcTy->getScalarSizeInBits() == DL->getPointerTypeSizeInBits(DstTy))
3186 return Instruction::IntToPtr;
3187 }
3188 return 0;
3189 case 99:
3190 // Cast combination can't happen (error in input). This is for all cases
3191 // where the MidTy is not the same for the two cast instructions.
3192 llvm_unreachable("Invalid Cast Combination");
3193 default:
3194 llvm_unreachable("Error in CastResults table!!!");
3195 }
3196}
3197
3199 const Twine &Name, InsertPosition InsertBefore) {
3200 assert(castIsValid(op, S, Ty) && "Invalid cast!");
3201 // Construct and return the appropriate CastInst subclass
3202 switch (op) {
3203 case Trunc: return new TruncInst (S, Ty, Name, InsertBefore);
3204 case ZExt: return new ZExtInst (S, Ty, Name, InsertBefore);
3205 case SExt: return new SExtInst (S, Ty, Name, InsertBefore);
3206 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertBefore);
3207 case FPExt: return new FPExtInst (S, Ty, Name, InsertBefore);
3208 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertBefore);
3209 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertBefore);
3210 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertBefore);
3211 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertBefore);
3212 case PtrToAddr: return new PtrToAddrInst (S, Ty, Name, InsertBefore);
3213 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertBefore);
3214 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertBefore);
3215 case BitCast:
3216 return new BitCastInst(S, Ty, Name, InsertBefore);
3217 case AddrSpaceCast:
3218 return new AddrSpaceCastInst(S, Ty, Name, InsertBefore);
3219 default:
3220 llvm_unreachable("Invalid opcode provided");
3221 }
3222}
3223
3225 InsertPosition InsertBefore) {
3226 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
3227 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
3228 return Create(Instruction::ZExt, S, Ty, Name, InsertBefore);
3229}
3230
3232 InsertPosition InsertBefore) {
3233 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
3234 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
3235 return Create(Instruction::SExt, S, Ty, Name, InsertBefore);
3236}
3237
3239 InsertPosition InsertBefore) {
3240 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
3241 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
3242 return Create(Instruction::Trunc, S, Ty, Name, InsertBefore);
3243}
3244
3245/// Create a BitCast or a PtrToInt cast instruction
3247 InsertPosition InsertBefore) {
3248 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
3249 assert((Ty->isIntOrIntVectorTy() || Ty->isPtrOrPtrVectorTy()) &&
3250 "Invalid cast");
3251 assert(Ty->isVectorTy() == S->getType()->isVectorTy() && "Invalid cast");
3252 assert((!Ty->isVectorTy() ||
3253 cast<VectorType>(Ty)->getElementCount() ==
3254 cast<VectorType>(S->getType())->getElementCount()) &&
3255 "Invalid cast");
3256
3257 if (Ty->isIntOrIntVectorTy())
3258 return Create(Instruction::PtrToInt, S, Ty, Name, InsertBefore);
3259
3260 return CreatePointerBitCastOrAddrSpaceCast(S, Ty, Name, InsertBefore);
3261}
3262
3264 Value *S, Type *Ty, const Twine &Name, InsertPosition InsertBefore) {
3265 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
3266 assert(Ty->isPtrOrPtrVectorTy() && "Invalid cast");
3267
3268 if (S->getType()->getPointerAddressSpace() != Ty->getPointerAddressSpace())
3269 return Create(Instruction::AddrSpaceCast, S, Ty, Name, InsertBefore);
3270
3271 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
3272}
3273
3275 const Twine &Name,
3276 InsertPosition InsertBefore) {
3277 if (S->getType()->isPointerTy() && Ty->isIntegerTy())
3278 return Create(Instruction::PtrToInt, S, Ty, Name, InsertBefore);
3279 if (S->getType()->isIntegerTy() && Ty->isPointerTy())
3280 return Create(Instruction::IntToPtr, S, Ty, Name, InsertBefore);
3281
3282 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
3283}
3284
3286 const Twine &Name,
3287 InsertPosition InsertBefore) {
3288 assert(C->getType()->isIntOrIntVectorTy() && Ty->isIntOrIntVectorTy() &&
3289 "Invalid integer cast");
3290 unsigned SrcBits = C->getType()->getScalarSizeInBits();
3291 unsigned DstBits = Ty->getScalarSizeInBits();
3292 Instruction::CastOps opcode =
3293 (SrcBits == DstBits ? Instruction::BitCast :
3294 (SrcBits > DstBits ? Instruction::Trunc :
3295 (isSigned ? Instruction::SExt : Instruction::ZExt)));
3296 return Create(opcode, C, Ty, Name, InsertBefore);
3297}
3298
3300 InsertPosition InsertBefore) {
3301 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
3302 "Invalid cast");
3303 unsigned SrcBits = C->getType()->getScalarSizeInBits();
3304 unsigned DstBits = Ty->getScalarSizeInBits();
3305 assert((C->getType() == Ty || SrcBits != DstBits) && "Invalid cast");
3306 Instruction::CastOps opcode =
3307 (SrcBits == DstBits ? Instruction::BitCast :
3308 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
3309 return Create(opcode, C, Ty, Name, InsertBefore);
3310}
3311
3312bool CastInst::isBitCastable(Type *SrcTy, Type *DestTy) {
3313 if (!SrcTy->isFirstClassType() || !DestTy->isFirstClassType())
3314 return false;
3315
3316 if (SrcTy == DestTy)
3317 return true;
3318
3319 if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy)) {
3320 if (VectorType *DestVecTy = dyn_cast<VectorType>(DestTy)) {
3321 if (SrcVecTy->getElementCount() == DestVecTy->getElementCount()) {
3322 // An element by element cast. Valid if casting the elements is valid.
3323 SrcTy = SrcVecTy->getElementType();
3324 DestTy = DestVecTy->getElementType();
3325 }
3326 }
3327 }
3328
3329 if (PointerType *DestPtrTy = dyn_cast<PointerType>(DestTy)) {
3330 if (PointerType *SrcPtrTy = dyn_cast<PointerType>(SrcTy)) {
3331 return SrcPtrTy->getAddressSpace() == DestPtrTy->getAddressSpace();
3332 }
3333 }
3334
3335 TypeSize SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr
3336 TypeSize DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr
3337
3338 // Could still have vectors of pointers if the number of elements doesn't
3339 // match
3340 if (SrcBits.getKnownMinValue() == 0 || DestBits.getKnownMinValue() == 0)
3341 return false;
3342
3343 if (SrcBits != DestBits)
3344 return false;
3345
3346 return true;
3347}
3348
3350 const DataLayout &DL) {
3351 // ptrtoint and inttoptr are not allowed on non-integral pointers
3352 if (auto *PtrTy = dyn_cast<PointerType>(SrcTy))
3353 if (auto *IntTy = dyn_cast<IntegerType>(DestTy))
3354 return (IntTy->getBitWidth() == DL.getPointerTypeSizeInBits(PtrTy) &&
3355 !DL.isNonIntegralPointerType(PtrTy));
3356 if (auto *PtrTy = dyn_cast<PointerType>(DestTy))
3357 if (auto *IntTy = dyn_cast<IntegerType>(SrcTy))
3358 return (IntTy->getBitWidth() == DL.getPointerTypeSizeInBits(PtrTy) &&
3359 !DL.isNonIntegralPointerType(PtrTy));
3360
3361 return isBitCastable(SrcTy, DestTy);
3362}
3363
3364// Provide a way to get a "cast" where the cast opcode is inferred from the
3365// types and size of the operand. This, basically, is a parallel of the
3366// logic in the castIsValid function below. This axiom should hold:
3367// castIsValid( getCastOpcode(Val, Ty), Val, Ty)
3368// should not assert in castIsValid. In other words, this produces a "correct"
3369// casting opcode for the arguments passed to it.
3372 const Value *Src, bool SrcIsSigned, Type *DestTy, bool DestIsSigned) {
3373 Type *SrcTy = Src->getType();
3374
3375 assert(SrcTy->isFirstClassType() && DestTy->isFirstClassType() &&
3376 "Only first class types are castable!");
3377
3378 if (SrcTy == DestTy)
3379 return BitCast;
3380
3381 // FIXME: Check address space sizes here
3382 if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy))
3383 if (VectorType *DestVecTy = dyn_cast<VectorType>(DestTy))
3384 if (SrcVecTy->getElementCount() == DestVecTy->getElementCount()) {
3385 // An element by element cast. Find the appropriate opcode based on the
3386 // element types.
3387 SrcTy = SrcVecTy->getElementType();
3388 DestTy = DestVecTy->getElementType();
3389 }
3390
3391 // Get the bit sizes, we'll need these
3392 // FIXME: This doesn't work for scalable vector types with different element
3393 // counts that don't call getElementType above.
3394 unsigned SrcBits =
3395 SrcTy->getPrimitiveSizeInBits().getFixedValue(); // 0 for ptr
3396 unsigned DestBits =
3397 DestTy->getPrimitiveSizeInBits().getFixedValue(); // 0 for ptr
3398
3399 // Run through the possibilities ...
3400 if (DestTy->isByteTy()) { // Casting to byte
3401 if (SrcTy->isIntegerTy()) { // Casting from integral
3402 assert(DestBits == SrcBits && "Illegal cast from integer to byte type");
3403 return BitCast;
3404 } else if (SrcTy->isPointerTy()) { // Casting from pointer
3405 assert(DestBits == SrcBits && "Illegal cast from pointer to byte type");
3406 return BitCast;
3407 }
3408 llvm_unreachable("Illegal cast to byte type");
3409 } else if (DestTy->isIntegerTy()) { // Casting to integral
3410 if (SrcTy->isIntegerTy()) { // Casting from integral
3411 if (DestBits < SrcBits)
3412 return Trunc; // int -> smaller int
3413 else if (DestBits > SrcBits) { // its an extension
3414 if (SrcIsSigned)
3415 return SExt; // signed -> SEXT
3416 else
3417 return ZExt; // unsigned -> ZEXT
3418 } else {
3419 return BitCast; // Same size, No-op cast
3420 }
3421 } else if (SrcTy->isFloatingPointTy()) { // Casting from floating pt
3422 if (DestIsSigned)
3423 return FPToSI; // FP -> sint
3424 else
3425 return FPToUI; // FP -> uint
3426 } else if (SrcTy->isVectorTy()) {
3427 assert(DestBits == SrcBits &&
3428 "Casting vector to integer of different width");
3429 return BitCast; // Same size, no-op cast
3430 } else {
3431 assert(SrcTy->isPointerTy() &&
3432 "Casting from a value that is not first-class type");
3433 return PtrToInt; // ptr -> int
3434 }
3435 } else if (DestTy->isFloatingPointTy()) { // Casting to floating pt
3436 if (SrcTy->isIntegerTy()) { // Casting from integral
3437 if (SrcIsSigned)
3438 return SIToFP; // sint -> FP
3439 else
3440 return UIToFP; // uint -> FP
3441 } else if (SrcTy->isFloatingPointTy()) { // Casting from floating pt
3442 if (DestBits < SrcBits) {
3443 return FPTrunc; // FP -> smaller FP
3444 } else if (DestBits > SrcBits) {
3445 return FPExt; // FP -> larger FP
3446 } else {
3447 return BitCast; // same size, no-op cast
3448 }
3449 } else if (SrcTy->isVectorTy()) {
3450 assert(DestBits == SrcBits &&
3451 "Casting vector to floating point of different width");
3452 return BitCast; // same size, no-op cast
3453 }
3454 llvm_unreachable("Casting pointer or non-first class to float");
3455 } else if (DestTy->isVectorTy()) {
3456 assert(DestBits == SrcBits &&
3457 "Illegal cast to vector (wrong type or size)");
3458 return BitCast;
3459 } else if (DestTy->isPointerTy()) {
3460 if (SrcTy->isPointerTy()) {
3461 if (DestTy->getPointerAddressSpace() != SrcTy->getPointerAddressSpace())
3462 return AddrSpaceCast;
3463 return BitCast; // ptr -> ptr
3464 } else if (SrcTy->isIntegerTy()) {
3465 return IntToPtr; // int -> ptr
3466 }
3467 llvm_unreachable("Casting pointer to other than pointer or int");
3468 }
3469 llvm_unreachable("Casting to type that is not first-class");
3470}
3471
3472//===----------------------------------------------------------------------===//
3473// CastInst SubClass Constructors
3474//===----------------------------------------------------------------------===//
3475
3476/// Check that the construction parameters for a CastInst are correct. This
3477/// could be broken out into the separate constructors but it is useful to have
3478/// it in one place and to eliminate the redundant code for getting the sizes
3479/// of the types involved.
3480bool
3482 if (!SrcTy->isFirstClassType() || !DstTy->isFirstClassType() ||
3483 SrcTy->isAggregateType() || DstTy->isAggregateType())
3484 return false;
3485
3486 // Get the size of the types in bits, and whether we are dealing
3487 // with vector types, we'll need this later.
3488 bool SrcIsVec = isa<VectorType>(SrcTy);
3489 bool DstIsVec = isa<VectorType>(DstTy);
3490 unsigned SrcScalarBitSize = SrcTy->getScalarSizeInBits();
3491 unsigned DstScalarBitSize = DstTy->getScalarSizeInBits();
3492
3493 // If these are vector types, get the lengths of the vectors (using zero for
3494 // scalar types means that checking that vector lengths match also checks that
3495 // scalars are not being converted to vectors or vectors to scalars).
3496 ElementCount SrcEC = SrcIsVec ? cast<VectorType>(SrcTy)->getElementCount()
3498 ElementCount DstEC = DstIsVec ? cast<VectorType>(DstTy)->getElementCount()
3500
3501 // Switch on the opcode provided
3502 switch (op) {
3503 default: return false; // This is an input error
3504 case Instruction::Trunc:
3505 return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() &&
3506 SrcEC == DstEC && SrcScalarBitSize > DstScalarBitSize;
3507 case Instruction::ZExt:
3508 return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() &&
3509 SrcEC == DstEC && SrcScalarBitSize < DstScalarBitSize;
3510 case Instruction::SExt:
3511 return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() &&
3512 SrcEC == DstEC && SrcScalarBitSize < DstScalarBitSize;
3513 case Instruction::FPTrunc:
3514 return SrcTy->isFPOrFPVectorTy() && DstTy->isFPOrFPVectorTy() &&
3515 SrcEC == DstEC && SrcScalarBitSize > DstScalarBitSize;
3516 case Instruction::FPExt:
3517 return SrcTy->isFPOrFPVectorTy() && DstTy->isFPOrFPVectorTy() &&
3518 SrcEC == DstEC && SrcScalarBitSize < DstScalarBitSize;
3519 case Instruction::UIToFP:
3520 case Instruction::SIToFP:
3521 return SrcTy->isIntOrIntVectorTy() && DstTy->isFPOrFPVectorTy() &&
3522 SrcEC == DstEC;
3523 case Instruction::FPToUI:
3524 case Instruction::FPToSI:
3525 return SrcTy->isFPOrFPVectorTy() && DstTy->isIntOrIntVectorTy() &&
3526 SrcEC == DstEC;
3527 case Instruction::PtrToAddr:
3528 case Instruction::PtrToInt:
3529 if (SrcEC != DstEC)
3530 return false;
3531 return SrcTy->isPtrOrPtrVectorTy() && DstTy->isIntOrIntVectorTy();
3532 case Instruction::IntToPtr:
3533 if (SrcEC != DstEC)
3534 return false;
3535 return SrcTy->isIntOrIntVectorTy() && DstTy->isPtrOrPtrVectorTy();
3536 case Instruction::BitCast: {
3537 Type *SrcScalarTy = SrcTy->getScalarType();
3538 if (SrcScalarTy->isTargetExtTy() || !SrcScalarTy->isSingleValueType())
3539 return false;
3540 Type *DstScalarTy = DstTy->getScalarType();
3541 if (DstScalarTy->isTargetExtTy() || !DstScalarTy->isSingleValueType())
3542 return false;
3543
3544 PointerType *SrcPtrTy = dyn_cast<PointerType>(SrcScalarTy);
3545 PointerType *DstPtrTy = dyn_cast<PointerType>(DstScalarTy);
3546
3547 // BitCast implies a no-op cast of type only. No bits change.
3548 // However, you can't cast pointers to anything but pointers/bytes.
3549 if ((SrcPtrTy && DstTy->isByteOrByteVectorTy()) ||
3550 (SrcTy->isByteOrByteVectorTy() && DstPtrTy))
3551 return true;
3552 if (!SrcPtrTy != !DstPtrTy)
3553 return false;
3554
3555 // For non-pointer cases, the cast is okay if the source and destination bit
3556 // widths are identical.
3557 if (!SrcPtrTy)
3558 return SrcTy->getPrimitiveSizeInBits() == DstTy->getPrimitiveSizeInBits();
3559
3560 // If both are pointers then the address spaces must match.
3561 if (SrcPtrTy->getAddressSpace() != DstPtrTy->getAddressSpace())
3562 return false;
3563
3564 // A vector of pointers must have the same number of elements.
3565 if (SrcIsVec && DstIsVec)
3566 return SrcEC == DstEC;
3567 if (SrcIsVec)
3568 return SrcEC == ElementCount::getFixed(1);
3569 if (DstIsVec)
3570 return DstEC == ElementCount::getFixed(1);
3571
3572 return true;
3573 }
3574 case Instruction::AddrSpaceCast: {
3575 PointerType *SrcPtrTy = dyn_cast<PointerType>(SrcTy->getScalarType());
3576 if (!SrcPtrTy)
3577 return false;
3578
3579 PointerType *DstPtrTy = dyn_cast<PointerType>(DstTy->getScalarType());
3580 if (!DstPtrTy)
3581 return false;
3582
3583 if (SrcPtrTy->getAddressSpace() == DstPtrTy->getAddressSpace())
3584 return false;
3585
3586 return SrcEC == DstEC;
3587 }
3588 }
3589}
3590
3592 InsertPosition InsertBefore)
3593 : CastInst(Ty, Trunc, S, Name, InsertBefore) {
3594 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
3595}
3596
3597ZExtInst::ZExtInst(Value *S, Type *Ty, const Twine &Name,
3598 InsertPosition InsertBefore)
3599 : CastInst(Ty, ZExt, S, Name, InsertBefore) {
3600 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
3601}
3602
3603SExtInst::SExtInst(Value *S, Type *Ty, const Twine &Name,
3604 InsertPosition InsertBefore)
3605 : CastInst(Ty, SExt, S, Name, InsertBefore) {
3606 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
3607}
3608
3610 InsertPosition InsertBefore)
3611 : CastInst(Ty, FPTrunc, S, Name, InsertBefore) {
3612 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
3613}
3614
3616 InsertPosition InsertBefore)
3617 : CastInst(Ty, FPExt, S, Name, InsertBefore) {
3618 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
3619}
3620
3622 InsertPosition InsertBefore)
3623 : CastInst(Ty, UIToFP, S, Name, InsertBefore) {
3624 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
3625}
3626
3628 InsertPosition InsertBefore)
3629 : CastInst(Ty, SIToFP, S, Name, InsertBefore) {
3630 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
3631}
3632
3634 InsertPosition InsertBefore)
3635 : CastInst(Ty, FPToUI, S, Name, InsertBefore) {
3636 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
3637}
3638
3640 InsertPosition InsertBefore)
3641 : CastInst(Ty, FPToSI, S, Name, InsertBefore) {
3642 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
3643}
3644
3646 InsertPosition InsertBefore)
3647 : CastInst(Ty, PtrToInt, S, Name, InsertBefore) {
3648 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
3649}
3650
3652 InsertPosition InsertBefore)
3653 : CastInst(Ty, PtrToAddr, S, Name, InsertBefore) {
3654 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToAddr");
3655}
3656
3658 InsertPosition InsertBefore)
3659 : CastInst(Ty, IntToPtr, S, Name, InsertBefore) {
3660 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
3661}
3662
3664 InsertPosition InsertBefore)
3665 : CastInst(Ty, BitCast, S, Name, InsertBefore) {
3666 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
3667}
3668
3670 InsertPosition InsertBefore)
3671 : CastInst(Ty, AddrSpaceCast, S, Name, InsertBefore) {
3672 assert(castIsValid(getOpcode(), S, Ty) && "Illegal AddrSpaceCast");
3673}
3674
3675//===----------------------------------------------------------------------===//
3676// CmpInst Classes
3677//===----------------------------------------------------------------------===//
3678
3680 Value *RHS, const Twine &Name, InsertPosition InsertBefore)
3681 : Instruction(ty, op, AllocMarker, InsertBefore) {
3682 Op<0>() = LHS;
3683 Op<1>() = RHS;
3684 setPredicate(predicate);
3685 setName(Name);
3686}
3687
3689 const Twine &Name, InsertPosition InsertBefore) {
3690 if (Op == Instruction::ICmp) {
3691 if (InsertBefore.isValid())
3692 return new ICmpInst(InsertBefore, CmpInst::Predicate(predicate),
3693 S1, S2, Name);
3694 else
3695 return new ICmpInst(CmpInst::Predicate(predicate),
3696 S1, S2, Name);
3697 }
3698
3699 if (InsertBefore.isValid())
3700 return new FCmpInst(InsertBefore, CmpInst::Predicate(predicate),
3701 S1, S2, Name);
3702 else
3703 return new FCmpInst(CmpInst::Predicate(predicate),
3704 S1, S2, Name);
3705}
3706
3708 Value *S2,
3709 const Instruction *FlagsSource,
3710 const Twine &Name,
3711 InsertPosition InsertBefore) {
3712 CmpInst *Inst = Create(Op, Pred, S1, S2, Name, InsertBefore);
3713 Inst->copyIRFlags(FlagsSource);
3714 return Inst;
3715}
3716
3718 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
3719 IC->swapOperands();
3720 else
3721 cast<FCmpInst>(this)->swapOperands();
3722}
3723
3725 if (const ICmpInst *IC = dyn_cast<ICmpInst>(this))
3726 return IC->isCommutative();
3727 return cast<FCmpInst>(this)->isCommutative();
3728}
3729
3732 return ICmpInst::isEquality(P);
3734 return FCmpInst::isEquality(P);
3735 llvm_unreachable("Unsupported predicate kind");
3736}
3737
3738// Returns true if either operand of CmpInst is a provably non-zero
3739// floating-point constant.
3740static bool hasNonZeroFPOperands(const CmpInst *Cmp) {
3741 auto *LHS = dyn_cast<Constant>(Cmp->getOperand(0));
3742 auto *RHS = dyn_cast<Constant>(Cmp->getOperand(1));
3743 if (auto *Const = LHS ? LHS : RHS) {
3744 using namespace llvm::PatternMatch;
3745 return match(Const, m_NonZeroNotDenormalFP());
3746 }
3747 return false;
3748}
3749
3750// Floating-point equality is not an equivalence when comparing +0.0 with
3751// -0.0, when comparing NaN with another value, or when flushing
3752// denormals-to-zero.
3753bool CmpInst::isEquivalence(bool Invert) const {
3754 switch (Invert ? getInversePredicate() : getPredicate()) {
3756 return true;
3758 if (!hasNoNaNs())
3759 return false;
3760 [[fallthrough]];
3762 return hasNonZeroFPOperands(this);
3763 default:
3764 return false;
3765 }
3766}
3767
3769 switch (pred) {
3770 default: llvm_unreachable("Unknown cmp predicate!");
3771 case ICMP_EQ: return ICMP_NE;
3772 case ICMP_NE: return ICMP_EQ;
3773 case ICMP_UGT: return ICMP_ULE;
3774 case ICMP_ULT: return ICMP_UGE;
3775 case ICMP_UGE: return ICMP_ULT;
3776 case ICMP_ULE: return ICMP_UGT;
3777 case ICMP_SGT: return ICMP_SLE;
3778 case ICMP_SLT: return ICMP_SGE;
3779 case ICMP_SGE: return ICMP_SLT;
3780 case ICMP_SLE: return ICMP_SGT;
3781
3782 case FCMP_OEQ: return FCMP_UNE;
3783 case FCMP_ONE: return FCMP_UEQ;
3784 case FCMP_OGT: return FCMP_ULE;
3785 case FCMP_OLT: return FCMP_UGE;
3786 case FCMP_OGE: return FCMP_ULT;
3787 case FCMP_OLE: return FCMP_UGT;
3788 case FCMP_UEQ: return FCMP_ONE;
3789 case FCMP_UNE: return FCMP_OEQ;
3790 case FCMP_UGT: return FCMP_OLE;
3791 case FCMP_ULT: return FCMP_OGE;
3792 case FCMP_UGE: return FCMP_OLT;
3793 case FCMP_ULE: return FCMP_OGT;
3794 case FCMP_ORD: return FCMP_UNO;
3795 case FCMP_UNO: return FCMP_ORD;
3796 case FCMP_TRUE: return FCMP_FALSE;
3797 case FCMP_FALSE: return FCMP_TRUE;
3798 }
3799}
3800
3802 switch (Pred) {
3803 default: return "unknown";
3804 case FCmpInst::FCMP_FALSE: return "false";
3805 case FCmpInst::FCMP_OEQ: return "oeq";
3806 case FCmpInst::FCMP_OGT: return "ogt";
3807 case FCmpInst::FCMP_OGE: return "oge";
3808 case FCmpInst::FCMP_OLT: return "olt";
3809 case FCmpInst::FCMP_OLE: return "ole";
3810 case FCmpInst::FCMP_ONE: return "one";
3811 case FCmpInst::FCMP_ORD: return "ord";
3812 case FCmpInst::FCMP_UNO: return "uno";
3813 case FCmpInst::FCMP_UEQ: return "ueq";
3814 case FCmpInst::FCMP_UGT: return "ugt";
3815 case FCmpInst::FCMP_UGE: return "uge";
3816 case FCmpInst::FCMP_ULT: return "ult";
3817 case FCmpInst::FCMP_ULE: return "ule";
3818 case FCmpInst::FCMP_UNE: return "une";
3819 case FCmpInst::FCMP_TRUE: return "true";
3820 case ICmpInst::ICMP_EQ: return "eq";
3821 case ICmpInst::ICMP_NE: return "ne";
3822 case ICmpInst::ICMP_SGT: return "sgt";
3823 case ICmpInst::ICMP_SGE: return "sge";
3824 case ICmpInst::ICMP_SLT: return "slt";
3825 case ICmpInst::ICMP_SLE: return "sle";
3826 case ICmpInst::ICMP_UGT: return "ugt";
3827 case ICmpInst::ICMP_UGE: return "uge";
3828 case ICmpInst::ICMP_ULT: return "ult";
3829 case ICmpInst::ICMP_ULE: return "ule";
3830 }
3831}
3832
3834 OS << CmpInst::getPredicateName(Pred);
3835 return OS;
3836}
3837
3839 switch (pred) {
3840 default: llvm_unreachable("Unknown icmp predicate!");
3841 case ICMP_EQ: case ICMP_NE:
3842 case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE:
3843 return pred;
3844 case ICMP_UGT: return ICMP_SGT;
3845 case ICMP_ULT: return ICMP_SLT;
3846 case ICMP_UGE: return ICMP_SGE;
3847 case ICMP_ULE: return ICMP_SLE;
3848 }
3849}
3850
3852 switch (pred) {
3853 default: llvm_unreachable("Unknown icmp predicate!");
3854 case ICMP_EQ: case ICMP_NE:
3855 case ICMP_UGT: case ICMP_ULT: case ICMP_UGE: case ICMP_ULE:
3856 return pred;
3857 case ICMP_SGT: return ICMP_UGT;
3858 case ICMP_SLT: return ICMP_ULT;
3859 case ICMP_SGE: return ICMP_UGE;
3860 case ICMP_SLE: return ICMP_ULE;
3861 }
3862}
3863
3865 switch (pred) {
3866 default: llvm_unreachable("Unknown cmp predicate!");
3867 case ICMP_EQ: case ICMP_NE:
3868 return pred;
3869 case ICMP_SGT: return ICMP_SLT;
3870 case ICMP_SLT: return ICMP_SGT;
3871 case ICMP_SGE: return ICMP_SLE;
3872 case ICMP_SLE: return ICMP_SGE;
3873 case ICMP_UGT: return ICMP_ULT;
3874 case ICMP_ULT: return ICMP_UGT;
3875 case ICMP_UGE: return ICMP_ULE;
3876 case ICMP_ULE: return ICMP_UGE;
3877
3878 case FCMP_FALSE: case FCMP_TRUE:
3879 case FCMP_OEQ: case FCMP_ONE:
3880 case FCMP_UEQ: case FCMP_UNE:
3881 case FCMP_ORD: case FCMP_UNO:
3882 return pred;
3883 case FCMP_OGT: return FCMP_OLT;
3884 case FCMP_OLT: return FCMP_OGT;
3885 case FCMP_OGE: return FCMP_OLE;
3886 case FCMP_OLE: return FCMP_OGE;
3887 case FCMP_UGT: return FCMP_ULT;
3888 case FCMP_ULT: return FCMP_UGT;
3889 case FCMP_UGE: return FCMP_ULE;
3890 case FCMP_ULE: return FCMP_UGE;
3891 }
3892}
3893
3895 switch (pred) {
3896 case ICMP_SGE:
3897 case ICMP_SLE:
3898 case ICMP_UGE:
3899 case ICMP_ULE:
3900 case FCMP_OGE:
3901 case FCMP_OLE:
3902 case FCMP_UGE:
3903 case FCMP_ULE:
3904 return true;
3905 default:
3906 return false;
3907 }
3908}
3909
3911 switch (pred) {
3912 case ICMP_SGT:
3913 case ICMP_SLT:
3914 case ICMP_UGT:
3915 case ICMP_ULT:
3916 case FCMP_OGT:
3917 case FCMP_OLT:
3918 case FCMP_UGT:
3919 case FCMP_ULT:
3920 return true;
3921 default:
3922 return false;
3923 }
3924}
3925
3927 switch (pred) {
3928 case ICMP_SGE:
3929 return ICMP_SGT;
3930 case ICMP_SLE:
3931 return ICMP_SLT;
3932 case ICMP_UGE:
3933 return ICMP_UGT;
3934 case ICMP_ULE:
3935 return ICMP_ULT;
3936 case FCMP_OGE:
3937 return FCMP_OGT;
3938 case FCMP_OLE:
3939 return FCMP_OLT;
3940 case FCMP_UGE:
3941 return FCMP_UGT;
3942 case FCMP_ULE:
3943 return FCMP_ULT;
3944 default:
3945 return pred;
3946 }
3947}
3948
3950 switch (pred) {
3951 case ICMP_SGT:
3952 return ICMP_SGE;
3953 case ICMP_SLT:
3954 return ICMP_SLE;
3955 case ICMP_UGT:
3956 return ICMP_UGE;
3957 case ICMP_ULT:
3958 return ICMP_ULE;
3959 case FCMP_OGT:
3960 return FCMP_OGE;
3961 case FCMP_OLT:
3962 return FCMP_OLE;
3963 case FCMP_UGT:
3964 return FCMP_UGE;
3965 case FCMP_ULT:
3966 return FCMP_ULE;
3967 default:
3968 return pred;
3969 }
3970}
3971
3973 assert(CmpInst::isRelational(pred) && "Call only with relational predicate!");
3974
3975 if (isStrictPredicate(pred))
3976 return getNonStrictPredicate(pred);
3977 if (isNonStrictPredicate(pred))
3978 return getStrictPredicate(pred);
3979
3980 llvm_unreachable("Unknown predicate!");
3981}
3982
3983bool ICmpInst::compare(const APInt &LHS, const APInt &RHS,
3984 ICmpInst::Predicate Pred) {
3985 assert(ICmpInst::isIntPredicate(Pred) && "Only for integer predicates!");
3986 switch (Pred) {
3988 return LHS.eq(RHS);
3990 return LHS.ne(RHS);
3992 return LHS.ugt(RHS);
3994 return LHS.uge(RHS);
3996 return LHS.ult(RHS);
3998 return LHS.ule(RHS);
4000 return LHS.sgt(RHS);
4002 return LHS.sge(RHS);
4004 return LHS.slt(RHS);
4006 return LHS.sle(RHS);
4007 default:
4008 llvm_unreachable("Unexpected non-integer predicate.");
4009 };
4010}
4011
4012bool FCmpInst::compare(const APFloat &LHS, const APFloat &RHS,
4013 FCmpInst::Predicate Pred) {
4014 APFloat::cmpResult R = LHS.compare(RHS);
4015 switch (Pred) {
4016 default:
4017 llvm_unreachable("Invalid FCmp Predicate");
4019 return false;
4021 return true;
4022 case FCmpInst::FCMP_UNO:
4023 return R == APFloat::cmpUnordered;
4024 case FCmpInst::FCMP_ORD:
4025 return R != APFloat::cmpUnordered;
4026 case FCmpInst::FCMP_UEQ:
4027 return R == APFloat::cmpUnordered || R == APFloat::cmpEqual;
4028 case FCmpInst::FCMP_OEQ:
4029 return R == APFloat::cmpEqual;
4030 case FCmpInst::FCMP_UNE:
4031 return R != APFloat::cmpEqual;
4032 case FCmpInst::FCMP_ONE:
4034 case FCmpInst::FCMP_ULT:
4035 return R == APFloat::cmpUnordered || R == APFloat::cmpLessThan;
4036 case FCmpInst::FCMP_OLT:
4037 return R == APFloat::cmpLessThan;
4038 case FCmpInst::FCMP_UGT:
4040 case FCmpInst::FCMP_OGT:
4041 return R == APFloat::cmpGreaterThan;
4042 case FCmpInst::FCMP_ULE:
4043 return R != APFloat::cmpGreaterThan;
4044 case FCmpInst::FCMP_OLE:
4045 return R == APFloat::cmpLessThan || R == APFloat::cmpEqual;
4046 case FCmpInst::FCMP_UGE:
4047 return R != APFloat::cmpLessThan;
4048 case FCmpInst::FCMP_OGE:
4049 return R == APFloat::cmpGreaterThan || R == APFloat::cmpEqual;
4050 }
4051}
4052
4053std::optional<bool> ICmpInst::compare(const KnownBits &LHS,
4054 const KnownBits &RHS,
4055 ICmpInst::Predicate Pred) {
4056 switch (Pred) {
4057 case ICmpInst::ICMP_EQ:
4058 return KnownBits::eq(LHS, RHS);
4059 case ICmpInst::ICMP_NE:
4060 return KnownBits::ne(LHS, RHS);
4061 case ICmpInst::ICMP_UGE:
4062 return KnownBits::uge(LHS, RHS);
4063 case ICmpInst::ICMP_UGT:
4064 return KnownBits::ugt(LHS, RHS);
4065 case ICmpInst::ICMP_ULE:
4066 return KnownBits::ule(LHS, RHS);
4067 case ICmpInst::ICMP_ULT:
4068 return KnownBits::ult(LHS, RHS);
4069 case ICmpInst::ICMP_SGE:
4070 return KnownBits::sge(LHS, RHS);
4071 case ICmpInst::ICMP_SGT:
4072 return KnownBits::sgt(LHS, RHS);
4073 case ICmpInst::ICMP_SLE:
4074 return KnownBits::sle(LHS, RHS);
4075 case ICmpInst::ICMP_SLT:
4076 return KnownBits::slt(LHS, RHS);
4077 default:
4078 llvm_unreachable("Unexpected non-integer predicate.");
4079 }
4080}
4081
4083 if (CmpInst::isEquality(pred))
4084 return pred;
4085 if (isSigned(pred))
4086 return getUnsignedPredicate(pred);
4087 if (isUnsigned(pred))
4088 return getSignedPredicate(pred);
4089
4090 llvm_unreachable("Unknown predicate!");
4091}
4092
4094 switch (predicate) {
4095 default: return false;
4098 case FCmpInst::FCMP_ORD: return true;
4099 }
4100}
4101
4103 switch (predicate) {
4104 default: return false;
4107 case FCmpInst::FCMP_UNO: return true;
4108 }
4109}
4110
4112 switch(predicate) {
4113 default: return false;
4114 case ICMP_EQ: case ICMP_UGE: case ICMP_ULE: case ICMP_SGE: case ICMP_SLE:
4115 case FCMP_TRUE: case FCMP_UEQ: case FCMP_UGE: case FCMP_ULE: return true;
4116 }
4117}
4118
4120 switch(predicate) {
4121 case ICMP_NE: case ICMP_UGT: case ICMP_ULT: case ICMP_SGT: case ICMP_SLT:
4122 case FCMP_FALSE: case FCMP_ONE: case FCMP_OGT: case FCMP_OLT: return true;
4123 default: return false;
4124 }
4125}
4126
4128 // If the predicates match, then we know the first condition implies the
4129 // second is true.
4130 if (CmpPredicate::getMatching(Pred1, Pred2))
4131 return true;
4132
4133 if (Pred1.hasSameSign() && CmpInst::isSigned(Pred2))
4135 else if (Pred2.hasSameSign() && CmpInst::isSigned(Pred1))
4137
4138 switch (Pred1) {
4139 default:
4140 break;
4141 case CmpInst::ICMP_EQ:
4142 // A == B implies A >=u B, A <=u B, A >=s B, and A <=s B are true.
4143 return Pred2 == CmpInst::ICMP_UGE || Pred2 == CmpInst::ICMP_ULE ||
4144 Pred2 == CmpInst::ICMP_SGE || Pred2 == CmpInst::ICMP_SLE;
4145 case CmpInst::ICMP_UGT: // A >u B implies A != B and A >=u B are true.
4146 return Pred2 == CmpInst::ICMP_NE || Pred2 == CmpInst::ICMP_UGE;
4147 case CmpInst::ICMP_ULT: // A <u B implies A != B and A <=u B are true.
4148 return Pred2 == CmpInst::ICMP_NE || Pred2 == CmpInst::ICMP_ULE;
4149 case CmpInst::ICMP_SGT: // A >s B implies A != B and A >=s B are true.
4150 return Pred2 == CmpInst::ICMP_NE || Pred2 == CmpInst::ICMP_SGE;
4151 case CmpInst::ICMP_SLT: // A <s B implies A != B and A <=s B are true.
4152 return Pred2 == CmpInst::ICMP_NE || Pred2 == CmpInst::ICMP_SLE;
4153 }
4154 return false;
4155}
4156
4158 CmpPredicate Pred2) {
4159 return isImpliedTrueByMatchingCmp(Pred1,
4161}
4162
4164 CmpPredicate Pred2) {
4165 if (isImpliedTrueByMatchingCmp(Pred1, Pred2))
4166 return true;
4167 if (isImpliedFalseByMatchingCmp(Pred1, Pred2))
4168 return false;
4169 return std::nullopt;
4170}
4171
4172//===----------------------------------------------------------------------===//
4173// CmpPredicate Implementation
4174//===----------------------------------------------------------------------===//
4175
4176std::optional<CmpPredicate> CmpPredicate::getMatching(CmpPredicate A,
4177 CmpPredicate B) {
4178 if (A.Pred == B.Pred)
4179 return A.HasSameSign == B.HasSameSign ? A : CmpPredicate(A.Pred);
4181 return {};
4182 if (A.HasSameSign &&
4184 return B.Pred;
4185 if (B.HasSameSign &&
4187 return A.Pred;
4188 return {};
4189}
4190
4194
4196 if (auto *ICI = dyn_cast<ICmpInst>(Cmp))
4197 return ICI->getCmpPredicate();
4198 return Cmp->getPredicate();
4199}
4200
4204
4208
4210 return getSwapped(get(Cmp));
4211}
4212
4213//===----------------------------------------------------------------------===//
4214// SwitchInst Implementation
4215//===----------------------------------------------------------------------===//
4216
4217void SwitchInst::init(Value *Value, BasicBlock *Default, unsigned NumReserved) {
4218 assert(Value && Default && NumReserved);
4219 ReservedSpace = NumReserved;
4220 allocHungoffUses(ReservedSpace);
4222
4223 Op<0>() = Value;
4224 Op<1>() = Default;
4225}
4226
4227/// SwitchInst ctor - Create a new switch instruction, specifying a value to
4228/// switch on and a default destination. The number of additional cases can
4229/// be specified here to make memory allocation more efficient. This
4230/// constructor can also autoinsert before another instruction.
4231SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
4232 InsertPosition InsertBefore)
4233 : Instruction(Type::getVoidTy(Value->getContext()), Instruction::Switch,
4234 AllocMarker, InsertBefore) {
4235 init(Value, Default, 2 + NumCases);
4236}
4237
4238SwitchInst::SwitchInst(const SwitchInst &SI)
4239 : Instruction(SI.getType(), Instruction::Switch, AllocMarker) {
4240 init(SI.getCondition(), SI.getDefaultDest(), SI.getNumOperands());
4241 setNumHungOffUseOperands(SI.getNumOperands());
4242 Use *OL = getOperandList();
4243 ConstantInt **VL = case_values();
4244 const Use *InOL = SI.getOperandList();
4245 ConstantInt *const *InVL = SI.case_values();
4246 for (unsigned i = 2, E = SI.getNumOperands(); i != E; ++i) {
4247 OL[i] = InOL[i];
4248 VL[i - 2] = InVL[i - 2];
4249 }
4250 SubclassOptionalData = SI.SubclassOptionalData;
4251}
4252
4253/// addCase - Add an entry to the switch instruction...
4254///
4256 unsigned NewCaseIdx = getNumCases();
4257 unsigned OpNo = getNumOperands();
4258 if (OpNo + 1 > ReservedSpace)
4259 growOperands(); // Get more space!
4260 // Initialize some new operands.
4261 assert(OpNo < ReservedSpace && "Growing didn't work!");
4262 setNumHungOffUseOperands(OpNo + 1);
4263 CaseHandle Case(this, NewCaseIdx);
4264 Case.setValue(OnVal);
4265 Case.setSuccessor(Dest);
4266}
4267
4268/// removeCase - This method removes the specified case and its successor
4269/// from the switch instruction.
4271 unsigned idx = I->getCaseIndex();
4272
4273 assert(2 + idx < getNumOperands() && "Case index out of range!!!");
4274
4275 unsigned NumOps = getNumOperands();
4276 Use *OL = getOperandList();
4277 ConstantInt **VL = case_values();
4278
4279 // Overwrite this case with the end of the list.
4280 if (2 + idx + 1 != NumOps) {
4281 OL[2 + idx] = OL[NumOps - 1];
4282 VL[idx] = VL[NumOps - 2 - 1];
4283 }
4284
4285 // Nuke the last value.
4286 OL[NumOps - 1].set(nullptr);
4287 VL[NumOps - 2 - 1] = nullptr;
4289
4290 return CaseIt(this, idx);
4291}
4292
4293/// growOperands - grow operands - This grows the operand list in response
4294/// to a push_back style of operation. This grows the number of ops by 3 times.
4295///
4296void SwitchInst::growOperands() {
4297 unsigned e = getNumOperands();
4298 unsigned NumOps = e*3;
4299
4300 ReservedSpace = NumOps;
4301 growHungoffUses(ReservedSpace, /*WithExtraValues=*/true);
4302}
4303
4305 MDNode *ProfileData = getBranchWeightMDNode(SI);
4306 if (!ProfileData)
4307 return;
4308
4309 if (getNumBranchWeights(*ProfileData) != SI.getNumSuccessors()) {
4310 llvm_unreachable("number of prof branch_weights metadata operands does "
4311 "not correspond to number of succesors");
4312 }
4313
4315 if (!extractBranchWeights(ProfileData, Weights))
4316 return;
4317 this->Weights = std::move(Weights);
4318}
4319
4322 if (Weights) {
4323 assert(SI.getNumSuccessors() == Weights->size() &&
4324 "num of prof branch_weights must accord with num of successors");
4325 Changed = true;
4326 // Copy the last case to the place of the removed one and shrink.
4327 // This is tightly coupled with the way SwitchInst::removeCase() removes
4328 // the cases in SwitchInst::removeCase(CaseIt).
4329 (*Weights)[I->getCaseIndex() + 1] = Weights->back();
4330 Weights->pop_back();
4331 }
4332 return SI.removeCase(I);
4333}
4334
4336 auto *DestBlock = I->getCaseSuccessor();
4337 if (Weights) {
4338 auto Weight = getSuccessorWeight(I->getCaseIndex() + 1);
4339 (*Weights)[0] = Weight.value();
4340 }
4341
4342 SI.setDefaultDest(DestBlock);
4343}
4344
4346 ConstantInt *OnVal, BasicBlock *Dest,
4348 SI.addCase(OnVal, Dest);
4349
4350 if (!Weights && W && *W) {
4351 Changed = true;
4352 Weights = SmallVector<uint32_t, 8>(SI.getNumSuccessors(), 0);
4353 (*Weights)[SI.getNumSuccessors() - 1] = *W;
4354 } else if (Weights) {
4355 Changed = true;
4356 Weights->push_back(W.value_or(0));
4357 }
4358 if (Weights)
4359 assert(SI.getNumSuccessors() == Weights->size() &&
4360 "num of prof branch_weights must accord with num of successors");
4361}
4362
4365 // Instruction is erased. Mark as unchanged to not touch it in the destructor.
4366 Changed = false;
4367 if (Weights)
4368 Weights->resize(0);
4369 return SI.eraseFromParent();
4370}
4371
4374 if (!Weights)
4375 return std::nullopt;
4376 return (*Weights)[idx];
4377}
4378
4381 if (!W)
4382 return;
4383
4384 if (!Weights && *W)
4385 Weights = SmallVector<uint32_t, 8>(SI.getNumSuccessors(), 0);
4386
4387 if (Weights) {
4388 auto &OldW = (*Weights)[idx];
4389 if (*W != OldW) {
4390 Changed = true;
4391 OldW = *W;
4392 }
4393 }
4394}
4395
4398 unsigned idx) {
4399 if (MDNode *ProfileData = getValidBranchWeightMDNode(SI)) {
4400 SmallVector<uint32_t> Weights;
4401 extractFromBranchWeightMD32(ProfileData, Weights);
4402 return Weights[idx];
4403 }
4404
4405 return std::nullopt;
4406}
4407
4408//===----------------------------------------------------------------------===//
4409// IndirectBrInst Implementation
4410//===----------------------------------------------------------------------===//
4411
4412void IndirectBrInst::init(Value *Address, unsigned NumDests) {
4413 assert(Address && Address->getType()->isPointerTy() &&
4414 "Address of indirectbr must be a pointer");
4415 ReservedSpace = 1 + NumDests;
4416 allocHungoffUses(ReservedSpace);
4418
4419 Op<0>() = Address;
4420}
4421
4422
4423/// growOperands - grow operands - This grows the operand list in response
4424/// to a push_back style of operation. This grows the number of ops by 2 times.
4425///
4426void IndirectBrInst::growOperands() {
4427 unsigned e = getNumOperands();
4428 unsigned NumOps = e*2;
4429
4430 ReservedSpace = NumOps;
4431 growHungoffUses(ReservedSpace);
4432}
4433
4434IndirectBrInst::IndirectBrInst(Value *Address, unsigned NumCases,
4435 InsertPosition InsertBefore)
4436 : Instruction(Type::getVoidTy(Address->getContext()),
4437 Instruction::IndirectBr, AllocMarker, InsertBefore) {
4438 init(Address, NumCases);
4439}
4440
4441IndirectBrInst::IndirectBrInst(const IndirectBrInst &IBI)
4442 : Instruction(Type::getVoidTy(IBI.getContext()), Instruction::IndirectBr,
4443 AllocMarker) {
4444 allocHungoffUses(IBI.getNumOperands());
4445 setNumHungOffUseOperands(IBI.NumUserOperands);
4446 Use *OL = getOperandList();
4447 const Use *InOL = IBI.getOperandList();
4448 for (unsigned i = 0, E = IBI.getNumOperands(); i != E; ++i)
4449 OL[i] = InOL[i];
4450 SubclassOptionalData = IBI.SubclassOptionalData;
4451}
4452
4453/// addDestination - Add a destination.
4454///
4456 unsigned OpNo = getNumOperands();
4457 if (OpNo+1 > ReservedSpace)
4458 growOperands(); // Get more space!
4459 // Initialize some new operands.
4460 assert(OpNo < ReservedSpace && "Growing didn't work!");
4462 getOperandList()[OpNo] = DestBB;
4463}
4464
4465/// removeDestination - This method removes the specified successor from the
4466/// indirectbr instruction.
4468 assert(idx < getNumOperands()-1 && "Successor index out of range!");
4469
4470 unsigned NumOps = getNumOperands();
4471 Use *OL = getOperandList();
4472
4473 // Replace this value with the last one.
4474 OL[idx+1] = OL[NumOps-1];
4475
4476 // Nuke the last value.
4477 OL[NumOps-1].set(nullptr);
4479}
4480
4481//===----------------------------------------------------------------------===//
4482// FreezeInst Implementation
4483//===----------------------------------------------------------------------===//
4484
4485FreezeInst::FreezeInst(Value *S, const Twine &Name, InsertPosition InsertBefore)
4486 : UnaryInstruction(S->getType(), Freeze, S, InsertBefore) {
4487 setName(Name);
4488}
4489
4490//===----------------------------------------------------------------------===//
4491// cloneImpl() implementations
4492//===----------------------------------------------------------------------===//
4493
4494// Define these methods here so vtables don't get emitted into every translation
4495// unit that uses these classes.
4496
4497GetElementPtrInst *GetElementPtrInst::cloneImpl() const {
4499 return new (AllocMarker) GetElementPtrInst(*this, AllocMarker);
4500}
4501
4505
4507 auto *I = static_cast<FPUnaryOperator *>(Create(getOpcode(), Op<0>()));
4508 I->FMF = FMF;
4509 return I;
4510}
4511
4514 "Should call FPBinaryOperator::cloneImpl!");
4515 return Create(getOpcode(), Op<0>(), Op<1>());
4516}
4517
4519 auto *I =
4520 static_cast<FPBinaryOperator *>(Create(getOpcode(), Op<0>(), Op<1>()));
4521 I->FMF = FMF;
4522 return I;
4523}
4524
4526 auto *I = new FCmpInst(getPredicate(), Op<0>(), Op<1>());
4527 I->FMF = FMF;
4528 return I;
4529}
4530
4532 auto *Result = new ICmpInst(getPredicate(), Op<0>(), Op<1>());
4533 Result->setSameSign(hasSameSign());
4534 return Result;
4535}
4536
4537ExtractValueInst *ExtractValueInst::cloneImpl() const {
4538 return new ExtractValueInst(*this);
4539}
4540
4541InsertValueInst *InsertValueInst::cloneImpl() const {
4542 return new InsertValueInst(*this);
4543}
4544
4547 getOperand(0), getAlign());
4548 Result->setUsedWithInAlloca(isUsedWithInAlloca());
4549 Result->setSwiftError(isSwiftError());
4550 return Result;
4551}
4552
4554 return new LoadInst(getType(), getOperand(0), Twine(), getProperties(),
4555 /*InsertBefore=*/nullptr);
4556}
4557
4559 return new StoreInst(getOperand(0), getOperand(1), getProperties(),
4560 /*InsertBefore=*/nullptr);
4561}
4562
4567 Result->setVolatile(isVolatile());
4568 Result->setWeak(isWeak());
4569 return Result;
4570}
4571
4573 AtomicRMWInst *Result = new AtomicRMWInst(
4576 Result->setVolatile(isVolatile());
4577 return Result;
4578}
4579
4583
4585 return new TruncInst(getOperand(0), getType());
4586}
4587
4589 return new ZExtInst(getOperand(0), getType());
4590}
4591
4593 return new SExtInst(getOperand(0), getType());
4594}
4595
4597 auto *I = new FPTruncInst(getOperand(0), getType());
4598 I->FMF = FMF;
4599 return I;
4600}
4601
4603 auto *I = new FPExtInst(getOperand(0), getType());
4604 I->FMF = FMF;
4605 return I;
4606}
4607
4609 auto *Result = new UIToFPInst(getOperand(0), getType());
4610 Result->FMF = FMF;
4611 return Result;
4612}
4613
4615 auto *Result = new SIToFPInst(getOperand(0), getType());
4616 Result->FMF = FMF;
4617 return Result;
4618}
4619
4621 return new FPToUIInst(getOperand(0), getType());
4622}
4623
4625 return new FPToSIInst(getOperand(0), getType());
4626}
4627
4629 return new PtrToIntInst(getOperand(0), getType());
4630}
4631
4635
4637 return new IntToPtrInst(getOperand(0), getType());
4638}
4639
4641 return new BitCastInst(getOperand(0), getType());
4642}
4643
4647
4648CallInst *CallInst::cloneImpl() const {
4649 if (hasOperandBundles()) {
4653 return new (AllocMarker) CallInst(*this, AllocMarker);
4654 }
4656 return new (AllocMarker) CallInst(*this, AllocMarker);
4657}
4658
4659SelectInst *SelectInst::cloneImpl() const {
4661 I->FMF = FMF;
4662 return I;
4663}
4664
4666 return new VAArgInst(getOperand(0), getType());
4667}
4668
4669ExtractElementInst *ExtractElementInst::cloneImpl() const {
4671}
4672
4673InsertElementInst *InsertElementInst::cloneImpl() const {
4675}
4676
4677BitInsertInst *BitInsertInst::cloneImpl() const {
4679}
4680
4681BitExtractInst *BitExtractInst::cloneImpl() const {
4683}
4684
4688
4689PHINode *PHINode::cloneImpl() const { return new (AllocMarker) PHINode(*this); }
4690
4691LandingPadInst *LandingPadInst::cloneImpl() const {
4692 return new LandingPadInst(*this);
4693}
4694
4695ReturnInst *ReturnInst::cloneImpl() const {
4697 return new (AllocMarker) ReturnInst(*this, AllocMarker);
4698}
4699
4700UncondBrInst *UncondBrInst::cloneImpl() const {
4701 return new (AllocMarker) UncondBrInst(*this);
4702}
4703
4704CondBrInst *CondBrInst::cloneImpl() const {
4705 return new (AllocMarker) CondBrInst(*this);
4706}
4707
4708SwitchInst *SwitchInst::cloneImpl() const { return new SwitchInst(*this); }
4709
4710IndirectBrInst *IndirectBrInst::cloneImpl() const {
4711 return new IndirectBrInst(*this);
4712}
4713
4714InvokeInst *InvokeInst::cloneImpl() const {
4715 if (hasOperandBundles()) {
4719 return new (AllocMarker) InvokeInst(*this, AllocMarker);
4720 }
4722 return new (AllocMarker) InvokeInst(*this, AllocMarker);
4723}
4724
4725CallBrInst *CallBrInst::cloneImpl() const {
4726 if (hasOperandBundles()) {
4730 return new (AllocMarker) CallBrInst(*this, AllocMarker);
4731 }
4733 return new (AllocMarker) CallBrInst(*this, AllocMarker);
4734}
4735
4736ResumeInst *ResumeInst::cloneImpl() const {
4737 return new (AllocMarker) ResumeInst(*this);
4738}
4739
4740CleanupReturnInst *CleanupReturnInst::cloneImpl() const {
4742 return new (AllocMarker) CleanupReturnInst(*this, AllocMarker);
4743}
4744
4745CatchReturnInst *CatchReturnInst::cloneImpl() const {
4746 return new (AllocMarker) CatchReturnInst(*this);
4747}
4748
4749CatchSwitchInst *CatchSwitchInst::cloneImpl() const {
4750 return new CatchSwitchInst(*this);
4751}
4752
4753FuncletPadInst *FuncletPadInst::cloneImpl() const {
4755 return new (AllocMarker) FuncletPadInst(*this, AllocMarker);
4756}
4757
4759 LLVMContext &Context = getContext();
4760 return new UnreachableInst(Context);
4761}
4762
4763bool UnreachableInst::shouldLowerToTrap(bool TrapUnreachable,
4764 bool NoTrapAfterNoreturn) const {
4765 if (!TrapUnreachable)
4766 return false;
4767
4768 // We may be able to ignore unreachable behind a noreturn call.
4770 Call && Call->doesNotReturn()) {
4771 if (NoTrapAfterNoreturn)
4772 return false;
4773 // Do not emit an additional trap instruction.
4774 if (Call->isNonContinuableTrap())
4775 return false;
4776 }
4777
4778 if (getFunction()->hasFnAttribute(Attribute::Naked))
4779 return false;
4780
4781 return true;
4782}
4783
4785 return new FreezeInst(getOperand(0));
4786}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
constexpr LLT S1
Rewrite undef for PHI
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Atomic ordering constants.
@ FnAttr
This file contains the simple types necessary to represent the attributes associated with functions a...
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define LLVM_ABI
Definition Compiler.h:211
This file contains the declarations for the subclasses of Constant, which represent the different fla...
@ Default
static bool isSigned(unsigned Opcode)
#define op(i)
Module.h This file contains the declarations for the Module class.
static Align computeLoadStoreDefaultAlign(Type *Ty, InsertPosition Pos)
static bool isImpliedFalseByMatchingCmp(CmpPredicate Pred1, CmpPredicate Pred2)
static Value * createPlaceholderForShuffleVector(Value *V)
static Align computeAllocaDefaultAlign(Type *Ty, InsertPosition Pos)
static bool hasNonZeroFPOperands(const CmpInst *Cmp)
static int matchShuffleAsBitRotate(ArrayRef< int > Mask, int NumSubElts)
Try to lower a vector shuffle as a bit rotation.
static Type * getIndexedTypeInternal(Type *Ty, ArrayRef< IndexTy > IdxList)
static bool isReplicationMaskWithParams(ArrayRef< int > Mask, int ReplicationFactor, int VF)
static bool isIdentityMaskImpl(ArrayRef< int > Mask, int NumOpElts)
static Value * getAISize(LLVMContext &Context, Value *Amt)
static bool isImpliedTrueByMatchingCmp(CmpPredicate Pred1, CmpPredicate Pred2)
static bool isSingleSourceMaskImpl(ArrayRef< int > Mask, int64_t NumOpElts)
const size_t AbstractManglingParser< Derived, Alloc >::NumOps
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
This file contains the declarations for metadata subclasses.
#define T
uint64_t IntrinsicInst * II
#define P(N)
This file contains the declarations for profiling metadata utility functions.
const SmallVectorImpl< MachineOperand > & Cond
Func getContext().diagnose(DiagnosticInfoUnsupported(Func
This file implements the SmallBitVector class.
This file defines the SmallVector class.
#define LLVM_DEBUG(...)
Definition Debug.h:119
static SymbolRef::Type getType(const Symbol *Sym)
Definition TapiFile.cpp:39
Value * RHS
Value * LHS
cmpResult
IEEE-754R 5.11: Floating Point Comparison Relations.
Definition APFloat.h:351
LLVM_ABI float convertToFloat() const
Converts this APFloat to host float value.
Definition APFloat.cpp:6132
Class for arbitrary precision integers.
Definition APInt.h:78
void setBit(unsigned BitPosition)
Set the given bit to 1 whose position is given as "bitPosition".
Definition APInt.h:1350
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition APInt.h:376
unsigned countr_zero() const
Count the number of trailing zero bits.
Definition APInt.h:1659
unsigned countl_zero() const
The APInt version of std::countl_zero.
Definition APInt.h:1618
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
Definition APInt.h:196
This class represents a conversion between pointers from one address space to another.
LLVM_ABI AddrSpaceCastInst * cloneImpl() const
Clone an identical AddrSpaceCastInst.
LLVM_ABI AddrSpaceCastInst(Value *S, Type *Ty, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructor with insert-before-instruction semantics.
LLVM_ABI std::optional< TypeSize > getAllocationSizeInBits(const DataLayout &DL) const
Get allocation size in bits.
bool isSwiftError() const
Return true if this alloca is used as a swifterror argument to a call.
LLVM_ABI bool isStaticAlloca() const
Return true if this alloca is in the entry block of the function and is a constant size.
Align getAlign() const
Return the alignment of the memory that is being allocated by the instruction.
LLVM_ABI TypeSize getAllocationBaseSize(const DataLayout &DL) const
Get the size of the allocated type.
LLVM_ABI AllocaInst * cloneImpl() const
Type * getAllocatedType() const
Return the type that is being allocated by the instruction.
bool isUsedWithInAlloca() const
Return true if this alloca is used as an inalloca argument to a call.
unsigned getAddressSpace() const
Return the address space for the allocation.
LLVM_ABI std::optional< TypeSize > getAllocationSize(const DataLayout &DL) const
Get allocation size in bytes.
LLVM_ABI bool isArrayAllocation() const
Return true if there is an allocation size parameter to the allocation instruction that is not 1.
void setAlignment(Align Align)
const Value * getArraySize() const
Get the number of elements allocated.
LLVM_ABI AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize, const Twine &Name, InsertPosition InsertBefore)
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
iterator end() const
Definition ArrayRef.h:130
size_t size() const
Get the array size.
Definition ArrayRef.h:141
iterator begin() const
Definition ArrayRef.h:129
bool empty() const
Check if the array is empty.
Definition ArrayRef.h:136
ArrayRef< T > slice(size_t N, size_t M) const
slice(n, m) - Chop off the first N elements of the array, and keep M elements in the array.
Definition ArrayRef.h:185
Class to represent array types.
void setSyncScopeID(SyncScope::ID SSID)
Sets the synchronization scope ID of this cmpxchg instruction.
bool isVolatile() const
Return true if this is a cmpxchg from a volatile memory location.
void setFailureOrdering(AtomicOrdering Ordering)
Sets the failure ordering constraint of this cmpxchg instruction.
AtomicOrdering getFailureOrdering() const
Returns the failure ordering constraint of this cmpxchg instruction.
void setSuccessOrdering(AtomicOrdering Ordering)
Sets the success ordering constraint of this cmpxchg instruction.
LLVM_ABI AtomicCmpXchgInst * cloneImpl() const
Align getAlign() const
Return the alignment of the memory that is being allocated by the instruction.
friend class Instruction
Iterator for Instructions in a `BasicBlock.
bool isWeak() const
Return true if this cmpxchg may spuriously fail.
void setAlignment(Align Align)
AtomicOrdering getSuccessOrdering() const
Returns the success ordering constraint of this cmpxchg instruction.
SyncScope::ID getSyncScopeID() const
Returns the synchronization scope ID of this cmpxchg instruction.
LLVM_ABI AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal, Align Alignment, AtomicOrdering SuccessOrdering, AtomicOrdering FailureOrdering, SyncScope::ID SSID, InsertPosition InsertBefore=nullptr)
bool isElementwise() const
Return true if this RMW has elementwise vector semantics.
Align getAlign() const
Return the alignment of the memory that is being allocated by the instruction.
LLVM_ABI AtomicRMWInst * cloneImpl() const
bool isVolatile() const
Return true if this is a RMW on a volatile memory location.
LLVM_ABI AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val, Align Alignment, AtomicOrdering Ordering, SyncScope::ID SSID, bool Elementwise=false, InsertPosition InsertBefore=nullptr)
BinOp
This enumeration lists the possible modifications atomicrmw can make.
@ Add
*p = old + v
@ FAdd
*p = old + v
@ USubCond
Subtract only if no unsigned overflow.
@ FMinimum
*p = minimum(old, v) minimum matches the behavior of llvm.minimum.
@ Min
*p = old <signed v ? old : v
@ Sub
*p = old - v
@ And
*p = old & v
@ Xor
*p = old ^ v
@ USubSat
*p = usub.sat(old, v) usub.sat matches the behavior of llvm.usub.sat.
@ FMaximum
*p = maximum(old, v) maximum matches the behavior of llvm.maximum.
@ FSub
*p = old - v
@ UIncWrap
Increment one up to a maximum value.
@ Max
*p = old >signed v ? old : v
@ UMin
*p = old <unsigned v ? old : v
@ FMin
*p = minnum(old, v) minnum matches the behavior of llvm.minnum.
@ UMax
*p = old >unsigned v ? old : v
@ FMaximumNum
*p = maximumnum(old, v) maximumnum matches the behavior of llvm.maximumnum.
@ FMax
*p = maxnum(old, v) maxnum matches the behavior of llvm.maxnum.
@ UDecWrap
Decrement one until a minimum value or zero.
@ FMinimumNum
*p = minimumnum(old, v) minimumnum matches the behavior of llvm.minimumnum.
@ Nand
*p = ~(old & v)
void setSyncScopeID(SyncScope::ID SSID)
Sets the synchronization scope ID of this rmw instruction.
void setOrdering(AtomicOrdering Ordering)
Sets the ordering constraint of this rmw instruction.
void setOperation(BinOp Operation)
friend class Instruction
Iterator for Instructions in a `BasicBlock.
BinOp getOperation() const
SyncScope::ID getSyncScopeID() const
Returns the synchronization scope ID of this rmw instruction.
void setAlignment(Align Align)
void setElementwise(bool V)
Specify whether this RMW has elementwise vector semantics.
static LLVM_ABI StringRef getOperationName(BinOp Op)
AtomicOrdering getOrdering() const
Returns the ordering constraint of this rmw instruction.
LLVM_ABI CaptureInfo getCaptureInfo() const
Functions, function parameters, and return types can have attributes to indicate how they should be t...
Definition Attributes.h:106
LLVM_ABI const ConstantRange & getRange() const
Returns the value of the range attribute.
AttrKind
This enumeration lists the attributes that can be associated with parameters, function results,...
Definition Attributes.h:125
static LLVM_ABI Attribute getWithMemoryEffects(LLVMContext &Context, MemoryEffects ME)
bool isValid() const
Return true if the attribute is any kind of attribute.
Definition Attributes.h:262
LLVM Basic Block Representation.
Definition BasicBlock.h:62
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this basic block belongs to.
static LLVM_ABI BinaryOperator * CreateNeg(Value *Op, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Helper functions to construct and inspect unary operations (NEG and NOT) via binary operators SUB and...
BinaryOps getOpcode() const
Definition InstrTypes.h:409
LLVM_ABI bool swapOperands()
Exchange the two operands to this instruction.
static LLVM_ABI BinaryOperator * CreateNot(Value *Op, const Twine &Name="", InsertPosition InsertBefore=nullptr)
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition InstrTypes.h:216
static LLVM_ABI BinaryOperator * Create(BinaryOps Op, Value *S1, Value *S2, const Twine &Name=Twine(), InsertPosition InsertBefore=nullptr)
Construct a binary instruction, given the opcode and the two operands.
LLVM_ABI BinaryOperator(BinaryOps iType, Value *S1, Value *S2, Type *Ty, const Twine &Name, InsertPosition InsertBefore)
static LLVM_ABI BinaryOperator * CreateNSWNeg(Value *Op, const Twine &Name="", InsertPosition InsertBefore=nullptr)
LLVM_ABI BinaryOperator * cloneImpl() const
This class represents a no-op cast from one type to another.
LLVM_ABI BitCastInst * cloneImpl() const
Clone an identical BitCastInst.
LLVM_ABI BitCastInst(Value *S, Type *Ty, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructor with insert-before-instruction semantics.
LLVM_ABI BitExtractInst * cloneImpl() const
Clone an identical BitExtractInst.
static LLVM_ABI const char * areInvalidOperands(const Type *Ty, Value *Val, Value *Offset)
Return a string if the specified operands are invalid for a bitextract operation, otherwise return nu...
static BitExtractInst * Create(Type *Ty, Value *Src, Value *Offset, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static LLVM_ABI const char * areInvalidOperands(Value *Base, Value *Val, Value *Offset)
Return a string if the specified operands are invalid for a bitinsert operation, otherwise return nul...
static BitInsertInst * Create(Value *Base, Value *Val, Value *Offset, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
LLVM_ABI BitInsertInst * cloneImpl() const
Clone an identical BitInsertInst.
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
LLVM_ABI FPClassTest getParamNoFPClass(unsigned i) const
Extract a test mask for disallowed floating-point value classes for the parameter.
bool isInlineAsm() const
Check if this call is an inline asm statement.
LLVM_ABI BundleOpInfo & getBundleOpInfoForOperand(unsigned OpIdx)
Return the BundleOpInfo for the operand at index OpIdx.
void setCallingConv(CallingConv::ID CC)
LLVM_ABI FPClassTest getRetNoFPClass() const
Extract a test mask for disallowed floating-point value classes for the return value.
bundle_op_iterator bundle_op_info_begin()
Return the start of the list of BundleOpInfo instances associated with this OperandBundleUser.
LLVM_ABI bool paramHasNonNullAttr(unsigned ArgNo, bool AllowUndefOrPoison) const
Return true if this argument has the nonnull attribute on either the CallBase instruction or the call...
LLVM_ABI MemoryEffects getMemoryEffects() const
void addFnAttr(Attribute::AttrKind Kind)
Adds the attribute to the function.
LLVM_ABI bool doesNotAccessMemory() const
Determine if the call does not access memory.
LLVM_ABI void getOperandBundlesAsDefs(SmallVectorImpl< OperandBundleDef > &Defs) const
Return the list of operand bundles attached to this instruction as a vector of OperandBundleDefs.
LLVM_ABI void setOnlyAccessesArgMemory()
OperandBundleUse getOperandBundleAt(unsigned Index) const
Return the operand bundle at a specific index.
OperandBundleUse operandBundleFromBundleOpInfo(const BundleOpInfo &BOI) const
Simple helper function to map a BundleOpInfo to an OperandBundleUse.
LLVM_ABI void setOnlyAccessesInaccessibleMemOrArgMem()
std::optional< OperandBundleUse > getOperandBundle(StringRef Name) const
Return an operand bundle by name, if present.
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
LLVM_ABI void setDoesNotAccessMemory()
AttributeSet getParamAttributes(unsigned ArgNo) const
Return the param attributes for this call.
bool hasRetAttr(Attribute::AttrKind Kind) const
Determine whether the return value has the given attribute.
LLVM_ABI bool onlyAccessesInaccessibleMemory() const
Determine if the function may only access memory that is inaccessible from the IR.
unsigned getNumOperandBundles() const
Return the number of operand bundles associated with this User.
CallingConv::ID getCallingConv() const
bundle_op_iterator bundle_op_info_end()
Return the end of the list of BundleOpInfo instances associated with this OperandBundleUser.
LLVM_ABI unsigned getNumSubclassExtraOperandsDynamic() const
Get the number of extra operands for instructions that don't have a fixed number of extra operands.
BundleOpInfo * bundle_op_iterator
LLVM_ABI bool paramHasAttr(unsigned ArgNo, Attribute::AttrKind Kind) const
Determine whether the argument or parameter has the given attribute.
User::op_iterator arg_begin()
Return the iterator pointing to the beginning of the argument list.
LLVM_ABI bool isMustTailCall() const
Tests if this call site must be tail call optimized.
LLVM_ABI bool isIndirectCall() const
Return true if the callsite is an indirect call.
LLVM_ABI bool onlyReadsMemory() const
Determine if the call does not access or only reads memory.
bool isByValArgument(unsigned ArgNo) const
Determine whether this argument is passed by value.
iterator_range< bundle_op_iterator > bundle_op_infos()
Return the range [bundle_op_info_begin, bundle_op_info_end).
LLVM_ABI void setOnlyReadsMemory()
static LLVM_ABI CallBase * addOperandBundle(CallBase *CB, uint32_t ID, OperandBundleDef OB, InsertPosition InsertPt=nullptr)
Create a clone of CB with operand bundle OB added.
LLVM_ABI bool onlyAccessesInaccessibleMemOrArgMem() const
Determine if the function may only access memory that is either inaccessible from the IR or pointed t...
static LLVM_ABI CallBase * removeOperandBundleAt(CallBase *CB, size_t Offset, InsertPosition InsertPtr=nullptr)
LLVM_ABI CaptureInfo getCaptureInfo(unsigned OpNo) const
Return which pointer components this operand may capture.
LLVM_ABI bool hasArgumentWithAdditionalReturnCaptureComponents() const
Returns whether the call has an argument that has an attribute like captures(ret: address,...
CallBase(AttributeList const &A, FunctionType *FT, ArgsTy &&... Args)
Value * getCalledOperand() const
LLVM_ABI void setOnlyWritesMemory()
LLVM_ABI op_iterator populateBundleOperandInfos(ArrayRef< OperandBundleDef > Bundles, const unsigned BeginIndex)
Populate the BundleOpInfo instances and the Use& vector from Bundles.
AttributeList Attrs
parameter attributes for callable
bool hasOperandBundlesOtherThan(ArrayRef< uint32_t > IDs) const
Return true if this operand bundle user contains operand bundles with tags other than those specified...
LLVM_ABI std::optional< ConstantRange > getRange() const
If this return value has a range attribute, return the value range of the argument.
LLVM_ABI bool isReturnNonNull() const
Return true if the return value is known to be not null.
Value * getArgOperand(unsigned i) const
FunctionType * FTy
uint64_t getRetDereferenceableBytes() const
Extract the number of dereferenceable bytes for a call or parameter (0=unknown).
User::op_iterator arg_end()
Return the iterator pointing to the end of the argument list.
FunctionType * getFunctionType() const
LLVM_ABI Intrinsic::ID getIntrinsicID() const
Returns the intrinsic ID of the intrinsic called or Intrinsic::not_intrinsic if the called function i...
static unsigned CountBundleInputs(ArrayRef< OperandBundleDef > Bundles)
Return the total number of values used in Bundles.
LLVM_ABI Value * getArgOperandWithAttribute(Attribute::AttrKind Kind) const
If one of the arguments has the specified attribute, returns its operand value.
LLVM_ABI void setOnlyAccessesInaccessibleMemory()
static LLVM_ABI CallBase * Create(CallBase *CB, ArrayRef< OperandBundleDef > Bundles, InsertPosition InsertPt=nullptr)
Create a clone of CB with a different set of operand bundles and insert it before InsertPt.
LLVM_ABI bool onlyWritesMemory() const
Determine if the call does not access or only writes memory.
LLVM_ABI bool hasClobberingOperandBundles() const
Return true if this operand bundle user has operand bundles that may write to the heap.
void setCalledOperand(Value *V)
static LLVM_ABI CallBase * removeOperandBundle(CallBase *CB, uint32_t ID, InsertPosition InsertPt=nullptr)
Create a clone of CB with operand bundle ID removed.
LLVM_ABI bool hasReadingOperandBundles() const
Return true if this operand bundle user has operand bundles that may read from the heap.
LLVM_ABI bool onlyAccessesArgMemory() const
Determine if the call can access memmory only using pointers based on its arguments.
unsigned arg_size() const
AttributeList getAttributes() const
Return the attributes for this call.
LLVM_ABI void setMemoryEffects(MemoryEffects ME)
bool hasOperandBundles() const
Return true if this User has any operand bundles.
LLVM_ABI bool isTailCall() const
Tests if this call site is marked as a tail call.
LLVM_ABI Function * getCaller()
Helper to get the caller (the parent function).
CallBr instruction, tracking function calls that may not return control but instead transfer it to a ...
SmallVector< BasicBlock *, 16 > getIndirectDests() const
void setDefaultDest(BasicBlock *B)
void setIndirectDest(unsigned i, BasicBlock *B)
BasicBlock * getDefaultDest() const
static CallBrInst * Create(FunctionType *Ty, Value *Func, BasicBlock *DefaultDest, ArrayRef< BasicBlock * > IndirectDests, ArrayRef< Value * > Args, const Twine &NameStr, InsertPosition InsertBefore=nullptr)
LLVM_ABI CallBrInst * cloneImpl() const
This class represents a function call, abstracting a target machine's calling convention.
LLVM_ABI void updateProfWeight(uint64_t S, uint64_t T)
Updates profile metadata by scaling it by S / T.
TailCallKind getTailCallKind() const
LLVM_ABI CallInst * cloneImpl() const
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Represents which components of the pointer may be captured in which location.
Definition ModRef.h:414
CaptureComponents getOtherComponents() const
Get components potentially captured through locations other than the return value.
Definition ModRef.h:446
static CaptureInfo none()
Create CaptureInfo that does not capture any components of the pointer.
Definition ModRef.h:427
static CaptureInfo all()
Create CaptureInfo that may capture all components of the pointer.
Definition ModRef.h:430
CaptureComponents getRetComponents() const
Get components potentially captured by the return value.
Definition ModRef.h:442
static LLVM_ABI Instruction::CastOps getCastOpcode(const Value *Val, bool SrcIsSigned, Type *Ty, bool DstIsSigned)
Returns the opcode necessary to cast Val into Ty using usual casting rules.
static LLVM_ABI CastInst * CreatePointerBitCastOrAddrSpaceCast(Value *S, Type *Ty, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Create a BitCast or an AddrSpaceCast cast instruction.
Instruction::CastOps getOpcode() const
Return the opcode of this CastInst.
Definition InstrTypes.h:674
static LLVM_ABI unsigned isEliminableCastPair(Instruction::CastOps firstOpcode, Instruction::CastOps secondOpcode, Type *SrcTy, Type *MidTy, Type *DstTy, const DataLayout *DL)
Determine how a pair of casts can be eliminated, if they can be at all.
static LLVM_ABI CastInst * CreateIntegerCast(Value *S, Type *Ty, bool isSigned, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Create a ZExt, BitCast, or Trunc for int -> int casts.
static LLVM_ABI CastInst * CreateFPCast(Value *S, Type *Ty, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Create an FPExt, BitCast, or FPTrunc for fp -> fp casts.
CastInst(Type *Ty, unsigned iType, Value *S, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructor with insert-before-instruction semantics for subclasses.
Definition InstrTypes.h:515
static LLVM_ABI bool isBitOrNoopPointerCastable(Type *SrcTy, Type *DestTy, const DataLayout &DL)
Check whether a bitcast, inttoptr, or ptrtoint cast between these types is valid and a no-op.
static LLVM_ABI bool isBitCastable(Type *SrcTy, Type *DestTy)
Check whether a bitcast between these types is valid.
static LLVM_ABI CastInst * CreateTruncOrBitCast(Value *S, Type *Ty, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Create a Trunc or BitCast cast instruction.
static LLVM_ABI CastInst * CreatePointerCast(Value *S, Type *Ty, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Create a BitCast, AddrSpaceCast or a PtrToInt cast instruction.
static LLVM_ABI CastInst * CreateBitOrPointerCast(Value *S, Type *Ty, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Create a BitCast, a PtrToInt, or an IntToPTr cast instruction.
static LLVM_ABI bool isNoopCast(Instruction::CastOps Opcode, Type *SrcTy, Type *DstTy, const DataLayout &DL)
A no-op cast is one that can be effected without changing any bits.
static LLVM_ABI CastInst * CreateZExtOrBitCast(Value *S, Type *Ty, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Create a ZExt or BitCast cast instruction.
static LLVM_ABI CastInst * Create(Instruction::CastOps, Value *S, Type *Ty, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Provides a way to construct any of the CastInst subclasses using an opcode instead of the subclass's ...
LLVM_ABI bool isIntegerCast() const
There are several places where we need to know if a cast instruction only deals with integer source a...
static LLVM_ABI CastInst * CreateSExtOrBitCast(Value *S, Type *Ty, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Create a SExt or BitCast cast instruction.
static LLVM_ABI bool castIsValid(Instruction::CastOps op, Type *SrcTy, Type *DstTy)
This method can be used to determine if a cast from SrcTy to DstTy using Opcode op is valid or not.
LLVM_ABI CatchReturnInst * cloneImpl() const
void setUnwindDest(BasicBlock *UnwindDest)
LLVM_ABI void addHandler(BasicBlock *Dest)
Add an entry to the switch instruction... Note: This action invalidates handler_end().
LLVM_ABI CatchSwitchInst * cloneImpl() const
mapped_iterator< op_iterator, DerefFnTy > handler_iterator
Value * getParentPad() const
void setParentPad(Value *ParentPad)
BasicBlock * getUnwindDest() const
LLVM_ABI void removeHandler(handler_iterator HI)
LLVM_ABI CleanupReturnInst * cloneImpl() const
This class is the base class for the comparison instructions.
Definition InstrTypes.h:728
Predicate getStrictPredicate() const
For example, SGE -> SGT, SLE -> SLT, ULE -> ULT, UGE -> UGT.
Definition InstrTypes.h:921
bool isEquality() const
Determine if this is an equals/not equals predicate.
Definition InstrTypes.h:978
void setPredicate(Predicate P)
Set the predicate for this instruction to the specified value.
Definition InstrTypes.h:831
bool isFalseWhenEqual() const
This is just a convenience.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:740
@ FCMP_OEQ
0 0 0 1 True if ordered and equal
Definition InstrTypes.h:743
@ FCMP_TRUE
1 1 1 1 Always true (always folded)
Definition InstrTypes.h:757
@ ICMP_SLT
signed less than
Definition InstrTypes.h:769
@ ICMP_SLE
signed less or equal
Definition InstrTypes.h:770
@ FCMP_OLT
0 1 0 0 True if ordered and less than
Definition InstrTypes.h:746
@ FCMP_ULE
1 1 0 1 True if unordered, less than, or equal
Definition InstrTypes.h:755
@ FCMP_OGT
0 0 1 0 True if ordered and greater than
Definition InstrTypes.h:744
@ FCMP_OGE
0 0 1 1 True if ordered and greater than or equal
Definition InstrTypes.h:745
@ ICMP_UGE
unsigned greater or equal
Definition InstrTypes.h:764
@ ICMP_UGT
unsigned greater than
Definition InstrTypes.h:763
@ ICMP_SGT
signed greater than
Definition InstrTypes.h:767
@ FCMP_ULT
1 1 0 0 True if unordered or less than
Definition InstrTypes.h:754
@ FCMP_ONE
0 1 1 0 True if ordered and operands are unequal
Definition InstrTypes.h:748
@ FCMP_UEQ
1 0 0 1 True if unordered or equal
Definition InstrTypes.h:751
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:765
@ FCMP_UGT
1 0 1 0 True if unordered or greater than
Definition InstrTypes.h:752
@ FCMP_OLE
0 1 0 1 True if ordered and less than or equal
Definition InstrTypes.h:747
@ FCMP_ORD
0 1 1 1 True if ordered (no nans)
Definition InstrTypes.h:749
@ ICMP_NE
not equal
Definition InstrTypes.h:762
@ ICMP_SGE
signed greater or equal
Definition InstrTypes.h:768
@ FCMP_UNE
1 1 1 0 True if unordered or not equal
Definition InstrTypes.h:756
@ ICMP_ULE
unsigned less or equal
Definition InstrTypes.h:766
@ FCMP_UGE
1 0 1 1 True if unordered, greater than, or equal
Definition InstrTypes.h:753
@ FCMP_FALSE
0 0 0 0 Always false (always folded)
Definition InstrTypes.h:742
@ FCMP_UNO
1 0 0 0 True if unordered: isnan(X) | isnan(Y)
Definition InstrTypes.h:750
LLVM_ABI bool isEquivalence(bool Invert=false) const
Determine if one operand of this compare can always be replaced by the other operand,...
bool isSigned() const
Definition InstrTypes.h:993
static LLVM_ABI bool isEquality(Predicate pred)
Determine if this is an equals/not equals predicate.
Predicate getSwappedPredicate() const
For example, EQ->EQ, SLE->SGE, ULT->UGT, OEQ->OEQ, ULE->UGE, OLT->OGT, etc.
Definition InstrTypes.h:890
bool isTrueWhenEqual() const
This is just a convenience.
static LLVM_ABI CmpInst * Create(OtherOps Op, Predicate Pred, Value *S1, Value *S2, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Construct a compare instruction, given the opcode, the predicate and the two operands.
static bool isFPPredicate(Predicate P)
Definition InstrTypes.h:833
Predicate getNonStrictPredicate() const
For example, SGT -> SGE, SLT -> SLE, ULT -> ULE, UGT -> UGE.
Definition InstrTypes.h:934
static LLVM_ABI CmpInst * CreateWithCopiedFlags(OtherOps Op, Predicate Pred, Value *S1, Value *S2, const Instruction *FlagsSource, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Construct a compare instruction, given the opcode, the predicate, the two operands and the instructio...
LLVM_ABI CmpInst(Type *ty, Instruction::OtherOps op, Predicate pred, Value *LHS, Value *RHS, const Twine &Name="", InsertPosition InsertBefore=nullptr)
bool isNonStrictPredicate() const
Definition InstrTypes.h:915
LLVM_ABI void swapOperands()
This is just a convenience that dispatches to the subclasses.
static bool isRelational(Predicate P)
Return true if the predicate is relational (not EQ or NE).
Definition InstrTypes.h:986
Predicate getInversePredicate() const
For example, EQ -> NE, UGT -> ULE, SLT -> SGE, OEQ -> UNE, UGT -> OLE, OLT -> UGE,...
Definition InstrTypes.h:852
static LLVM_ABI StringRef getPredicateName(Predicate P)
Predicate getPredicate() const
Return the predicate for this instruction.
Definition InstrTypes.h:828
bool isStrictPredicate() const
Definition InstrTypes.h:906
static LLVM_ABI bool isUnordered(Predicate predicate)
Determine if the predicate is an unordered operation.
Predicate getFlippedStrictnessPredicate() const
For predicate of kind "is X or equal to 0" returns the predicate "is X".
Definition InstrTypes.h:956
static bool isIntPredicate(Predicate P)
Definition InstrTypes.h:839
static LLVM_ABI bool isOrdered(Predicate predicate)
Determine if the predicate is an ordered operation.
bool isUnsigned() const
Definition InstrTypes.h:999
LLVM_ABI bool isCommutative() const
This is just a convenience that dispatches to the subclasses.
An abstraction over a floating-point predicate, and a pack of an integer predicate with samesign info...
static LLVM_ABI std::optional< CmpPredicate > getMatching(CmpPredicate A, CmpPredicate B)
Compares two CmpPredicates taking samesign into account and returns the canonicalized CmpPredicate if...
static LLVM_ABI CmpPredicate getInverse(CmpPredicate P)
Get the inverse predicate of a CmpPredicate.
CmpPredicate()
Default constructor.
static LLVM_ABI CmpPredicate get(const CmpInst *Cmp)
Do a ICmpInst::getCmpPredicate() or CmpInst::getPredicate(), as appropriate.
LLVM_ABI CmpInst::Predicate getPreferredSignedPredicate() const
Attempts to return a signed CmpInst::Predicate from the CmpPredicate.
bool hasSameSign() const
Query samesign information, for optimizations.
static LLVM_ABI CmpPredicate getSwapped(CmpPredicate P)
Get the swapped predicate of a CmpPredicate.
Conditional Branch instruction.
LLVM_ABI void swapSuccessors()
Swap the successors of this branch instruction.
LLVM_ABI CondBrInst * cloneImpl() const
Value * getCondition() const
ConstantFP - Floating Point Values [float, double].
Definition Constants.h:420
const APFloat & getValueAPF() const
Definition Constants.h:463
This is the shared class of boolean and integer constants.
Definition Constants.h:87
LLVM_ABI ConstantRange intersectWith(const ConstantRange &CR, PreferredRangeType Type=Smallest) const
Return the range that results from the intersection of this range with another range.
static LLVM_ABI Constant * get(ArrayRef< Constant * > V)
This is an important base class in LLVM.
Definition Constant.h:44
static LLVM_ABI Constant * getAllOnesValue(Type *Ty)
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
static constexpr ElementCount getFixed(ScalarTy MinVal)
Definition TypeSize.h:306
LLVM_ABI ExtractElementInst * cloneImpl() const
static ExtractElementInst * Create(Value *Vec, Value *Idx, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static LLVM_ABI bool isValidOperands(const Value *Vec, const Value *Idx)
Return true if an extractelement instruction can be formed with the specified operands.
This instruction extracts a struct member or array element value from an aggregate value.
static LLVM_ABI Type * getIndexedType(Type *Agg, ArrayRef< unsigned > Idxs)
Returns the type of the element that would be extracted with an extractvalue instruction with the spe...
LLVM_ABI ExtractValueInst * cloneImpl() const
This instruction compares its operands according to the predicate given to the constructor.
bool isEquality() const
static LLVM_ABI bool compare(const APFloat &LHS, const APFloat &RHS, FCmpInst::Predicate Pred)
Return result of LHS Pred RHS comparison.
LLVM_ABI FCmpInst * cloneImpl() const
Clone an identical FCmpInst.
FCmpInst(InsertPosition InsertBefore, Predicate pred, Value *LHS, Value *RHS, const Twine &NameStr="")
Constructor with insertion semantics.
Binary operators support fast-math flags, users should not use this class directly,...
Definition InstrTypes.h:476
This class represents an extension of floating point types.
LLVM_ABI FPExtInst * cloneImpl() const
Clone an identical FPExtInst.
LLVM_ABI FPExtInst(Value *S, Type *Ty, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructor with insert-before-instruction semantics.
LLVM_ABI float getFPAccuracy() const
Get the maximum error permitted by this operation in ULPs.
This class represents a cast from floating point to signed integer.
LLVM_ABI FPToSIInst(Value *S, Type *Ty, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructor with insert-before-instruction semantics.
LLVM_ABI FPToSIInst * cloneImpl() const
Clone an identical FPToSIInst.
This class represents a cast from floating point to unsigned integer.
LLVM_ABI FPToUIInst * cloneImpl() const
Clone an identical FPToUIInst.
LLVM_ABI FPToUIInst(Value *S, Type *Ty, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructor with insert-before-instruction semantics.
This class represents a truncation of floating point types.
LLVM_ABI FPTruncInst(Value *S, Type *Ty, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructor with insert-before-instruction semantics.
LLVM_ABI FPTruncInst * cloneImpl() const
Clone an identical FPTruncInst.
Unary operators support fast-math flags, users should not use this class directly,...
Definition InstrTypes.h:179
LLVM_ABI FenceInst(LLVMContext &C, AtomicOrdering Ordering, SyncScope::ID SSID=SyncScope::System, InsertPosition InsertBefore=nullptr)
SyncScope::ID getSyncScopeID() const
Returns the synchronization scope ID of this fence instruction.
void setSyncScopeID(SyncScope::ID SSID)
Sets the synchronization scope ID of this fence instruction.
LLVM_ABI FenceInst * cloneImpl() const
friend class Instruction
Iterator for Instructions in a `BasicBlock.
void setOrdering(AtomicOrdering Ordering)
Sets the ordering constraint of this fence instruction.
AtomicOrdering getOrdering() const
Returns the ordering constraint of this fence instruction.
Class to represent fixed width SIMD vectors.
LLVM_ABI FreezeInst(Value *S, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
LLVM_ABI FreezeInst * cloneImpl() const
Clone an identical FreezeInst.
void setParentPad(Value *ParentPad)
Value * getParentPad() const
Convenience accessors.
LLVM_ABI FuncletPadInst * cloneImpl() const
Class to represent function types.
unsigned getNumParams() const
Return the number of fixed parameters this function type requires.
Type * getParamType(unsigned i) const
Parameter type accessors.
bool isVarArg() const
Represents flags for the getelementptr instruction/expression.
static GEPNoWrapFlags inBounds()
GEPNoWrapFlags withoutInBounds() const
unsigned getRaw() const
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
LLVM_ABI bool isInBounds() const
Determine whether the GEP has the inbounds flag.
LLVM_ABI bool hasNoUnsignedSignedWrap() const
Determine whether the GEP has the nusw flag.
static LLVM_ABI Type * getTypeAtIndex(Type *Ty, Value *Idx)
Return the type of the element at the given index of an indexable type.
LLVM_ABI bool hasAllZeroIndices() const
Return true if all of the indices of this GEP are zeros.
LLVM_ABI bool hasNoUnsignedWrap() const
Determine whether the GEP has the nuw flag.
LLVM_ABI bool hasAllConstantIndices() const
Return true if all of the indices of this GEP are constant integers.
LLVM_ABI void setIsInBounds(bool b=true)
Set or clear the inbounds flag on this GEP instruction.
static LLVM_ABI Type * getIndexedType(Type *Ty, ArrayRef< Value * > IdxList)
Returns the result type of a getelementptr with the given source element type and indexes.
LLVM_ABI bool accumulateConstantOffset(const DataLayout &DL, APInt &Offset) const
Accumulate the constant address offset of this GEP if possible.
LLVM_ABI GetElementPtrInst * cloneImpl() const
LLVM_ABI bool collectOffset(const DataLayout &DL, unsigned BitWidth, SmallMapVector< Value *, APInt, 4 > &VariableOffsets, APInt &ConstantOffset) const
LLVM_ABI void setNoWrapFlags(GEPNoWrapFlags NW)
Set nowrap flags for GEP instruction.
LLVM_ABI GEPNoWrapFlags getNoWrapFlags() const
Get the nowrap flags for the GEP instruction.
Module * getParent()
Get the module that this global value is contained inside of...
This instruction compares its operands according to the predicate given to the constructor.
bool hasSameSign() const
An icmp instruction, which can be marked as "samesign", indicating that the two operands have the sam...
ICmpInst(InsertPosition InsertBefore, Predicate pred, Value *LHS, Value *RHS, const Twine &NameStr="")
Constructor with insertion semantics.
static LLVM_ABI bool compare(const APInt &LHS, const APInt &RHS, ICmpInst::Predicate Pred)
Return result of LHS Pred RHS comparison.
LLVM_ABI ICmpInst * cloneImpl() const
Clone an identical ICmpInst.
Predicate getFlippedSignednessPredicate() const
For example, SLT->ULT, ULT->SLT, SLE->ULE, ULE->SLE, EQ->EQ.
Predicate getSignedPredicate() const
For example, EQ->EQ, SLE->SLE, UGT->SGT, etc.
static CmpPredicate getInverseCmpPredicate(CmpPredicate Pred)
bool isEquality() const
Return true if this predicate is either EQ or NE.
static LLVM_ABI Predicate getFlippedSignednessPredicate(Predicate Pred)
For example, SLT->ULT, ULT->SLT, SLE->ULE, ULE->SLE, EQ->EQ.
static LLVM_ABI std::optional< bool > isImpliedByMatchingCmp(CmpPredicate Pred1, CmpPredicate Pred2)
Determine if Pred1 implies Pred2 is true, false, or if nothing can be inferred about the implication,...
Predicate getUnsignedPredicate() const
For example, EQ->EQ, SLE->ULE, UGT->UGT, etc.
Indirect Branch Instruction.
LLVM_ABI void addDestination(BasicBlock *Dest)
Add a destination.
LLVM_ABI void removeDestination(unsigned i)
This method removes the specified successor from the indirectbr instruction.
LLVM_ABI IndirectBrInst * cloneImpl() const
LLVM_ABI InsertElementInst * cloneImpl() const
static InsertElementInst * Create(Value *Vec, Value *NewElt, Value *Idx, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static LLVM_ABI bool isValidOperands(const Value *Vec, const Value *NewElt, const Value *Idx)
Return true if an insertelement instruction can be formed with the specified operands.
bool isValid() const
Definition Instruction.h:59
BasicBlock * getBasicBlock()
Definition Instruction.h:60
This instruction inserts a struct field of array element value into an aggregate value.
LLVM_ABI InsertValueInst * cloneImpl() const
BitfieldElement::Type getSubclassData() const
LLVM_ABI bool hasNoNaNs() const LLVM_READONLY
Determine whether the no-NaNs flag is set.
LLVM_ABI void copyIRFlags(const Value *V, bool IncludeWrapFlags=true)
Convenience method to copy supported exact, fast-math, and (optionally) wrapping flags from V to this...
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
LLVM_ABI bool isCommutative() const LLVM_READONLY
Return true if the instruction is commutative:
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
LLVM_ABI const Function * getFunction() const
Return the function this instruction belongs to.
LLVM_ABI void swapProfMetadata()
If the instruction has "branch_weights" MD_prof metadata and the MDNode has three operands (including...
LLVM_ABI bool isVolatile() const LLVM_READONLY
Return true if this instruction has a volatile memory access.
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
Bitfield::Element< uint16_t, 0, 16 > OpaqueField
Instruction(const Instruction &)=delete
friend class Value
friend class BasicBlock
Various leaf nodes.
void setSubclassData(typename BitfieldElement::Type Value)
This class represents a cast from an integer to a pointer.
LLVM_ABI IntToPtrInst(Value *S, Type *Ty, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructor with insert-before-instruction semantics.
LLVM_ABI IntToPtrInst * cloneImpl() const
Clone an identical IntToPtrInst.
Invoke instruction.
BasicBlock * getUnwindDest() const
void setNormalDest(BasicBlock *B)
LLVM_ABI InvokeInst * cloneImpl() const
LLVM_ABI LandingPadInst * getLandingPadInst() const
Get the landingpad instruction from the landing pad block (the unwind destination).
void setUnwindDest(BasicBlock *B)
LLVM_ABI void updateProfWeight(uint64_t S, uint64_t T)
Updates profile metadata by scaling it by S / T.
static InvokeInst * Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal, BasicBlock *IfException, ArrayRef< Value * > Args, const Twine &NameStr, InsertPosition InsertBefore=nullptr)
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
LLVMContextImpl *const pImpl
Definition LLVMContext.h:78
The landingpad instruction holds all of the information necessary to generate correct exception handl...
bool isCleanup() const
Return 'true' if this landingpad instruction is a cleanup.
LLVM_ABI LandingPadInst * cloneImpl() const
static LLVM_ABI LandingPadInst * Create(Type *RetTy, unsigned NumReservedClauses, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedClauses is a hint for the number of incoming clauses that this landingpad w...
LLVM_ABI void addClause(Constant *ClauseVal)
Add a catch or filter clause to the landing pad.
void setCleanup(bool V)
Indicate that this landingpad instruction is a cleanup.
void setElementwise(bool V)
Specify whether this is an elementwise atomic load or not.
void setAlignment(Align Align)
bool isVolatile() const
Return true if this is a load from a volatile memory location.
void setAtomic(AtomicOrdering Ordering, SyncScope::ID SSID=SyncScope::System)
Sets the ordering constraint and the synchronization scope ID of this load instruction.
LLVM_ABI LoadInst * cloneImpl() const
void setVolatile(bool V)
Specify whether this is a volatile load or not.
LoadStoreInstProperties getProperties() const
Returns the properties of this load instruction.
LLVM_ABI LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, InsertPosition InsertBefore)
Metadata node.
Definition Metadata.h:1081
const MDOperand & getOperand(unsigned I) const
Definition Metadata.h:1437
static MemoryEffectsBase readOnly()
Definition ModRef.h:133
bool onlyWritesMemory() const
Whether this function only (at most) writes memory.
Definition ModRef.h:252
bool doesNotAccessMemory() const
Whether this function accesses no memory.
Definition ModRef.h:246
static MemoryEffectsBase argMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
Definition ModRef.h:143
static MemoryEffectsBase inaccessibleMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
Definition ModRef.h:149
bool onlyAccessesInaccessibleMem() const
Whether this function only (at most) accesses inaccessible memory.
Definition ModRef.h:265
bool onlyAccessesArgPointees() const
Whether this function only (at most) accesses argument memory.
Definition ModRef.h:255
bool onlyReadsMemory() const
Whether this function only (at most) reads memory.
Definition ModRef.h:249
static MemoryEffectsBase writeOnly()
Definition ModRef.h:138
static MemoryEffectsBase inaccessibleOrArgMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
Definition ModRef.h:166
static MemoryEffectsBase none()
Definition ModRef.h:128
bool onlyAccessesInaccessibleOrArgMem() const
Whether this function only (at most) accesses argument and inaccessible memory.
Definition ModRef.h:305
StringRef getTag() const
void allocHungoffUses(unsigned N)
const_block_iterator block_begin() const
LLVM_ABI void removeIncomingValueIf(function_ref< bool(unsigned)> Predicate, bool DeletePHIIfEmpty=true)
Remove all incoming values for which the predicate returns true.
void setIncomingBlock(unsigned i, BasicBlock *BB)
LLVM_ABI Value * removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty=true)
Remove an incoming value.
LLVM_ABI bool hasConstantOrUndefValue() const
Whether the specified PHI node always merges together the same value, assuming undefs are equal to a ...
void setIncomingValue(unsigned i, Value *V)
const_block_iterator block_end() const
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
LLVM_ABI Value * hasConstantValue() const
If the specified PHI node always merges together the same value, return the value,...
LLVM_ABI PHINode * cloneImpl() const
unsigned getNumIncomingValues() const
Return the number of incoming edges.
Class to represent pointers.
unsigned getAddressSpace() const
Return the address space of the Pointer type.
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
This class represents a cast from a pointer to an address (non-capturing ptrtoint).
LLVM_ABI PtrToAddrInst(Value *S, Type *Ty, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructor with insert-before-instruction semantics.
LLVM_ABI PtrToAddrInst * cloneImpl() const
Clone an identical PtrToAddrInst.
This class represents a cast from a pointer to an integer.
LLVM_ABI PtrToIntInst(Value *S, Type *Ty, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructor with insert-before-instruction semantics.
LLVM_ABI PtrToIntInst * cloneImpl() const
Clone an identical PtrToIntInst.
Resume the propagation of an exception.
LLVM_ABI ResumeInst * cloneImpl() const
Return a value (possibly void), from a function.
LLVM_ABI ReturnInst * cloneImpl() const
This class represents a sign extension of integer types.
LLVM_ABI SExtInst * cloneImpl() const
Clone an identical SExtInst.
LLVM_ABI SExtInst(Value *S, Type *Ty, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructor with insert-before-instruction semantics.
This class represents a cast from signed integer to floating point.
LLVM_ABI SIToFPInst * cloneImpl() const
Clone an identical SIToFPInst.
LLVM_ABI SIToFPInst(Value *S, Type *Ty, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructor with insert-before-instruction semantics.
Class to represent scalable SIMD vectors.
LLVM_ABI SelectInst * cloneImpl() const
static LLVM_ABI const char * areInvalidOperands(Value *Cond, Value *True, Value *False)
Return a string if the specified operands are invalid for a select operation, otherwise return null.
static SelectInst * Create(Value *C, Value *S1, Value *S2, const Twine &NameStr="", InsertPosition InsertBefore=nullptr, const Instruction *MDFrom=nullptr)
static LLVM_ABI 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 LLVM_ABI 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...
int getMaskValue(unsigned Elt) const
Return the shuffle mask value of this instruction for the given element index.
LLVM_ABI ShuffleVectorInst(Value *V1, Value *Mask, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static LLVM_ABI 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 LLVM_ABI bool isSelectMask(ArrayRef< int > Mask, int NumSrcElts)
Return true if this shuffle mask chooses elements from its source vectors without lane crossings.
static LLVM_ABI 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,...
VectorType * getType() const
Overload to return most specific vector type.
LLVM_ABI bool isIdentityWithExtract() const
Return true if this shuffle extracts the first N elements of exactly one source vector.
static LLVM_ABI bool isOneUseSingleSourceMask(ArrayRef< int > Mask, int VF)
Return true if this shuffle mask represents "clustered" mask of size VF, i.e.
LLVM_ABI bool isIdentityWithPadding() const
Return true if this shuffle lengthens exactly one source vector with undefs in the high elements.
static LLVM_ABI bool isSingleSourceMask(ArrayRef< int > Mask, int NumSrcElts)
Return true if this shuffle mask chooses elements from exactly one source vector.
LLVM_ABI bool isConcat() const
Return true if this shuffle concatenates its 2 source vectors.
static LLVM_ABI 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,...
LLVM_ABI ShuffleVectorInst * cloneImpl() const
static LLVM_ABI bool isIdentityMask(ArrayRef< int > Mask, int NumSrcElts)
Return true if this shuffle mask chooses elements from exactly one source vector without lane crossin...
static LLVM_ABI bool isExtractSubvectorMask(ArrayRef< int > Mask, int NumSrcElts, int &Index)
Return true if this shuffle mask is an extract subvector mask.
LLVM_ABI void setShuffleMask(ArrayRef< int > Mask)
friend class Instruction
Iterator for Instructions in a `BasicBlock.
LLVM_ABI bool isInterleave(unsigned Factor)
Return if this shuffle interleaves its two input vectors together.
static LLVM_ABI bool isReverseMask(ArrayRef< int > Mask, int NumSrcElts)
Return true if this shuffle mask swaps the order of elements from exactly one source vector.
static LLVM_ABI bool isTransposeMask(ArrayRef< int > Mask, int NumSrcElts)
Return true if this shuffle mask is a transpose mask.
LLVM_ABI void commute()
Swap the operands and adjust the mask to preserve the semantics of the instruction.
static LLVM_ABI bool isInsertSubvectorMask(ArrayRef< int > Mask, int NumSrcElts, int &NumSubElts, int &Index)
Return true if this shuffle mask is an insert subvector mask.
static LLVM_ABI Constant * convertShuffleMaskForBitcode(ArrayRef< int > Mask, Type *ResultTy)
static LLVM_ABI 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 LLVM_ABI 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 is a 'bitvector' (really, a variable-sized bit array), optimized for the case when the array is ...
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void reserve(size_type N)
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
void resize(size_type N)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
void setVolatile(bool V)
Specify whether this is a volatile store or not.
void setAlignment(Align Align)
friend class Instruction
Iterator for Instructions in a `BasicBlock.
LoadStoreInstProperties getProperties() const
Returns the properties of this store instruction.
LLVM_ABI StoreInst * cloneImpl() const
void setElementwise(bool V)
Specify whether this is an elementwise atomic store or not.
LLVM_ABI StoreInst(Value *Val, Value *Ptr, InsertPosition InsertBefore)
bool isVolatile() const
Return true if this is a store to a volatile memory location.
void setAtomic(AtomicOrdering Ordering, SyncScope::ID SSID=SyncScope::System)
Sets the ordering constraint and the synchronization scope ID of this store instruction.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
Class to represent struct types.
LLVM_ABI void setSuccessorWeight(unsigned idx, CaseWeightOpt W)
LLVM_ABI Instruction::InstListType::iterator eraseFromParent()
Delegate the call to the underlying SwitchInst::eraseFromParent() and mark this object to not touch t...
LLVM_ABI void addCase(ConstantInt *OnVal, BasicBlock *Dest, CaseWeightOpt W)
Delegate the call to the underlying SwitchInst::addCase() and set the specified branch weight for the...
LLVM_ABI CaseWeightOpt getSuccessorWeight(unsigned idx)
LLVM_ABI void replaceDefaultDest(SwitchInst::CaseIt I)
Replace the default destination by given case.
std::optional< uint32_t > CaseWeightOpt
LLVM_ABI SwitchInst::CaseIt removeCase(SwitchInst::CaseIt I)
Delegate the call to the underlying SwitchInst::removeCase() and remove correspondent branch weight.
void setValue(ConstantInt *V) const
Sets the new value for current case.
void setSuccessor(BasicBlock *S) const
Sets the new successor for current case.
Multiway switch.
void allocHungoffUses(unsigned N)
LLVM_ABI SwitchInst * cloneImpl() const
LLVM_ABI void addCase(ConstantInt *OnVal, BasicBlock *Dest)
Add an entry to the switch instruction.
CaseIteratorImpl< CaseHandle > CaseIt
ConstantInt *const * case_values() const
unsigned getNumCases() const
Return the number of 'cases' in this switch instruction, excluding the default case.
LLVM_ABI CaseIt removeCase(CaseIt I)
This method removes the specified case and its successor from the switch instruction.
Target - Wrapper for Target specific information.
This class represents a truncation of integer types.
LLVM_ABI TruncInst * cloneImpl() const
Clone an identical TruncInst.
LLVM_ABI TruncInst(Value *S, Type *Ty, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructor with insert-before-instruction semantics.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
static constexpr TypeSize getFixed(ScalarTy ExactSize)
Definition TypeSize.h:348
static constexpr TypeSize get(ScalarTy Quantity, bool Scalable)
Definition TypeSize.h:345
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
bool isByteTy() const
True if this is an instance of ByteType.
Definition Type.h:237
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:283
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
Definition Type.cpp:299
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
Definition Type.h:258
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:277
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
bool isSingleValueType() const
Return true if the type is a valid type for a register in codegen.
Definition Type.h:306
LLVM_ABI bool isFirstClassType() const
Return true if the type is "first class", meaning it is a valid type for a Value.
Definition Type.cpp:241
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:363
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition Type.cpp:187
bool isByteOrByteVectorTy() const
Return true if this is a byte type or a vector of byte types.
Definition Type.h:243
bool isTargetExtTy() const
Return true if this is a target extension type.
Definition Type.h:205
bool isAggregateType() const
Return true if the type is an aggregate type.
Definition Type.h:314
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Definition Type.h:130
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.cpp:222
static LLVM_ABI IntegerType * getInt1Ty(LLVMContext &C)
Definition Type.cpp:296
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
Definition Type.h:186
bool isPtrOrPtrVectorTy() const
Return true if this is a pointer type or a vector of pointer types.
Definition Type.h:280
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:252
bool isTokenTy() const
Return true if this is 'token'.
Definition Type.h:231
bool isFPOrFPVectorTy() const
Return true if this is a FP type or a vector of FP.
Definition Type.h:222
This class represents a cast unsigned integer to floating point.
LLVM_ABI UIToFPInst(Value *S, Type *Ty, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructor with insert-before-instruction semantics.
LLVM_ABI UIToFPInst * cloneImpl() const
Clone an identical UIToFPInst.
UnaryInstruction(Type *Ty, unsigned iType, Value *V, InsertPosition InsertBefore=nullptr)
Definition InstrTypes.h:71
static LLVM_ABI UnaryOperator * Create(UnaryOps Op, Value *S, const Twine &Name=Twine(), InsertPosition InsertBefore=nullptr)
Construct a unary instruction, given the opcode and an operand.
LLVM_ABI UnaryOperator(UnaryOps iType, Value *S, Type *Ty, const Twine &Name, InsertPosition InsertBefore)
LLVM_ABI UnaryOperator * cloneImpl() const
UnaryOps getOpcode() const
Definition InstrTypes.h:163
Unconditional Branch instruction.
LLVM_ABI UncondBrInst * cloneImpl() const
LLVM_ABI UnreachableInst(LLVMContext &C, InsertPosition InsertBefore=nullptr)
LLVM_ABI bool shouldLowerToTrap(bool TrapUnreachable, bool NoTrapAfterNoreturn) const
friend class Instruction
Iterator for Instructions in a `BasicBlock.
LLVM_ABI UnreachableInst * cloneImpl() const
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
LLVM_ABI void set(Value *Val)
Definition Value.h:876
Use * op_iterator
Definition User.h:254
const Use * getOperandList() const
Definition User.h:200
op_iterator op_begin()
Definition User.h:259
LLVM_ABI void allocHungoffUses(unsigned N, bool WithExtraValues=false)
Allocate the array of Uses, followed by a pointer (with bottom bit set) to the User.
Definition User.cpp:48
const Use & getOperandUse(unsigned i) const
Definition User.h:220
void setNumHungOffUseOperands(unsigned NumOps)
Subclasses with hung off uses need to manage the operand count themselves.
Definition User.h:240
Use & Op()
Definition User.h:171
LLVM_ABI void growHungoffUses(unsigned N, bool WithExtraValues=false)
Grow the number of hung off uses.
Definition User.cpp:65
Value * getOperand(unsigned i) const
Definition User.h:207
unsigned getNumOperands() const
Definition User.h:229
op_iterator op_end()
Definition User.h:261
VAArgInst(Value *List, Type *Ty, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
LLVM_ABI VAArgInst * cloneImpl() const
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
unsigned char SubclassOptionalData
Hold arbitary subclass data.
Definition Value.h:85
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
Definition Value.cpp:390
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:549
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:260
unsigned NumUserOperands
Definition Value.h:109
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:315
Base class of all SIMD vector types.
ElementCount getElementCount() const
Return an ElementCount instance to represent the (possibly scalable) number of elements in the vector...
static LLVM_ABI VectorType * get(Type *ElementType, ElementCount EC)
This static method is the primary way to construct an VectorType.
This class represents zero extension of integer types.
LLVM_ABI ZExtInst(Value *S, Type *Ty, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructor with insert-before-instruction semantics.
LLVM_ABI ZExtInst * cloneImpl() const
Clone an identical ZExtInst.
constexpr ScalarTy getFixedValue() const
Definition TypeSize.h:201
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
Definition TypeSize.h:166
An efficient, type-erasing, non-owning reference to a callable.
typename base_list_type::iterator iterator
Definition ilist.h:121
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
CallInst * Call
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Attrs[]
Key for Kernel::Metadata::mAttrs.
bool match(Val *V, const Pattern &P)
cstfp_pred_ty< is_non_zero_not_denormal_fp > m_NonZeroNotDenormalFP()
Match a floating-point non-zero that is not a denormal.
initializer< Ty > init(const Ty &Val)
@ Switch
The "resume-switch" lowering, where there are separate resume and destroy functions that are shared b...
Definition CoroShape.h:32
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > extract(Y &&MD)
Extract a Value from Metadata.
Definition Metadata.h:679
NodeAddr< UseNode * > Use
Definition RDFGraph.h:385
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:577
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition STLExtras.h:1685
unsigned getPointerAddressSpace(const Type *T)
Definition SPIRVUtils.h:393
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
constexpr auto seq_inclusive(T Begin, T End)
Iterate over an integral type from Begin to End inclusive.
Definition Sequence.h:361
@ Load
The value being inserted comes from a load (InsertElement only).
@ Store
The extracted value is stored (ExtractElement only).
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
LLVM_ABI MDNode * getBranchWeightMDNode(const Instruction &I)
Get the branch weights metadata node.
MemoryEffectsBase< IRMemLocation > MemoryEffects
Summary of how a function affects memory in the program.
Definition ModRef.h:356
constexpr auto equal_to(T &&Arg)
Functor variant of std::equal_to that can be used as a UnaryPredicate in functional algorithms like a...
Definition STLExtras.h:2189
std::enable_if_t< std::is_unsigned_v< T >, std::optional< T > > checkedMulUnsigned(T LHS, T RHS)
Multiply two unsigned integers LHS and RHS.
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
LLVM_ABI MDNode * getValidBranchWeightMDNode(const Instruction &I)
Get the valid branch weights metadata node.
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition MathExtras.h:280
decltype(auto) get(const PointerIntPair< PointerTy, IntBits, IntType, PtrTraits, Info > &Pair)
FPClassTest
Floating-point class tests, supported by 'is_fpclass' intrinsic.
LLVM_ABI bool NullPointerIsDefined(const Function *F, unsigned AS=0)
Check whether null pointer dereferencing is considered undefined behavior for a given function or an ...
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
bool isPointerTy(const Type *T)
Definition SPIRVUtils.h:381
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
constexpr int PoisonMaskElem
LLVM_ABI unsigned getNumBranchWeights(const MDNode &ProfileData)
AtomicOrdering
Atomic ordering for LLVM's memory model.
LLVM_ABI void extractFromBranchWeightMD32(const MDNode *ProfileData, SmallVectorImpl< uint32_t > &Weights)
Faster version of extractBranchWeights() that skips checks and must only be called with "branch_weigh...
OperandBundleDefT< Value * > OperandBundleDef
Definition AutoUpgrade.h:34
@ Mul
Product of integers.
@ FSub
Subtraction of floats.
@ Xor
Bitwise or logical XOR of integers.
@ FMul
Product of floats.
@ Sub
Subtraction of integers.
@ Add
Sum of integers.
@ FAdd
Sum of floats.
DWARFExpression::Operation Op
raw_ostream & operator<<(raw_ostream &OS, const APFixedPoint &FX)
OutputIt copy(R &&Range, OutputIt Out)
Definition STLExtras.h:1901
const IROptions & getIROptions(const LLVMContext &C)
Definition IROptions.h:27
constexpr unsigned BitWidth
LLVM_ABI bool extractBranchWeights(const MDNode *ProfileData, SmallVectorImpl< uint32_t > &Weights)
Extract branch weights from MD_prof metadata.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
constexpr auto seq(T Begin, T End)
Iterate over an integral type from Begin up to - but not including - End.
Definition Sequence.h:341
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
bool capturesAnything(CaptureComponents CC)
Definition ModRef.h:379
bool all_equal(std::initializer_list< T > Values)
Returns true if all Values in the initializer lists are equal or the list.
Definition STLExtras.h:2182
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:267
LLVM_ABI void scaleProfData(Instruction &I, uint64_t S, uint64_t T)
Scaling the profile data attached to 'I' using the ratio of S/T.
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
Summary of memprof metadata on allocations.
Used to keep track of an operand bundle.
uint32_t End
The index in the Use& vector where operands for this operand bundle ends.
uint32_t Begin
The index in the Use& vector where operands for this operand bundle starts.
static LLVM_ABI std::optional< bool > eq(const KnownBits &LHS, const KnownBits &RHS)
Determine if these known bits always give the same ICMP_EQ result.
static LLVM_ABI std::optional< bool > ne(const KnownBits &LHS, const KnownBits &RHS)
Determine if these known bits always give the same ICMP_NE result.
static LLVM_ABI std::optional< bool > sge(const KnownBits &LHS, const KnownBits &RHS)
Determine if these known bits always give the same ICMP_SGE result.
static LLVM_ABI std::optional< bool > ugt(const KnownBits &LHS, const KnownBits &RHS)
Determine if these known bits always give the same ICMP_UGT result.
static LLVM_ABI std::optional< bool > slt(const KnownBits &LHS, const KnownBits &RHS)
Determine if these known bits always give the same ICMP_SLT result.
static LLVM_ABI std::optional< bool > ult(const KnownBits &LHS, const KnownBits &RHS)
Determine if these known bits always give the same ICMP_ULT result.
static LLVM_ABI std::optional< bool > ule(const KnownBits &LHS, const KnownBits &RHS)
Determine if these known bits always give the same ICMP_ULE result.
static LLVM_ABI std::optional< bool > sle(const KnownBits &LHS, const KnownBits &RHS)
Determine if these known bits always give the same ICMP_SLE result.
static LLVM_ABI std::optional< bool > sgt(const KnownBits &LHS, const KnownBits &RHS)
Determine if these known bits always give the same ICMP_SGT result.
static LLVM_ABI std::optional< bool > uge(const KnownBits &LHS, const KnownBits &RHS)
Determine if these known bits always give the same ICMP_UGE result.
A structure representing the properties of a load or store instruction.
Matching combinators.
A MapVector that performs no allocations if smaller than a certain size.
Definition MapVector.h:342
Indicates this User has operands co-allocated.
Definition User.h:60
Indicates this User has operands and a descriptor co-allocated .
Definition User.h:66