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