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