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