LLVM 23.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 "LLVMContextImpl.h"
18#include "llvm/ADT/Twine.h"
19#include "llvm/IR/Attributes.h"
20#include "llvm/IR/BasicBlock.h"
21#include "llvm/IR/Constant.h"
23#include "llvm/IR/Constants.h"
24#include "llvm/IR/DataLayout.h"
26#include "llvm/IR/Function.h"
27#include "llvm/IR/InstrTypes.h"
28#include "llvm/IR/Instruction.h"
29#include "llvm/IR/Intrinsics.h"
30#include "llvm/IR/LLVMContext.h"
31#include "llvm/IR/MDBuilder.h"
32#include "llvm/IR/Metadata.h"
33#include "llvm/IR/Module.h"
34#include "llvm/IR/Operator.h"
37#include "llvm/IR/Type.h"
38#include "llvm/IR/Value.h"
46#include "llvm/Support/ModRef.h"
48#include <algorithm>
49#include <cassert>
50#include <cstdint>
51#include <optional>
52#include <vector>
53
54using namespace llvm;
55
57 "disable-i2p-p2i-opt", cl::init(false),
58 cl::desc("Disables inttoptr/ptrtoint roundtrip optimization"));
59
60//===----------------------------------------------------------------------===//
61// AllocaInst Class
62//===----------------------------------------------------------------------===//
63
64std::optional<TypeSize>
66 TypeSize Size = DL.getTypeAllocSize(getAllocatedType());
67 // Zero-sized types can return early since 0 * N = 0 for any array size N.
68 if (Size.isZero())
69 return Size;
70 if (isArrayAllocation()) {
72 if (!C)
73 return std::nullopt;
74 assert(!Size.isScalable() && "Array elements cannot have a scalable size");
75 auto CheckedProd =
76 checkedMulUnsigned(Size.getKnownMinValue(), C->getZExtValue());
77 if (!CheckedProd)
78 return std::nullopt;
79 return TypeSize::getFixed(*CheckedProd);
80 }
81 return Size;
82}
83
84std::optional<TypeSize>
86 std::optional<TypeSize> Size = getAllocationSize(DL);
87 if (!Size)
88 return std::nullopt;
89 auto CheckedProd = checkedMulUnsigned(Size->getKnownMinValue(),
90 static_cast<TypeSize::ScalarTy>(8));
91 if (!CheckedProd)
92 return std::nullopt;
93 return TypeSize::get(*CheckedProd, Size->isScalable());
94}
95
96//===----------------------------------------------------------------------===//
97// SelectInst Class
98//===----------------------------------------------------------------------===//
99
100/// areInvalidOperands - Return a string if the specified operands are invalid
101/// for a select operation, otherwise return null.
102const char *SelectInst::areInvalidOperands(Value *Op0, Value *Op1, Value *Op2) {
103 if (Op1->getType() != Op2->getType())
104 return "both values to select must have same type";
105
106 if (Op1->getType()->isTokenTy())
107 return "select values cannot have token type";
108
109 if (VectorType *VT = dyn_cast<VectorType>(Op0->getType())) {
110 // Vector select.
111 if (VT->getElementType() != Type::getInt1Ty(Op0->getContext()))
112 return "vector select condition element type must be i1";
114 if (!ET)
115 return "selected values for vector select must be vectors";
116 if (ET->getElementCount() != VT->getElementCount())
117 return "vector select requires selected vectors to have "
118 "the same vector length as select condition";
119 } else if (Op0->getType() != Type::getInt1Ty(Op0->getContext())) {
120 return "select condition must be i1 or <n x i1>";
121 }
122 return nullptr;
123}
124
125//===----------------------------------------------------------------------===//
126// PHINode Class
127//===----------------------------------------------------------------------===//
128
129PHINode::PHINode(const PHINode &PN)
130 : Instruction(PN.getType(), Instruction::PHI, AllocMarker),
131 ReservedSpace(PN.getNumOperands()) {
134 std::copy(PN.op_begin(), PN.op_end(), op_begin());
135 copyIncomingBlocks(make_range(PN.block_begin(), PN.block_end()));
136 FMF = PN.FMF;
137}
138
139// removeIncomingValue - Remove an incoming value. This is useful if a
140// predecessor basic block is deleted.
141Value *PHINode::removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty) {
142 Value *Removed = getIncomingValue(Idx);
143 // Swap with the end of the list.
144 unsigned Last = getNumOperands() - 1;
145 if (Idx != Last) {
148 }
149
150 // Nuke the last value.
151 Op<-1>().set(nullptr);
153
154 // If the PHI node is dead, because it has zero entries, nuke it now.
155 if (getNumOperands() == 0 && DeletePHIIfEmpty) {
156 // If anyone is using this PHI, make them use a dummy value instead...
159 }
160 return Removed;
161}
162
163void PHINode::removeIncomingValueIf(function_ref<bool(unsigned)> Predicate,
164 bool DeletePHIIfEmpty) {
165 unsigned NumOps = getNumIncomingValues();
166
167 // Loop backwards in case the predicate is purely index based.
168 for (unsigned Idx = NumOps; Idx-- > 0;) {
169 if (Predicate(Idx)) {
170 unsigned LastIdx = NumOps - 1;
171 if (Idx != LastIdx) {
172 setIncomingValue(Idx, getIncomingValue(LastIdx));
173 setIncomingBlock(Idx, getIncomingBlock(LastIdx));
174 }
175 getOperandUse(LastIdx).set(nullptr);
176 NumOps--;
177 }
178 }
179
181
182 // If the PHI node is dead, because it has zero entries, nuke it now.
183 if (getNumOperands() == 0 && DeletePHIIfEmpty) {
184 // If anyone is using this PHI, make them use a dummy value instead...
187 }
188}
189
190/// growOperands - grow operands - This grows the operand list in response
191/// to a push_back style of operation. This grows the number of ops by 1.5
192/// times.
193///
194void PHINode::growOperands() {
195 unsigned e = getNumOperands();
196 unsigned NumOps = e + e / 2;
197 if (NumOps < 2) NumOps = 2; // 2 op PHI nodes are VERY common.
198
199 ReservedSpace = NumOps;
200 growHungoffUses(ReservedSpace, /*WithExtraValues=*/true);
201}
202
203/// hasConstantValue - If the specified PHI node always merges together the same
204/// value, return the value, otherwise return null.
206 // Exploit the fact that phi nodes always have at least one entry.
207 Value *ConstantValue = getIncomingValue(0);
208 for (unsigned i = 1, e = getNumIncomingValues(); i != e; ++i)
209 if (getIncomingValue(i) != ConstantValue && getIncomingValue(i) != this) {
210 if (ConstantValue != this)
211 return nullptr; // Incoming values not all the same.
212 // The case where the first value is this PHI.
213 ConstantValue = getIncomingValue(i);
214 }
215 if (ConstantValue == this)
216 return PoisonValue::get(getType());
217 return ConstantValue;
218}
219
220/// hasConstantOrUndefValue - Whether the specified PHI node always merges
221/// together the same value, assuming that undefs result in the same value as
222/// non-undefs.
223/// Unlike \ref hasConstantValue, this does not return a value because the
224/// unique non-undef incoming value need not dominate the PHI node.
226 Value *ConstantValue = nullptr;
227 for (unsigned i = 0, e = getNumIncomingValues(); i != e; ++i) {
228 Value *Incoming = getIncomingValue(i);
229 if (Incoming != this && !isa<UndefValue>(Incoming)) {
230 if (ConstantValue && ConstantValue != Incoming)
231 return false;
232 ConstantValue = Incoming;
233 }
234 }
235 return true;
236}
237
238//===----------------------------------------------------------------------===//
239// LandingPadInst Implementation
240//===----------------------------------------------------------------------===//
241
242LandingPadInst::LandingPadInst(Type *RetTy, unsigned NumReservedValues,
243 const Twine &NameStr,
244 InsertPosition InsertBefore)
245 : Instruction(RetTy, Instruction::LandingPad, AllocMarker, InsertBefore) {
246 init(NumReservedValues, NameStr);
247}
248
249LandingPadInst::LandingPadInst(const LandingPadInst &LP)
250 : Instruction(LP.getType(), Instruction::LandingPad, AllocMarker),
251 ReservedSpace(LP.getNumOperands()) {
254 Use *OL = getOperandList();
255 const Use *InOL = LP.getOperandList();
256 for (unsigned I = 0, E = ReservedSpace; I != E; ++I)
257 OL[I] = InOL[I];
258
259 setCleanup(LP.isCleanup());
260}
261
262LandingPadInst *LandingPadInst::Create(Type *RetTy, unsigned NumReservedClauses,
263 const Twine &NameStr,
264 InsertPosition InsertBefore) {
265 return new LandingPadInst(RetTy, NumReservedClauses, NameStr, InsertBefore);
266}
267
268void LandingPadInst::init(unsigned NumReservedValues, const Twine &NameStr) {
269 ReservedSpace = NumReservedValues;
271 allocHungoffUses(ReservedSpace);
272 setName(NameStr);
273 setCleanup(false);
274}
275
276/// growOperands - grow operands - This grows the operand list in response to a
277/// push_back style of operation. This grows the number of ops by 2 times.
278void LandingPadInst::growOperands(unsigned Size) {
279 unsigned e = getNumOperands();
280 if (ReservedSpace >= e + Size) return;
281 ReservedSpace = (std::max(e, 1U) + Size / 2) * 2;
282 growHungoffUses(ReservedSpace);
283}
284
286 unsigned OpNo = getNumOperands();
287 growOperands(1);
288 assert(OpNo < ReservedSpace && "Growing didn't work!");
290 getOperandList()[OpNo] = Val;
291}
292
293//===----------------------------------------------------------------------===//
294// CallBase Implementation
295//===----------------------------------------------------------------------===//
296
298 InsertPosition InsertPt) {
299 switch (CB->getOpcode()) {
300 case Instruction::Call:
301 return CallInst::Create(cast<CallInst>(CB), Bundles, InsertPt);
302 case Instruction::Invoke:
303 return InvokeInst::Create(cast<InvokeInst>(CB), Bundles, InsertPt);
304 case Instruction::CallBr:
305 return CallBrInst::Create(cast<CallBrInst>(CB), Bundles, InsertPt);
306 default:
307 llvm_unreachable("Unknown CallBase sub-class!");
308 }
309}
310
312 InsertPosition InsertPt) {
314 for (unsigned i = 0, e = CI->getNumOperandBundles(); i < e; ++i) {
315 auto ChildOB = CI->getOperandBundleAt(i);
316 if (ChildOB.getTagName() != OpB.getTag())
317 OpDefs.emplace_back(ChildOB);
318 }
319 OpDefs.emplace_back(OpB);
320 return CallBase::Create(CI, OpDefs, InsertPt);
321}
322
324
326 assert(getOpcode() == Instruction::CallBr && "Unexpected opcode!");
327 return cast<CallBrInst>(this)->getNumIndirectDests() + 1;
328}
329
331 const Value *V = getCalledOperand();
332 if (isa<Function>(V) || isa<Constant>(V))
333 return false;
334 return !isInlineAsm();
335}
336
337/// Tests if this call site must be tail call optimized. Only a CallInst can
338/// be tail call optimized.
340 if (auto *CI = dyn_cast<CallInst>(this))
341 return CI->isMustTailCall();
342 return false;
343}
344
345/// Tests if this call site is marked as a tail call.
347 if (auto *CI = dyn_cast<CallInst>(this))
348 return CI->isTailCall();
349 return false;
350}
351
354 return F->getIntrinsicID();
356}
357
359 FPClassTest Mask = Attrs.getRetNoFPClass();
360
361 if (const Function *F = getCalledFunction())
362 Mask |= F->getAttributes().getRetNoFPClass();
363 return Mask;
364}
365
367 FPClassTest Mask = Attrs.getParamNoFPClass(i);
368
369 if (const Function *F = getCalledFunction())
370 Mask |= F->getAttributes().getParamNoFPClass(i);
371 return Mask;
372}
373
374std::optional<ConstantRange> CallBase::getRange() const {
375 Attribute CallAttr = Attrs.getRetAttr(Attribute::Range);
377 if (const Function *F = getCalledFunction())
378 FnAttr = F->getRetAttribute(Attribute::Range);
379
380 if (CallAttr.isValid() && FnAttr.isValid())
381 return CallAttr.getRange().intersectWith(FnAttr.getRange());
382 if (CallAttr.isValid())
383 return CallAttr.getRange();
384 if (FnAttr.isValid())
385 return FnAttr.getRange();
386 return std::nullopt;
387}
388
390 if (hasRetAttr(Attribute::NonNull))
391 return true;
392
393 if (getRetDereferenceableBytes() > 0 &&
395 return true;
396
397 return false;
398}
399
401 unsigned Index;
402
403 if (Attrs.hasAttrSomewhere(Kind, &Index))
404 return getArgOperand(Index - AttributeList::FirstArgIndex);
405 if (const Function *F = getCalledFunction())
406 if (F->getAttributes().hasAttrSomewhere(Kind, &Index))
407 return getArgOperand(Index - AttributeList::FirstArgIndex);
408
409 return nullptr;
410}
411
412/// Determine whether the argument or parameter has the given attribute.
413bool CallBase::paramHasAttr(unsigned ArgNo, Attribute::AttrKind Kind) const {
414 assert(ArgNo < arg_size() && "Param index out of bounds!");
415
416 if (Attrs.hasParamAttr(ArgNo, Kind))
417 return true;
418
419 const Function *F = getCalledFunction();
420 if (!F)
421 return false;
422
423 if (!F->getAttributes().hasParamAttr(ArgNo, Kind))
424 return false;
425
426 // Take into account mod/ref by operand bundles.
427 switch (Kind) {
428 case Attribute::ReadNone:
430 case Attribute::ReadOnly:
432 case Attribute::WriteOnly:
433 return !hasReadingOperandBundles();
434 default:
435 return true;
436 }
437}
438
440 bool AllowUndefOrPoison) const {
442 "Argument must be a pointer");
443 if (paramHasAttr(ArgNo, Attribute::NonNull) &&
444 (AllowUndefOrPoison || paramHasAttr(ArgNo, Attribute::NoUndef)))
445 return true;
446
447 if (paramHasAttr(ArgNo, Attribute::Dereferenceable) &&
449 getCaller(),
451 return true;
452
453 return false;
454}
455
456bool CallBase::hasFnAttrOnCalledFunction(Attribute::AttrKind Kind) const {
458 return F->getAttributes().hasFnAttr(Kind);
459
460 return false;
461}
462
463bool CallBase::hasFnAttrOnCalledFunction(StringRef Kind) const {
465 return F->getAttributes().hasFnAttr(Kind);
466
467 return false;
468}
469
470template <typename AK>
471Attribute CallBase::getFnAttrOnCalledFunction(AK Kind) const {
472 if constexpr (std::is_same_v<AK, Attribute::AttrKind>) {
473 // getMemoryEffects() correctly combines memory effects from the call-site,
474 // operand bundles and function.
475 assert(Kind != Attribute::Memory && "Use getMemoryEffects() instead");
476 }
477
479 return F->getAttributes().getFnAttr(Kind);
480
481 return Attribute();
482}
483
484template LLVM_ABI Attribute
485CallBase::getFnAttrOnCalledFunction(Attribute::AttrKind Kind) const;
486template LLVM_ABI Attribute
487CallBase::getFnAttrOnCalledFunction(StringRef Kind) const;
488
489template <typename AK>
490Attribute CallBase::getParamAttrOnCalledFunction(unsigned ArgNo,
491 AK Kind) const {
493
494 if (auto *F = dyn_cast<Function>(V))
495 return F->getAttributes().getParamAttr(ArgNo, Kind);
496
497 return Attribute();
498}
499template LLVM_ABI Attribute CallBase::getParamAttrOnCalledFunction(
500 unsigned ArgNo, Attribute::AttrKind Kind) const;
501template LLVM_ABI Attribute
502CallBase::getParamAttrOnCalledFunction(unsigned ArgNo, StringRef Kind) const;
503
506 for (unsigned i = 0, e = getNumOperandBundles(); i != e; ++i)
508}
509
512 const unsigned BeginIndex) {
513 auto It = op_begin() + BeginIndex;
514 for (auto &B : Bundles)
515 It = std::copy(B.input_begin(), B.input_end(), It);
516
517 auto *ContextImpl = getContext().pImpl;
518 auto BI = Bundles.begin();
519 unsigned CurrentIndex = BeginIndex;
520
521 for (auto &BOI : bundle_op_infos()) {
522 assert(BI != Bundles.end() && "Incorrect allocation?");
523
524 BOI.Tag = ContextImpl->getOrInsertBundleTag(BI->getTag());
525 BOI.Begin = CurrentIndex;
526 BOI.End = CurrentIndex + BI->input_size();
527 CurrentIndex = BOI.End;
528 BI++;
529 }
530
531 assert(BI == Bundles.end() && "Incorrect allocation?");
532
533 return It;
534}
535
537 /// When there isn't many bundles, we do a simple linear search.
538 /// Else fallback to a binary-search that use the fact that bundles usually
539 /// have similar number of argument to get faster convergence.
541 for (auto &BOI : bundle_op_infos())
542 if (BOI.Begin <= OpIdx && OpIdx < BOI.End)
543 return BOI;
544
545 llvm_unreachable("Did not find operand bundle for operand!");
546 }
547
548 assert(OpIdx >= arg_size() && "the Idx is not in the operand bundles");
550 OpIdx < std::prev(bundle_op_info_end())->End &&
551 "The Idx isn't in the operand bundle");
552
553 /// We need a decimal number below and to prevent using floating point numbers
554 /// we use an intergal value multiplied by this constant.
555 constexpr unsigned NumberScaling = 1024;
556
559 bundle_op_iterator Current = Begin;
560
561 while (Begin != End) {
562 unsigned ScaledOperandPerBundle =
563 NumberScaling * (std::prev(End)->End - Begin->Begin) / (End - Begin);
564 Current = Begin + (((OpIdx - Begin->Begin) * NumberScaling) /
565 ScaledOperandPerBundle);
566 if (Current >= End)
567 Current = std::prev(End);
568 assert(Current < End && Current >= Begin &&
569 "the operand bundle doesn't cover every value in the range");
570 if (OpIdx >= Current->Begin && OpIdx < Current->End)
571 break;
572 if (OpIdx >= Current->End)
573 Begin = Current + 1;
574 else
575 End = Current;
576 }
577
578 assert(OpIdx >= Current->Begin && OpIdx < Current->End &&
579 "the operand bundle doesn't cover every value in the range");
580 return *Current;
581}
582
585 InsertPosition InsertPt) {
586 if (CB->getOperandBundle(ID))
587 return CB;
588
590 CB->getOperandBundlesAsDefs(Bundles);
591 Bundles.push_back(OB);
592 return Create(CB, Bundles, InsertPt);
593}
594
596 InsertPosition InsertPt) {
598 bool CreateNew = false;
599
600 for (unsigned I = 0, E = CB->getNumOperandBundles(); I != E; ++I) {
601 auto Bundle = CB->getOperandBundleAt(I);
602 if (Bundle.getTagID() == ID) {
603 CreateNew = true;
604 continue;
605 }
606 Bundles.emplace_back(Bundle);
607 }
608
609 return CreateNew ? Create(CB, Bundles, InsertPt) : CB;
610}
611
613 InsertPosition InsertPt) {
614 auto OpBundleCount = CB->getNumOperandBundles();
615 assert(Offset < OpBundleCount &&
616 "Trying to remove non-existant operand bundle");
618 Bundles.reserve(OpBundleCount - 1);
619 size_t I = 0;
620 for (; I != Offset; ++I)
621 Bundles.emplace_back(CB->getOperandBundleAt(I));
622 ++I;
623 for (; I != OpBundleCount; ++I)
624 Bundles.emplace_back(CB->getOperandBundleAt(I));
625 return Create(CB, Bundles, InsertPt);
626}
627
629 // Implementation note: this is a conservative implementation of operand
630 // bundle semantics, where *any* non-assume operand bundle (other than
631 // ptrauth) forces a callsite to be at least readonly.
636 getIntrinsicID() != Intrinsic::assume;
637}
638
647
649 MemoryEffects ME = getAttributes().getMemoryEffects();
650 if (auto *Fn = dyn_cast<Function>(getCalledOperand())) {
651 MemoryEffects FnME = Fn->getMemoryEffects();
652 if (hasOperandBundles()) {
653 // TODO: Add a method to get memory effects for operand bundles instead.
655 FnME |= MemoryEffects::readOnly();
657 FnME |= MemoryEffects::writeOnly();
658 }
659 if (isVolatile()) {
660 // Volatile operations also access inaccessible memory.
662 }
663 ME &= FnME;
664 }
665 return ME;
666}
670
671/// Determine if the function does not access memory.
678
679/// Determine if the function does not access or only reads memory.
686
687/// Determine if the function does not access or only writes memory.
694
695/// Determine if the call can access memmory only using pointers based
696/// on its arguments.
703
704/// Determine if the function may only access memory that is
705/// inaccessible from the IR.
712
713/// Determine if the function may only access memory that is
714/// either inaccessible from the IR or pointed to by its arguments.
722
724 if (OpNo < arg_size()) {
725 // If the argument is passed byval, the callee does not have access to the
726 // original pointer and thus cannot capture it.
727 if (isByValArgument(OpNo))
728 return CaptureInfo::none();
729
731 if (auto *Fn = dyn_cast<Function>(getCalledOperand()))
732 CI &= Fn->getAttributes().getParamAttrs(OpNo).getCaptureInfo();
733 return CI;
734 }
735
736 // Bundles on assumes are captures(none).
737 if (getIntrinsicID() == Intrinsic::assume)
738 return CaptureInfo::none();
739
740 // deopt operand bundles are captures(none)
741 auto &BOI = getBundleOpInfoForOperand(OpNo);
742 auto OBU = operandBundleFromBundleOpInfo(BOI);
743 return OBU.isDeoptOperandBundle() ? CaptureInfo::none() : CaptureInfo::all();
744}
745
747 for (unsigned I = 0, E = arg_size(); I < E; ++I) {
749 continue;
750
752 if (auto *Fn = dyn_cast<Function>(getCalledOperand()))
753 CI &= Fn->getAttributes().getParamAttrs(I).getCaptureInfo();
755 return true;
756 }
757 return false;
758}
759
760//===----------------------------------------------------------------------===//
761// CallInst Implementation
762//===----------------------------------------------------------------------===//
763
764void CallInst::init(FunctionType *FTy, Value *Func, ArrayRef<Value *> Args,
765 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr) {
766 this->FTy = FTy;
767 assert(getNumOperands() == Args.size() + CountBundleInputs(Bundles) + 1 &&
768 "NumOperands not set up?");
769
770#ifndef NDEBUG
771 assert((Args.size() == FTy->getNumParams() ||
772 (FTy->isVarArg() && Args.size() > FTy->getNumParams())) &&
773 "Calling a function with bad signature!");
774
775 for (unsigned i = 0; i != Args.size(); ++i)
776 assert((i >= FTy->getNumParams() ||
777 FTy->getParamType(i) == Args[i]->getType()) &&
778 "Calling a function with a bad signature!");
779#endif
780
781 // Set operands in order of their index to match use-list-order
782 // prediction.
783 llvm::copy(Args, op_begin());
784 setCalledOperand(Func);
785
786 auto It = populateBundleOperandInfos(Bundles, Args.size());
787 (void)It;
788 assert(It + 1 == op_end() && "Should add up!");
789
790 setName(NameStr);
791}
792
793void CallInst::init(FunctionType *FTy, Value *Func, const Twine &NameStr) {
794 this->FTy = FTy;
795 assert(getNumOperands() == 1 && "NumOperands not set up?");
796 setCalledOperand(Func);
797
798 assert(FTy->getNumParams() == 0 && "Calling a function with bad signature");
799
800 setName(NameStr);
801}
802
803CallInst::CallInst(FunctionType *Ty, Value *Func, const Twine &Name,
804 AllocInfo AllocInfo, InsertPosition InsertBefore)
805 : CallBase(Ty->getReturnType(), Instruction::Call, AllocInfo,
806 InsertBefore) {
807 init(Ty, Func, Name);
808}
809
810CallInst::CallInst(const CallInst &CI, AllocInfo AllocInfo)
811 : CallBase(CI.Attrs, CI.FTy, CI.getType(), Instruction::Call, AllocInfo) {
813 "Wrong number of operands allocated");
814 setTailCallKind(CI.getTailCallKind());
816
817 std::copy(CI.op_begin(), CI.op_end(), op_begin());
818 std::copy(CI.bundle_op_info_begin(), CI.bundle_op_info_end(),
820 FMF = CI.FMF;
821}
822
824 InsertPosition InsertPt) {
825 std::vector<Value *> Args(CI->arg_begin(), CI->arg_end());
826
827 auto *NewCI = CallInst::Create(CI->getFunctionType(), CI->getCalledOperand(),
828 Args, OpB, CI->getName(), InsertPt);
829 NewCI->setTailCallKind(CI->getTailCallKind());
830 NewCI->setCallingConv(CI->getCallingConv());
831 NewCI->FMF = CI->FMF;
832 NewCI->setAttributes(CI->getAttributes());
833 NewCI->setDebugLoc(CI->getDebugLoc());
834 return NewCI;
835}
836
837// Update profile weight for call instruction by scaling it using the ratio
838// of S/T. The meaning of "branch_weights" meta data for call instruction is
839// transfered to represent call count.
841 if (T == 0) {
842 LLVM_DEBUG(dbgs() << "Attempting to update profile weights will result in "
843 "div by 0. Ignoring. Likely the function "
844 << getParent()->getParent()->getName()
845 << " has 0 entry count, and contains call instructions "
846 "with non-zero prof info.");
847 return;
848 }
849 scaleProfData(*this, S, T);
850}
851
852//===----------------------------------------------------------------------===//
853// InvokeInst Implementation
854//===----------------------------------------------------------------------===//
855
856void InvokeInst::init(FunctionType *FTy, Value *Fn, BasicBlock *IfNormal,
857 BasicBlock *IfException, ArrayRef<Value *> Args,
859 const Twine &NameStr) {
860 this->FTy = FTy;
861
863 ComputeNumOperands(Args.size(), CountBundleInputs(Bundles)) &&
864 "NumOperands not set up?");
865
866#ifndef NDEBUG
867 assert(((Args.size() == FTy->getNumParams()) ||
868 (FTy->isVarArg() && Args.size() > FTy->getNumParams())) &&
869 "Invoking a function with bad signature");
870
871 for (unsigned i = 0, e = Args.size(); i != e; i++)
872 assert((i >= FTy->getNumParams() ||
873 FTy->getParamType(i) == Args[i]->getType()) &&
874 "Invoking a function with a bad signature!");
875#endif
876
877 // Set operands in order of their index to match use-list-order
878 // prediction.
879 llvm::copy(Args, op_begin());
880 setNormalDest(IfNormal);
881 setUnwindDest(IfException);
883
884 auto It = populateBundleOperandInfos(Bundles, Args.size());
885 (void)It;
886 assert(It + 3 == op_end() && "Should add up!");
887
888 setName(NameStr);
889}
890
891InvokeInst::InvokeInst(const InvokeInst &II, AllocInfo AllocInfo)
892 : CallBase(II.Attrs, II.FTy, II.getType(), Instruction::Invoke, AllocInfo) {
893 assert(getNumOperands() == II.getNumOperands() &&
894 "Wrong number of operands allocated");
895 setCallingConv(II.getCallingConv());
896 std::copy(II.op_begin(), II.op_end(), op_begin());
897 std::copy(II.bundle_op_info_begin(), II.bundle_op_info_end(),
899 SubclassOptionalData = II.SubclassOptionalData;
900}
901
903 InsertPosition InsertPt) {
904 std::vector<Value *> Args(II->arg_begin(), II->arg_end());
905
906 auto *NewII = InvokeInst::Create(
907 II->getFunctionType(), II->getCalledOperand(), II->getNormalDest(),
908 II->getUnwindDest(), Args, OpB, II->getName(), InsertPt);
909 NewII->setCallingConv(II->getCallingConv());
910 NewII->SubclassOptionalData = II->SubclassOptionalData;
911 NewII->setAttributes(II->getAttributes());
912 NewII->setDebugLoc(II->getDebugLoc());
913 return NewII;
914}
915
917 return cast<LandingPadInst>(getUnwindDest()->getFirstNonPHIIt());
918}
919
921 if (T == 0) {
922 LLVM_DEBUG(dbgs() << "Attempting to update profile weights will result in "
923 "div by 0. Ignoring. Likely the function "
924 << getParent()->getParent()->getName()
925 << " has 0 entry count, and contains call instructions "
926 "with non-zero prof info.");
927 return;
928 }
929 scaleProfData(*this, S, T);
930}
931
932//===----------------------------------------------------------------------===//
933// CallBrInst Implementation
934//===----------------------------------------------------------------------===//
935
936void CallBrInst::init(FunctionType *FTy, Value *Fn, BasicBlock *Fallthrough,
937 ArrayRef<BasicBlock *> IndirectDests,
940 const Twine &NameStr) {
941 this->FTy = FTy;
942
943 assert(getNumOperands() == ComputeNumOperands(Args.size(),
944 IndirectDests.size(),
945 CountBundleInputs(Bundles)) &&
946 "NumOperands not set up?");
947
948#ifndef NDEBUG
949 assert(((Args.size() == FTy->getNumParams()) ||
950 (FTy->isVarArg() && Args.size() > FTy->getNumParams())) &&
951 "Calling a function with bad signature");
952
953 for (unsigned i = 0, e = Args.size(); i != e; i++)
954 assert((i >= FTy->getNumParams() ||
955 FTy->getParamType(i) == Args[i]->getType()) &&
956 "Calling a function with a bad signature!");
957#endif
958
959 // Set operands in order of their index to match use-list-order
960 // prediction.
961 llvm::copy(Args, op_begin());
962 NumIndirectDests = IndirectDests.size();
963 setDefaultDest(Fallthrough);
964 for (unsigned i = 0; i != NumIndirectDests; ++i)
965 setIndirectDest(i, IndirectDests[i]);
967
968 auto It = populateBundleOperandInfos(Bundles, Args.size());
969 (void)It;
970 assert(It + 2 + IndirectDests.size() == op_end() && "Should add up!");
971
972 setName(NameStr);
973}
974
975CallBrInst::CallBrInst(const CallBrInst &CBI, AllocInfo AllocInfo)
976 : CallBase(CBI.Attrs, CBI.FTy, CBI.getType(), Instruction::CallBr,
977 AllocInfo) {
979 "Wrong number of operands allocated");
981 std::copy(CBI.op_begin(), CBI.op_end(), op_begin());
982 std::copy(CBI.bundle_op_info_begin(), CBI.bundle_op_info_end(),
985 NumIndirectDests = CBI.NumIndirectDests;
986}
987
988CallBrInst *CallBrInst::Create(CallBrInst *CBI, ArrayRef<OperandBundleDef> OpB,
989 InsertPosition InsertPt) {
990 std::vector<Value *> Args(CBI->arg_begin(), CBI->arg_end());
991
992 auto *NewCBI = CallBrInst::Create(
993 CBI->getFunctionType(), CBI->getCalledOperand(), CBI->getDefaultDest(),
994 CBI->getIndirectDests(), Args, OpB, CBI->getName(), InsertPt);
995 NewCBI->setCallingConv(CBI->getCallingConv());
996 NewCBI->SubclassOptionalData = CBI->SubclassOptionalData;
997 NewCBI->setAttributes(CBI->getAttributes());
998 NewCBI->setDebugLoc(CBI->getDebugLoc());
999 NewCBI->NumIndirectDests = CBI->NumIndirectDests;
1000 return NewCBI;
1001}
1002
1003//===----------------------------------------------------------------------===//
1004// ReturnInst Implementation
1005//===----------------------------------------------------------------------===//
1006
1007ReturnInst::ReturnInst(const ReturnInst &RI, AllocInfo AllocInfo)
1008 : Instruction(Type::getVoidTy(RI.getContext()), Instruction::Ret,
1009 AllocInfo) {
1011 "Wrong number of operands allocated");
1012 if (RI.getNumOperands())
1013 Op<0>() = RI.Op<0>();
1015}
1016
1017ReturnInst::ReturnInst(LLVMContext &C, Value *retVal, AllocInfo AllocInfo,
1018 InsertPosition InsertBefore)
1019 : Instruction(Type::getVoidTy(C), Instruction::Ret, AllocInfo,
1020 InsertBefore) {
1021 if (retVal)
1022 Op<0>() = retVal;
1023}
1024
1025//===----------------------------------------------------------------------===//
1026// ResumeInst Implementation
1027//===----------------------------------------------------------------------===//
1028
1029ResumeInst::ResumeInst(const ResumeInst &RI)
1030 : Instruction(Type::getVoidTy(RI.getContext()), Instruction::Resume,
1031 AllocMarker) {
1032 Op<0>() = RI.Op<0>();
1033}
1034
1035ResumeInst::ResumeInst(Value *Exn, InsertPosition InsertBefore)
1036 : Instruction(Type::getVoidTy(Exn->getContext()), Instruction::Resume,
1037 AllocMarker, InsertBefore) {
1038 Op<0>() = Exn;
1039}
1040
1041//===----------------------------------------------------------------------===//
1042// CleanupReturnInst Implementation
1043//===----------------------------------------------------------------------===//
1044
1045CleanupReturnInst::CleanupReturnInst(const CleanupReturnInst &CRI,
1047 : Instruction(CRI.getType(), Instruction::CleanupRet, AllocInfo) {
1049 "Wrong number of operands allocated");
1050 setSubclassData<Instruction::OpaqueField>(
1052 Op<0>() = CRI.Op<0>();
1053 if (CRI.hasUnwindDest())
1054 Op<1>() = CRI.Op<1>();
1055}
1056
1057void CleanupReturnInst::init(Value *CleanupPad, BasicBlock *UnwindBB) {
1058 if (UnwindBB)
1059 setSubclassData<UnwindDestField>(true);
1060
1061 Op<0>() = CleanupPad;
1062 if (UnwindBB)
1063 Op<1>() = UnwindBB;
1064}
1065
1066CleanupReturnInst::CleanupReturnInst(Value *CleanupPad, BasicBlock *UnwindBB,
1068 InsertPosition InsertBefore)
1069 : Instruction(Type::getVoidTy(CleanupPad->getContext()),
1070 Instruction::CleanupRet, AllocInfo, InsertBefore) {
1071 init(CleanupPad, UnwindBB);
1072}
1073
1074//===----------------------------------------------------------------------===//
1075// CatchReturnInst Implementation
1076//===----------------------------------------------------------------------===//
1077void CatchReturnInst::init(Value *CatchPad, BasicBlock *BB) {
1078 Op<0>() = CatchPad;
1079 Op<1>() = BB;
1080}
1081
1082CatchReturnInst::CatchReturnInst(const CatchReturnInst &CRI)
1083 : Instruction(Type::getVoidTy(CRI.getContext()), Instruction::CatchRet,
1084 AllocMarker) {
1085 Op<0>() = CRI.Op<0>();
1086 Op<1>() = CRI.Op<1>();
1087}
1088
1089CatchReturnInst::CatchReturnInst(Value *CatchPad, BasicBlock *BB,
1090 InsertPosition InsertBefore)
1091 : Instruction(Type::getVoidTy(BB->getContext()), Instruction::CatchRet,
1092 AllocMarker, InsertBefore) {
1093 init(CatchPad, BB);
1094}
1095
1096//===----------------------------------------------------------------------===//
1097// CatchSwitchInst Implementation
1098//===----------------------------------------------------------------------===//
1099
1100CatchSwitchInst::CatchSwitchInst(Value *ParentPad, BasicBlock *UnwindDest,
1101 unsigned NumReservedValues,
1102 const Twine &NameStr,
1103 InsertPosition InsertBefore)
1104 : Instruction(ParentPad->getType(), Instruction::CatchSwitch, AllocMarker,
1105 InsertBefore) {
1106 if (UnwindDest)
1107 ++NumReservedValues;
1108 init(ParentPad, UnwindDest, NumReservedValues + 1);
1109 setName(NameStr);
1110}
1111
1112CatchSwitchInst::CatchSwitchInst(const CatchSwitchInst &CSI)
1113 : Instruction(CSI.getType(), Instruction::CatchSwitch, AllocMarker) {
1115 init(CSI.getParentPad(), CSI.getUnwindDest(), CSI.getNumOperands());
1116 setNumHungOffUseOperands(ReservedSpace);
1117 Use *OL = getOperandList();
1118 const Use *InOL = CSI.getOperandList();
1119 for (unsigned I = 1, E = ReservedSpace; I != E; ++I)
1120 OL[I] = InOL[I];
1121}
1122
1123void CatchSwitchInst::init(Value *ParentPad, BasicBlock *UnwindDest,
1124 unsigned NumReservedValues) {
1125 assert(ParentPad && NumReservedValues);
1126
1127 ReservedSpace = NumReservedValues;
1128 setNumHungOffUseOperands(UnwindDest ? 2 : 1);
1129 allocHungoffUses(ReservedSpace);
1130
1131 Op<0>() = ParentPad;
1132 if (UnwindDest) {
1134 setUnwindDest(UnwindDest);
1135 }
1136}
1137
1138/// growOperands - grow operands - This grows the operand list in response to a
1139/// push_back style of operation. This grows the number of ops by 2 times.
1140void CatchSwitchInst::growOperands(unsigned Size) {
1141 unsigned NumOperands = getNumOperands();
1142 assert(NumOperands >= 1);
1143 if (ReservedSpace >= NumOperands + Size)
1144 return;
1145 ReservedSpace = (NumOperands + Size / 2) * 2;
1146 growHungoffUses(ReservedSpace);
1147}
1148
1150 unsigned OpNo = getNumOperands();
1151 growOperands(1);
1152 assert(OpNo < ReservedSpace && "Growing didn't work!");
1154 getOperandList()[OpNo] = Handler;
1155}
1156
1158 // Move all subsequent handlers up one.
1159 Use *EndDst = op_end() - 1;
1160 for (Use *CurDst = HI.getCurrent(); CurDst != EndDst; ++CurDst)
1161 *CurDst = *(CurDst + 1);
1162 // Null out the last handler use.
1163 *EndDst = nullptr;
1164
1166}
1167
1168//===----------------------------------------------------------------------===//
1169// FuncletPadInst Implementation
1170//===----------------------------------------------------------------------===//
1171void FuncletPadInst::init(Value *ParentPad, ArrayRef<Value *> Args,
1172 const Twine &NameStr) {
1173 assert(getNumOperands() == 1 + Args.size() && "NumOperands not set up?");
1174 llvm::copy(Args, op_begin());
1175 setParentPad(ParentPad);
1176 setName(NameStr);
1177}
1178
1179FuncletPadInst::FuncletPadInst(const FuncletPadInst &FPI, AllocInfo AllocInfo)
1180 : Instruction(FPI.getType(), FPI.getOpcode(), AllocInfo) {
1182 "Wrong number of operands allocated");
1183 std::copy(FPI.op_begin(), FPI.op_end(), op_begin());
1185}
1186
1187FuncletPadInst::FuncletPadInst(Instruction::FuncletPadOps Op, Value *ParentPad,
1189 const Twine &NameStr,
1190 InsertPosition InsertBefore)
1191 : Instruction(ParentPad->getType(), Op, AllocInfo, InsertBefore) {
1192 init(ParentPad, Args, NameStr);
1193}
1194
1195//===----------------------------------------------------------------------===//
1196// UnreachableInst Implementation
1197//===----------------------------------------------------------------------===//
1198
1200 InsertPosition InsertBefore)
1201 : Instruction(Type::getVoidTy(Context), Instruction::Unreachable,
1202 AllocMarker, InsertBefore) {}
1203
1204//===----------------------------------------------------------------------===//
1205// UncondBrInst Implementation
1206//===----------------------------------------------------------------------===//
1207
1208// Suppress deprecation warnings from BranchInst.
1210
1211UncondBrInst::UncondBrInst(BasicBlock *Target, InsertPosition InsertBefore)
1212 : BranchInst(Type::getVoidTy(Target->getContext()), Instruction::UncondBr,
1213 AllocMarker, InsertBefore) {
1214 Op<-1>() = Target;
1215}
1216
1217UncondBrInst::UncondBrInst(const UncondBrInst &BI)
1218 : BranchInst(Type::getVoidTy(BI.getContext()), Instruction::UncondBr,
1219 AllocMarker) {
1220 Op<-1>() = BI.Op<-1>();
1221 SubclassOptionalData = BI.SubclassOptionalData;
1222}
1223
1224//===----------------------------------------------------------------------===//
1225// CondBrInst Implementation
1226//===----------------------------------------------------------------------===//
1227
1228void CondBrInst::AssertOK() {
1229 assert(getCondition()->getType()->isIntegerTy(1) &&
1230 "May only branch on boolean predicates!");
1231}
1232
1233CondBrInst::CondBrInst(Value *Cond, BasicBlock *IfTrue, BasicBlock *IfFalse,
1234 InsertPosition InsertBefore)
1235 : BranchInst(Type::getVoidTy(IfTrue->getContext()), Instruction::CondBr,
1236 AllocMarker, InsertBefore) {
1237 // Assign in order of operand index to make use-list order predictable.
1238 Op<-3>() = Cond;
1239 Op<-2>() = IfTrue;
1240 Op<-1>() = IfFalse;
1241#ifndef NDEBUG
1242 AssertOK();
1243#endif
1244}
1245
1246CondBrInst::CondBrInst(const CondBrInst &BI)
1247 : BranchInst(Type::getVoidTy(BI.getContext()), Instruction::CondBr,
1248 AllocMarker) {
1249 // Assign in order of operand index to make use-list order predictable.
1250 Op<-3>() = BI.Op<-3>();
1251 Op<-2>() = BI.Op<-2>();
1252 Op<-1>() = BI.Op<-1>();
1253 SubclassOptionalData = BI.SubclassOptionalData;
1254}
1255
1257 Op<-1>().swap(Op<-2>());
1258
1259 // Update profile metadata if present and it matches our structural
1260 // expectations.
1261 swapProfMetadata();
1262}
1263
1264// Suppress deprecation warnings from BranchInst.
1266
1267//===----------------------------------------------------------------------===//
1268// AllocaInst Implementation
1269//===----------------------------------------------------------------------===//
1270
1271static Value *getAISize(LLVMContext &Context, Value *Amt) {
1272 if (!Amt)
1273 Amt = ConstantInt::get(Type::getInt32Ty(Context), 1);
1274 else {
1275 assert(!isa<BasicBlock>(Amt) &&
1276 "Passed basic block into allocation size parameter! Use other ctor");
1277 assert(Amt->getType()->isIntegerTy() &&
1278 "Allocation array size is not an integer!");
1279 }
1280 return Amt;
1281}
1282
1284 assert(Pos.isValid() &&
1285 "Insertion position cannot be null when alignment not provided!");
1286 BasicBlock *BB = Pos.getBasicBlock();
1287 assert(BB->getParent() &&
1288 "BB must be in a Function when alignment not provided!");
1289 const DataLayout &DL = BB->getDataLayout();
1290 return DL.getPrefTypeAlign(Ty);
1291}
1292
1293AllocaInst::AllocaInst(Type *Ty, unsigned AddrSpace, const Twine &Name,
1294 InsertPosition InsertBefore)
1295 : AllocaInst(Ty, AddrSpace, /*ArraySize=*/nullptr, Name, InsertBefore) {}
1296
1297AllocaInst::AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize,
1298 const Twine &Name, InsertPosition InsertBefore)
1299 : AllocaInst(Ty, AddrSpace, ArraySize,
1300 computeAllocaDefaultAlign(Ty, InsertBefore), Name,
1301 InsertBefore) {}
1302
1303AllocaInst::AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize,
1304 Align Align, const Twine &Name,
1305 InsertPosition InsertBefore)
1306 : UnaryInstruction(PointerType::get(Ty->getContext(), AddrSpace), Alloca,
1307 getAISize(Ty->getContext(), ArraySize), InsertBefore),
1308 AllocatedType(Ty) {
1310 assert(!Ty->isVoidTy() && "Cannot allocate void!");
1311 setName(Name);
1312}
1313
1316 return !CI->isOne();
1317 return true;
1318}
1319
1320/// isStaticAlloca - Return true if this alloca is in the entry block of the
1321/// function and is a constant size. If so, the code generator will fold it
1322/// into the prolog/epilog code, so it is basically free.
1324 // Must be constant size.
1325 if (!isa<ConstantInt>(getArraySize())) return false;
1326
1327 // Must be in the entry block.
1328 const BasicBlock *Parent = getParent();
1329 return Parent->isEntryBlock() && !isUsedWithInAlloca();
1330}
1331
1332//===----------------------------------------------------------------------===//
1333// LoadInst Implementation
1334//===----------------------------------------------------------------------===//
1335
1336void LoadInst::AssertOK() {
1338 "Ptr must have pointer type.");
1339}
1340
1342 assert(Pos.isValid() &&
1343 "Insertion position cannot be null when alignment not provided!");
1344 BasicBlock *BB = Pos.getBasicBlock();
1345 assert(BB->getParent() &&
1346 "BB must be in a Function when alignment not provided!");
1347 const DataLayout &DL = BB->getDataLayout();
1348 return DL.getABITypeAlign(Ty);
1349}
1350
1351LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name,
1352 InsertPosition InsertBef)
1353 : LoadInst(Ty, Ptr, Name, /*isVolatile=*/false, InsertBef) {}
1354
1355LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile,
1356 InsertPosition InsertBef)
1357 : LoadInst(Ty, Ptr, Name, isVolatile,
1358 computeLoadStoreDefaultAlign(Ty, InsertBef), InsertBef) {}
1359
1360LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile,
1361 Align Align, InsertPosition InsertBef)
1362 : LoadInst(Ty, Ptr, Name, isVolatile, Align, AtomicOrdering::NotAtomic,
1363 SyncScope::System, InsertBef) {}
1364
1365LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile,
1367 InsertPosition InsertBef)
1368 : UnaryInstruction(Ty, Load, Ptr, InsertBef) {
1371 setAtomic(Order, SSID);
1372 AssertOK();
1373 setName(Name);
1374}
1375
1376//===----------------------------------------------------------------------===//
1377// StoreInst Implementation
1378//===----------------------------------------------------------------------===//
1379
1380void StoreInst::AssertOK() {
1381 assert(getOperand(0) && getOperand(1) && "Both operands must be non-null!");
1383 "Ptr must have pointer type!");
1384}
1385
1387 : StoreInst(val, addr, /*isVolatile=*/false, InsertBefore) {}
1388
1390 InsertPosition InsertBefore)
1391 : StoreInst(val, addr, isVolatile,
1392 computeLoadStoreDefaultAlign(val->getType(), InsertBefore),
1393 InsertBefore) {}
1394
1396 InsertPosition InsertBefore)
1398 SyncScope::System, InsertBefore) {}
1399
1401 AtomicOrdering Order, SyncScope::ID SSID,
1402 InsertPosition InsertBefore)
1403 : Instruction(Type::getVoidTy(val->getContext()), Store, AllocMarker,
1404 InsertBefore) {
1405 Op<0>() = val;
1406 Op<1>() = addr;
1409 setAtomic(Order, SSID);
1410 AssertOK();
1411}
1412
1413//===----------------------------------------------------------------------===//
1414// AtomicCmpXchgInst Implementation
1415//===----------------------------------------------------------------------===//
1416
1417void AtomicCmpXchgInst::Init(Value *Ptr, Value *Cmp, Value *NewVal,
1418 Align Alignment, AtomicOrdering SuccessOrdering,
1419 AtomicOrdering FailureOrdering,
1420 SyncScope::ID SSID) {
1421 Op<0>() = Ptr;
1422 Op<1>() = Cmp;
1423 Op<2>() = NewVal;
1424 setSuccessOrdering(SuccessOrdering);
1425 setFailureOrdering(FailureOrdering);
1426 setSyncScopeID(SSID);
1427 setAlignment(Alignment);
1428
1429 assert(getOperand(0) && getOperand(1) && getOperand(2) &&
1430 "All operands must be non-null!");
1432 "Ptr must have pointer type!");
1433 assert(getOperand(1)->getType() == getOperand(2)->getType() &&
1434 "Cmp type and NewVal type must be same!");
1435}
1436
1438 Align Alignment,
1439 AtomicOrdering SuccessOrdering,
1440 AtomicOrdering FailureOrdering,
1441 SyncScope::ID SSID,
1442 InsertPosition InsertBefore)
1443 : Instruction(
1444 StructType::get(Cmp->getType(), Type::getInt1Ty(Cmp->getContext())),
1445 AtomicCmpXchg, AllocMarker, InsertBefore) {
1446 Init(Ptr, Cmp, NewVal, Alignment, SuccessOrdering, FailureOrdering, SSID);
1447}
1448
1449//===----------------------------------------------------------------------===//
1450// AtomicRMWInst Implementation
1451//===----------------------------------------------------------------------===//
1452
1453void AtomicRMWInst::Init(BinOp Operation, Value *Ptr, Value *Val,
1454 Align Alignment, AtomicOrdering Ordering,
1455 SyncScope::ID SSID, bool Elementwise) {
1456 assert(Ordering != AtomicOrdering::NotAtomic &&
1457 "atomicrmw instructions can only be atomic.");
1458 assert(Ordering != AtomicOrdering::Unordered &&
1459 "atomicrmw instructions cannot be unordered.");
1460 Op<0>() = Ptr;
1461 Op<1>() = Val;
1463 setOrdering(Ordering);
1464 setSyncScopeID(SSID);
1465 setElementwise(Elementwise);
1466 setAlignment(Alignment);
1467
1468 assert(getOperand(0) && getOperand(1) && "All operands must be non-null!");
1470 "Ptr must have pointer type!");
1471 assert(Ordering != AtomicOrdering::NotAtomic &&
1472 "AtomicRMW instructions must be atomic!");
1473}
1474
1476 Align Alignment, AtomicOrdering Ordering,
1477 SyncScope::ID SSID, bool Elementwise,
1478 InsertPosition InsertBefore)
1479 : Instruction(Val->getType(), AtomicRMW, AllocMarker, InsertBefore) {
1480 Init(Operation, Ptr, Val, Alignment, Ordering, SSID, Elementwise);
1481}
1482
1484 switch (Op) {
1486 return "xchg";
1487 case AtomicRMWInst::Add:
1488 return "add";
1489 case AtomicRMWInst::Sub:
1490 return "sub";
1491 case AtomicRMWInst::And:
1492 return "and";
1494 return "nand";
1495 case AtomicRMWInst::Or:
1496 return "or";
1497 case AtomicRMWInst::Xor:
1498 return "xor";
1499 case AtomicRMWInst::Max:
1500 return "max";
1501 case AtomicRMWInst::Min:
1502 return "min";
1504 return "umax";
1506 return "umin";
1508 return "fadd";
1510 return "fsub";
1512 return "fmax";
1514 return "fmin";
1516 return "fmaximum";
1518 return "fminimum";
1520 return "fmaximumnum";
1522 return "fminimumnum";
1524 return "uinc_wrap";
1526 return "udec_wrap";
1528 return "usub_cond";
1530 return "usub_sat";
1532 return "<invalid operation>";
1533 }
1534
1535 llvm_unreachable("invalid atomicrmw operation");
1536}
1537
1538//===----------------------------------------------------------------------===//
1539// FenceInst Implementation
1540//===----------------------------------------------------------------------===//
1541
1543 SyncScope::ID SSID, InsertPosition InsertBefore)
1544 : Instruction(Type::getVoidTy(C), Fence, AllocMarker, InsertBefore) {
1545 setOrdering(Ordering);
1546 setSyncScopeID(SSID);
1547}
1548
1549//===----------------------------------------------------------------------===//
1550// GetElementPtrInst Implementation
1551//===----------------------------------------------------------------------===//
1552
1553void GetElementPtrInst::init(Value *Ptr, ArrayRef<Value *> IdxList,
1554 const Twine &Name) {
1555 assert(getNumOperands() == 1 + IdxList.size() &&
1556 "NumOperands not initialized?");
1557 Op<0>() = Ptr;
1558 llvm::copy(IdxList, op_begin() + 1);
1559 setName(Name);
1560}
1561
1562GetElementPtrInst::GetElementPtrInst(const GetElementPtrInst &GEPI,
1564 : Instruction(GEPI.getType(), GetElementPtr, AllocInfo),
1565 SourceElementType(GEPI.SourceElementType),
1566 ResultElementType(GEPI.ResultElementType) {
1567 assert(getNumOperands() == GEPI.getNumOperands() &&
1568 "Wrong number of operands allocated");
1569 std::copy(GEPI.op_begin(), GEPI.op_end(), op_begin());
1571}
1572
1574 if (auto *Struct = dyn_cast<StructType>(Ty)) {
1575 if (!Struct->indexValid(Idx))
1576 return nullptr;
1577 return Struct->getTypeAtIndex(Idx);
1578 }
1579 if (!Idx->getType()->isIntOrIntVectorTy())
1580 return nullptr;
1581 if (auto *Array = dyn_cast<ArrayType>(Ty))
1582 return Array->getElementType();
1583 if (auto *Vector = dyn_cast<VectorType>(Ty))
1584 return Vector->getElementType();
1585 return nullptr;
1586}
1587
1589 if (auto *Struct = dyn_cast<StructType>(Ty)) {
1590 if (Idx >= Struct->getNumElements())
1591 return nullptr;
1592 return Struct->getElementType(Idx);
1593 }
1594 if (auto *Array = dyn_cast<ArrayType>(Ty))
1595 return Array->getElementType();
1596 if (auto *Vector = dyn_cast<VectorType>(Ty))
1597 return Vector->getElementType();
1598 return nullptr;
1599}
1600
1601template <typename IndexTy>
1603 if (IdxList.empty())
1604 return Ty;
1605 for (IndexTy V : IdxList.slice(1)) {
1607 if (!Ty)
1608 return Ty;
1609 }
1610 return Ty;
1611}
1612
1616
1618 ArrayRef<Constant *> IdxList) {
1619 return getIndexedTypeInternal(Ty, IdxList);
1620}
1621
1625
1626/// hasAllZeroIndices - Return true if all of the indices of this GEP are
1627/// zeros. If so, the result pointer and the first operand have the same
1628/// value, just potentially different types.
1630 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1632 if (!CI->isZero()) return false;
1633 } else {
1634 return false;
1635 }
1636 }
1637 return true;
1638}
1639
1640/// hasAllConstantIndices - Return true if all of the indices of this GEP are
1641/// constant integers. If so, the result pointer and the first operand have
1642/// a constant offset between them.
1644 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1646 return false;
1647 }
1648 return true;
1649}
1650
1654
1656 GEPNoWrapFlags NW = cast<GEPOperator>(this)->getNoWrapFlags();
1657 if (B)
1659 else
1660 NW = NW.withoutInBounds();
1661 setNoWrapFlags(NW);
1662}
1663
1665 return cast<GEPOperator>(this)->getNoWrapFlags();
1666}
1667
1669 return cast<GEPOperator>(this)->isInBounds();
1670}
1671
1673 return cast<GEPOperator>(this)->hasNoUnsignedSignedWrap();
1674}
1675
1677 return cast<GEPOperator>(this)->hasNoUnsignedWrap();
1678}
1679
1681 APInt &Offset) const {
1682 // Delegate to the generic GEPOperator implementation.
1683 return cast<GEPOperator>(this)->accumulateConstantOffset(DL, Offset);
1684}
1685
1687 const DataLayout &DL, unsigned BitWidth,
1688 SmallMapVector<Value *, APInt, 4> &VariableOffsets,
1689 APInt &ConstantOffset) const {
1690 // Delegate to the generic GEPOperator implementation.
1691 return cast<GEPOperator>(this)->collectOffset(DL, BitWidth, VariableOffsets,
1692 ConstantOffset);
1693}
1694
1695//===----------------------------------------------------------------------===//
1696// ExtractElementInst Implementation
1697//===----------------------------------------------------------------------===//
1698
1699ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1700 const Twine &Name,
1701 InsertPosition InsertBef)
1702 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1703 ExtractElement, AllocMarker, InsertBef) {
1704 assert(isValidOperands(Val, Index) &&
1705 "Invalid extractelement instruction operands!");
1706 Op<0>() = Val;
1707 Op<1>() = Index;
1708 setName(Name);
1709}
1710
1711bool ExtractElementInst::isValidOperands(const Value *Val, const Value *Index) {
1712 if (!Val->getType()->isVectorTy() || !Index->getType()->isIntegerTy())
1713 return false;
1714 return true;
1715}
1716
1717//===----------------------------------------------------------------------===//
1718// InsertElementInst Implementation
1719//===----------------------------------------------------------------------===//
1720
1721InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1722 const Twine &Name,
1723 InsertPosition InsertBef)
1724 : Instruction(Vec->getType(), InsertElement, AllocMarker, InsertBef) {
1725 assert(isValidOperands(Vec, Elt, Index) &&
1726 "Invalid insertelement instruction operands!");
1727 Op<0>() = Vec;
1728 Op<1>() = Elt;
1729 Op<2>() = Index;
1730 setName(Name);
1731}
1732
1734 const Value *Index) {
1735 if (!Vec->getType()->isVectorTy())
1736 return false; // First operand of insertelement must be vector type.
1737
1738 if (Elt->getType() != cast<VectorType>(Vec->getType())->getElementType())
1739 return false;// Second operand of insertelement must be vector element type.
1740
1741 if (!Index->getType()->isIntegerTy())
1742 return false; // Third operand of insertelement must be i32.
1743 return true;
1744}
1745
1746//===----------------------------------------------------------------------===//
1747// ShuffleVectorInst Implementation
1748//===----------------------------------------------------------------------===//
1749
1751 assert(V && "Cannot create placeholder of nullptr V");
1752 return PoisonValue::get(V->getType());
1753}
1754
1756 InsertPosition InsertBefore)
1758 InsertBefore) {}
1759
1761 const Twine &Name,
1762 InsertPosition InsertBefore)
1764 InsertBefore) {}
1765
1767 const Twine &Name,
1768 InsertPosition InsertBefore)
1769 : Instruction(
1770 VectorType::get(cast<VectorType>(V1->getType())->getElementType(),
1771 cast<VectorType>(Mask->getType())->getElementCount()),
1772 ShuffleVector, AllocMarker, InsertBefore) {
1773 assert(isValidOperands(V1, V2, Mask) &&
1774 "Invalid shuffle vector instruction operands!");
1775
1776 Op<0>() = V1;
1777 Op<1>() = V2;
1778 SmallVector<int, 16> MaskArr;
1779 getShuffleMask(cast<Constant>(Mask), MaskArr);
1780 setShuffleMask(MaskArr);
1781 setName(Name);
1782}
1783
1785 const Twine &Name,
1786 InsertPosition InsertBefore)
1787 : Instruction(
1788 VectorType::get(cast<VectorType>(V1->getType())->getElementType(),
1789 Mask.size(), isa<ScalableVectorType>(V1->getType())),
1790 ShuffleVector, AllocMarker, InsertBefore) {
1791 assert(isValidOperands(V1, V2, Mask) &&
1792 "Invalid shuffle vector instruction operands!");
1793 Op<0>() = V1;
1794 Op<1>() = V2;
1795 setShuffleMask(Mask);
1796 setName(Name);
1797}
1798
1800 int NumOpElts = cast<FixedVectorType>(Op<0>()->getType())->getNumElements();
1801 int NumMaskElts = ShuffleMask.size();
1802 SmallVector<int, 16> NewMask(NumMaskElts);
1803 for (int i = 0; i != NumMaskElts; ++i) {
1804 int MaskElt = getMaskValue(i);
1805 if (MaskElt == PoisonMaskElem) {
1806 NewMask[i] = PoisonMaskElem;
1807 continue;
1808 }
1809 assert(MaskElt >= 0 && MaskElt < 2 * NumOpElts && "Out-of-range mask");
1810 MaskElt = (MaskElt < NumOpElts) ? MaskElt + NumOpElts : MaskElt - NumOpElts;
1811 NewMask[i] = MaskElt;
1812 }
1813 setShuffleMask(NewMask);
1814 Op<0>().swap(Op<1>());
1815}
1816
1818 ArrayRef<int> Mask) {
1819 // V1 and V2 must be vectors of the same type.
1820 if (!isa<VectorType>(V1->getType()) || V1->getType() != V2->getType())
1821 return false;
1822
1823 // Make sure the mask elements make sense.
1824 int V1Size =
1825 cast<VectorType>(V1->getType())->getElementCount().getKnownMinValue();
1826 for (int Elem : Mask)
1827 if (Elem != PoisonMaskElem && Elem >= V1Size * 2)
1828 return false;
1829
1831 if ((Mask[0] != 0 && Mask[0] != PoisonMaskElem) || !all_equal(Mask))
1832 return false;
1833
1834 return true;
1835}
1836
1838 const Value *Mask) {
1839 // V1 and V2 must be vectors of the same type.
1840 if (!V1->getType()->isVectorTy() || V1->getType() != V2->getType())
1841 return false;
1842
1843 // Mask must be vector of i32, and must be the same kind of vector as the
1844 // input vectors
1845 auto *MaskTy = dyn_cast<VectorType>(Mask->getType());
1846 if (!MaskTy || !MaskTy->getElementType()->isIntegerTy(32) ||
1848 return false;
1849
1850 // Check to see if Mask is valid.
1852 return true;
1853
1854 // NOTE: Through vector ConstantInt we have the potential to support more
1855 // than just zero splat masks but that requires a LangRef change.
1856 if (isa<ScalableVectorType>(MaskTy))
1857 return false;
1858
1859 unsigned V1Size = cast<FixedVectorType>(V1->getType())->getNumElements();
1860
1861 if (const auto *CI = dyn_cast<ConstantInt>(Mask))
1862 return !CI->uge(V1Size * 2);
1863
1864 if (const auto *MV = dyn_cast<ConstantVector>(Mask)) {
1865 for (Value *Op : MV->operands()) {
1866 if (auto *CI = dyn_cast<ConstantInt>(Op)) {
1867 if (CI->uge(V1Size*2))
1868 return false;
1869 } else if (!isa<UndefValue>(Op)) {
1870 return false;
1871 }
1872 }
1873 return true;
1874 }
1875
1876 if (const auto *CDS = dyn_cast<ConstantDataSequential>(Mask)) {
1877 for (unsigned i = 0, e = cast<FixedVectorType>(MaskTy)->getNumElements();
1878 i != e; ++i)
1879 if (CDS->getElementAsInteger(i) >= V1Size*2)
1880 return false;
1881 return true;
1882 }
1883
1884 return false;
1885}
1886
1888 SmallVectorImpl<int> &Result) {
1889 ElementCount EC = cast<VectorType>(Mask->getType())->getElementCount();
1890
1891 if (isa<ConstantAggregateZero>(Mask) || isa<UndefValue>(Mask)) {
1892 int MaskVal = isa<UndefValue>(Mask) ? -1 : 0;
1893 Result.append(EC.getKnownMinValue(), MaskVal);
1894 return;
1895 }
1896
1897 assert(!EC.isScalable() &&
1898 "Scalable vector shuffle mask must be undef or zeroinitializer");
1899
1900 unsigned NumElts = EC.getFixedValue();
1901
1902 Result.reserve(NumElts);
1903
1904 if (auto *CDS = dyn_cast<ConstantDataSequential>(Mask)) {
1905 for (unsigned i = 0; i != NumElts; ++i)
1906 Result.push_back(CDS->getElementAsInteger(i));
1907 return;
1908 }
1909 for (unsigned i = 0; i != NumElts; ++i) {
1910 Constant *C = Mask->getAggregateElement(i);
1911 Result.push_back(isa<UndefValue>(C) ? -1 :
1912 cast<ConstantInt>(C)->getZExtValue());
1913 }
1914}
1915
1917 ShuffleMask.assign(Mask.begin(), Mask.end());
1918 ShuffleMaskForBitcode = convertShuffleMaskForBitcode(Mask, getType());
1919}
1920
1922 Type *ResultTy) {
1923 Type *Int32Ty = Type::getInt32Ty(ResultTy->getContext());
1924 if (isa<ScalableVectorType>(ResultTy)) {
1925 assert(all_equal(Mask) && "Unexpected shuffle");
1926 Type *VecTy = VectorType::get(Int32Ty, Mask.size(), true);
1927 if (Mask[0] == 0)
1928 return Constant::getNullValue(VecTy);
1929 return PoisonValue::get(VecTy);
1930 }
1932 for (int Elem : Mask) {
1933 if (Elem == PoisonMaskElem)
1935 else
1936 MaskConst.push_back(ConstantInt::get(Int32Ty, Elem));
1937 }
1938 return ConstantVector::get(MaskConst);
1939}
1940
1941static bool isSingleSourceMaskImpl(ArrayRef<int> Mask, int NumOpElts) {
1942 assert(!Mask.empty() && "Shuffle mask must contain elements");
1943 bool UsesLHS = false;
1944 bool UsesRHS = false;
1945 for (int I : Mask) {
1946 if (I == -1)
1947 continue;
1948 assert(I >= 0 && I < (NumOpElts * 2) &&
1949 "Out-of-bounds shuffle mask element");
1950 UsesLHS |= (I < NumOpElts);
1951 UsesRHS |= (I >= NumOpElts);
1952 if (UsesLHS && UsesRHS)
1953 return false;
1954 }
1955 // Allow for degenerate case: completely undef mask means neither source is used.
1956 return UsesLHS || UsesRHS;
1957}
1958
1960 // We don't have vector operand size information, so assume operands are the
1961 // same size as the mask.
1962 return isSingleSourceMaskImpl(Mask, NumSrcElts);
1963}
1964
1965static bool isIdentityMaskImpl(ArrayRef<int> Mask, int NumOpElts) {
1966 if (!isSingleSourceMaskImpl(Mask, NumOpElts))
1967 return false;
1968 for (int i = 0, NumMaskElts = Mask.size(); i < NumMaskElts; ++i) {
1969 if (Mask[i] == -1)
1970 continue;
1971 if (Mask[i] != i && Mask[i] != (NumOpElts + i))
1972 return false;
1973 }
1974 return true;
1975}
1976
1978 if (Mask.size() != static_cast<unsigned>(NumSrcElts))
1979 return false;
1980 // We don't have vector operand size information, so assume operands are the
1981 // same size as the mask.
1982 return isIdentityMaskImpl(Mask, NumSrcElts);
1983}
1984
1986 if (Mask.size() != static_cast<unsigned>(NumSrcElts))
1987 return false;
1988 if (!isSingleSourceMask(Mask, NumSrcElts))
1989 return false;
1990
1991 // The number of elements in the mask must be at least 2.
1992 if (NumSrcElts < 2)
1993 return false;
1994
1995 for (int I = 0, E = Mask.size(); I < E; ++I) {
1996 if (Mask[I] == -1)
1997 continue;
1998 if (Mask[I] != (NumSrcElts - 1 - I) &&
1999 Mask[I] != (NumSrcElts + NumSrcElts - 1 - I))
2000 return false;
2001 }
2002 return true;
2003}
2004
2006 if (Mask.size() != static_cast<unsigned>(NumSrcElts))
2007 return false;
2008 if (!isSingleSourceMask(Mask, NumSrcElts))
2009 return false;
2010 for (int I = 0, E = Mask.size(); I < E; ++I) {
2011 if (Mask[I] == -1)
2012 continue;
2013 if (Mask[I] != 0 && Mask[I] != NumSrcElts)
2014 return false;
2015 }
2016 return true;
2017}
2018
2020 if (Mask.size() != static_cast<unsigned>(NumSrcElts))
2021 return false;
2022 // Select is differentiated from identity. It requires using both sources.
2023 if (isSingleSourceMask(Mask, NumSrcElts))
2024 return false;
2025 for (int I = 0, E = Mask.size(); I < E; ++I) {
2026 if (Mask[I] == -1)
2027 continue;
2028 if (Mask[I] != I && Mask[I] != (NumSrcElts + I))
2029 return false;
2030 }
2031 return true;
2032}
2033
2035 // Example masks that will return true:
2036 // v1 = <a, b, c, d>
2037 // v2 = <e, f, g, h>
2038 // trn1 = shufflevector v1, v2 <0, 4, 2, 6> = <a, e, c, g>
2039 // trn2 = shufflevector v1, v2 <1, 5, 3, 7> = <b, f, d, h>
2040
2041 if (Mask.size() != static_cast<unsigned>(NumSrcElts))
2042 return false;
2043 // 1. The number of elements in the mask must be a power-of-2 and at least 2.
2044 int Sz = Mask.size();
2045 if (Sz < 2 || !isPowerOf2_32(Sz))
2046 return false;
2047
2048 // 2. The first element of the mask must be either a 0 or a 1.
2049 if (Mask[0] != 0 && Mask[0] != 1)
2050 return false;
2051
2052 // 3. The difference between the first 2 elements must be equal to the
2053 // number of elements in the mask.
2054 if ((Mask[1] - Mask[0]) != NumSrcElts)
2055 return false;
2056
2057 // 4. The difference between consecutive even-numbered and odd-numbered
2058 // elements must be equal to 2.
2059 for (int I = 2; I < Sz; ++I) {
2060 int MaskEltVal = Mask[I];
2061 if (MaskEltVal == -1)
2062 return false;
2063 int MaskEltPrevVal = Mask[I - 2];
2064 if (MaskEltVal - MaskEltPrevVal != 2)
2065 return false;
2066 }
2067 return true;
2068}
2069
2071 int &Index) {
2072 if (Mask.size() != static_cast<unsigned>(NumSrcElts))
2073 return false;
2074 // Example: shufflevector <4 x n> A, <4 x n> B, <1,2,3,4>
2075 int StartIndex = -1;
2076 for (int I = 0, E = Mask.size(); I != E; ++I) {
2077 int MaskEltVal = Mask[I];
2078 if (MaskEltVal == -1)
2079 continue;
2080
2081 if (StartIndex == -1) {
2082 // Don't support a StartIndex that begins in the second input, or if the
2083 // first non-undef index would access below the StartIndex.
2084 if (MaskEltVal < I || NumSrcElts <= (MaskEltVal - I))
2085 return false;
2086
2087 StartIndex = MaskEltVal - I;
2088 continue;
2089 }
2090
2091 // Splice is sequential starting from StartIndex.
2092 if (MaskEltVal != (StartIndex + I))
2093 return false;
2094 }
2095
2096 if (StartIndex == -1)
2097 return false;
2098
2099 // NOTE: This accepts StartIndex == 0 (COPY).
2100 Index = StartIndex;
2101 return true;
2102}
2103
2105 int NumSrcElts, int &Index) {
2106 // Must extract from a single source.
2107 if (!isSingleSourceMaskImpl(Mask, NumSrcElts))
2108 return false;
2109
2110 // Must be smaller (else this is an Identity shuffle).
2111 if (NumSrcElts <= (int)Mask.size())
2112 return false;
2113
2114 // Find start of extraction, accounting that we may start with an UNDEF.
2115 int SubIndex = -1;
2116 for (int i = 0, e = Mask.size(); i != e; ++i) {
2117 int M = Mask[i];
2118 if (M < 0)
2119 continue;
2120 int Offset = (M % NumSrcElts) - i;
2121 if (0 <= SubIndex && SubIndex != Offset)
2122 return false;
2123 SubIndex = Offset;
2124 }
2125
2126 if (0 <= SubIndex && SubIndex + (int)Mask.size() <= NumSrcElts) {
2127 Index = SubIndex;
2128 return true;
2129 }
2130 return false;
2131}
2132
2134 int NumSrcElts, int &NumSubElts,
2135 int &Index) {
2136 int NumMaskElts = Mask.size();
2137
2138 // Don't try to match if we're shuffling to a smaller size.
2139 if (NumMaskElts < NumSrcElts)
2140 return false;
2141
2142 // TODO: We don't recognize self-insertion/widening.
2143 if (isSingleSourceMaskImpl(Mask, NumSrcElts))
2144 return false;
2145
2146 // Determine which mask elements are attributed to which source.
2147 APInt UndefElts = APInt::getZero(NumMaskElts);
2148 APInt Src0Elts = APInt::getZero(NumMaskElts);
2149 APInt Src1Elts = APInt::getZero(NumMaskElts);
2150 bool Src0Identity = true;
2151 bool Src1Identity = true;
2152
2153 for (int i = 0; i != NumMaskElts; ++i) {
2154 int M = Mask[i];
2155 if (M < 0) {
2156 UndefElts.setBit(i);
2157 continue;
2158 }
2159 if (M < NumSrcElts) {
2160 Src0Elts.setBit(i);
2161 Src0Identity &= (M == i);
2162 continue;
2163 }
2164 Src1Elts.setBit(i);
2165 Src1Identity &= (M == (i + NumSrcElts));
2166 }
2167 assert((Src0Elts | Src1Elts | UndefElts).isAllOnes() &&
2168 "unknown shuffle elements");
2169 assert(!Src0Elts.isZero() && !Src1Elts.isZero() &&
2170 "2-source shuffle not found");
2171
2172 // Determine lo/hi span ranges.
2173 // TODO: How should we handle undefs at the start of subvector insertions?
2174 int Src0Lo = Src0Elts.countr_zero();
2175 int Src1Lo = Src1Elts.countr_zero();
2176 int Src0Hi = NumMaskElts - Src0Elts.countl_zero();
2177 int Src1Hi = NumMaskElts - Src1Elts.countl_zero();
2178
2179 // If src0 is in place, see if the src1 elements is inplace within its own
2180 // span.
2181 if (Src0Identity) {
2182 int NumSub1Elts = Src1Hi - Src1Lo;
2183 ArrayRef<int> Sub1Mask = Mask.slice(Src1Lo, NumSub1Elts);
2184 if (isIdentityMaskImpl(Sub1Mask, NumSrcElts)) {
2185 NumSubElts = NumSub1Elts;
2186 Index = Src1Lo;
2187 return true;
2188 }
2189 }
2190
2191 // If src1 is in place, see if the src0 elements is inplace within its own
2192 // span.
2193 if (Src1Identity) {
2194 int NumSub0Elts = Src0Hi - Src0Lo;
2195 ArrayRef<int> Sub0Mask = Mask.slice(Src0Lo, NumSub0Elts);
2196 if (isIdentityMaskImpl(Sub0Mask, NumSrcElts)) {
2197 NumSubElts = NumSub0Elts;
2198 Index = Src0Lo;
2199 return true;
2200 }
2201 }
2202
2203 return false;
2204}
2205
2207 // FIXME: Not currently possible to express a shuffle mask for a scalable
2208 // vector for this case.
2210 return false;
2211
2212 int NumOpElts = cast<FixedVectorType>(Op<0>()->getType())->getNumElements();
2213 int NumMaskElts = cast<FixedVectorType>(getType())->getNumElements();
2214 if (NumMaskElts <= NumOpElts)
2215 return false;
2216
2217 // The first part of the mask must choose elements from exactly 1 source op.
2219 if (!isIdentityMaskImpl(Mask, NumOpElts))
2220 return false;
2221
2222 // All extending must be with undef elements.
2223 for (int i = NumOpElts; i < NumMaskElts; ++i)
2224 if (Mask[i] != -1)
2225 return false;
2226
2227 return true;
2228}
2229
2231 // FIXME: Not currently possible to express a shuffle mask for a scalable
2232 // vector for this case.
2234 return false;
2235
2236 int NumOpElts = cast<FixedVectorType>(Op<0>()->getType())->getNumElements();
2237 int NumMaskElts = cast<FixedVectorType>(getType())->getNumElements();
2238 if (NumMaskElts >= NumOpElts)
2239 return false;
2240
2241 return isIdentityMaskImpl(getShuffleMask(), NumOpElts);
2242}
2243
2245 // Vector concatenation is differentiated from identity with padding.
2247 return false;
2248
2249 // FIXME: Not currently possible to express a shuffle mask for a scalable
2250 // vector for this case.
2252 return false;
2253
2254 int NumOpElts = cast<FixedVectorType>(Op<0>()->getType())->getNumElements();
2255 int NumMaskElts = cast<FixedVectorType>(getType())->getNumElements();
2256 if (NumMaskElts != NumOpElts * 2)
2257 return false;
2258
2259 // Use the mask length rather than the operands' vector lengths here. We
2260 // already know that the shuffle returns a vector twice as long as the inputs,
2261 // and neither of the inputs are undef vectors. If the mask picks consecutive
2262 // elements from both inputs, then this is a concatenation of the inputs.
2263 return isIdentityMaskImpl(getShuffleMask(), NumMaskElts);
2264}
2265
2267 int ReplicationFactor, int VF) {
2268 assert(Mask.size() == (unsigned)ReplicationFactor * VF &&
2269 "Unexpected mask size.");
2270
2271 for (int CurrElt : seq(VF)) {
2272 ArrayRef<int> CurrSubMask = Mask.take_front(ReplicationFactor);
2273 assert(CurrSubMask.size() == (unsigned)ReplicationFactor &&
2274 "Run out of mask?");
2275 Mask = Mask.drop_front(ReplicationFactor);
2276 if (!all_of(CurrSubMask, [CurrElt](int MaskElt) {
2277 return MaskElt == PoisonMaskElem || MaskElt == CurrElt;
2278 }))
2279 return false;
2280 }
2281 assert(Mask.empty() && "Did not consume the whole mask?");
2282
2283 return true;
2284}
2285
2287 int &ReplicationFactor, int &VF) {
2288 // undef-less case is trivial.
2289 if (!llvm::is_contained(Mask, PoisonMaskElem)) {
2290 ReplicationFactor =
2291 Mask.take_while([](int MaskElt) { return MaskElt == 0; }).size();
2292 if (ReplicationFactor == 0 || Mask.size() % ReplicationFactor != 0)
2293 return false;
2294 VF = Mask.size() / ReplicationFactor;
2295 return isReplicationMaskWithParams(Mask, ReplicationFactor, VF);
2296 }
2297
2298 // However, if the mask contains undef's, we have to enumerate possible tuples
2299 // and pick one. There are bounds on replication factor: [1, mask size]
2300 // (where RF=1 is an identity shuffle, RF=mask size is a broadcast shuffle)
2301 // Additionally, mask size is a replication factor multiplied by vector size,
2302 // which further significantly reduces the search space.
2303
2304 // Before doing that, let's perform basic correctness checking first.
2305 int Largest = -1;
2306 for (int MaskElt : Mask) {
2307 if (MaskElt == PoisonMaskElem)
2308 continue;
2309 // Elements must be in non-decreasing order.
2310 if (MaskElt < Largest)
2311 return false;
2312 Largest = std::max(Largest, MaskElt);
2313 }
2314
2315 // Prefer larger replication factor if all else equal.
2316 for (int PossibleReplicationFactor :
2317 reverse(seq_inclusive<unsigned>(1, Mask.size()))) {
2318 if (Mask.size() % PossibleReplicationFactor != 0)
2319 continue;
2320 int PossibleVF = Mask.size() / PossibleReplicationFactor;
2321 if (!isReplicationMaskWithParams(Mask, PossibleReplicationFactor,
2322 PossibleVF))
2323 continue;
2324 ReplicationFactor = PossibleReplicationFactor;
2325 VF = PossibleVF;
2326 return true;
2327 }
2328
2329 return false;
2330}
2331
2332bool ShuffleVectorInst::isReplicationMask(int &ReplicationFactor,
2333 int &VF) const {
2334 // Not possible to express a shuffle mask for a scalable vector for this
2335 // case.
2337 return false;
2338
2339 VF = cast<FixedVectorType>(Op<0>()->getType())->getNumElements();
2340 if (ShuffleMask.size() % VF != 0)
2341 return false;
2342 ReplicationFactor = ShuffleMask.size() / VF;
2343
2344 return isReplicationMaskWithParams(ShuffleMask, ReplicationFactor, VF);
2345}
2346
2348 if (VF <= 0 || Mask.size() < static_cast<unsigned>(VF) ||
2349 Mask.size() % VF != 0)
2350 return false;
2351 for (unsigned K = 0, Sz = Mask.size(); K < Sz; K += VF) {
2352 ArrayRef<int> SubMask = Mask.slice(K, VF);
2353 if (all_of(SubMask, equal_to(PoisonMaskElem)))
2354 continue;
2355 SmallBitVector Used(VF, false);
2356 for (int Idx : SubMask) {
2357 if (Idx != PoisonMaskElem && Idx < VF)
2358 Used.set(Idx);
2359 }
2360 if (!Used.all())
2361 return false;
2362 }
2363 return true;
2364}
2365
2366/// Return true if this shuffle mask is a replication mask.
2368 // Not possible to express a shuffle mask for a scalable vector for this
2369 // case.
2371 return false;
2372 if (!isSingleSourceMask(ShuffleMask, VF))
2373 return false;
2374
2375 return isOneUseSingleSourceMask(ShuffleMask, VF);
2376}
2377
2378bool ShuffleVectorInst::isInterleave(unsigned Factor) {
2380 // shuffle_vector can only interleave fixed length vectors - for scalable
2381 // vectors, see the @llvm.vector.interleave2 intrinsic
2382 if (!OpTy)
2383 return false;
2384 unsigned OpNumElts = OpTy->getNumElements();
2385
2386 return isInterleaveMask(ShuffleMask, Factor, OpNumElts * 2);
2387}
2388
2390 ArrayRef<int> Mask, unsigned Factor, unsigned NumInputElts,
2391 SmallVectorImpl<unsigned> &StartIndexes) {
2392 unsigned NumElts = Mask.size();
2393 if (NumElts % Factor)
2394 return false;
2395
2396 unsigned LaneLen = NumElts / Factor;
2397 if (!isPowerOf2_32(LaneLen))
2398 return false;
2399
2400 StartIndexes.resize(Factor);
2401
2402 // Check whether each element matches the general interleaved rule.
2403 // Ignore undef elements, as long as the defined elements match the rule.
2404 // Outer loop processes all factors (x, y, z in the above example)
2405 unsigned I = 0, J;
2406 for (; I < Factor; I++) {
2407 unsigned SavedLaneValue;
2408 unsigned SavedNoUndefs = 0;
2409
2410 // Inner loop processes consecutive accesses (x, x+1... in the example)
2411 for (J = 0; J < LaneLen - 1; J++) {
2412 // Lane computes x's position in the Mask
2413 unsigned Lane = J * Factor + I;
2414 unsigned NextLane = Lane + Factor;
2415 int LaneValue = Mask[Lane];
2416 int NextLaneValue = Mask[NextLane];
2417
2418 // If both are defined, values must be sequential
2419 if (LaneValue >= 0 && NextLaneValue >= 0 &&
2420 LaneValue + 1 != NextLaneValue)
2421 break;
2422
2423 // If the next value is undef, save the current one as reference
2424 if (LaneValue >= 0 && NextLaneValue < 0) {
2425 SavedLaneValue = LaneValue;
2426 SavedNoUndefs = 1;
2427 }
2428
2429 // Undefs are allowed, but defined elements must still be consecutive:
2430 // i.e.: x,..., undef,..., x + 2,..., undef,..., undef,..., x + 5, ....
2431 // Verify this by storing the last non-undef followed by an undef
2432 // Check that following non-undef masks are incremented with the
2433 // corresponding distance.
2434 if (SavedNoUndefs > 0 && LaneValue < 0) {
2435 SavedNoUndefs++;
2436 if (NextLaneValue >= 0 &&
2437 SavedLaneValue + SavedNoUndefs != (unsigned)NextLaneValue)
2438 break;
2439 }
2440 }
2441
2442 if (J < LaneLen - 1)
2443 return false;
2444
2445 int StartMask = 0;
2446 if (Mask[I] >= 0) {
2447 // Check that the start of the I range (J=0) is greater than 0
2448 StartMask = Mask[I];
2449 } else if (Mask[(LaneLen - 1) * Factor + I] >= 0) {
2450 // StartMask defined by the last value in lane
2451 StartMask = Mask[(LaneLen - 1) * Factor + I] - J;
2452 } else if (SavedNoUndefs > 0) {
2453 // StartMask defined by some non-zero value in the j loop
2454 StartMask = SavedLaneValue - (LaneLen - 1 - SavedNoUndefs);
2455 }
2456 // else StartMask remains set to 0, i.e. all elements are undefs
2457
2458 if (StartMask < 0)
2459 return false;
2460 // We must stay within the vectors; This case can happen with undefs.
2461 if (StartMask + LaneLen > NumInputElts)
2462 return false;
2463
2464 StartIndexes[I] = StartMask;
2465 }
2466
2467 return true;
2468}
2469
2470/// Check if the mask is a DE-interleave mask of the given factor
2471/// \p Factor like:
2472/// <Index, Index+Factor, ..., Index+(NumElts-1)*Factor>
2474 unsigned Factor,
2475 unsigned &Index) {
2476 // Check all potential start indices from 0 to (Factor - 1).
2477 for (unsigned Idx = 0; Idx < Factor; Idx++) {
2478 unsigned I = 0;
2479
2480 // Check that elements are in ascending order by Factor. Ignore undef
2481 // elements.
2482 for (; I < Mask.size(); I++)
2483 if (Mask[I] >= 0 && static_cast<unsigned>(Mask[I]) != Idx + I * Factor)
2484 break;
2485
2486 if (I == Mask.size()) {
2487 Index = Idx;
2488 return true;
2489 }
2490 }
2491
2492 return false;
2493}
2494
2495/// Try to lower a vector shuffle as a bit rotation.
2496///
2497/// Look for a repeated rotation pattern in each sub group.
2498/// Returns an element-wise left bit rotation amount or -1 if failed.
2499static int matchShuffleAsBitRotate(ArrayRef<int> Mask, int NumSubElts) {
2500 int NumElts = Mask.size();
2501 assert((NumElts % NumSubElts) == 0 && "Illegal shuffle mask");
2502
2503 int RotateAmt = -1;
2504 for (int i = 0; i != NumElts; i += NumSubElts) {
2505 for (int j = 0; j != NumSubElts; ++j) {
2506 int M = Mask[i + j];
2507 if (M < 0)
2508 continue;
2509 if (M < i || M >= i + NumSubElts)
2510 return -1;
2511 int Offset = (NumSubElts - (M - (i + j))) % NumSubElts;
2512 if (0 <= RotateAmt && Offset != RotateAmt)
2513 return -1;
2514 RotateAmt = Offset;
2515 }
2516 }
2517 return RotateAmt;
2518}
2519
2521 ArrayRef<int> Mask, unsigned EltSizeInBits, unsigned MinSubElts,
2522 unsigned MaxSubElts, unsigned &NumSubElts, unsigned &RotateAmt) {
2523 for (NumSubElts = MinSubElts; NumSubElts <= MaxSubElts; NumSubElts *= 2) {
2524 int EltRotateAmt = matchShuffleAsBitRotate(Mask, NumSubElts);
2525 if (EltRotateAmt < 0)
2526 continue;
2527 RotateAmt = EltRotateAmt * EltSizeInBits;
2528 return true;
2529 }
2530
2531 return false;
2532}
2533
2534//===----------------------------------------------------------------------===//
2535// InsertValueInst Class
2536//===----------------------------------------------------------------------===//
2537
2538void InsertValueInst::init(Value *Agg, Value *Val, ArrayRef<unsigned> Idxs,
2539 const Twine &Name) {
2540 assert(getNumOperands() == 2 && "NumOperands not initialized?");
2541
2542 // There's no fundamental reason why we require at least one index
2543 // (other than weirdness with &*IdxBegin being invalid; see
2544 // getelementptr's init routine for example). But there's no
2545 // present need to support it.
2546 assert(!Idxs.empty() && "InsertValueInst must have at least one index");
2547
2549 Val->getType() && "Inserted value must match indexed type!");
2550 Op<0>() = Agg;
2551 Op<1>() = Val;
2552
2553 Indices.append(Idxs.begin(), Idxs.end());
2554 setName(Name);
2555}
2556
2557InsertValueInst::InsertValueInst(const InsertValueInst &IVI)
2558 : Instruction(IVI.getType(), InsertValue, AllocMarker),
2559 Indices(IVI.Indices) {
2560 Op<0>() = IVI.getOperand(0);
2561 Op<1>() = IVI.getOperand(1);
2563}
2564
2565//===----------------------------------------------------------------------===//
2566// ExtractValueInst Class
2567//===----------------------------------------------------------------------===//
2568
2569void ExtractValueInst::init(ArrayRef<unsigned> Idxs, const Twine &Name) {
2570 assert(getNumOperands() == 1 && "NumOperands not initialized?");
2571
2572 // There's no fundamental reason why we require at least one index.
2573 // But there's no present need to support it.
2574 assert(!Idxs.empty() && "ExtractValueInst must have at least one index");
2575
2576 Indices.append(Idxs.begin(), Idxs.end());
2577 setName(Name);
2578}
2579
2580ExtractValueInst::ExtractValueInst(const ExtractValueInst &EVI)
2581 : UnaryInstruction(EVI.getType(), ExtractValue, EVI.getOperand(0),
2582 (BasicBlock *)nullptr),
2583 Indices(EVI.Indices) {
2585}
2586
2587// getIndexedType - Returns the type of the element that would be extracted
2588// with an extractvalue instruction with the specified parameters.
2589//
2590// A null type is returned if the indices are invalid for the specified
2591// pointer type.
2592//
2594 ArrayRef<unsigned> Idxs) {
2595 for (unsigned Index : Idxs) {
2596 // We can't use CompositeType::indexValid(Index) here.
2597 // indexValid() always returns true for arrays because getelementptr allows
2598 // out-of-bounds indices. Since we don't allow those for extractvalue and
2599 // insertvalue we need to check array indexing manually.
2600 // Since the only other types we can index into are struct types it's just
2601 // as easy to check those manually as well.
2602 if (ArrayType *AT = dyn_cast<ArrayType>(Agg)) {
2603 if (Index >= AT->getNumElements())
2604 return nullptr;
2605 Agg = AT->getElementType();
2606 } else if (StructType *ST = dyn_cast<StructType>(Agg)) {
2607 if (Index >= ST->getNumElements())
2608 return nullptr;
2609 Agg = ST->getElementType(Index);
2610 } else {
2611 // Not a valid type to index into.
2612 return nullptr;
2613 }
2614 }
2615 return Agg;
2616}
2617
2618//===----------------------------------------------------------------------===//
2619// UnaryOperator Class
2620//===----------------------------------------------------------------------===//
2621
2623 const Twine &Name, InsertPosition InsertBefore)
2624 : UnaryInstruction(Ty, iType, S, InsertBefore) {
2625 Op<0>() = S;
2626 setName(Name);
2627 AssertOK();
2628}
2629
2631 InsertPosition InsertBefore) {
2632 switch (Op) {
2633 case UnaryOps::FNeg:
2634 return new FPUnaryOperator(Op, S, S->getType(), Name, InsertBefore);
2635 default:
2636 return new UnaryOperator(Op, S, S->getType(), Name, InsertBefore);
2637 }
2638}
2639
2640void UnaryOperator::AssertOK() {
2641 Value *LHS = getOperand(0);
2642 (void)LHS; // Silence warnings.
2643#ifndef NDEBUG
2644 switch (getOpcode()) {
2645 case FNeg:
2646 assert(getType() == LHS->getType() &&
2647 "Unary operation should return same type as operand!");
2648 assert(getType()->isFPOrFPVectorTy() &&
2649 "Tried to create a floating-point operation on a "
2650 "non-floating-point type!");
2651 break;
2652 default: llvm_unreachable("Invalid opcode provided");
2653 }
2654#endif
2655}
2656
2657//===----------------------------------------------------------------------===//
2658// BinaryOperator Class
2659//===----------------------------------------------------------------------===//
2660
2662 const Twine &Name, InsertPosition InsertBefore)
2663 : Instruction(Ty, iType, AllocMarker, InsertBefore) {
2664 Op<0>() = S1;
2665 Op<1>() = S2;
2666 setName(Name);
2667 AssertOK();
2668}
2669
2670void BinaryOperator::AssertOK() {
2671 Value *LHS = getOperand(0), *RHS = getOperand(1);
2672 (void)LHS; (void)RHS; // Silence warnings.
2673 assert(LHS->getType() == RHS->getType() &&
2674 "Binary operator operand types must match!");
2675#ifndef NDEBUG
2676 switch (getOpcode()) {
2677 case Add: case Sub:
2678 case Mul:
2679 assert(getType() == LHS->getType() &&
2680 "Arithmetic operation should return same type as operands!");
2681 assert(getType()->isIntOrIntVectorTy() &&
2682 "Tried to create an integer operation on a non-integer type!");
2683 break;
2684 case FAdd: case FSub:
2685 case FMul:
2686 assert(getType() == LHS->getType() &&
2687 "Arithmetic operation should return same type as operands!");
2688 assert(getType()->isFPOrFPVectorTy() &&
2689 "Tried to create a floating-point operation on a "
2690 "non-floating-point type!");
2691 break;
2692 case UDiv:
2693 case SDiv:
2694 assert(getType() == LHS->getType() &&
2695 "Arithmetic operation should return same type as operands!");
2696 assert(getType()->isIntOrIntVectorTy() &&
2697 "Incorrect operand type (not integer) for S/UDIV");
2698 break;
2699 case FDiv:
2700 assert(getType() == LHS->getType() &&
2701 "Arithmetic operation should return same type as operands!");
2702 assert(getType()->isFPOrFPVectorTy() &&
2703 "Incorrect operand type (not floating point) for FDIV");
2704 break;
2705 case URem:
2706 case SRem:
2707 assert(getType() == LHS->getType() &&
2708 "Arithmetic operation should return same type as operands!");
2709 assert(getType()->isIntOrIntVectorTy() &&
2710 "Incorrect operand type (not integer) for S/UREM");
2711 break;
2712 case FRem:
2713 assert(getType() == LHS->getType() &&
2714 "Arithmetic operation should return same type as operands!");
2715 assert(getType()->isFPOrFPVectorTy() &&
2716 "Incorrect operand type (not floating point) for FREM");
2717 break;
2718 case Shl:
2719 case LShr:
2720 case AShr:
2721 assert(getType() == LHS->getType() &&
2722 "Shift operation should return same type as operands!");
2723 assert(getType()->isIntOrIntVectorTy() &&
2724 "Tried to create a shift operation on a non-integral type!");
2725 break;
2726 case And: case Or:
2727 case Xor:
2728 assert(getType() == LHS->getType() &&
2729 "Logical operation should return same type as operands!");
2730 assert(getType()->isIntOrIntVectorTy() &&
2731 "Tried to create a logical operation on a non-integral type!");
2732 break;
2733 default: llvm_unreachable("Invalid opcode provided");
2734 }
2735#endif
2736}
2737
2739 const Twine &Name,
2740 InsertPosition InsertBefore) {
2741 assert(S1->getType() == S2->getType() &&
2742 "Cannot create binary operator with two operands of differing type!");
2743 switch (Op) {
2744 case BinaryOps::FAdd:
2745 case BinaryOps::FSub:
2746 case BinaryOps::FMul:
2747 case BinaryOps::FDiv:
2748 case BinaryOps::FRem:
2749 return new FPBinaryOperator(Op, S1, S2, S1->getType(), Name, InsertBefore);
2750 default:
2751 return new BinaryOperator(Op, S1, S2, S1->getType(), Name, InsertBefore);
2752 }
2753}
2754
2756 InsertPosition InsertBefore) {
2757 Value *Zero = ConstantInt::get(Op->getType(), 0);
2758 return new BinaryOperator(Instruction::Sub, Zero, Op, Op->getType(), Name,
2759 InsertBefore);
2760}
2761
2763 InsertPosition InsertBefore) {
2764 Value *Zero = ConstantInt::get(Op->getType(), 0);
2765 return BinaryOperator::CreateNSWSub(Zero, Op, Name, InsertBefore);
2766}
2767
2769 InsertPosition InsertBefore) {
2770 Constant *C = Constant::getAllOnesValue(Op->getType());
2771 return new BinaryOperator(Instruction::Xor, Op, C,
2772 Op->getType(), Name, InsertBefore);
2773}
2774
2775// Exchange the two operands to this instruction. This instruction is safe to
2776// use on any binary instruction and does not modify the semantics of the
2777// instruction.
2779 if (!isCommutative())
2780 return true; // Can't commute operands
2781 Op<0>().swap(Op<1>());
2782 return false;
2783}
2784
2785//===----------------------------------------------------------------------===//
2786// FPMathOperator Class
2787//===----------------------------------------------------------------------===//
2788
2790 const MDNode *MD =
2791 cast<Instruction>(this)->getMetadata(LLVMContext::MD_fpmath);
2792 if (!MD)
2793 return 0.0;
2795 return Accuracy->getValueAPF().convertToFloat();
2796}
2797
2798//===----------------------------------------------------------------------===//
2799// CastInst Class
2800//===----------------------------------------------------------------------===//
2801
2802// Just determine if this cast only deals with integral->integral conversion.
2804 switch (getOpcode()) {
2805 default: return false;
2806 case Instruction::ZExt:
2807 case Instruction::SExt:
2808 case Instruction::Trunc:
2809 return true;
2810 case Instruction::BitCast:
2811 return getOperand(0)->getType()->isIntegerTy() &&
2812 getType()->isIntegerTy();
2813 }
2814}
2815
2816/// This function determines if the CastInst does not require any bits to be
2817/// changed in order to effect the cast. Essentially, it identifies cases where
2818/// no code gen is necessary for the cast, hence the name no-op cast. For
2819/// example, the following are all no-op casts:
2820/// # bitcast i32* %x to i8*
2821/// # bitcast <2 x i32> %x to <4 x i16>
2822/// # ptrtoint i32* %x to i32 ; on 32-bit plaforms only
2823/// Determine if the described cast is a no-op.
2825 Type *SrcTy,
2826 Type *DestTy,
2827 const DataLayout &DL) {
2828 assert(castIsValid(Opcode, SrcTy, DestTy) && "method precondition");
2829 switch (Opcode) {
2830 default: llvm_unreachable("Invalid CastOp");
2831 case Instruction::Trunc:
2832 case Instruction::ZExt:
2833 case Instruction::SExt:
2834 case Instruction::FPTrunc:
2835 case Instruction::FPExt:
2836 case Instruction::UIToFP:
2837 case Instruction::SIToFP:
2838 case Instruction::FPToUI:
2839 case Instruction::FPToSI:
2840 case Instruction::AddrSpaceCast:
2841 // TODO: Target informations may give a more accurate answer here.
2842 return false;
2843 case Instruction::BitCast:
2844 return true; // BitCast never modifies bits.
2845 case Instruction::PtrToAddr:
2846 case Instruction::PtrToInt:
2847 return DL.getIntPtrType(SrcTy)->getScalarSizeInBits() ==
2848 DestTy->getScalarSizeInBits();
2849 case Instruction::IntToPtr:
2850 return DL.getIntPtrType(DestTy)->getScalarSizeInBits() ==
2851 SrcTy->getScalarSizeInBits();
2852 }
2853}
2854
2856 return isNoopCast(getOpcode(), getOperand(0)->getType(), getType(), DL);
2857}
2858
2859/// This function determines if a pair of casts can be eliminated and what
2860/// opcode should be used in the elimination. This assumes that there are two
2861/// instructions like this:
2862/// * %F = firstOpcode SrcTy %x to MidTy
2863/// * %S = secondOpcode MidTy %F to DstTy
2864/// The function returns a resultOpcode so these two casts can be replaced with:
2865/// * %Replacement = resultOpcode %SrcTy %x to DstTy
2866/// If no such cast is permitted, the function returns 0.
2868 Instruction::CastOps secondOp,
2869 Type *SrcTy, Type *MidTy, Type *DstTy,
2870 const DataLayout *DL) {
2871 // Define the 144 possibilities for these two cast instructions. The values
2872 // in this matrix determine what to do in a given situation and select the
2873 // case in the switch below. The rows correspond to firstOp, the columns
2874 // correspond to secondOp. In looking at the table below, keep in mind
2875 // the following cast properties:
2876 //
2877 // Size Compare Source Destination
2878 // Operator Src ? Size Type Sign Type Sign
2879 // -------- ------------ ------------------- ---------------------
2880 // TRUNC > Integer Any Integral Any
2881 // ZEXT < Integral Unsigned Integer Any
2882 // SEXT < Integral Signed Integer Any
2883 // FPTOUI n/a FloatPt n/a Integral Unsigned
2884 // FPTOSI n/a FloatPt n/a Integral Signed
2885 // UITOFP n/a Integral Unsigned FloatPt n/a
2886 // SITOFP n/a Integral Signed FloatPt n/a
2887 // FPTRUNC > FloatPt n/a FloatPt n/a
2888 // FPEXT < FloatPt n/a FloatPt n/a
2889 // PTRTOINT n/a Pointer n/a Integral Unsigned
2890 // PTRTOADDR n/a Pointer n/a Integral Unsigned
2891 // INTTOPTR n/a Integral Unsigned Pointer n/a
2892 // BITCAST = FirstClass n/a FirstClass n/a
2893 // ADDRSPCST n/a Pointer n/a Pointer n/a
2894 //
2895 // NOTE: some transforms are safe, but we consider them to be non-profitable.
2896 // For example, we could merge "fptoui double to i32" + "zext i32 to i64",
2897 // into "fptoui double to i64", but this loses information about the range
2898 // of the produced value (we no longer know the top-part is all zeros).
2899 // Further this conversion is often much more expensive for typical hardware,
2900 // and causes issues when building libgcc. We disallow fptosi+sext for the
2901 // same reason.
2902 const unsigned numCastOps =
2903 Instruction::CastOpsEnd - Instruction::CastOpsBegin;
2904 // clang-format off
2905 static const uint8_t CastResults[numCastOps][numCastOps] = {
2906 // T F F U S F F P P I B A -+
2907 // R Z S P P I I T P 2 2 N T S |
2908 // U E E 2 2 2 2 R E I A T C C +- secondOp
2909 // N X X U S F F N X N D 2 V V |
2910 // C T T I I P P C T T R P T T -+
2911 { 1, 0, 0,99,99, 0, 0,99,99,99,99, 0, 3, 0}, // Trunc -+
2912 { 8, 1, 9,99,99, 2,17,99,99,99,99, 2, 3, 0}, // ZExt |
2913 { 8, 0, 1,99,99, 0, 2,99,99,99,99, 0, 3, 0}, // SExt |
2914 { 0, 0, 0,99,99, 0, 0,99,99,99,99, 0, 3, 0}, // FPToUI |
2915 { 0, 0, 0,99,99, 0, 0,99,99,99,99, 0, 3, 0}, // FPToSI |
2916 { 99,99,99, 0, 0,99,99, 0, 0,99,99,99, 4, 0}, // UIToFP +- firstOp
2917 { 99,99,99, 0, 0,99,99, 0, 0,99,99,99, 4, 0}, // SIToFP |
2918 { 99,99,99, 0, 0,99,99, 0, 0,99,99,99, 4, 0}, // FPTrunc |
2919 { 99,99,99, 2, 2,99,99, 8, 2,99,99,99, 4, 0}, // FPExt |
2920 { 1, 0, 0,99,99, 0, 0,99,99,99,99, 7, 3, 0}, // PtrToInt |
2921 { 0, 0, 0,99,99, 0, 0,99,99,99,99, 0, 3, 0}, // PtrToAddr |
2922 { 99,99,99,99,99,99,99,99,99,11,11,99,15, 0}, // IntToPtr |
2923 { 5, 5, 5, 0, 0, 5, 5, 0, 0,16,16, 5, 1,14}, // BitCast |
2924 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,13,12}, // AddrSpaceCast -+
2925 };
2926 // clang-format on
2927
2928 // TODO: This logic could be encoded into the table above and handled in the
2929 // switch below.
2930 // If either of the casts are a bitcast from scalar to vector, disallow the
2931 // merging. However, any pair of bitcasts are allowed.
2932 bool IsFirstBitcast = (firstOp == Instruction::BitCast);
2933 bool IsSecondBitcast = (secondOp == Instruction::BitCast);
2934 bool AreBothBitcasts = IsFirstBitcast && IsSecondBitcast;
2935
2936 // Check if any of the casts convert scalars <-> vectors.
2937 if ((IsFirstBitcast && isa<VectorType>(SrcTy) != isa<VectorType>(MidTy)) ||
2938 (IsSecondBitcast && isa<VectorType>(MidTy) != isa<VectorType>(DstTy)))
2939 if (!AreBothBitcasts)
2940 return 0;
2941
2942 int ElimCase = CastResults[firstOp-Instruction::CastOpsBegin]
2943 [secondOp-Instruction::CastOpsBegin];
2944 switch (ElimCase) {
2945 case 0:
2946 // Categorically disallowed.
2947 return 0;
2948 case 1:
2949 // Allowed, use first cast's opcode.
2950 return firstOp;
2951 case 2:
2952 // Allowed, use second cast's opcode.
2953 return secondOp;
2954 case 3:
2955 // No-op cast in second op implies firstOp as long as the DestTy
2956 // is integer and we are not converting between a vector and a
2957 // non-vector type.
2958 if (!SrcTy->isVectorTy() && DstTy->isIntegerTy())
2959 return firstOp;
2960 return 0;
2961 case 4:
2962 // No-op cast in second op implies firstOp as long as the DestTy
2963 // matches MidTy.
2964 if (DstTy == MidTy)
2965 return firstOp;
2966 return 0;
2967 case 5:
2968 // No-op cast in first op implies secondOp as long as the SrcTy
2969 // is an integer.
2970 if (SrcTy->isIntegerTy())
2971 return secondOp;
2972 return 0;
2973 case 7: {
2974 // Disable inttoptr/ptrtoint optimization if enabled.
2975 if (DisableI2pP2iOpt)
2976 return 0;
2977
2978 // Cannot simplify if address spaces are different!
2979 if (SrcTy != DstTy)
2980 return 0;
2981
2982 // Cannot simplify if the intermediate integer size is smaller than the
2983 // pointer size.
2984 unsigned MidSize = MidTy->getScalarSizeInBits();
2985 if (!DL || MidSize < DL->getPointerTypeSizeInBits(SrcTy))
2986 return 0;
2987
2988 return Instruction::BitCast;
2989 }
2990 case 8: {
2991 // ext, trunc -> bitcast, if the SrcTy and DstTy are the same
2992 // ext, trunc -> ext, if sizeof(SrcTy) < sizeof(DstTy)
2993 // ext, trunc -> trunc, if sizeof(SrcTy) > sizeof(DstTy)
2994 unsigned SrcSize = SrcTy->getScalarSizeInBits();
2995 unsigned DstSize = DstTy->getScalarSizeInBits();
2996 if (SrcTy == DstTy)
2997 return Instruction::BitCast;
2998 if (SrcSize < DstSize)
2999 return firstOp;
3000 if (SrcSize > DstSize)
3001 return secondOp;
3002 return 0;
3003 }
3004 case 9:
3005 // zext, sext -> zext, because sext can't sign extend after zext
3006 return Instruction::ZExt;
3007 case 11: {
3008 // inttoptr, ptrtoint/ptrtoaddr -> integer cast
3009 if (!DL)
3010 return 0;
3011 unsigned MidSize = secondOp == Instruction::PtrToAddr
3012 ? DL->getAddressSizeInBits(MidTy)
3013 : DL->getPointerTypeSizeInBits(MidTy);
3014 unsigned SrcSize = SrcTy->getScalarSizeInBits();
3015 unsigned DstSize = DstTy->getScalarSizeInBits();
3016 // If the middle size is smaller than both source and destination,
3017 // an additional masking operation would be required.
3018 if (MidSize < SrcSize && MidSize < DstSize)
3019 return 0;
3020 if (DstSize < SrcSize)
3021 return Instruction::Trunc;
3022 if (DstSize > SrcSize)
3023 return Instruction::ZExt;
3024 return Instruction::BitCast;
3025 }
3026 case 12:
3027 // addrspacecast, addrspacecast -> bitcast, if SrcAS == DstAS
3028 // addrspacecast, addrspacecast -> addrspacecast, if SrcAS != DstAS
3029 if (SrcTy->getPointerAddressSpace() != DstTy->getPointerAddressSpace())
3030 return Instruction::AddrSpaceCast;
3031 return Instruction::BitCast;
3032 case 13:
3033 // FIXME: this state can be merged with (1), but the following assert
3034 // is useful to check the correcteness of the sequence due to semantic
3035 // change of bitcast.
3036 assert(
3037 SrcTy->isPtrOrPtrVectorTy() &&
3038 MidTy->isPtrOrPtrVectorTy() &&
3039 DstTy->isPtrOrPtrVectorTy() &&
3040 SrcTy->getPointerAddressSpace() != MidTy->getPointerAddressSpace() &&
3041 MidTy->getPointerAddressSpace() == DstTy->getPointerAddressSpace() &&
3042 "Illegal addrspacecast, bitcast sequence!");
3043 // Allowed, use first cast's opcode
3044 return firstOp;
3045 case 14:
3046 // bitcast, addrspacecast -> addrspacecast
3047 return Instruction::AddrSpaceCast;
3048 case 15:
3049 // FIXME: this state can be merged with (1), but the following assert
3050 // is useful to check the correcteness of the sequence due to semantic
3051 // change of bitcast.
3052 assert(
3053 SrcTy->isIntOrIntVectorTy() &&
3054 MidTy->isPtrOrPtrVectorTy() &&
3055 DstTy->isPtrOrPtrVectorTy() &&
3056 MidTy->getPointerAddressSpace() == DstTy->getPointerAddressSpace() &&
3057 "Illegal inttoptr, bitcast sequence!");
3058 // Allowed, use first cast's opcode
3059 return firstOp;
3060 case 16:
3061 // FIXME: this state can be merged with (2), but the following assert
3062 // is useful to check the correcteness of the sequence due to semantic
3063 // change of bitcast.
3064 assert(
3065 SrcTy->isPtrOrPtrVectorTy() &&
3066 MidTy->isPtrOrPtrVectorTy() &&
3067 DstTy->isIntOrIntVectorTy() &&
3068 SrcTy->getPointerAddressSpace() == MidTy->getPointerAddressSpace() &&
3069 "Illegal bitcast, ptrtoint sequence!");
3070 // Allowed, use second cast's opcode
3071 return secondOp;
3072 case 17:
3073 // (sitofp (zext x)) -> (uitofp x)
3074 return Instruction::UIToFP;
3075 case 99:
3076 // Cast combination can't happen (error in input). This is for all cases
3077 // where the MidTy is not the same for the two cast instructions.
3078 llvm_unreachable("Invalid Cast Combination");
3079 default:
3080 llvm_unreachable("Error in CastResults table!!!");
3081 }
3082}
3083
3085 const Twine &Name, InsertPosition InsertBefore) {
3086 assert(castIsValid(op, S, Ty) && "Invalid cast!");
3087 // Construct and return the appropriate CastInst subclass
3088 switch (op) {
3089 case Trunc: return new TruncInst (S, Ty, Name, InsertBefore);
3090 case ZExt: return new ZExtInst (S, Ty, Name, InsertBefore);
3091 case SExt: return new SExtInst (S, Ty, Name, InsertBefore);
3092 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertBefore);
3093 case FPExt: return new FPExtInst (S, Ty, Name, InsertBefore);
3094 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertBefore);
3095 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertBefore);
3096 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertBefore);
3097 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertBefore);
3098 case PtrToAddr: return new PtrToAddrInst (S, Ty, Name, InsertBefore);
3099 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertBefore);
3100 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertBefore);
3101 case BitCast:
3102 return new BitCastInst(S, Ty, Name, InsertBefore);
3103 case AddrSpaceCast:
3104 return new AddrSpaceCastInst(S, Ty, Name, InsertBefore);
3105 default:
3106 llvm_unreachable("Invalid opcode provided");
3107 }
3108}
3109
3111 InsertPosition InsertBefore) {
3112 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
3113 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
3114 return Create(Instruction::ZExt, S, Ty, Name, InsertBefore);
3115}
3116
3118 InsertPosition InsertBefore) {
3119 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
3120 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
3121 return Create(Instruction::SExt, S, Ty, Name, InsertBefore);
3122}
3123
3125 InsertPosition InsertBefore) {
3126 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
3127 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
3128 return Create(Instruction::Trunc, S, Ty, Name, InsertBefore);
3129}
3130
3131/// Create a BitCast or a PtrToInt cast instruction
3133 InsertPosition InsertBefore) {
3134 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
3135 assert((Ty->isIntOrIntVectorTy() || Ty->isPtrOrPtrVectorTy()) &&
3136 "Invalid cast");
3137 assert(Ty->isVectorTy() == S->getType()->isVectorTy() && "Invalid cast");
3138 assert((!Ty->isVectorTy() ||
3139 cast<VectorType>(Ty)->getElementCount() ==
3140 cast<VectorType>(S->getType())->getElementCount()) &&
3141 "Invalid cast");
3142
3143 if (Ty->isIntOrIntVectorTy())
3144 return Create(Instruction::PtrToInt, S, Ty, Name, InsertBefore);
3145
3146 return CreatePointerBitCastOrAddrSpaceCast(S, Ty, Name, InsertBefore);
3147}
3148
3150 Value *S, Type *Ty, const Twine &Name, InsertPosition InsertBefore) {
3151 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
3152 assert(Ty->isPtrOrPtrVectorTy() && "Invalid cast");
3153
3154 if (S->getType()->getPointerAddressSpace() != Ty->getPointerAddressSpace())
3155 return Create(Instruction::AddrSpaceCast, S, Ty, Name, InsertBefore);
3156
3157 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
3158}
3159
3161 const Twine &Name,
3162 InsertPosition InsertBefore) {
3163 if (S->getType()->isPointerTy() && Ty->isIntegerTy())
3164 return Create(Instruction::PtrToInt, S, Ty, Name, InsertBefore);
3165 if (S->getType()->isIntegerTy() && Ty->isPointerTy())
3166 return Create(Instruction::IntToPtr, S, Ty, Name, InsertBefore);
3167
3168 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
3169}
3170
3172 const Twine &Name,
3173 InsertPosition InsertBefore) {
3174 assert(C->getType()->isIntOrIntVectorTy() && Ty->isIntOrIntVectorTy() &&
3175 "Invalid integer cast");
3176 unsigned SrcBits = C->getType()->getScalarSizeInBits();
3177 unsigned DstBits = Ty->getScalarSizeInBits();
3178 Instruction::CastOps opcode =
3179 (SrcBits == DstBits ? Instruction::BitCast :
3180 (SrcBits > DstBits ? Instruction::Trunc :
3181 (isSigned ? Instruction::SExt : Instruction::ZExt)));
3182 return Create(opcode, C, Ty, Name, InsertBefore);
3183}
3184
3186 InsertPosition InsertBefore) {
3187 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
3188 "Invalid cast");
3189 unsigned SrcBits = C->getType()->getScalarSizeInBits();
3190 unsigned DstBits = Ty->getScalarSizeInBits();
3191 assert((C->getType() == Ty || SrcBits != DstBits) && "Invalid cast");
3192 Instruction::CastOps opcode =
3193 (SrcBits == DstBits ? Instruction::BitCast :
3194 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
3195 return Create(opcode, C, Ty, Name, InsertBefore);
3196}
3197
3198bool CastInst::isBitCastable(Type *SrcTy, Type *DestTy) {
3199 if (!SrcTy->isFirstClassType() || !DestTy->isFirstClassType())
3200 return false;
3201
3202 if (SrcTy == DestTy)
3203 return true;
3204
3205 if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy)) {
3206 if (VectorType *DestVecTy = dyn_cast<VectorType>(DestTy)) {
3207 if (SrcVecTy->getElementCount() == DestVecTy->getElementCount()) {
3208 // An element by element cast. Valid if casting the elements is valid.
3209 SrcTy = SrcVecTy->getElementType();
3210 DestTy = DestVecTy->getElementType();
3211 }
3212 }
3213 }
3214
3215 if (PointerType *DestPtrTy = dyn_cast<PointerType>(DestTy)) {
3216 if (PointerType *SrcPtrTy = dyn_cast<PointerType>(SrcTy)) {
3217 return SrcPtrTy->getAddressSpace() == DestPtrTy->getAddressSpace();
3218 }
3219 }
3220
3221 TypeSize SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr
3222 TypeSize DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr
3223
3224 // Could still have vectors of pointers if the number of elements doesn't
3225 // match
3226 if (SrcBits.getKnownMinValue() == 0 || DestBits.getKnownMinValue() == 0)
3227 return false;
3228
3229 if (SrcBits != DestBits)
3230 return false;
3231
3232 return true;
3233}
3234
3236 const DataLayout &DL) {
3237 // ptrtoint and inttoptr are not allowed on non-integral pointers
3238 if (auto *PtrTy = dyn_cast<PointerType>(SrcTy))
3239 if (auto *IntTy = dyn_cast<IntegerType>(DestTy))
3240 return (IntTy->getBitWidth() == DL.getPointerTypeSizeInBits(PtrTy) &&
3241 !DL.isNonIntegralPointerType(PtrTy));
3242 if (auto *PtrTy = dyn_cast<PointerType>(DestTy))
3243 if (auto *IntTy = dyn_cast<IntegerType>(SrcTy))
3244 return (IntTy->getBitWidth() == DL.getPointerTypeSizeInBits(PtrTy) &&
3245 !DL.isNonIntegralPointerType(PtrTy));
3246
3247 return isBitCastable(SrcTy, DestTy);
3248}
3249
3250// Provide a way to get a "cast" where the cast opcode is inferred from the
3251// types and size of the operand. This, basically, is a parallel of the
3252// logic in the castIsValid function below. This axiom should hold:
3253// castIsValid( getCastOpcode(Val, Ty), Val, Ty)
3254// should not assert in castIsValid. In other words, this produces a "correct"
3255// casting opcode for the arguments passed to it.
3258 const Value *Src, bool SrcIsSigned, Type *DestTy, bool DestIsSigned) {
3259 Type *SrcTy = Src->getType();
3260
3261 assert(SrcTy->isFirstClassType() && DestTy->isFirstClassType() &&
3262 "Only first class types are castable!");
3263
3264 if (SrcTy == DestTy)
3265 return BitCast;
3266
3267 // FIXME: Check address space sizes here
3268 if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy))
3269 if (VectorType *DestVecTy = dyn_cast<VectorType>(DestTy))
3270 if (SrcVecTy->getElementCount() == DestVecTy->getElementCount()) {
3271 // An element by element cast. Find the appropriate opcode based on the
3272 // element types.
3273 SrcTy = SrcVecTy->getElementType();
3274 DestTy = DestVecTy->getElementType();
3275 }
3276
3277 // Get the bit sizes, we'll need these
3278 // FIXME: This doesn't work for scalable vector types with different element
3279 // counts that don't call getElementType above.
3280 unsigned SrcBits =
3281 SrcTy->getPrimitiveSizeInBits().getFixedValue(); // 0 for ptr
3282 unsigned DestBits =
3283 DestTy->getPrimitiveSizeInBits().getFixedValue(); // 0 for ptr
3284
3285 // Run through the possibilities ...
3286 if (DestTy->isByteTy()) { // Casting to byte
3287 if (SrcTy->isIntegerTy()) { // Casting from integral
3288 assert(DestBits == SrcBits && "Illegal cast from integer to byte type");
3289 return BitCast;
3290 } else if (SrcTy->isPointerTy()) { // Casting from pointer
3291 assert(DestBits == SrcBits && "Illegal cast from pointer to byte type");
3292 return BitCast;
3293 }
3294 llvm_unreachable("Illegal cast to byte type");
3295 } else if (DestTy->isIntegerTy()) { // Casting to integral
3296 if (SrcTy->isIntegerTy()) { // Casting from integral
3297 if (DestBits < SrcBits)
3298 return Trunc; // int -> smaller int
3299 else if (DestBits > SrcBits) { // its an extension
3300 if (SrcIsSigned)
3301 return SExt; // signed -> SEXT
3302 else
3303 return ZExt; // unsigned -> ZEXT
3304 } else {
3305 return BitCast; // Same size, No-op cast
3306 }
3307 } else if (SrcTy->isFloatingPointTy()) { // Casting from floating pt
3308 if (DestIsSigned)
3309 return FPToSI; // FP -> sint
3310 else
3311 return FPToUI; // FP -> uint
3312 } else if (SrcTy->isVectorTy()) {
3313 assert(DestBits == SrcBits &&
3314 "Casting vector to integer of different width");
3315 return BitCast; // Same size, no-op cast
3316 } else {
3317 assert(SrcTy->isPointerTy() &&
3318 "Casting from a value that is not first-class type");
3319 return PtrToInt; // ptr -> int
3320 }
3321 } else if (DestTy->isFloatingPointTy()) { // Casting to floating pt
3322 if (SrcTy->isIntegerTy()) { // Casting from integral
3323 if (SrcIsSigned)
3324 return SIToFP; // sint -> FP
3325 else
3326 return UIToFP; // uint -> FP
3327 } else if (SrcTy->isFloatingPointTy()) { // Casting from floating pt
3328 if (DestBits < SrcBits) {
3329 return FPTrunc; // FP -> smaller FP
3330 } else if (DestBits > SrcBits) {
3331 return FPExt; // FP -> larger FP
3332 } else {
3333 return BitCast; // same size, no-op cast
3334 }
3335 } else if (SrcTy->isVectorTy()) {
3336 assert(DestBits == SrcBits &&
3337 "Casting vector to floating point of different width");
3338 return BitCast; // same size, no-op cast
3339 }
3340 llvm_unreachable("Casting pointer or non-first class to float");
3341 } else if (DestTy->isVectorTy()) {
3342 assert(DestBits == SrcBits &&
3343 "Illegal cast to vector (wrong type or size)");
3344 return BitCast;
3345 } else if (DestTy->isPointerTy()) {
3346 if (SrcTy->isPointerTy()) {
3347 if (DestTy->getPointerAddressSpace() != SrcTy->getPointerAddressSpace())
3348 return AddrSpaceCast;
3349 return BitCast; // ptr -> ptr
3350 } else if (SrcTy->isIntegerTy()) {
3351 return IntToPtr; // int -> ptr
3352 }
3353 llvm_unreachable("Casting pointer to other than pointer or int");
3354 }
3355 llvm_unreachable("Casting to type that is not first-class");
3356}
3357
3358//===----------------------------------------------------------------------===//
3359// CastInst SubClass Constructors
3360//===----------------------------------------------------------------------===//
3361
3362/// Check that the construction parameters for a CastInst are correct. This
3363/// could be broken out into the separate constructors but it is useful to have
3364/// it in one place and to eliminate the redundant code for getting the sizes
3365/// of the types involved.
3366bool
3368 if (!SrcTy->isFirstClassType() || !DstTy->isFirstClassType() ||
3369 SrcTy->isAggregateType() || DstTy->isAggregateType())
3370 return false;
3371
3372 // Get the size of the types in bits, and whether we are dealing
3373 // with vector types, we'll need this later.
3374 bool SrcIsVec = isa<VectorType>(SrcTy);
3375 bool DstIsVec = isa<VectorType>(DstTy);
3376 unsigned SrcScalarBitSize = SrcTy->getScalarSizeInBits();
3377 unsigned DstScalarBitSize = DstTy->getScalarSizeInBits();
3378
3379 // If these are vector types, get the lengths of the vectors (using zero for
3380 // scalar types means that checking that vector lengths match also checks that
3381 // scalars are not being converted to vectors or vectors to scalars).
3382 ElementCount SrcEC = SrcIsVec ? cast<VectorType>(SrcTy)->getElementCount()
3384 ElementCount DstEC = DstIsVec ? cast<VectorType>(DstTy)->getElementCount()
3386
3387 // Switch on the opcode provided
3388 switch (op) {
3389 default: return false; // This is an input error
3390 case Instruction::Trunc:
3391 return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() &&
3392 SrcEC == DstEC && SrcScalarBitSize > DstScalarBitSize;
3393 case Instruction::ZExt:
3394 return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() &&
3395 SrcEC == DstEC && SrcScalarBitSize < DstScalarBitSize;
3396 case Instruction::SExt:
3397 return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() &&
3398 SrcEC == DstEC && SrcScalarBitSize < DstScalarBitSize;
3399 case Instruction::FPTrunc:
3400 return SrcTy->isFPOrFPVectorTy() && DstTy->isFPOrFPVectorTy() &&
3401 SrcEC == DstEC && SrcScalarBitSize > DstScalarBitSize;
3402 case Instruction::FPExt:
3403 return SrcTy->isFPOrFPVectorTy() && DstTy->isFPOrFPVectorTy() &&
3404 SrcEC == DstEC && SrcScalarBitSize < DstScalarBitSize;
3405 case Instruction::UIToFP:
3406 case Instruction::SIToFP:
3407 return SrcTy->isIntOrIntVectorTy() && DstTy->isFPOrFPVectorTy() &&
3408 SrcEC == DstEC;
3409 case Instruction::FPToUI:
3410 case Instruction::FPToSI:
3411 return SrcTy->isFPOrFPVectorTy() && DstTy->isIntOrIntVectorTy() &&
3412 SrcEC == DstEC;
3413 case Instruction::PtrToAddr:
3414 case Instruction::PtrToInt:
3415 if (SrcEC != DstEC)
3416 return false;
3417 return SrcTy->isPtrOrPtrVectorTy() && DstTy->isIntOrIntVectorTy();
3418 case Instruction::IntToPtr:
3419 if (SrcEC != DstEC)
3420 return false;
3421 return SrcTy->isIntOrIntVectorTy() && DstTy->isPtrOrPtrVectorTy();
3422 case Instruction::BitCast: {
3423 PointerType *SrcPtrTy = dyn_cast<PointerType>(SrcTy->getScalarType());
3424 PointerType *DstPtrTy = dyn_cast<PointerType>(DstTy->getScalarType());
3425
3426 // BitCast implies a no-op cast of type only. No bits change.
3427 // However, you can't cast pointers to anything but pointers/bytes.
3428 if ((SrcPtrTy && DstTy->isByteOrByteVectorTy()) ||
3429 (SrcTy->isByteOrByteVectorTy() && DstPtrTy))
3430 return true;
3431 if (!SrcPtrTy != !DstPtrTy)
3432 return false;
3433
3434 // For non-pointer cases, the cast is okay if the source and destination bit
3435 // widths are identical.
3436 if (!SrcPtrTy)
3437 return SrcTy->getPrimitiveSizeInBits() == DstTy->getPrimitiveSizeInBits();
3438
3439 // If both are pointers then the address spaces must match.
3440 if (SrcPtrTy->getAddressSpace() != DstPtrTy->getAddressSpace())
3441 return false;
3442
3443 // A vector of pointers must have the same number of elements.
3444 if (SrcIsVec && DstIsVec)
3445 return SrcEC == DstEC;
3446 if (SrcIsVec)
3447 return SrcEC == ElementCount::getFixed(1);
3448 if (DstIsVec)
3449 return DstEC == ElementCount::getFixed(1);
3450
3451 return true;
3452 }
3453 case Instruction::AddrSpaceCast: {
3454 PointerType *SrcPtrTy = dyn_cast<PointerType>(SrcTy->getScalarType());
3455 if (!SrcPtrTy)
3456 return false;
3457
3458 PointerType *DstPtrTy = dyn_cast<PointerType>(DstTy->getScalarType());
3459 if (!DstPtrTy)
3460 return false;
3461
3462 if (SrcPtrTy->getAddressSpace() == DstPtrTy->getAddressSpace())
3463 return false;
3464
3465 return SrcEC == DstEC;
3466 }
3467 }
3468}
3469
3471 InsertPosition InsertBefore)
3472 : CastInst(Ty, Trunc, S, Name, InsertBefore) {
3473 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
3474}
3475
3476ZExtInst::ZExtInst(Value *S, Type *Ty, const Twine &Name,
3477 InsertPosition InsertBefore)
3478 : CastInst(Ty, ZExt, S, Name, InsertBefore) {
3479 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
3480}
3481
3482SExtInst::SExtInst(Value *S, Type *Ty, const Twine &Name,
3483 InsertPosition InsertBefore)
3484 : CastInst(Ty, SExt, S, Name, InsertBefore) {
3485 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
3486}
3487
3489 InsertPosition InsertBefore)
3490 : CastInst(Ty, FPTrunc, S, Name, InsertBefore) {
3491 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
3492}
3493
3495 InsertPosition InsertBefore)
3496 : CastInst(Ty, FPExt, S, Name, InsertBefore) {
3497 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
3498}
3499
3501 InsertPosition InsertBefore)
3502 : CastInst(Ty, UIToFP, S, Name, InsertBefore) {
3503 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
3504}
3505
3507 InsertPosition InsertBefore)
3508 : CastInst(Ty, SIToFP, S, Name, InsertBefore) {
3509 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
3510}
3511
3513 InsertPosition InsertBefore)
3514 : CastInst(Ty, FPToUI, S, Name, InsertBefore) {
3515 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
3516}
3517
3519 InsertPosition InsertBefore)
3520 : CastInst(Ty, FPToSI, S, Name, InsertBefore) {
3521 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
3522}
3523
3525 InsertPosition InsertBefore)
3526 : CastInst(Ty, PtrToInt, S, Name, InsertBefore) {
3527 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
3528}
3529
3531 InsertPosition InsertBefore)
3532 : CastInst(Ty, PtrToAddr, S, Name, InsertBefore) {
3533 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToAddr");
3534}
3535
3537 InsertPosition InsertBefore)
3538 : CastInst(Ty, IntToPtr, S, Name, InsertBefore) {
3539 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
3540}
3541
3543 InsertPosition InsertBefore)
3544 : CastInst(Ty, BitCast, S, Name, InsertBefore) {
3545 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
3546}
3547
3549 InsertPosition InsertBefore)
3550 : CastInst(Ty, AddrSpaceCast, S, Name, InsertBefore) {
3551 assert(castIsValid(getOpcode(), S, Ty) && "Illegal AddrSpaceCast");
3552}
3553
3554//===----------------------------------------------------------------------===//
3555// CmpInst Classes
3556//===----------------------------------------------------------------------===//
3557
3559 Value *RHS, const Twine &Name, InsertPosition InsertBefore)
3560 : Instruction(ty, op, AllocMarker, InsertBefore) {
3561 Op<0>() = LHS;
3562 Op<1>() = RHS;
3563 setPredicate(predicate);
3564 setName(Name);
3565}
3566
3568 const Twine &Name, InsertPosition InsertBefore) {
3569 if (Op == Instruction::ICmp) {
3570 if (InsertBefore.isValid())
3571 return new ICmpInst(InsertBefore, CmpInst::Predicate(predicate),
3572 S1, S2, Name);
3573 else
3574 return new ICmpInst(CmpInst::Predicate(predicate),
3575 S1, S2, Name);
3576 }
3577
3578 if (InsertBefore.isValid())
3579 return new FCmpInst(InsertBefore, CmpInst::Predicate(predicate),
3580 S1, S2, Name);
3581 else
3582 return new FCmpInst(CmpInst::Predicate(predicate),
3583 S1, S2, Name);
3584}
3585
3587 Value *S2,
3588 const Instruction *FlagsSource,
3589 const Twine &Name,
3590 InsertPosition InsertBefore) {
3591 CmpInst *Inst = Create(Op, Pred, S1, S2, Name, InsertBefore);
3592 Inst->copyIRFlags(FlagsSource);
3593 return Inst;
3594}
3595
3597 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
3598 IC->swapOperands();
3599 else
3600 cast<FCmpInst>(this)->swapOperands();
3601}
3602
3604 if (const ICmpInst *IC = dyn_cast<ICmpInst>(this))
3605 return IC->isCommutative();
3606 return cast<FCmpInst>(this)->isCommutative();
3607}
3608
3611 return ICmpInst::isEquality(P);
3613 return FCmpInst::isEquality(P);
3614 llvm_unreachable("Unsupported predicate kind");
3615}
3616
3617// Returns true if either operand of CmpInst is a provably non-zero
3618// floating-point constant.
3619static bool hasNonZeroFPOperands(const CmpInst *Cmp) {
3620 auto *LHS = dyn_cast<Constant>(Cmp->getOperand(0));
3621 auto *RHS = dyn_cast<Constant>(Cmp->getOperand(1));
3622 if (auto *Const = LHS ? LHS : RHS) {
3623 using namespace llvm::PatternMatch;
3624 return match(Const, m_NonZeroNotDenormalFP());
3625 }
3626 return false;
3627}
3628
3629// Floating-point equality is not an equivalence when comparing +0.0 with
3630// -0.0, when comparing NaN with another value, or when flushing
3631// denormals-to-zero.
3632bool CmpInst::isEquivalence(bool Invert) const {
3633 switch (Invert ? getInversePredicate() : getPredicate()) {
3635 return true;
3637 if (!hasNoNaNs())
3638 return false;
3639 [[fallthrough]];
3641 return hasNonZeroFPOperands(this);
3642 default:
3643 return false;
3644 }
3645}
3646
3648 switch (pred) {
3649 default: llvm_unreachable("Unknown cmp predicate!");
3650 case ICMP_EQ: return ICMP_NE;
3651 case ICMP_NE: return ICMP_EQ;
3652 case ICMP_UGT: return ICMP_ULE;
3653 case ICMP_ULT: return ICMP_UGE;
3654 case ICMP_UGE: return ICMP_ULT;
3655 case ICMP_ULE: return ICMP_UGT;
3656 case ICMP_SGT: return ICMP_SLE;
3657 case ICMP_SLT: return ICMP_SGE;
3658 case ICMP_SGE: return ICMP_SLT;
3659 case ICMP_SLE: return ICMP_SGT;
3660
3661 case FCMP_OEQ: return FCMP_UNE;
3662 case FCMP_ONE: return FCMP_UEQ;
3663 case FCMP_OGT: return FCMP_ULE;
3664 case FCMP_OLT: return FCMP_UGE;
3665 case FCMP_OGE: return FCMP_ULT;
3666 case FCMP_OLE: return FCMP_UGT;
3667 case FCMP_UEQ: return FCMP_ONE;
3668 case FCMP_UNE: return FCMP_OEQ;
3669 case FCMP_UGT: return FCMP_OLE;
3670 case FCMP_ULT: return FCMP_OGE;
3671 case FCMP_UGE: return FCMP_OLT;
3672 case FCMP_ULE: return FCMP_OGT;
3673 case FCMP_ORD: return FCMP_UNO;
3674 case FCMP_UNO: return FCMP_ORD;
3675 case FCMP_TRUE: return FCMP_FALSE;
3676 case FCMP_FALSE: return FCMP_TRUE;
3677 }
3678}
3679
3681 switch (Pred) {
3682 default: return "unknown";
3683 case FCmpInst::FCMP_FALSE: return "false";
3684 case FCmpInst::FCMP_OEQ: return "oeq";
3685 case FCmpInst::FCMP_OGT: return "ogt";
3686 case FCmpInst::FCMP_OGE: return "oge";
3687 case FCmpInst::FCMP_OLT: return "olt";
3688 case FCmpInst::FCMP_OLE: return "ole";
3689 case FCmpInst::FCMP_ONE: return "one";
3690 case FCmpInst::FCMP_ORD: return "ord";
3691 case FCmpInst::FCMP_UNO: return "uno";
3692 case FCmpInst::FCMP_UEQ: return "ueq";
3693 case FCmpInst::FCMP_UGT: return "ugt";
3694 case FCmpInst::FCMP_UGE: return "uge";
3695 case FCmpInst::FCMP_ULT: return "ult";
3696 case FCmpInst::FCMP_ULE: return "ule";
3697 case FCmpInst::FCMP_UNE: return "une";
3698 case FCmpInst::FCMP_TRUE: return "true";
3699 case ICmpInst::ICMP_EQ: return "eq";
3700 case ICmpInst::ICMP_NE: return "ne";
3701 case ICmpInst::ICMP_SGT: return "sgt";
3702 case ICmpInst::ICMP_SGE: return "sge";
3703 case ICmpInst::ICMP_SLT: return "slt";
3704 case ICmpInst::ICMP_SLE: return "sle";
3705 case ICmpInst::ICMP_UGT: return "ugt";
3706 case ICmpInst::ICMP_UGE: return "uge";
3707 case ICmpInst::ICMP_ULT: return "ult";
3708 case ICmpInst::ICMP_ULE: return "ule";
3709 }
3710}
3711
3713 OS << CmpInst::getPredicateName(Pred);
3714 return OS;
3715}
3716
3718 switch (pred) {
3719 default: llvm_unreachable("Unknown icmp predicate!");
3720 case ICMP_EQ: case ICMP_NE:
3721 case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE:
3722 return pred;
3723 case ICMP_UGT: return ICMP_SGT;
3724 case ICMP_ULT: return ICMP_SLT;
3725 case ICMP_UGE: return ICMP_SGE;
3726 case ICMP_ULE: return ICMP_SLE;
3727 }
3728}
3729
3731 switch (pred) {
3732 default: llvm_unreachable("Unknown icmp predicate!");
3733 case ICMP_EQ: case ICMP_NE:
3734 case ICMP_UGT: case ICMP_ULT: case ICMP_UGE: case ICMP_ULE:
3735 return pred;
3736 case ICMP_SGT: return ICMP_UGT;
3737 case ICMP_SLT: return ICMP_ULT;
3738 case ICMP_SGE: return ICMP_UGE;
3739 case ICMP_SLE: return ICMP_ULE;
3740 }
3741}
3742
3744 switch (pred) {
3745 default: llvm_unreachable("Unknown cmp predicate!");
3746 case ICMP_EQ: case ICMP_NE:
3747 return pred;
3748 case ICMP_SGT: return ICMP_SLT;
3749 case ICMP_SLT: return ICMP_SGT;
3750 case ICMP_SGE: return ICMP_SLE;
3751 case ICMP_SLE: return ICMP_SGE;
3752 case ICMP_UGT: return ICMP_ULT;
3753 case ICMP_ULT: return ICMP_UGT;
3754 case ICMP_UGE: return ICMP_ULE;
3755 case ICMP_ULE: return ICMP_UGE;
3756
3757 case FCMP_FALSE: case FCMP_TRUE:
3758 case FCMP_OEQ: case FCMP_ONE:
3759 case FCMP_UEQ: case FCMP_UNE:
3760 case FCMP_ORD: case FCMP_UNO:
3761 return pred;
3762 case FCMP_OGT: return FCMP_OLT;
3763 case FCMP_OLT: return FCMP_OGT;
3764 case FCMP_OGE: return FCMP_OLE;
3765 case FCMP_OLE: return FCMP_OGE;
3766 case FCMP_UGT: return FCMP_ULT;
3767 case FCMP_ULT: return FCMP_UGT;
3768 case FCMP_UGE: return FCMP_ULE;
3769 case FCMP_ULE: return FCMP_UGE;
3770 }
3771}
3772
3774 switch (pred) {
3775 case ICMP_SGE:
3776 case ICMP_SLE:
3777 case ICMP_UGE:
3778 case ICMP_ULE:
3779 case FCMP_OGE:
3780 case FCMP_OLE:
3781 case FCMP_UGE:
3782 case FCMP_ULE:
3783 return true;
3784 default:
3785 return false;
3786 }
3787}
3788
3790 switch (pred) {
3791 case ICMP_SGT:
3792 case ICMP_SLT:
3793 case ICMP_UGT:
3794 case ICMP_ULT:
3795 case FCMP_OGT:
3796 case FCMP_OLT:
3797 case FCMP_UGT:
3798 case FCMP_ULT:
3799 return true;
3800 default:
3801 return false;
3802 }
3803}
3804
3806 switch (pred) {
3807 case ICMP_SGE:
3808 return ICMP_SGT;
3809 case ICMP_SLE:
3810 return ICMP_SLT;
3811 case ICMP_UGE:
3812 return ICMP_UGT;
3813 case ICMP_ULE:
3814 return ICMP_ULT;
3815 case FCMP_OGE:
3816 return FCMP_OGT;
3817 case FCMP_OLE:
3818 return FCMP_OLT;
3819 case FCMP_UGE:
3820 return FCMP_UGT;
3821 case FCMP_ULE:
3822 return FCMP_ULT;
3823 default:
3824 return pred;
3825 }
3826}
3827
3829 switch (pred) {
3830 case ICMP_SGT:
3831 return ICMP_SGE;
3832 case ICMP_SLT:
3833 return ICMP_SLE;
3834 case ICMP_UGT:
3835 return ICMP_UGE;
3836 case ICMP_ULT:
3837 return ICMP_ULE;
3838 case FCMP_OGT:
3839 return FCMP_OGE;
3840 case FCMP_OLT:
3841 return FCMP_OLE;
3842 case FCMP_UGT:
3843 return FCMP_UGE;
3844 case FCMP_ULT:
3845 return FCMP_ULE;
3846 default:
3847 return pred;
3848 }
3849}
3850
3852 assert(CmpInst::isRelational(pred) && "Call only with relational predicate!");
3853
3854 if (isStrictPredicate(pred))
3855 return getNonStrictPredicate(pred);
3856 if (isNonStrictPredicate(pred))
3857 return getStrictPredicate(pred);
3858
3859 llvm_unreachable("Unknown predicate!");
3860}
3861
3862bool ICmpInst::compare(const APInt &LHS, const APInt &RHS,
3863 ICmpInst::Predicate Pred) {
3864 assert(ICmpInst::isIntPredicate(Pred) && "Only for integer predicates!");
3865 switch (Pred) {
3867 return LHS.eq(RHS);
3869 return LHS.ne(RHS);
3871 return LHS.ugt(RHS);
3873 return LHS.uge(RHS);
3875 return LHS.ult(RHS);
3877 return LHS.ule(RHS);
3879 return LHS.sgt(RHS);
3881 return LHS.sge(RHS);
3883 return LHS.slt(RHS);
3885 return LHS.sle(RHS);
3886 default:
3887 llvm_unreachable("Unexpected non-integer predicate.");
3888 };
3889}
3890
3891bool FCmpInst::compare(const APFloat &LHS, const APFloat &RHS,
3892 FCmpInst::Predicate Pred) {
3893 APFloat::cmpResult R = LHS.compare(RHS);
3894 switch (Pred) {
3895 default:
3896 llvm_unreachable("Invalid FCmp Predicate");
3898 return false;
3900 return true;
3901 case FCmpInst::FCMP_UNO:
3902 return R == APFloat::cmpUnordered;
3903 case FCmpInst::FCMP_ORD:
3904 return R != APFloat::cmpUnordered;
3905 case FCmpInst::FCMP_UEQ:
3906 return R == APFloat::cmpUnordered || R == APFloat::cmpEqual;
3907 case FCmpInst::FCMP_OEQ:
3908 return R == APFloat::cmpEqual;
3909 case FCmpInst::FCMP_UNE:
3910 return R != APFloat::cmpEqual;
3911 case FCmpInst::FCMP_ONE:
3913 case FCmpInst::FCMP_ULT:
3914 return R == APFloat::cmpUnordered || R == APFloat::cmpLessThan;
3915 case FCmpInst::FCMP_OLT:
3916 return R == APFloat::cmpLessThan;
3917 case FCmpInst::FCMP_UGT:
3919 case FCmpInst::FCMP_OGT:
3920 return R == APFloat::cmpGreaterThan;
3921 case FCmpInst::FCMP_ULE:
3922 return R != APFloat::cmpGreaterThan;
3923 case FCmpInst::FCMP_OLE:
3924 return R == APFloat::cmpLessThan || R == APFloat::cmpEqual;
3925 case FCmpInst::FCMP_UGE:
3926 return R != APFloat::cmpLessThan;
3927 case FCmpInst::FCMP_OGE:
3928 return R == APFloat::cmpGreaterThan || R == APFloat::cmpEqual;
3929 }
3930}
3931
3932std::optional<bool> ICmpInst::compare(const KnownBits &LHS,
3933 const KnownBits &RHS,
3934 ICmpInst::Predicate Pred) {
3935 switch (Pred) {
3936 case ICmpInst::ICMP_EQ:
3937 return KnownBits::eq(LHS, RHS);
3938 case ICmpInst::ICMP_NE:
3939 return KnownBits::ne(LHS, RHS);
3940 case ICmpInst::ICMP_UGE:
3941 return KnownBits::uge(LHS, RHS);
3942 case ICmpInst::ICMP_UGT:
3943 return KnownBits::ugt(LHS, RHS);
3944 case ICmpInst::ICMP_ULE:
3945 return KnownBits::ule(LHS, RHS);
3946 case ICmpInst::ICMP_ULT:
3947 return KnownBits::ult(LHS, RHS);
3948 case ICmpInst::ICMP_SGE:
3949 return KnownBits::sge(LHS, RHS);
3950 case ICmpInst::ICMP_SGT:
3951 return KnownBits::sgt(LHS, RHS);
3952 case ICmpInst::ICMP_SLE:
3953 return KnownBits::sle(LHS, RHS);
3954 case ICmpInst::ICMP_SLT:
3955 return KnownBits::slt(LHS, RHS);
3956 default:
3957 llvm_unreachable("Unexpected non-integer predicate.");
3958 }
3959}
3960
3962 if (CmpInst::isEquality(pred))
3963 return pred;
3964 if (isSigned(pred))
3965 return getUnsignedPredicate(pred);
3966 if (isUnsigned(pred))
3967 return getSignedPredicate(pred);
3968
3969 llvm_unreachable("Unknown predicate!");
3970}
3971
3973 switch (predicate) {
3974 default: return false;
3977 case FCmpInst::FCMP_ORD: return true;
3978 }
3979}
3980
3982 switch (predicate) {
3983 default: return false;
3986 case FCmpInst::FCMP_UNO: return true;
3987 }
3988}
3989
3991 switch(predicate) {
3992 default: return false;
3993 case ICMP_EQ: case ICMP_UGE: case ICMP_ULE: case ICMP_SGE: case ICMP_SLE:
3994 case FCMP_TRUE: case FCMP_UEQ: case FCMP_UGE: case FCMP_ULE: return true;
3995 }
3996}
3997
3999 switch(predicate) {
4000 case ICMP_NE: case ICMP_UGT: case ICMP_ULT: case ICMP_SGT: case ICMP_SLT:
4001 case FCMP_FALSE: case FCMP_ONE: case FCMP_OGT: case FCMP_OLT: return true;
4002 default: return false;
4003 }
4004}
4005
4007 // If the predicates match, then we know the first condition implies the
4008 // second is true.
4009 if (CmpPredicate::getMatching(Pred1, Pred2))
4010 return true;
4011
4012 if (Pred1.hasSameSign() && CmpInst::isSigned(Pred2))
4014 else if (Pred2.hasSameSign() && CmpInst::isSigned(Pred1))
4016
4017 switch (Pred1) {
4018 default:
4019 break;
4020 case CmpInst::ICMP_EQ:
4021 // A == B implies A >=u B, A <=u B, A >=s B, and A <=s B are true.
4022 return Pred2 == CmpInst::ICMP_UGE || Pred2 == CmpInst::ICMP_ULE ||
4023 Pred2 == CmpInst::ICMP_SGE || Pred2 == CmpInst::ICMP_SLE;
4024 case CmpInst::ICMP_UGT: // A >u B implies A != B and A >=u B are true.
4025 return Pred2 == CmpInst::ICMP_NE || Pred2 == CmpInst::ICMP_UGE;
4026 case CmpInst::ICMP_ULT: // A <u B implies A != B and A <=u B are true.
4027 return Pred2 == CmpInst::ICMP_NE || Pred2 == CmpInst::ICMP_ULE;
4028 case CmpInst::ICMP_SGT: // A >s B implies A != B and A >=s B are true.
4029 return Pred2 == CmpInst::ICMP_NE || Pred2 == CmpInst::ICMP_SGE;
4030 case CmpInst::ICMP_SLT: // A <s B implies A != B and A <=s B are true.
4031 return Pred2 == CmpInst::ICMP_NE || Pred2 == CmpInst::ICMP_SLE;
4032 }
4033 return false;
4034}
4035
4037 CmpPredicate Pred2) {
4038 return isImpliedTrueByMatchingCmp(Pred1,
4040}
4041
4043 CmpPredicate Pred2) {
4044 if (isImpliedTrueByMatchingCmp(Pred1, Pred2))
4045 return true;
4046 if (isImpliedFalseByMatchingCmp(Pred1, Pred2))
4047 return false;
4048 return std::nullopt;
4049}
4050
4051//===----------------------------------------------------------------------===//
4052// CmpPredicate Implementation
4053//===----------------------------------------------------------------------===//
4054
4055std::optional<CmpPredicate> CmpPredicate::getMatching(CmpPredicate A,
4056 CmpPredicate B) {
4057 if (A.Pred == B.Pred)
4058 return A.HasSameSign == B.HasSameSign ? A : CmpPredicate(A.Pred);
4060 return {};
4061 if (A.HasSameSign &&
4063 return B.Pred;
4064 if (B.HasSameSign &&
4066 return A.Pred;
4067 return {};
4068}
4069
4073
4075 if (auto *ICI = dyn_cast<ICmpInst>(Cmp))
4076 return ICI->getCmpPredicate();
4077 return Cmp->getPredicate();
4078}
4079
4083
4087
4089 return getSwapped(get(Cmp));
4090}
4091
4092//===----------------------------------------------------------------------===//
4093// SwitchInst Implementation
4094//===----------------------------------------------------------------------===//
4095
4096void SwitchInst::init(Value *Value, BasicBlock *Default, unsigned NumReserved) {
4097 assert(Value && Default && NumReserved);
4098 ReservedSpace = NumReserved;
4100 allocHungoffUses(ReservedSpace);
4101
4102 Op<0>() = Value;
4103 Op<1>() = Default;
4104}
4105
4106/// SwitchInst ctor - Create a new switch instruction, specifying a value to
4107/// switch on and a default destination. The number of additional cases can
4108/// be specified here to make memory allocation more efficient. This
4109/// constructor can also autoinsert before another instruction.
4110SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
4111 InsertPosition InsertBefore)
4112 : Instruction(Type::getVoidTy(Value->getContext()), Instruction::Switch,
4113 AllocMarker, InsertBefore) {
4114 init(Value, Default, 2 + NumCases);
4115}
4116
4117SwitchInst::SwitchInst(const SwitchInst &SI)
4118 : Instruction(SI.getType(), Instruction::Switch, AllocMarker) {
4119 init(SI.getCondition(), SI.getDefaultDest(), SI.getNumOperands());
4120 setNumHungOffUseOperands(SI.getNumOperands());
4121 Use *OL = getOperandList();
4122 ConstantInt **VL = case_values();
4123 const Use *InOL = SI.getOperandList();
4124 ConstantInt *const *InVL = SI.case_values();
4125 for (unsigned i = 2, E = SI.getNumOperands(); i != E; ++i) {
4126 OL[i] = InOL[i];
4127 VL[i - 2] = InVL[i - 2];
4128 }
4129 SubclassOptionalData = SI.SubclassOptionalData;
4130}
4131
4132/// addCase - Add an entry to the switch instruction...
4133///
4135 unsigned NewCaseIdx = getNumCases();
4136 unsigned OpNo = getNumOperands();
4137 if (OpNo + 1 > ReservedSpace)
4138 growOperands(); // Get more space!
4139 // Initialize some new operands.
4140 assert(OpNo < ReservedSpace && "Growing didn't work!");
4141 setNumHungOffUseOperands(OpNo + 1);
4142 CaseHandle Case(this, NewCaseIdx);
4143 Case.setValue(OnVal);
4144 Case.setSuccessor(Dest);
4145}
4146
4147/// removeCase - This method removes the specified case and its successor
4148/// from the switch instruction.
4150 unsigned idx = I->getCaseIndex();
4151
4152 assert(2 + idx < getNumOperands() && "Case index out of range!!!");
4153
4154 unsigned NumOps = getNumOperands();
4155 Use *OL = getOperandList();
4156 ConstantInt **VL = case_values();
4157
4158 // Overwrite this case with the end of the list.
4159 if (2 + idx + 1 != NumOps) {
4160 OL[2 + idx] = OL[NumOps - 1];
4161 VL[idx] = VL[NumOps - 2 - 1];
4162 }
4163
4164 // Nuke the last value.
4165 OL[NumOps - 1].set(nullptr);
4166 VL[NumOps - 2 - 1] = nullptr;
4168
4169 return CaseIt(this, idx);
4170}
4171
4172/// growOperands - grow operands - This grows the operand list in response
4173/// to a push_back style of operation. This grows the number of ops by 3 times.
4174///
4175void SwitchInst::growOperands() {
4176 unsigned e = getNumOperands();
4177 unsigned NumOps = e*3;
4178
4179 ReservedSpace = NumOps;
4180 growHungoffUses(ReservedSpace, /*WithExtraValues=*/true);
4181}
4182
4184 MDNode *ProfileData = getBranchWeightMDNode(SI);
4185 if (!ProfileData)
4186 return;
4187
4188 if (getNumBranchWeights(*ProfileData) != SI.getNumSuccessors()) {
4189 llvm_unreachable("number of prof branch_weights metadata operands does "
4190 "not correspond to number of succesors");
4191 }
4192
4194 if (!extractBranchWeights(ProfileData, Weights))
4195 return;
4196 this->Weights = std::move(Weights);
4197}
4198
4201 if (Weights) {
4202 assert(SI.getNumSuccessors() == Weights->size() &&
4203 "num of prof branch_weights must accord with num of successors");
4204 Changed = true;
4205 // Copy the last case to the place of the removed one and shrink.
4206 // This is tightly coupled with the way SwitchInst::removeCase() removes
4207 // the cases in SwitchInst::removeCase(CaseIt).
4208 (*Weights)[I->getCaseIndex() + 1] = Weights->back();
4209 Weights->pop_back();
4210 }
4211 return SI.removeCase(I);
4212}
4213
4215 auto *DestBlock = I->getCaseSuccessor();
4216 if (Weights) {
4217 auto Weight = getSuccessorWeight(I->getCaseIndex() + 1);
4218 (*Weights)[0] = Weight.value();
4219 }
4220
4221 SI.setDefaultDest(DestBlock);
4222}
4223
4225 ConstantInt *OnVal, BasicBlock *Dest,
4227 SI.addCase(OnVal, Dest);
4228
4229 if (!Weights && W && *W) {
4230 Changed = true;
4231 Weights = SmallVector<uint32_t, 8>(SI.getNumSuccessors(), 0);
4232 (*Weights)[SI.getNumSuccessors() - 1] = *W;
4233 } else if (Weights) {
4234 Changed = true;
4235 Weights->push_back(W.value_or(0));
4236 }
4237 if (Weights)
4238 assert(SI.getNumSuccessors() == Weights->size() &&
4239 "num of prof branch_weights must accord with num of successors");
4240}
4241
4244 // Instruction is erased. Mark as unchanged to not touch it in the destructor.
4245 Changed = false;
4246 if (Weights)
4247 Weights->resize(0);
4248 return SI.eraseFromParent();
4249}
4250
4253 if (!Weights)
4254 return std::nullopt;
4255 return (*Weights)[idx];
4256}
4257
4260 if (!W)
4261 return;
4262
4263 if (!Weights && *W)
4264 Weights = SmallVector<uint32_t, 8>(SI.getNumSuccessors(), 0);
4265
4266 if (Weights) {
4267 auto &OldW = (*Weights)[idx];
4268 if (*W != OldW) {
4269 Changed = true;
4270 OldW = *W;
4271 }
4272 }
4273}
4274
4277 unsigned idx) {
4278 if (MDNode *ProfileData = getValidBranchWeightMDNode(SI)) {
4279 SmallVector<uint32_t> Weights;
4280 extractFromBranchWeightMD32(ProfileData, Weights);
4281 return Weights[idx];
4282 }
4283
4284 return std::nullopt;
4285}
4286
4287//===----------------------------------------------------------------------===//
4288// IndirectBrInst Implementation
4289//===----------------------------------------------------------------------===//
4290
4291void IndirectBrInst::init(Value *Address, unsigned NumDests) {
4292 assert(Address && Address->getType()->isPointerTy() &&
4293 "Address of indirectbr must be a pointer");
4294 ReservedSpace = 1+NumDests;
4296 allocHungoffUses(ReservedSpace);
4297
4298 Op<0>() = Address;
4299}
4300
4301
4302/// growOperands - grow operands - This grows the operand list in response
4303/// to a push_back style of operation. This grows the number of ops by 2 times.
4304///
4305void IndirectBrInst::growOperands() {
4306 unsigned e = getNumOperands();
4307 unsigned NumOps = e*2;
4308
4309 ReservedSpace = NumOps;
4310 growHungoffUses(ReservedSpace);
4311}
4312
4313IndirectBrInst::IndirectBrInst(Value *Address, unsigned NumCases,
4314 InsertPosition InsertBefore)
4315 : Instruction(Type::getVoidTy(Address->getContext()),
4316 Instruction::IndirectBr, AllocMarker, InsertBefore) {
4317 init(Address, NumCases);
4318}
4319
4320IndirectBrInst::IndirectBrInst(const IndirectBrInst &IBI)
4321 : Instruction(Type::getVoidTy(IBI.getContext()), Instruction::IndirectBr,
4322 AllocMarker) {
4323 NumUserOperands = IBI.NumUserOperands;
4324 allocHungoffUses(IBI.getNumOperands());
4325 Use *OL = getOperandList();
4326 const Use *InOL = IBI.getOperandList();
4327 for (unsigned i = 0, E = IBI.getNumOperands(); i != E; ++i)
4328 OL[i] = InOL[i];
4329 SubclassOptionalData = IBI.SubclassOptionalData;
4330}
4331
4332/// addDestination - Add a destination.
4333///
4335 unsigned OpNo = getNumOperands();
4336 if (OpNo+1 > ReservedSpace)
4337 growOperands(); // Get more space!
4338 // Initialize some new operands.
4339 assert(OpNo < ReservedSpace && "Growing didn't work!");
4341 getOperandList()[OpNo] = DestBB;
4342}
4343
4344/// removeDestination - This method removes the specified successor from the
4345/// indirectbr instruction.
4347 assert(idx < getNumOperands()-1 && "Successor index out of range!");
4348
4349 unsigned NumOps = getNumOperands();
4350 Use *OL = getOperandList();
4351
4352 // Replace this value with the last one.
4353 OL[idx+1] = OL[NumOps-1];
4354
4355 // Nuke the last value.
4356 OL[NumOps-1].set(nullptr);
4358}
4359
4360//===----------------------------------------------------------------------===//
4361// FreezeInst Implementation
4362//===----------------------------------------------------------------------===//
4363
4364FreezeInst::FreezeInst(Value *S, const Twine &Name, InsertPosition InsertBefore)
4365 : UnaryInstruction(S->getType(), Freeze, S, InsertBefore) {
4366 setName(Name);
4367}
4368
4369//===----------------------------------------------------------------------===//
4370// cloneImpl() implementations
4371//===----------------------------------------------------------------------===//
4372
4373// Define these methods here so vtables don't get emitted into every translation
4374// unit that uses these classes.
4375
4376GetElementPtrInst *GetElementPtrInst::cloneImpl() const {
4378 return new (AllocMarker) GetElementPtrInst(*this, AllocMarker);
4379}
4380
4384
4386 auto *I = static_cast<FPUnaryOperator *>(Create(getOpcode(), Op<0>()));
4387 I->FMF = FMF;
4388 return I;
4389}
4390
4393 "Should call FPBinaryOperator::cloneImpl!");
4394 return Create(getOpcode(), Op<0>(), Op<1>());
4395}
4396
4398 auto *I =
4399 static_cast<FPBinaryOperator *>(Create(getOpcode(), Op<0>(), Op<1>()));
4400 I->FMF = FMF;
4401 return I;
4402}
4403
4405 auto *I = new FCmpInst(getPredicate(), Op<0>(), Op<1>());
4406 I->FMF = FMF;
4407 return I;
4408}
4409
4411 auto *Result = new ICmpInst(getPredicate(), Op<0>(), Op<1>());
4412 Result->setSameSign(hasSameSign());
4413 return Result;
4414}
4415
4416ExtractValueInst *ExtractValueInst::cloneImpl() const {
4417 return new ExtractValueInst(*this);
4418}
4419
4420InsertValueInst *InsertValueInst::cloneImpl() const {
4421 return new InsertValueInst(*this);
4422}
4423
4426 getOperand(0), getAlign());
4427 Result->setUsedWithInAlloca(isUsedWithInAlloca());
4428 Result->setSwiftError(isSwiftError());
4429 return Result;
4430}
4431
4433 return new LoadInst(getType(), getOperand(0), Twine(), isVolatile(),
4435}
4436
4441
4446 Result->setVolatile(isVolatile());
4447 Result->setWeak(isWeak());
4448 return Result;
4449}
4450
4452 AtomicRMWInst *Result = new AtomicRMWInst(
4455 Result->setVolatile(isVolatile());
4456 return Result;
4457}
4458
4462
4464 return new TruncInst(getOperand(0), getType());
4465}
4466
4468 return new ZExtInst(getOperand(0), getType());
4469}
4470
4472 return new SExtInst(getOperand(0), getType());
4473}
4474
4476 auto *I = new FPTruncInst(getOperand(0), getType());
4477 I->FMF = FMF;
4478 return I;
4479}
4480
4482 auto *I = new FPExtInst(getOperand(0), getType());
4483 I->FMF = FMF;
4484 return I;
4485}
4486
4488 return new UIToFPInst(getOperand(0), getType());
4489}
4490
4492 return new SIToFPInst(getOperand(0), getType());
4493}
4494
4496 return new FPToUIInst(getOperand(0), getType());
4497}
4498
4500 return new FPToSIInst(getOperand(0), getType());
4501}
4502
4504 return new PtrToIntInst(getOperand(0), getType());
4505}
4506
4510
4512 return new IntToPtrInst(getOperand(0), getType());
4513}
4514
4516 return new BitCastInst(getOperand(0), getType());
4517}
4518
4522
4523CallInst *CallInst::cloneImpl() const {
4524 if (hasOperandBundles()) {
4528 return new (AllocMarker) CallInst(*this, AllocMarker);
4529 }
4531 return new (AllocMarker) CallInst(*this, AllocMarker);
4532}
4533
4534SelectInst *SelectInst::cloneImpl() const {
4536 I->FMF = FMF;
4537 return I;
4538}
4539
4541 return new VAArgInst(getOperand(0), getType());
4542}
4543
4544ExtractElementInst *ExtractElementInst::cloneImpl() const {
4546}
4547
4548InsertElementInst *InsertElementInst::cloneImpl() const {
4550}
4551
4555
4556PHINode *PHINode::cloneImpl() const { return new (AllocMarker) PHINode(*this); }
4557
4558LandingPadInst *LandingPadInst::cloneImpl() const {
4559 return new LandingPadInst(*this);
4560}
4561
4562ReturnInst *ReturnInst::cloneImpl() const {
4564 return new (AllocMarker) ReturnInst(*this, AllocMarker);
4565}
4566
4567UncondBrInst *UncondBrInst::cloneImpl() const {
4568 return new (AllocMarker) UncondBrInst(*this);
4569}
4570
4571CondBrInst *CondBrInst::cloneImpl() const {
4572 return new (AllocMarker) CondBrInst(*this);
4573}
4574
4575SwitchInst *SwitchInst::cloneImpl() const { return new SwitchInst(*this); }
4576
4577IndirectBrInst *IndirectBrInst::cloneImpl() const {
4578 return new IndirectBrInst(*this);
4579}
4580
4581InvokeInst *InvokeInst::cloneImpl() const {
4582 if (hasOperandBundles()) {
4586 return new (AllocMarker) InvokeInst(*this, AllocMarker);
4587 }
4589 return new (AllocMarker) InvokeInst(*this, AllocMarker);
4590}
4591
4592CallBrInst *CallBrInst::cloneImpl() const {
4593 if (hasOperandBundles()) {
4597 return new (AllocMarker) CallBrInst(*this, AllocMarker);
4598 }
4600 return new (AllocMarker) CallBrInst(*this, AllocMarker);
4601}
4602
4603ResumeInst *ResumeInst::cloneImpl() const {
4604 return new (AllocMarker) ResumeInst(*this);
4605}
4606
4607CleanupReturnInst *CleanupReturnInst::cloneImpl() const {
4609 return new (AllocMarker) CleanupReturnInst(*this, AllocMarker);
4610}
4611
4612CatchReturnInst *CatchReturnInst::cloneImpl() const {
4613 return new (AllocMarker) CatchReturnInst(*this);
4614}
4615
4616CatchSwitchInst *CatchSwitchInst::cloneImpl() const {
4617 return new CatchSwitchInst(*this);
4618}
4619
4620FuncletPadInst *FuncletPadInst::cloneImpl() const {
4622 return new (AllocMarker) FuncletPadInst(*this, AllocMarker);
4623}
4624
4626 LLVMContext &Context = getContext();
4627 return new UnreachableInst(Context);
4628}
4629
4630bool UnreachableInst::shouldLowerToTrap(bool TrapUnreachable,
4631 bool NoTrapAfterNoreturn) const {
4632 if (!TrapUnreachable)
4633 return false;
4634
4635 // We may be able to ignore unreachable behind a noreturn call.
4637 Call && Call->doesNotReturn()) {
4638 if (NoTrapAfterNoreturn)
4639 return false;
4640 // Do not emit an additional trap instruction.
4641 if (Call->isNonContinuableTrap())
4642 return false;
4643 }
4644
4645 if (getFunction()->hasFnAttribute(Attribute::Naked))
4646 return false;
4647
4648 return true;
4649}
4650
4652 return new FreezeInst(getOperand(0));
4653}
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< 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_SUPPRESS_DEPRECATED_DECLARATIONS_PUSH
Definition Compiler.h:269
#define LLVM_SUPPRESS_DEPRECATED_DECLARATIONS_POP
Definition Compiler.h:270
#define LLVM_ABI
Definition Compiler.h:213
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 cl::opt< bool > DisableI2pP2iOpt("disable-i2p-p2i-opt", cl::init(false), cl::desc("Disables inttoptr/ptrtoint roundtrip optimization"))
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 bool isSingleSourceMaskImpl(ArrayRef< int > Mask, int NumOpElts)
static bool isImpliedTrueByMatchingCmp(CmpPredicate Pred1, CmpPredicate Pred2)
static LLVM_SUPPRESS_DEPRECATED_DECLARATIONS_POP Value * getAISize(LLVMContext &Context, Value *Amt)
static Value * getOpcode(Value &V, Type &Ty, InstrumentationConfig &IConf, InstrumentorIRBuilderTy &IIRB)
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
MachineInstr unsigned OpIdx
uint64_t IntrinsicInst * II
#define P(N)
PowerPC Reduce CR logical Operation
This file contains the declarations for profiling metadata utility functions.
const SmallVectorImpl< MachineOperand > & Cond
static unsigned getNumElements(Type *Ty)
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:334
LLVM_ABI float convertToFloat() const
Converts this APFloat to host float value.
Definition APFloat.cpp:5999
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:1353
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition APInt.h:381
unsigned countr_zero() const
Count the number of trailing zero bits.
Definition APInt.h:1662
unsigned countl_zero() const
The APInt version of std::countl_zero.
Definition APInt.h:1621
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
Definition APInt.h:201
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 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:105
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:124
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:261
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.
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:43
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:309
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.
unsigned getNumElements() const
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:63
BasicBlock * getBasicBlock()
Definition Instruction.h:64
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 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:68
LLVMContextImpl *const pImpl
Definition LLVMContext.h:70
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 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
AtomicOrdering getOrdering() const
Returns the ordering constraint of this load instruction.
void setVolatile(bool V)
Specify whether this is a volatile load or not.
SyncScope::ID getSyncScopeID() const
Returns the synchronization scope ID of this load instruction.
LLVM_ABI LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, InsertPosition InsertBefore)
Align getAlign() const
Return the alignment of the access that is being performed.
Metadata node.
Definition Metadata.h:1080
const MDOperand & getOperand(unsigned I) const
Definition Metadata.h:1444
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).
PtrToAddrInst(Value *S, Type *Ty, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructor with insert-before-instruction semantics.
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.
AtomicOrdering getOrdering() const
Returns the ordering constraint of this store instruction.
Align getAlign() const
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.
LLVM_ABI StoreInst * cloneImpl() const
LLVM_ABI StoreInst(Value *Val, Value *Ptr, InsertPosition InsertBefore)
SyncScope::ID getSyncScopeID() const
Returns the synchronization scope ID of this store instruction.
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:343
static constexpr TypeSize get(ScalarTy Quantity, bool Scalable)
Definition TypeSize.h:340
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:242
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:290
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
Definition Type.cpp:313
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
Definition Type.h:263
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:284
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
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:255
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:370
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition Type.cpp:201
bool isByteOrByteVectorTy() const
Return true if this is a byte type or a vector of byte types.
Definition Type.h:248
bool isAggregateType() const
Return true if the type is an aggregate type.
Definition Type.h:321
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:236
static LLVM_ABI IntegerType * getInt1Ty(LLVMContext &C)
Definition Type.cpp:310
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:287
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:257
bool isTokenTy() const
Return true if this is 'token'.
Definition Type.h:236
bool isFPOrFPVectorTy() const
Return true if this is a FP type or a vector of FP.
Definition Type.h:227
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:883
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:54
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:71
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:255
unsigned char SubclassOptionalData
Hold subclass data that can be dropped.
Definition Value.h:85
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
Definition Value.cpp:393
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:258
unsigned NumUserOperands
Definition Value.h:109
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:318
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:200
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
Definition TypeSize.h:165
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.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
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:31
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > extract(Y &&MD)
Extract a Value from Metadata.
Definition Metadata.h:668
NodeAddr< UseNode * > Use
Definition RDFGraph.h:385
Context & getContext() const
Definition BasicBlock.h:99
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:558
auto seq_inclusive(T Begin, T End)
Iterate over an integral type from Begin to End inclusive.
Definition Sequence.h:325
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:1738
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:1668
unsigned getPointerAddressSpace(const Type *T)
Definition SPIRVUtils.h:377
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
FunctionAddr VTableAddr uintptr_t uintptr_t Int32Ty
Definition InstrProf.h:328
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:2172
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:407
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:279
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:371
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
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:1884
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
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1946
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:2165
auto seq(T Begin, T End)
Iterate over an integral type from Begin up to - but not including - End.
Definition Sequence.h:305
@ Default
The result value is uniform if and only if all operands are uniform.
Definition Uniformity.h:20
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.
Matching combinators.
A MapVector that performs no allocations if smaller than a certain size.
Definition MapVector.h:334
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