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