1 //===- Instructions.cpp - Implement the LLVM instructions -----------------===//
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
7 //===----------------------------------------------------------------------===//
9 // This file implements all of the non-inline methods for the LLVM instruction
12 //===----------------------------------------------------------------------===//
14 #include "llvm/IR/Instructions.h"
15 #include "LLVMContextImpl.h"
16 #include "llvm/ADT/None.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/CallSite.h"
22 #include "llvm/IR/Constant.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/Type.h"
36 #include "llvm/IR/Value.h"
37 #include "llvm/Support/AtomicOrdering.h"
38 #include "llvm/Support/Casting.h"
39 #include "llvm/Support/ErrorHandling.h"
40 #include "llvm/Support/MathExtras.h"
48 static cl::opt
<bool> SwitchInstProfUpdateWrapperStrict(
49 "switch-inst-prof-update-wrapper-strict", cl::Hidden
,
50 cl::desc("Assert that prof branch_weights metadata is valid when creating "
51 "an instance of SwitchInstProfUpdateWrapper"),
54 //===----------------------------------------------------------------------===//
56 //===----------------------------------------------------------------------===//
59 AllocaInst::getAllocationSizeInBits(const DataLayout
&DL
) const {
60 uint64_t Size
= DL
.getTypeAllocSizeInBits(getAllocatedType());
61 if (isArrayAllocation()) {
62 auto C
= dyn_cast
<ConstantInt
>(getArraySize());
65 Size
*= C
->getZExtValue();
70 //===----------------------------------------------------------------------===//
72 //===----------------------------------------------------------------------===//
74 User::op_iterator
CallSite::getCallee() const {
75 return cast
<CallBase
>(getInstruction())->op_end() - 1;
78 //===----------------------------------------------------------------------===//
80 //===----------------------------------------------------------------------===//
82 /// areInvalidOperands - Return a string if the specified operands are invalid
83 /// for a select operation, otherwise return null.
84 const char *SelectInst::areInvalidOperands(Value
*Op0
, Value
*Op1
, Value
*Op2
) {
85 if (Op1
->getType() != Op2
->getType())
86 return "both values to select must have same type";
88 if (Op1
->getType()->isTokenTy())
89 return "select values cannot have token type";
91 if (VectorType
*VT
= dyn_cast
<VectorType
>(Op0
->getType())) {
93 if (VT
->getElementType() != Type::getInt1Ty(Op0
->getContext()))
94 return "vector select condition element type must be i1";
95 VectorType
*ET
= dyn_cast
<VectorType
>(Op1
->getType());
97 return "selected values for vector select must be vectors";
98 if (ET
->getNumElements() != VT
->getNumElements())
99 return "vector select requires selected vectors to have "
100 "the same vector length as select condition";
101 } else if (Op0
->getType() != Type::getInt1Ty(Op0
->getContext())) {
102 return "select condition must be i1 or <n x i1>";
107 //===----------------------------------------------------------------------===//
109 //===----------------------------------------------------------------------===//
111 PHINode::PHINode(const PHINode
&PN
)
112 : Instruction(PN
.getType(), Instruction::PHI
, nullptr, PN
.getNumOperands()),
113 ReservedSpace(PN
.getNumOperands()) {
114 allocHungoffUses(PN
.getNumOperands());
115 std::copy(PN
.op_begin(), PN
.op_end(), op_begin());
116 std::copy(PN
.block_begin(), PN
.block_end(), block_begin());
117 SubclassOptionalData
= PN
.SubclassOptionalData
;
120 // removeIncomingValue - Remove an incoming value. This is useful if a
121 // predecessor basic block is deleted.
122 Value
*PHINode::removeIncomingValue(unsigned Idx
, bool DeletePHIIfEmpty
) {
123 Value
*Removed
= getIncomingValue(Idx
);
125 // Move everything after this operand down.
127 // FIXME: we could just swap with the end of the list, then erase. However,
128 // clients might not expect this to happen. The code as it is thrashes the
129 // use/def lists, which is kinda lame.
130 std::copy(op_begin() + Idx
+ 1, op_end(), op_begin() + Idx
);
131 std::copy(block_begin() + Idx
+ 1, block_end(), block_begin() + Idx
);
133 // Nuke the last value.
134 Op
<-1>().set(nullptr);
135 setNumHungOffUseOperands(getNumOperands() - 1);
137 // If the PHI node is dead, because it has zero entries, nuke it now.
138 if (getNumOperands() == 0 && DeletePHIIfEmpty
) {
139 // If anyone is using this PHI, make them use a dummy value instead...
140 replaceAllUsesWith(UndefValue::get(getType()));
146 /// growOperands - grow operands - This grows the operand list in response
147 /// to a push_back style of operation. This grows the number of ops by 1.5
150 void PHINode::growOperands() {
151 unsigned e
= getNumOperands();
152 unsigned NumOps
= e
+ e
/ 2;
153 if (NumOps
< 2) NumOps
= 2; // 2 op PHI nodes are VERY common.
155 ReservedSpace
= NumOps
;
156 growHungoffUses(ReservedSpace
, /* IsPhi */ true);
159 /// hasConstantValue - If the specified PHI node always merges together the same
160 /// value, return the value, otherwise return null.
161 Value
*PHINode::hasConstantValue() const {
162 // Exploit the fact that phi nodes always have at least one entry.
163 Value
*ConstantValue
= getIncomingValue(0);
164 for (unsigned i
= 1, e
= getNumIncomingValues(); i
!= e
; ++i
)
165 if (getIncomingValue(i
) != ConstantValue
&& getIncomingValue(i
) != this) {
166 if (ConstantValue
!= this)
167 return nullptr; // Incoming values not all the same.
168 // The case where the first value is this PHI.
169 ConstantValue
= getIncomingValue(i
);
171 if (ConstantValue
== this)
172 return UndefValue::get(getType());
173 return ConstantValue
;
176 /// hasConstantOrUndefValue - Whether the specified PHI node always merges
177 /// together the same value, assuming that undefs result in the same value as
179 /// Unlike \ref hasConstantValue, this does not return a value because the
180 /// unique non-undef incoming value need not dominate the PHI node.
181 bool PHINode::hasConstantOrUndefValue() const {
182 Value
*ConstantValue
= nullptr;
183 for (unsigned i
= 0, e
= getNumIncomingValues(); i
!= e
; ++i
) {
184 Value
*Incoming
= getIncomingValue(i
);
185 if (Incoming
!= this && !isa
<UndefValue
>(Incoming
)) {
186 if (ConstantValue
&& ConstantValue
!= Incoming
)
188 ConstantValue
= Incoming
;
194 //===----------------------------------------------------------------------===//
195 // LandingPadInst Implementation
196 //===----------------------------------------------------------------------===//
198 LandingPadInst::LandingPadInst(Type
*RetTy
, unsigned NumReservedValues
,
199 const Twine
&NameStr
, Instruction
*InsertBefore
)
200 : Instruction(RetTy
, Instruction::LandingPad
, nullptr, 0, InsertBefore
) {
201 init(NumReservedValues
, NameStr
);
204 LandingPadInst::LandingPadInst(Type
*RetTy
, unsigned NumReservedValues
,
205 const Twine
&NameStr
, BasicBlock
*InsertAtEnd
)
206 : Instruction(RetTy
, Instruction::LandingPad
, nullptr, 0, InsertAtEnd
) {
207 init(NumReservedValues
, NameStr
);
210 LandingPadInst::LandingPadInst(const LandingPadInst
&LP
)
211 : Instruction(LP
.getType(), Instruction::LandingPad
, nullptr,
212 LP
.getNumOperands()),
213 ReservedSpace(LP
.getNumOperands()) {
214 allocHungoffUses(LP
.getNumOperands());
215 Use
*OL
= getOperandList();
216 const Use
*InOL
= LP
.getOperandList();
217 for (unsigned I
= 0, E
= ReservedSpace
; I
!= E
; ++I
)
220 setCleanup(LP
.isCleanup());
223 LandingPadInst
*LandingPadInst::Create(Type
*RetTy
, unsigned NumReservedClauses
,
224 const Twine
&NameStr
,
225 Instruction
*InsertBefore
) {
226 return new LandingPadInst(RetTy
, NumReservedClauses
, NameStr
, InsertBefore
);
229 LandingPadInst
*LandingPadInst::Create(Type
*RetTy
, unsigned NumReservedClauses
,
230 const Twine
&NameStr
,
231 BasicBlock
*InsertAtEnd
) {
232 return new LandingPadInst(RetTy
, NumReservedClauses
, NameStr
, InsertAtEnd
);
235 void LandingPadInst::init(unsigned NumReservedValues
, const Twine
&NameStr
) {
236 ReservedSpace
= NumReservedValues
;
237 setNumHungOffUseOperands(0);
238 allocHungoffUses(ReservedSpace
);
243 /// growOperands - grow operands - This grows the operand list in response to a
244 /// push_back style of operation. This grows the number of ops by 2 times.
245 void LandingPadInst::growOperands(unsigned Size
) {
246 unsigned e
= getNumOperands();
247 if (ReservedSpace
>= e
+ Size
) return;
248 ReservedSpace
= (std::max(e
, 1U) + Size
/ 2) * 2;
249 growHungoffUses(ReservedSpace
);
252 void LandingPadInst::addClause(Constant
*Val
) {
253 unsigned OpNo
= getNumOperands();
255 assert(OpNo
< ReservedSpace
&& "Growing didn't work!");
256 setNumHungOffUseOperands(getNumOperands() + 1);
257 getOperandList()[OpNo
] = Val
;
260 //===----------------------------------------------------------------------===//
261 // CallBase Implementation
262 //===----------------------------------------------------------------------===//
264 Function
*CallBase::getCaller() { return getParent()->getParent(); }
266 unsigned CallBase::getNumSubclassExtraOperandsDynamic() const {
267 assert(getOpcode() == Instruction::CallBr
&& "Unexpected opcode!");
268 return cast
<CallBrInst
>(this)->getNumIndirectDests() + 1;
271 bool CallBase::isIndirectCall() const {
272 const Value
*V
= getCalledValue();
273 if (isa
<Function
>(V
) || isa
<Constant
>(V
))
275 if (const CallInst
*CI
= dyn_cast
<CallInst
>(this))
276 if (CI
->isInlineAsm())
281 /// Tests if this call site must be tail call optimized. Only a CallInst can
282 /// be tail call optimized.
283 bool CallBase::isMustTailCall() const {
284 if (auto *CI
= dyn_cast
<CallInst
>(this))
285 return CI
->isMustTailCall();
289 /// Tests if this call site is marked as a tail call.
290 bool CallBase::isTailCall() const {
291 if (auto *CI
= dyn_cast
<CallInst
>(this))
292 return CI
->isTailCall();
296 Intrinsic::ID
CallBase::getIntrinsicID() const {
297 if (auto *F
= getCalledFunction())
298 return F
->getIntrinsicID();
299 return Intrinsic::not_intrinsic
;
302 bool CallBase::isReturnNonNull() const {
303 if (hasRetAttr(Attribute::NonNull
))
306 if (getDereferenceableBytes(AttributeList::ReturnIndex
) > 0 &&
307 !NullPointerIsDefined(getCaller(),
308 getType()->getPointerAddressSpace()))
314 Value
*CallBase::getReturnedArgOperand() const {
317 if (Attrs
.hasAttrSomewhere(Attribute::Returned
, &Index
) && Index
)
318 return getArgOperand(Index
- AttributeList::FirstArgIndex
);
319 if (const Function
*F
= getCalledFunction())
320 if (F
->getAttributes().hasAttrSomewhere(Attribute::Returned
, &Index
) &&
322 return getArgOperand(Index
- AttributeList::FirstArgIndex
);
327 bool CallBase::hasRetAttr(Attribute::AttrKind Kind
) const {
328 if (Attrs
.hasAttribute(AttributeList::ReturnIndex
, Kind
))
331 // Look at the callee, if available.
332 if (const Function
*F
= getCalledFunction())
333 return F
->getAttributes().hasAttribute(AttributeList::ReturnIndex
, Kind
);
337 /// Determine whether the argument or parameter has the given attribute.
338 bool CallBase::paramHasAttr(unsigned ArgNo
, Attribute::AttrKind Kind
) const {
339 assert(ArgNo
< getNumArgOperands() && "Param index out of bounds!");
341 if (Attrs
.hasParamAttribute(ArgNo
, Kind
))
343 if (const Function
*F
= getCalledFunction())
344 return F
->getAttributes().hasParamAttribute(ArgNo
, Kind
);
348 bool CallBase::hasFnAttrOnCalledFunction(Attribute::AttrKind Kind
) const {
349 if (const Function
*F
= getCalledFunction())
350 return F
->getAttributes().hasAttribute(AttributeList::FunctionIndex
, Kind
);
354 bool CallBase::hasFnAttrOnCalledFunction(StringRef Kind
) const {
355 if (const Function
*F
= getCalledFunction())
356 return F
->getAttributes().hasAttribute(AttributeList::FunctionIndex
, Kind
);
360 CallBase::op_iterator
361 CallBase::populateBundleOperandInfos(ArrayRef
<OperandBundleDef
> Bundles
,
362 const unsigned BeginIndex
) {
363 auto It
= op_begin() + BeginIndex
;
364 for (auto &B
: Bundles
)
365 It
= std::copy(B
.input_begin(), B
.input_end(), It
);
367 auto *ContextImpl
= getContext().pImpl
;
368 auto BI
= Bundles
.begin();
369 unsigned CurrentIndex
= BeginIndex
;
371 for (auto &BOI
: bundle_op_infos()) {
372 assert(BI
!= Bundles
.end() && "Incorrect allocation?");
374 BOI
.Tag
= ContextImpl
->getOrInsertBundleTag(BI
->getTag());
375 BOI
.Begin
= CurrentIndex
;
376 BOI
.End
= CurrentIndex
+ BI
->input_size();
377 CurrentIndex
= BOI
.End
;
381 assert(BI
== Bundles
.end() && "Incorrect allocation?");
386 //===----------------------------------------------------------------------===//
387 // CallInst Implementation
388 //===----------------------------------------------------------------------===//
390 void CallInst::init(FunctionType
*FTy
, Value
*Func
, ArrayRef
<Value
*> Args
,
391 ArrayRef
<OperandBundleDef
> Bundles
, const Twine
&NameStr
) {
393 assert(getNumOperands() == Args
.size() + CountBundleInputs(Bundles
) + 1 &&
394 "NumOperands not set up?");
395 setCalledOperand(Func
);
398 assert((Args
.size() == FTy
->getNumParams() ||
399 (FTy
->isVarArg() && Args
.size() > FTy
->getNumParams())) &&
400 "Calling a function with bad signature!");
402 for (unsigned i
= 0; i
!= Args
.size(); ++i
)
403 assert((i
>= FTy
->getNumParams() ||
404 FTy
->getParamType(i
) == Args
[i
]->getType()) &&
405 "Calling a function with a bad signature!");
408 llvm::copy(Args
, op_begin());
410 auto It
= populateBundleOperandInfos(Bundles
, Args
.size());
412 assert(It
+ 1 == op_end() && "Should add up!");
417 void CallInst::init(FunctionType
*FTy
, Value
*Func
, const Twine
&NameStr
) {
419 assert(getNumOperands() == 1 && "NumOperands not set up?");
420 setCalledOperand(Func
);
422 assert(FTy
->getNumParams() == 0 && "Calling a function with bad signature");
427 CallInst::CallInst(FunctionType
*Ty
, Value
*Func
, const Twine
&Name
,
428 Instruction
*InsertBefore
)
429 : CallBase(Ty
->getReturnType(), Instruction::Call
,
430 OperandTraits
<CallBase
>::op_end(this) - 1, 1, InsertBefore
) {
431 init(Ty
, Func
, Name
);
434 CallInst::CallInst(FunctionType
*Ty
, Value
*Func
, const Twine
&Name
,
435 BasicBlock
*InsertAtEnd
)
436 : CallBase(Ty
->getReturnType(), Instruction::Call
,
437 OperandTraits
<CallBase
>::op_end(this) - 1, 1, InsertAtEnd
) {
438 init(Ty
, Func
, Name
);
441 CallInst::CallInst(const CallInst
&CI
)
442 : CallBase(CI
.Attrs
, CI
.FTy
, CI
.getType(), Instruction::Call
,
443 OperandTraits
<CallBase
>::op_end(this) - CI
.getNumOperands(),
444 CI
.getNumOperands()) {
445 setTailCallKind(CI
.getTailCallKind());
446 setCallingConv(CI
.getCallingConv());
448 std::copy(CI
.op_begin(), CI
.op_end(), op_begin());
449 std::copy(CI
.bundle_op_info_begin(), CI
.bundle_op_info_end(),
450 bundle_op_info_begin());
451 SubclassOptionalData
= CI
.SubclassOptionalData
;
454 CallInst
*CallInst::Create(CallInst
*CI
, ArrayRef
<OperandBundleDef
> OpB
,
455 Instruction
*InsertPt
) {
456 std::vector
<Value
*> Args(CI
->arg_begin(), CI
->arg_end());
458 auto *NewCI
= CallInst::Create(CI
->getFunctionType(), CI
->getCalledValue(),
459 Args
, OpB
, CI
->getName(), InsertPt
);
460 NewCI
->setTailCallKind(CI
->getTailCallKind());
461 NewCI
->setCallingConv(CI
->getCallingConv());
462 NewCI
->SubclassOptionalData
= CI
->SubclassOptionalData
;
463 NewCI
->setAttributes(CI
->getAttributes());
464 NewCI
->setDebugLoc(CI
->getDebugLoc());
468 // Update profile weight for call instruction by scaling it using the ratio
469 // of S/T. The meaning of "branch_weights" meta data for call instruction is
470 // transfered to represent call count.
471 void CallInst::updateProfWeight(uint64_t S
, uint64_t T
) {
472 auto *ProfileData
= getMetadata(LLVMContext::MD_prof
);
473 if (ProfileData
== nullptr)
476 auto *ProfDataName
= dyn_cast
<MDString
>(ProfileData
->getOperand(0));
477 if (!ProfDataName
|| (!ProfDataName
->getString().equals("branch_weights") &&
478 !ProfDataName
->getString().equals("VP")))
482 LLVM_DEBUG(dbgs() << "Attempting to update profile weights will result in "
483 "div by 0. Ignoring. Likely the function "
484 << getParent()->getParent()->getName()
485 << " has 0 entry count, and contains call instructions "
486 "with non-zero prof info.");
490 MDBuilder
MDB(getContext());
491 SmallVector
<Metadata
*, 3> Vals
;
492 Vals
.push_back(ProfileData
->getOperand(0));
493 APInt
APS(128, S
), APT(128, T
);
494 if (ProfDataName
->getString().equals("branch_weights") &&
495 ProfileData
->getNumOperands() > 0) {
496 // Using APInt::div may be expensive, but most cases should fit 64 bits.
497 APInt
Val(128, mdconst::dyn_extract
<ConstantInt
>(ProfileData
->getOperand(1))
501 Vals
.push_back(MDB
.createConstant(ConstantInt::get(
502 Type::getInt64Ty(getContext()), Val
.udiv(APT
).getLimitedValue())));
503 } else if (ProfDataName
->getString().equals("VP"))
504 for (unsigned i
= 1; i
< ProfileData
->getNumOperands(); i
+= 2) {
505 // The first value is the key of the value profile, which will not change.
506 Vals
.push_back(ProfileData
->getOperand(i
));
507 // Using APInt::div may be expensive, but most cases should fit 64 bits.
509 mdconst::dyn_extract
<ConstantInt
>(ProfileData
->getOperand(i
+ 1))
513 Vals
.push_back(MDB
.createConstant(
514 ConstantInt::get(Type::getInt64Ty(getContext()),
515 Val
.udiv(APT
).getLimitedValue())));
517 setMetadata(LLVMContext::MD_prof
, MDNode::get(getContext(), Vals
));
520 /// IsConstantOne - Return true only if val is constant int 1
521 static bool IsConstantOne(Value
*val
) {
522 assert(val
&& "IsConstantOne does not work with nullptr val");
523 const ConstantInt
*CVal
= dyn_cast
<ConstantInt
>(val
);
524 return CVal
&& CVal
->isOne();
527 static Instruction
*createMalloc(Instruction
*InsertBefore
,
528 BasicBlock
*InsertAtEnd
, Type
*IntPtrTy
,
529 Type
*AllocTy
, Value
*AllocSize
,
531 ArrayRef
<OperandBundleDef
> OpB
,
532 Function
*MallocF
, const Twine
&Name
) {
533 assert(((!InsertBefore
&& InsertAtEnd
) || (InsertBefore
&& !InsertAtEnd
)) &&
534 "createMalloc needs either InsertBefore or InsertAtEnd");
536 // malloc(type) becomes:
537 // bitcast (i8* malloc(typeSize)) to type*
538 // malloc(type, arraySize) becomes:
539 // bitcast (i8* malloc(typeSize*arraySize)) to type*
541 ArraySize
= ConstantInt::get(IntPtrTy
, 1);
542 else if (ArraySize
->getType() != IntPtrTy
) {
544 ArraySize
= CastInst::CreateIntegerCast(ArraySize
, IntPtrTy
, false,
547 ArraySize
= CastInst::CreateIntegerCast(ArraySize
, IntPtrTy
, false,
551 if (!IsConstantOne(ArraySize
)) {
552 if (IsConstantOne(AllocSize
)) {
553 AllocSize
= ArraySize
; // Operand * 1 = Operand
554 } else if (Constant
*CO
= dyn_cast
<Constant
>(ArraySize
)) {
555 Constant
*Scale
= ConstantExpr::getIntegerCast(CO
, IntPtrTy
,
557 // Malloc arg is constant product of type size and array size
558 AllocSize
= ConstantExpr::getMul(Scale
, cast
<Constant
>(AllocSize
));
560 // Multiply type size by the array size...
562 AllocSize
= BinaryOperator::CreateMul(ArraySize
, AllocSize
,
563 "mallocsize", InsertBefore
);
565 AllocSize
= BinaryOperator::CreateMul(ArraySize
, AllocSize
,
566 "mallocsize", InsertAtEnd
);
570 assert(AllocSize
->getType() == IntPtrTy
&& "malloc arg is wrong size");
571 // Create the call to Malloc.
572 BasicBlock
*BB
= InsertBefore
? InsertBefore
->getParent() : InsertAtEnd
;
573 Module
*M
= BB
->getParent()->getParent();
574 Type
*BPTy
= Type::getInt8PtrTy(BB
->getContext());
575 FunctionCallee MallocFunc
= MallocF
;
577 // prototype malloc as "void *malloc(size_t)"
578 MallocFunc
= M
->getOrInsertFunction("malloc", BPTy
, IntPtrTy
);
579 PointerType
*AllocPtrType
= PointerType::getUnqual(AllocTy
);
580 CallInst
*MCall
= nullptr;
581 Instruction
*Result
= nullptr;
583 MCall
= CallInst::Create(MallocFunc
, AllocSize
, OpB
, "malloccall",
586 if (Result
->getType() != AllocPtrType
)
587 // Create a cast instruction to convert to the right type...
588 Result
= new BitCastInst(MCall
, AllocPtrType
, Name
, InsertBefore
);
590 MCall
= CallInst::Create(MallocFunc
, AllocSize
, OpB
, "malloccall");
592 if (Result
->getType() != AllocPtrType
) {
593 InsertAtEnd
->getInstList().push_back(MCall
);
594 // Create a cast instruction to convert to the right type...
595 Result
= new BitCastInst(MCall
, AllocPtrType
, Name
);
598 MCall
->setTailCall();
599 if (Function
*F
= dyn_cast
<Function
>(MallocFunc
.getCallee())) {
600 MCall
->setCallingConv(F
->getCallingConv());
601 if (!F
->returnDoesNotAlias())
602 F
->setReturnDoesNotAlias();
604 assert(!MCall
->getType()->isVoidTy() && "Malloc has void return type");
609 /// CreateMalloc - Generate the IR for a call to malloc:
610 /// 1. Compute the malloc call's argument as the specified type's size,
611 /// possibly multiplied by the array size if the array size is not
613 /// 2. Call malloc with that argument.
614 /// 3. Bitcast the result of the malloc call to the specified type.
615 Instruction
*CallInst::CreateMalloc(Instruction
*InsertBefore
,
616 Type
*IntPtrTy
, Type
*AllocTy
,
617 Value
*AllocSize
, Value
*ArraySize
,
620 return createMalloc(InsertBefore
, nullptr, IntPtrTy
, AllocTy
, AllocSize
,
621 ArraySize
, None
, MallocF
, Name
);
623 Instruction
*CallInst::CreateMalloc(Instruction
*InsertBefore
,
624 Type
*IntPtrTy
, Type
*AllocTy
,
625 Value
*AllocSize
, Value
*ArraySize
,
626 ArrayRef
<OperandBundleDef
> OpB
,
629 return createMalloc(InsertBefore
, nullptr, IntPtrTy
, AllocTy
, AllocSize
,
630 ArraySize
, OpB
, MallocF
, Name
);
633 /// CreateMalloc - Generate the IR for a call to malloc:
634 /// 1. Compute the malloc call's argument as the specified type's size,
635 /// possibly multiplied by the array size if the array size is not
637 /// 2. Call malloc with that argument.
638 /// 3. Bitcast the result of the malloc call to the specified type.
639 /// Note: This function does not add the bitcast to the basic block, that is the
640 /// responsibility of the caller.
641 Instruction
*CallInst::CreateMalloc(BasicBlock
*InsertAtEnd
,
642 Type
*IntPtrTy
, Type
*AllocTy
,
643 Value
*AllocSize
, Value
*ArraySize
,
644 Function
*MallocF
, const Twine
&Name
) {
645 return createMalloc(nullptr, InsertAtEnd
, IntPtrTy
, AllocTy
, AllocSize
,
646 ArraySize
, None
, MallocF
, Name
);
648 Instruction
*CallInst::CreateMalloc(BasicBlock
*InsertAtEnd
,
649 Type
*IntPtrTy
, Type
*AllocTy
,
650 Value
*AllocSize
, Value
*ArraySize
,
651 ArrayRef
<OperandBundleDef
> OpB
,
652 Function
*MallocF
, const Twine
&Name
) {
653 return createMalloc(nullptr, InsertAtEnd
, IntPtrTy
, AllocTy
, AllocSize
,
654 ArraySize
, OpB
, MallocF
, Name
);
657 static Instruction
*createFree(Value
*Source
,
658 ArrayRef
<OperandBundleDef
> Bundles
,
659 Instruction
*InsertBefore
,
660 BasicBlock
*InsertAtEnd
) {
661 assert(((!InsertBefore
&& InsertAtEnd
) || (InsertBefore
&& !InsertAtEnd
)) &&
662 "createFree needs either InsertBefore or InsertAtEnd");
663 assert(Source
->getType()->isPointerTy() &&
664 "Can not free something of nonpointer type!");
666 BasicBlock
*BB
= InsertBefore
? InsertBefore
->getParent() : InsertAtEnd
;
667 Module
*M
= BB
->getParent()->getParent();
669 Type
*VoidTy
= Type::getVoidTy(M
->getContext());
670 Type
*IntPtrTy
= Type::getInt8PtrTy(M
->getContext());
671 // prototype free as "void free(void*)"
672 FunctionCallee FreeFunc
= M
->getOrInsertFunction("free", VoidTy
, IntPtrTy
);
673 CallInst
*Result
= nullptr;
674 Value
*PtrCast
= Source
;
676 if (Source
->getType() != IntPtrTy
)
677 PtrCast
= new BitCastInst(Source
, IntPtrTy
, "", InsertBefore
);
678 Result
= CallInst::Create(FreeFunc
, PtrCast
, Bundles
, "", InsertBefore
);
680 if (Source
->getType() != IntPtrTy
)
681 PtrCast
= new BitCastInst(Source
, IntPtrTy
, "", InsertAtEnd
);
682 Result
= CallInst::Create(FreeFunc
, PtrCast
, Bundles
, "");
684 Result
->setTailCall();
685 if (Function
*F
= dyn_cast
<Function
>(FreeFunc
.getCallee()))
686 Result
->setCallingConv(F
->getCallingConv());
691 /// CreateFree - Generate the IR for a call to the builtin free function.
692 Instruction
*CallInst::CreateFree(Value
*Source
, Instruction
*InsertBefore
) {
693 return createFree(Source
, None
, InsertBefore
, nullptr);
695 Instruction
*CallInst::CreateFree(Value
*Source
,
696 ArrayRef
<OperandBundleDef
> Bundles
,
697 Instruction
*InsertBefore
) {
698 return createFree(Source
, Bundles
, InsertBefore
, nullptr);
701 /// CreateFree - Generate the IR for a call to the builtin free function.
702 /// Note: This function does not add the call to the basic block, that is the
703 /// responsibility of the caller.
704 Instruction
*CallInst::CreateFree(Value
*Source
, BasicBlock
*InsertAtEnd
) {
705 Instruction
*FreeCall
= createFree(Source
, None
, nullptr, InsertAtEnd
);
706 assert(FreeCall
&& "CreateFree did not create a CallInst");
709 Instruction
*CallInst::CreateFree(Value
*Source
,
710 ArrayRef
<OperandBundleDef
> Bundles
,
711 BasicBlock
*InsertAtEnd
) {
712 Instruction
*FreeCall
= createFree(Source
, Bundles
, nullptr, InsertAtEnd
);
713 assert(FreeCall
&& "CreateFree did not create a CallInst");
717 //===----------------------------------------------------------------------===//
718 // InvokeInst Implementation
719 //===----------------------------------------------------------------------===//
721 void InvokeInst::init(FunctionType
*FTy
, Value
*Fn
, BasicBlock
*IfNormal
,
722 BasicBlock
*IfException
, ArrayRef
<Value
*> Args
,
723 ArrayRef
<OperandBundleDef
> Bundles
,
724 const Twine
&NameStr
) {
727 assert((int)getNumOperands() ==
728 ComputeNumOperands(Args
.size(), CountBundleInputs(Bundles
)) &&
729 "NumOperands not set up?");
730 setNormalDest(IfNormal
);
731 setUnwindDest(IfException
);
732 setCalledOperand(Fn
);
735 assert(((Args
.size() == FTy
->getNumParams()) ||
736 (FTy
->isVarArg() && Args
.size() > FTy
->getNumParams())) &&
737 "Invoking a function with bad signature");
739 for (unsigned i
= 0, e
= Args
.size(); i
!= e
; i
++)
740 assert((i
>= FTy
->getNumParams() ||
741 FTy
->getParamType(i
) == Args
[i
]->getType()) &&
742 "Invoking a function with a bad signature!");
745 llvm::copy(Args
, op_begin());
747 auto It
= populateBundleOperandInfos(Bundles
, Args
.size());
749 assert(It
+ 3 == op_end() && "Should add up!");
754 InvokeInst::InvokeInst(const InvokeInst
&II
)
755 : CallBase(II
.Attrs
, II
.FTy
, II
.getType(), Instruction::Invoke
,
756 OperandTraits
<CallBase
>::op_end(this) - II
.getNumOperands(),
757 II
.getNumOperands()) {
758 setCallingConv(II
.getCallingConv());
759 std::copy(II
.op_begin(), II
.op_end(), op_begin());
760 std::copy(II
.bundle_op_info_begin(), II
.bundle_op_info_end(),
761 bundle_op_info_begin());
762 SubclassOptionalData
= II
.SubclassOptionalData
;
765 InvokeInst
*InvokeInst::Create(InvokeInst
*II
, ArrayRef
<OperandBundleDef
> OpB
,
766 Instruction
*InsertPt
) {
767 std::vector
<Value
*> Args(II
->arg_begin(), II
->arg_end());
769 auto *NewII
= InvokeInst::Create(II
->getFunctionType(), II
->getCalledValue(),
770 II
->getNormalDest(), II
->getUnwindDest(),
771 Args
, OpB
, II
->getName(), InsertPt
);
772 NewII
->setCallingConv(II
->getCallingConv());
773 NewII
->SubclassOptionalData
= II
->SubclassOptionalData
;
774 NewII
->setAttributes(II
->getAttributes());
775 NewII
->setDebugLoc(II
->getDebugLoc());
780 LandingPadInst
*InvokeInst::getLandingPadInst() const {
781 return cast
<LandingPadInst
>(getUnwindDest()->getFirstNonPHI());
784 //===----------------------------------------------------------------------===//
785 // CallBrInst Implementation
786 //===----------------------------------------------------------------------===//
788 void CallBrInst::init(FunctionType
*FTy
, Value
*Fn
, BasicBlock
*Fallthrough
,
789 ArrayRef
<BasicBlock
*> IndirectDests
,
790 ArrayRef
<Value
*> Args
,
791 ArrayRef
<OperandBundleDef
> Bundles
,
792 const Twine
&NameStr
) {
795 assert((int)getNumOperands() ==
796 ComputeNumOperands(Args
.size(), IndirectDests
.size(),
797 CountBundleInputs(Bundles
)) &&
798 "NumOperands not set up?");
799 NumIndirectDests
= IndirectDests
.size();
800 setDefaultDest(Fallthrough
);
801 for (unsigned i
= 0; i
!= NumIndirectDests
; ++i
)
802 setIndirectDest(i
, IndirectDests
[i
]);
803 setCalledOperand(Fn
);
806 assert(((Args
.size() == FTy
->getNumParams()) ||
807 (FTy
->isVarArg() && Args
.size() > FTy
->getNumParams())) &&
808 "Calling a function with bad signature");
810 for (unsigned i
= 0, e
= Args
.size(); i
!= e
; i
++)
811 assert((i
>= FTy
->getNumParams() ||
812 FTy
->getParamType(i
) == Args
[i
]->getType()) &&
813 "Calling a function with a bad signature!");
816 std::copy(Args
.begin(), Args
.end(), op_begin());
818 auto It
= populateBundleOperandInfos(Bundles
, Args
.size());
820 assert(It
+ 2 + IndirectDests
.size() == op_end() && "Should add up!");
825 CallBrInst::CallBrInst(const CallBrInst
&CBI
)
826 : CallBase(CBI
.Attrs
, CBI
.FTy
, CBI
.getType(), Instruction::CallBr
,
827 OperandTraits
<CallBase
>::op_end(this) - CBI
.getNumOperands(),
828 CBI
.getNumOperands()) {
829 setCallingConv(CBI
.getCallingConv());
830 std::copy(CBI
.op_begin(), CBI
.op_end(), op_begin());
831 std::copy(CBI
.bundle_op_info_begin(), CBI
.bundle_op_info_end(),
832 bundle_op_info_begin());
833 SubclassOptionalData
= CBI
.SubclassOptionalData
;
834 NumIndirectDests
= CBI
.NumIndirectDests
;
837 CallBrInst
*CallBrInst::Create(CallBrInst
*CBI
, ArrayRef
<OperandBundleDef
> OpB
,
838 Instruction
*InsertPt
) {
839 std::vector
<Value
*> Args(CBI
->arg_begin(), CBI
->arg_end());
841 auto *NewCBI
= CallBrInst::Create(CBI
->getFunctionType(),
842 CBI
->getCalledValue(),
843 CBI
->getDefaultDest(),
844 CBI
->getIndirectDests(),
845 Args
, OpB
, CBI
->getName(), InsertPt
);
846 NewCBI
->setCallingConv(CBI
->getCallingConv());
847 NewCBI
->SubclassOptionalData
= CBI
->SubclassOptionalData
;
848 NewCBI
->setAttributes(CBI
->getAttributes());
849 NewCBI
->setDebugLoc(CBI
->getDebugLoc());
850 NewCBI
->NumIndirectDests
= CBI
->NumIndirectDests
;
854 //===----------------------------------------------------------------------===//
855 // ReturnInst Implementation
856 //===----------------------------------------------------------------------===//
858 ReturnInst::ReturnInst(const ReturnInst
&RI
)
859 : Instruction(Type::getVoidTy(RI
.getContext()), Instruction::Ret
,
860 OperandTraits
<ReturnInst
>::op_end(this) - RI
.getNumOperands(),
861 RI
.getNumOperands()) {
862 if (RI
.getNumOperands())
863 Op
<0>() = RI
.Op
<0>();
864 SubclassOptionalData
= RI
.SubclassOptionalData
;
867 ReturnInst::ReturnInst(LLVMContext
&C
, Value
*retVal
, Instruction
*InsertBefore
)
868 : Instruction(Type::getVoidTy(C
), Instruction::Ret
,
869 OperandTraits
<ReturnInst
>::op_end(this) - !!retVal
, !!retVal
,
875 ReturnInst::ReturnInst(LLVMContext
&C
, Value
*retVal
, BasicBlock
*InsertAtEnd
)
876 : Instruction(Type::getVoidTy(C
), Instruction::Ret
,
877 OperandTraits
<ReturnInst
>::op_end(this) - !!retVal
, !!retVal
,
883 ReturnInst::ReturnInst(LLVMContext
&Context
, BasicBlock
*InsertAtEnd
)
884 : Instruction(Type::getVoidTy(Context
), Instruction::Ret
,
885 OperandTraits
<ReturnInst
>::op_end(this), 0, InsertAtEnd
) {}
887 //===----------------------------------------------------------------------===//
888 // ResumeInst Implementation
889 //===----------------------------------------------------------------------===//
891 ResumeInst::ResumeInst(const ResumeInst
&RI
)
892 : Instruction(Type::getVoidTy(RI
.getContext()), Instruction::Resume
,
893 OperandTraits
<ResumeInst
>::op_begin(this), 1) {
894 Op
<0>() = RI
.Op
<0>();
897 ResumeInst::ResumeInst(Value
*Exn
, Instruction
*InsertBefore
)
898 : Instruction(Type::getVoidTy(Exn
->getContext()), Instruction::Resume
,
899 OperandTraits
<ResumeInst
>::op_begin(this), 1, InsertBefore
) {
903 ResumeInst::ResumeInst(Value
*Exn
, BasicBlock
*InsertAtEnd
)
904 : Instruction(Type::getVoidTy(Exn
->getContext()), Instruction::Resume
,
905 OperandTraits
<ResumeInst
>::op_begin(this), 1, InsertAtEnd
) {
909 //===----------------------------------------------------------------------===//
910 // CleanupReturnInst Implementation
911 //===----------------------------------------------------------------------===//
913 CleanupReturnInst::CleanupReturnInst(const CleanupReturnInst
&CRI
)
914 : Instruction(CRI
.getType(), Instruction::CleanupRet
,
915 OperandTraits
<CleanupReturnInst
>::op_end(this) -
916 CRI
.getNumOperands(),
917 CRI
.getNumOperands()) {
918 setInstructionSubclassData(CRI
.getSubclassDataFromInstruction());
919 Op
<0>() = CRI
.Op
<0>();
920 if (CRI
.hasUnwindDest())
921 Op
<1>() = CRI
.Op
<1>();
924 void CleanupReturnInst::init(Value
*CleanupPad
, BasicBlock
*UnwindBB
) {
926 setInstructionSubclassData(getSubclassDataFromInstruction() | 1);
928 Op
<0>() = CleanupPad
;
933 CleanupReturnInst::CleanupReturnInst(Value
*CleanupPad
, BasicBlock
*UnwindBB
,
934 unsigned Values
, Instruction
*InsertBefore
)
935 : Instruction(Type::getVoidTy(CleanupPad
->getContext()),
936 Instruction::CleanupRet
,
937 OperandTraits
<CleanupReturnInst
>::op_end(this) - Values
,
938 Values
, InsertBefore
) {
939 init(CleanupPad
, UnwindBB
);
942 CleanupReturnInst::CleanupReturnInst(Value
*CleanupPad
, BasicBlock
*UnwindBB
,
943 unsigned Values
, BasicBlock
*InsertAtEnd
)
944 : Instruction(Type::getVoidTy(CleanupPad
->getContext()),
945 Instruction::CleanupRet
,
946 OperandTraits
<CleanupReturnInst
>::op_end(this) - Values
,
947 Values
, InsertAtEnd
) {
948 init(CleanupPad
, UnwindBB
);
951 //===----------------------------------------------------------------------===//
952 // CatchReturnInst Implementation
953 //===----------------------------------------------------------------------===//
954 void CatchReturnInst::init(Value
*CatchPad
, BasicBlock
*BB
) {
959 CatchReturnInst::CatchReturnInst(const CatchReturnInst
&CRI
)
960 : Instruction(Type::getVoidTy(CRI
.getContext()), Instruction::CatchRet
,
961 OperandTraits
<CatchReturnInst
>::op_begin(this), 2) {
962 Op
<0>() = CRI
.Op
<0>();
963 Op
<1>() = CRI
.Op
<1>();
966 CatchReturnInst::CatchReturnInst(Value
*CatchPad
, BasicBlock
*BB
,
967 Instruction
*InsertBefore
)
968 : Instruction(Type::getVoidTy(BB
->getContext()), Instruction::CatchRet
,
969 OperandTraits
<CatchReturnInst
>::op_begin(this), 2,
974 CatchReturnInst::CatchReturnInst(Value
*CatchPad
, BasicBlock
*BB
,
975 BasicBlock
*InsertAtEnd
)
976 : Instruction(Type::getVoidTy(BB
->getContext()), Instruction::CatchRet
,
977 OperandTraits
<CatchReturnInst
>::op_begin(this), 2,
982 //===----------------------------------------------------------------------===//
983 // CatchSwitchInst Implementation
984 //===----------------------------------------------------------------------===//
986 CatchSwitchInst::CatchSwitchInst(Value
*ParentPad
, BasicBlock
*UnwindDest
,
987 unsigned NumReservedValues
,
988 const Twine
&NameStr
,
989 Instruction
*InsertBefore
)
990 : Instruction(ParentPad
->getType(), Instruction::CatchSwitch
, nullptr, 0,
994 init(ParentPad
, UnwindDest
, NumReservedValues
+ 1);
998 CatchSwitchInst::CatchSwitchInst(Value
*ParentPad
, BasicBlock
*UnwindDest
,
999 unsigned NumReservedValues
,
1000 const Twine
&NameStr
, BasicBlock
*InsertAtEnd
)
1001 : Instruction(ParentPad
->getType(), Instruction::CatchSwitch
, nullptr, 0,
1004 ++NumReservedValues
;
1005 init(ParentPad
, UnwindDest
, NumReservedValues
+ 1);
1009 CatchSwitchInst::CatchSwitchInst(const CatchSwitchInst
&CSI
)
1010 : Instruction(CSI
.getType(), Instruction::CatchSwitch
, nullptr,
1011 CSI
.getNumOperands()) {
1012 init(CSI
.getParentPad(), CSI
.getUnwindDest(), CSI
.getNumOperands());
1013 setNumHungOffUseOperands(ReservedSpace
);
1014 Use
*OL
= getOperandList();
1015 const Use
*InOL
= CSI
.getOperandList();
1016 for (unsigned I
= 1, E
= ReservedSpace
; I
!= E
; ++I
)
1020 void CatchSwitchInst::init(Value
*ParentPad
, BasicBlock
*UnwindDest
,
1021 unsigned NumReservedValues
) {
1022 assert(ParentPad
&& NumReservedValues
);
1024 ReservedSpace
= NumReservedValues
;
1025 setNumHungOffUseOperands(UnwindDest
? 2 : 1);
1026 allocHungoffUses(ReservedSpace
);
1028 Op
<0>() = ParentPad
;
1030 setInstructionSubclassData(getSubclassDataFromInstruction() | 1);
1031 setUnwindDest(UnwindDest
);
1035 /// growOperands - grow operands - This grows the operand list in response to a
1036 /// push_back style of operation. This grows the number of ops by 2 times.
1037 void CatchSwitchInst::growOperands(unsigned Size
) {
1038 unsigned NumOperands
= getNumOperands();
1039 assert(NumOperands
>= 1);
1040 if (ReservedSpace
>= NumOperands
+ Size
)
1042 ReservedSpace
= (NumOperands
+ Size
/ 2) * 2;
1043 growHungoffUses(ReservedSpace
);
1046 void CatchSwitchInst::addHandler(BasicBlock
*Handler
) {
1047 unsigned OpNo
= getNumOperands();
1049 assert(OpNo
< ReservedSpace
&& "Growing didn't work!");
1050 setNumHungOffUseOperands(getNumOperands() + 1);
1051 getOperandList()[OpNo
] = Handler
;
1054 void CatchSwitchInst::removeHandler(handler_iterator HI
) {
1055 // Move all subsequent handlers up one.
1056 Use
*EndDst
= op_end() - 1;
1057 for (Use
*CurDst
= HI
.getCurrent(); CurDst
!= EndDst
; ++CurDst
)
1058 *CurDst
= *(CurDst
+ 1);
1059 // Null out the last handler use.
1062 setNumHungOffUseOperands(getNumOperands() - 1);
1065 //===----------------------------------------------------------------------===//
1066 // FuncletPadInst Implementation
1067 //===----------------------------------------------------------------------===//
1068 void FuncletPadInst::init(Value
*ParentPad
, ArrayRef
<Value
*> Args
,
1069 const Twine
&NameStr
) {
1070 assert(getNumOperands() == 1 + Args
.size() && "NumOperands not set up?");
1071 llvm::copy(Args
, op_begin());
1072 setParentPad(ParentPad
);
1076 FuncletPadInst::FuncletPadInst(const FuncletPadInst
&FPI
)
1077 : Instruction(FPI
.getType(), FPI
.getOpcode(),
1078 OperandTraits
<FuncletPadInst
>::op_end(this) -
1079 FPI
.getNumOperands(),
1080 FPI
.getNumOperands()) {
1081 std::copy(FPI
.op_begin(), FPI
.op_end(), op_begin());
1082 setParentPad(FPI
.getParentPad());
1085 FuncletPadInst::FuncletPadInst(Instruction::FuncletPadOps Op
, Value
*ParentPad
,
1086 ArrayRef
<Value
*> Args
, unsigned Values
,
1087 const Twine
&NameStr
, Instruction
*InsertBefore
)
1088 : Instruction(ParentPad
->getType(), Op
,
1089 OperandTraits
<FuncletPadInst
>::op_end(this) - Values
, Values
,
1091 init(ParentPad
, Args
, NameStr
);
1094 FuncletPadInst::FuncletPadInst(Instruction::FuncletPadOps Op
, Value
*ParentPad
,
1095 ArrayRef
<Value
*> Args
, unsigned Values
,
1096 const Twine
&NameStr
, BasicBlock
*InsertAtEnd
)
1097 : Instruction(ParentPad
->getType(), Op
,
1098 OperandTraits
<FuncletPadInst
>::op_end(this) - Values
, Values
,
1100 init(ParentPad
, Args
, NameStr
);
1103 //===----------------------------------------------------------------------===//
1104 // UnreachableInst Implementation
1105 //===----------------------------------------------------------------------===//
1107 UnreachableInst::UnreachableInst(LLVMContext
&Context
,
1108 Instruction
*InsertBefore
)
1109 : Instruction(Type::getVoidTy(Context
), Instruction::Unreachable
, nullptr,
1111 UnreachableInst::UnreachableInst(LLVMContext
&Context
, BasicBlock
*InsertAtEnd
)
1112 : Instruction(Type::getVoidTy(Context
), Instruction::Unreachable
, nullptr,
1115 //===----------------------------------------------------------------------===//
1116 // BranchInst Implementation
1117 //===----------------------------------------------------------------------===//
1119 void BranchInst::AssertOK() {
1120 if (isConditional())
1121 assert(getCondition()->getType()->isIntegerTy(1) &&
1122 "May only branch on boolean predicates!");
1125 BranchInst::BranchInst(BasicBlock
*IfTrue
, Instruction
*InsertBefore
)
1126 : Instruction(Type::getVoidTy(IfTrue
->getContext()), Instruction::Br
,
1127 OperandTraits
<BranchInst
>::op_end(this) - 1, 1,
1129 assert(IfTrue
&& "Branch destination may not be null!");
1133 BranchInst::BranchInst(BasicBlock
*IfTrue
, BasicBlock
*IfFalse
, Value
*Cond
,
1134 Instruction
*InsertBefore
)
1135 : Instruction(Type::getVoidTy(IfTrue
->getContext()), Instruction::Br
,
1136 OperandTraits
<BranchInst
>::op_end(this) - 3, 3,
1146 BranchInst::BranchInst(BasicBlock
*IfTrue
, BasicBlock
*InsertAtEnd
)
1147 : Instruction(Type::getVoidTy(IfTrue
->getContext()), Instruction::Br
,
1148 OperandTraits
<BranchInst
>::op_end(this) - 1, 1, InsertAtEnd
) {
1149 assert(IfTrue
&& "Branch destination may not be null!");
1153 BranchInst::BranchInst(BasicBlock
*IfTrue
, BasicBlock
*IfFalse
, Value
*Cond
,
1154 BasicBlock
*InsertAtEnd
)
1155 : Instruction(Type::getVoidTy(IfTrue
->getContext()), Instruction::Br
,
1156 OperandTraits
<BranchInst
>::op_end(this) - 3, 3, InsertAtEnd
) {
1165 BranchInst::BranchInst(const BranchInst
&BI
)
1166 : Instruction(Type::getVoidTy(BI
.getContext()), Instruction::Br
,
1167 OperandTraits
<BranchInst
>::op_end(this) - BI
.getNumOperands(),
1168 BI
.getNumOperands()) {
1169 Op
<-1>() = BI
.Op
<-1>();
1170 if (BI
.getNumOperands() != 1) {
1171 assert(BI
.getNumOperands() == 3 && "BR can have 1 or 3 operands!");
1172 Op
<-3>() = BI
.Op
<-3>();
1173 Op
<-2>() = BI
.Op
<-2>();
1175 SubclassOptionalData
= BI
.SubclassOptionalData
;
1178 void BranchInst::swapSuccessors() {
1179 assert(isConditional() &&
1180 "Cannot swap successors of an unconditional branch");
1181 Op
<-1>().swap(Op
<-2>());
1183 // Update profile metadata if present and it matches our structural
1188 //===----------------------------------------------------------------------===//
1189 // AllocaInst Implementation
1190 //===----------------------------------------------------------------------===//
1192 static Value
*getAISize(LLVMContext
&Context
, Value
*Amt
) {
1194 Amt
= ConstantInt::get(Type::getInt32Ty(Context
), 1);
1196 assert(!isa
<BasicBlock
>(Amt
) &&
1197 "Passed basic block into allocation size parameter! Use other ctor");
1198 assert(Amt
->getType()->isIntegerTy() &&
1199 "Allocation array size is not an integer!");
1204 AllocaInst::AllocaInst(Type
*Ty
, unsigned AddrSpace
, const Twine
&Name
,
1205 Instruction
*InsertBefore
)
1206 : AllocaInst(Ty
, AddrSpace
, /*ArraySize=*/nullptr, Name
, InsertBefore
) {}
1208 AllocaInst::AllocaInst(Type
*Ty
, unsigned AddrSpace
, const Twine
&Name
,
1209 BasicBlock
*InsertAtEnd
)
1210 : AllocaInst(Ty
, AddrSpace
, /*ArraySize=*/nullptr, Name
, InsertAtEnd
) {}
1212 AllocaInst::AllocaInst(Type
*Ty
, unsigned AddrSpace
, Value
*ArraySize
,
1213 const Twine
&Name
, Instruction
*InsertBefore
)
1214 : AllocaInst(Ty
, AddrSpace
, ArraySize
, /*Align=*/0, Name
, InsertBefore
) {}
1216 AllocaInst::AllocaInst(Type
*Ty
, unsigned AddrSpace
, Value
*ArraySize
,
1217 const Twine
&Name
, BasicBlock
*InsertAtEnd
)
1218 : AllocaInst(Ty
, AddrSpace
, ArraySize
, /*Align=*/0, Name
, InsertAtEnd
) {}
1220 AllocaInst::AllocaInst(Type
*Ty
, unsigned AddrSpace
, Value
*ArraySize
,
1221 unsigned Align
, const Twine
&Name
,
1222 Instruction
*InsertBefore
)
1223 : UnaryInstruction(PointerType::get(Ty
, AddrSpace
), Alloca
,
1224 getAISize(Ty
->getContext(), ArraySize
), InsertBefore
),
1226 setAlignment(Align
);
1227 assert(!Ty
->isVoidTy() && "Cannot allocate void!");
1231 AllocaInst::AllocaInst(Type
*Ty
, unsigned AddrSpace
, Value
*ArraySize
,
1232 unsigned Align
, const Twine
&Name
,
1233 BasicBlock
*InsertAtEnd
)
1234 : UnaryInstruction(PointerType::get(Ty
, AddrSpace
), Alloca
,
1235 getAISize(Ty
->getContext(), ArraySize
), InsertAtEnd
),
1237 setAlignment(Align
);
1238 assert(!Ty
->isVoidTy() && "Cannot allocate void!");
1242 void AllocaInst::setAlignment(unsigned Align
) {
1243 assert((Align
& (Align
-1)) == 0 && "Alignment is not a power of 2!");
1244 assert(Align
<= MaximumAlignment
&&
1245 "Alignment is greater than MaximumAlignment!");
1246 setInstructionSubclassData((getSubclassDataFromInstruction() & ~31) |
1247 (Log2_32(Align
) + 1));
1248 assert(getAlignment() == Align
&& "Alignment representation error!");
1251 bool AllocaInst::isArrayAllocation() const {
1252 if (ConstantInt
*CI
= dyn_cast
<ConstantInt
>(getOperand(0)))
1253 return !CI
->isOne();
1257 /// isStaticAlloca - Return true if this alloca is in the entry block of the
1258 /// function and is a constant size. If so, the code generator will fold it
1259 /// into the prolog/epilog code, so it is basically free.
1260 bool AllocaInst::isStaticAlloca() const {
1261 // Must be constant size.
1262 if (!isa
<ConstantInt
>(getArraySize())) return false;
1264 // Must be in the entry block.
1265 const BasicBlock
*Parent
= getParent();
1266 return Parent
== &Parent
->getParent()->front() && !isUsedWithInAlloca();
1269 //===----------------------------------------------------------------------===//
1270 // LoadInst Implementation
1271 //===----------------------------------------------------------------------===//
1273 void LoadInst::AssertOK() {
1274 assert(getOperand(0)->getType()->isPointerTy() &&
1275 "Ptr must have pointer type.");
1276 assert(!(isAtomic() && getAlignment() == 0) &&
1277 "Alignment required for atomic load");
1280 LoadInst::LoadInst(Type
*Ty
, Value
*Ptr
, const Twine
&Name
,
1281 Instruction
*InsertBef
)
1282 : LoadInst(Ty
, Ptr
, Name
, /*isVolatile=*/false, InsertBef
) {}
1284 LoadInst::LoadInst(Type
*Ty
, Value
*Ptr
, const Twine
&Name
,
1285 BasicBlock
*InsertAE
)
1286 : LoadInst(Ty
, Ptr
, Name
, /*isVolatile=*/false, InsertAE
) {}
1288 LoadInst::LoadInst(Type
*Ty
, Value
*Ptr
, const Twine
&Name
, bool isVolatile
,
1289 Instruction
*InsertBef
)
1290 : LoadInst(Ty
, Ptr
, Name
, isVolatile
, /*Align=*/0, InsertBef
) {}
1292 LoadInst::LoadInst(Type
*Ty
, Value
*Ptr
, const Twine
&Name
, bool isVolatile
,
1293 BasicBlock
*InsertAE
)
1294 : LoadInst(Ty
, Ptr
, Name
, isVolatile
, /*Align=*/0, InsertAE
) {}
1296 LoadInst::LoadInst(Type
*Ty
, Value
*Ptr
, const Twine
&Name
, bool isVolatile
,
1297 unsigned Align
, Instruction
*InsertBef
)
1298 : LoadInst(Ty
, Ptr
, Name
, isVolatile
, Align
, AtomicOrdering::NotAtomic
,
1299 SyncScope::System
, InsertBef
) {}
1301 LoadInst::LoadInst(Type
*Ty
, Value
*Ptr
, const Twine
&Name
, bool isVolatile
,
1302 unsigned Align
, BasicBlock
*InsertAE
)
1303 : LoadInst(Ty
, Ptr
, Name
, isVolatile
, Align
, AtomicOrdering::NotAtomic
,
1304 SyncScope::System
, InsertAE
) {}
1306 LoadInst::LoadInst(Type
*Ty
, Value
*Ptr
, const Twine
&Name
, bool isVolatile
,
1307 unsigned Align
, AtomicOrdering Order
,
1308 SyncScope::ID SSID
, Instruction
*InsertBef
)
1309 : UnaryInstruction(Ty
, Load
, Ptr
, InsertBef
) {
1310 assert(Ty
== cast
<PointerType
>(Ptr
->getType())->getElementType());
1311 setVolatile(isVolatile
);
1312 setAlignment(Align
);
1313 setAtomic(Order
, SSID
);
1318 LoadInst::LoadInst(Type
*Ty
, Value
*Ptr
, const Twine
&Name
, bool isVolatile
,
1319 unsigned Align
, AtomicOrdering Order
, SyncScope::ID SSID
,
1320 BasicBlock
*InsertAE
)
1321 : UnaryInstruction(Ty
, Load
, Ptr
, InsertAE
) {
1322 assert(Ty
== cast
<PointerType
>(Ptr
->getType())->getElementType());
1323 setVolatile(isVolatile
);
1324 setAlignment(Align
);
1325 setAtomic(Order
, SSID
);
1330 void LoadInst::setAlignment(unsigned Align
) {
1331 assert((Align
& (Align
-1)) == 0 && "Alignment is not a power of 2!");
1332 assert(Align
<= MaximumAlignment
&&
1333 "Alignment is greater than MaximumAlignment!");
1334 setInstructionSubclassData((getSubclassDataFromInstruction() & ~(31 << 1)) |
1335 ((Log2_32(Align
)+1)<<1));
1336 assert(getAlignment() == Align
&& "Alignment representation error!");
1339 //===----------------------------------------------------------------------===//
1340 // StoreInst Implementation
1341 //===----------------------------------------------------------------------===//
1343 void StoreInst::AssertOK() {
1344 assert(getOperand(0) && getOperand(1) && "Both operands must be non-null!");
1345 assert(getOperand(1)->getType()->isPointerTy() &&
1346 "Ptr must have pointer type!");
1347 assert(getOperand(0)->getType() ==
1348 cast
<PointerType
>(getOperand(1)->getType())->getElementType()
1349 && "Ptr must be a pointer to Val type!");
1350 assert(!(isAtomic() && getAlignment() == 0) &&
1351 "Alignment required for atomic store");
1354 StoreInst::StoreInst(Value
*val
, Value
*addr
, Instruction
*InsertBefore
)
1355 : StoreInst(val
, addr
, /*isVolatile=*/false, InsertBefore
) {}
1357 StoreInst::StoreInst(Value
*val
, Value
*addr
, BasicBlock
*InsertAtEnd
)
1358 : StoreInst(val
, addr
, /*isVolatile=*/false, InsertAtEnd
) {}
1360 StoreInst::StoreInst(Value
*val
, Value
*addr
, bool isVolatile
,
1361 Instruction
*InsertBefore
)
1362 : StoreInst(val
, addr
, isVolatile
, /*Align=*/0, InsertBefore
) {}
1364 StoreInst::StoreInst(Value
*val
, Value
*addr
, bool isVolatile
,
1365 BasicBlock
*InsertAtEnd
)
1366 : StoreInst(val
, addr
, isVolatile
, /*Align=*/0, InsertAtEnd
) {}
1368 StoreInst::StoreInst(Value
*val
, Value
*addr
, bool isVolatile
, unsigned Align
,
1369 Instruction
*InsertBefore
)
1370 : StoreInst(val
, addr
, isVolatile
, Align
, AtomicOrdering::NotAtomic
,
1371 SyncScope::System
, InsertBefore
) {}
1373 StoreInst::StoreInst(Value
*val
, Value
*addr
, bool isVolatile
, unsigned Align
,
1374 BasicBlock
*InsertAtEnd
)
1375 : StoreInst(val
, addr
, isVolatile
, Align
, AtomicOrdering::NotAtomic
,
1376 SyncScope::System
, InsertAtEnd
) {}
1378 StoreInst::StoreInst(Value
*val
, Value
*addr
, bool isVolatile
,
1379 unsigned Align
, AtomicOrdering Order
,
1381 Instruction
*InsertBefore
)
1382 : Instruction(Type::getVoidTy(val
->getContext()), Store
,
1383 OperandTraits
<StoreInst
>::op_begin(this),
1384 OperandTraits
<StoreInst
>::operands(this),
1388 setVolatile(isVolatile
);
1389 setAlignment(Align
);
1390 setAtomic(Order
, SSID
);
1394 StoreInst::StoreInst(Value
*val
, Value
*addr
, bool isVolatile
,
1395 unsigned Align
, AtomicOrdering Order
,
1397 BasicBlock
*InsertAtEnd
)
1398 : Instruction(Type::getVoidTy(val
->getContext()), Store
,
1399 OperandTraits
<StoreInst
>::op_begin(this),
1400 OperandTraits
<StoreInst
>::operands(this),
1404 setVolatile(isVolatile
);
1405 setAlignment(Align
);
1406 setAtomic(Order
, SSID
);
1410 void StoreInst::setAlignment(unsigned Align
) {
1411 assert((Align
& (Align
-1)) == 0 && "Alignment is not a power of 2!");
1412 assert(Align
<= MaximumAlignment
&&
1413 "Alignment is greater than MaximumAlignment!");
1414 setInstructionSubclassData((getSubclassDataFromInstruction() & ~(31 << 1)) |
1415 ((Log2_32(Align
)+1) << 1));
1416 assert(getAlignment() == Align
&& "Alignment representation error!");
1419 //===----------------------------------------------------------------------===//
1420 // AtomicCmpXchgInst Implementation
1421 //===----------------------------------------------------------------------===//
1423 void AtomicCmpXchgInst::Init(Value
*Ptr
, Value
*Cmp
, Value
*NewVal
,
1424 AtomicOrdering SuccessOrdering
,
1425 AtomicOrdering FailureOrdering
,
1426 SyncScope::ID SSID
) {
1430 setSuccessOrdering(SuccessOrdering
);
1431 setFailureOrdering(FailureOrdering
);
1432 setSyncScopeID(SSID
);
1434 assert(getOperand(0) && getOperand(1) && getOperand(2) &&
1435 "All operands must be non-null!");
1436 assert(getOperand(0)->getType()->isPointerTy() &&
1437 "Ptr must have pointer type!");
1438 assert(getOperand(1)->getType() ==
1439 cast
<PointerType
>(getOperand(0)->getType())->getElementType()
1440 && "Ptr must be a pointer to Cmp type!");
1441 assert(getOperand(2)->getType() ==
1442 cast
<PointerType
>(getOperand(0)->getType())->getElementType()
1443 && "Ptr must be a pointer to NewVal type!");
1444 assert(SuccessOrdering
!= AtomicOrdering::NotAtomic
&&
1445 "AtomicCmpXchg instructions must be atomic!");
1446 assert(FailureOrdering
!= AtomicOrdering::NotAtomic
&&
1447 "AtomicCmpXchg instructions must be atomic!");
1448 assert(!isStrongerThan(FailureOrdering
, SuccessOrdering
) &&
1449 "AtomicCmpXchg failure argument shall be no stronger than the success "
1451 assert(FailureOrdering
!= AtomicOrdering::Release
&&
1452 FailureOrdering
!= AtomicOrdering::AcquireRelease
&&
1453 "AtomicCmpXchg failure ordering cannot include release semantics");
1456 AtomicCmpXchgInst::AtomicCmpXchgInst(Value
*Ptr
, Value
*Cmp
, Value
*NewVal
,
1457 AtomicOrdering SuccessOrdering
,
1458 AtomicOrdering FailureOrdering
,
1460 Instruction
*InsertBefore
)
1462 StructType::get(Cmp
->getType(), Type::getInt1Ty(Cmp
->getContext())),
1463 AtomicCmpXchg
, OperandTraits
<AtomicCmpXchgInst
>::op_begin(this),
1464 OperandTraits
<AtomicCmpXchgInst
>::operands(this), InsertBefore
) {
1465 Init(Ptr
, Cmp
, NewVal
, SuccessOrdering
, FailureOrdering
, SSID
);
1468 AtomicCmpXchgInst::AtomicCmpXchgInst(Value
*Ptr
, Value
*Cmp
, Value
*NewVal
,
1469 AtomicOrdering SuccessOrdering
,
1470 AtomicOrdering FailureOrdering
,
1472 BasicBlock
*InsertAtEnd
)
1474 StructType::get(Cmp
->getType(), Type::getInt1Ty(Cmp
->getContext())),
1475 AtomicCmpXchg
, OperandTraits
<AtomicCmpXchgInst
>::op_begin(this),
1476 OperandTraits
<AtomicCmpXchgInst
>::operands(this), InsertAtEnd
) {
1477 Init(Ptr
, Cmp
, NewVal
, SuccessOrdering
, FailureOrdering
, SSID
);
1480 //===----------------------------------------------------------------------===//
1481 // AtomicRMWInst Implementation
1482 //===----------------------------------------------------------------------===//
1484 void AtomicRMWInst::Init(BinOp Operation
, Value
*Ptr
, Value
*Val
,
1485 AtomicOrdering Ordering
,
1486 SyncScope::ID SSID
) {
1489 setOperation(Operation
);
1490 setOrdering(Ordering
);
1491 setSyncScopeID(SSID
);
1493 assert(getOperand(0) && getOperand(1) &&
1494 "All operands must be non-null!");
1495 assert(getOperand(0)->getType()->isPointerTy() &&
1496 "Ptr must have pointer type!");
1497 assert(getOperand(1)->getType() ==
1498 cast
<PointerType
>(getOperand(0)->getType())->getElementType()
1499 && "Ptr must be a pointer to Val type!");
1500 assert(Ordering
!= AtomicOrdering::NotAtomic
&&
1501 "AtomicRMW instructions must be atomic!");
1504 AtomicRMWInst::AtomicRMWInst(BinOp Operation
, Value
*Ptr
, Value
*Val
,
1505 AtomicOrdering Ordering
,
1507 Instruction
*InsertBefore
)
1508 : Instruction(Val
->getType(), AtomicRMW
,
1509 OperandTraits
<AtomicRMWInst
>::op_begin(this),
1510 OperandTraits
<AtomicRMWInst
>::operands(this),
1512 Init(Operation
, Ptr
, Val
, Ordering
, SSID
);
1515 AtomicRMWInst::AtomicRMWInst(BinOp Operation
, Value
*Ptr
, Value
*Val
,
1516 AtomicOrdering Ordering
,
1518 BasicBlock
*InsertAtEnd
)
1519 : Instruction(Val
->getType(), AtomicRMW
,
1520 OperandTraits
<AtomicRMWInst
>::op_begin(this),
1521 OperandTraits
<AtomicRMWInst
>::operands(this),
1523 Init(Operation
, Ptr
, Val
, Ordering
, SSID
);
1526 StringRef
AtomicRMWInst::getOperationName(BinOp Op
) {
1528 case AtomicRMWInst::Xchg
:
1530 case AtomicRMWInst::Add
:
1532 case AtomicRMWInst::Sub
:
1534 case AtomicRMWInst::And
:
1536 case AtomicRMWInst::Nand
:
1538 case AtomicRMWInst::Or
:
1540 case AtomicRMWInst::Xor
:
1542 case AtomicRMWInst::Max
:
1544 case AtomicRMWInst::Min
:
1546 case AtomicRMWInst::UMax
:
1548 case AtomicRMWInst::UMin
:
1550 case AtomicRMWInst::FAdd
:
1552 case AtomicRMWInst::FSub
:
1554 case AtomicRMWInst::BAD_BINOP
:
1555 return "<invalid operation>";
1558 llvm_unreachable("invalid atomicrmw operation");
1561 //===----------------------------------------------------------------------===//
1562 // FenceInst Implementation
1563 //===----------------------------------------------------------------------===//
1565 FenceInst::FenceInst(LLVMContext
&C
, AtomicOrdering Ordering
,
1567 Instruction
*InsertBefore
)
1568 : Instruction(Type::getVoidTy(C
), Fence
, nullptr, 0, InsertBefore
) {
1569 setOrdering(Ordering
);
1570 setSyncScopeID(SSID
);
1573 FenceInst::FenceInst(LLVMContext
&C
, AtomicOrdering Ordering
,
1575 BasicBlock
*InsertAtEnd
)
1576 : Instruction(Type::getVoidTy(C
), Fence
, nullptr, 0, InsertAtEnd
) {
1577 setOrdering(Ordering
);
1578 setSyncScopeID(SSID
);
1581 //===----------------------------------------------------------------------===//
1582 // GetElementPtrInst Implementation
1583 //===----------------------------------------------------------------------===//
1585 void GetElementPtrInst::init(Value
*Ptr
, ArrayRef
<Value
*> IdxList
,
1586 const Twine
&Name
) {
1587 assert(getNumOperands() == 1 + IdxList
.size() &&
1588 "NumOperands not initialized?");
1590 llvm::copy(IdxList
, op_begin() + 1);
1594 GetElementPtrInst::GetElementPtrInst(const GetElementPtrInst
&GEPI
)
1595 : Instruction(GEPI
.getType(), GetElementPtr
,
1596 OperandTraits
<GetElementPtrInst
>::op_end(this) -
1597 GEPI
.getNumOperands(),
1598 GEPI
.getNumOperands()),
1599 SourceElementType(GEPI
.SourceElementType
),
1600 ResultElementType(GEPI
.ResultElementType
) {
1601 std::copy(GEPI
.op_begin(), GEPI
.op_end(), op_begin());
1602 SubclassOptionalData
= GEPI
.SubclassOptionalData
;
1605 /// getIndexedType - Returns the type of the element that would be accessed with
1606 /// a gep instruction with the specified parameters.
1608 /// The Idxs pointer should point to a continuous piece of memory containing the
1609 /// indices, either as Value* or uint64_t.
1611 /// A null type is returned if the indices are invalid for the specified
1614 template <typename IndexTy
>
1615 static Type
*getIndexedTypeInternal(Type
*Agg
, ArrayRef
<IndexTy
> IdxList
) {
1616 // Handle the special case of the empty set index set, which is always valid.
1617 if (IdxList
.empty())
1620 // If there is at least one index, the top level type must be sized, otherwise
1621 // it cannot be 'stepped over'.
1622 if (!Agg
->isSized())
1625 unsigned CurIdx
= 1;
1626 for (; CurIdx
!= IdxList
.size(); ++CurIdx
) {
1627 CompositeType
*CT
= dyn_cast
<CompositeType
>(Agg
);
1628 if (!CT
|| CT
->isPointerTy()) return nullptr;
1629 IndexTy Index
= IdxList
[CurIdx
];
1630 if (!CT
->indexValid(Index
)) return nullptr;
1631 Agg
= CT
->getTypeAtIndex(Index
);
1633 return CurIdx
== IdxList
.size() ? Agg
: nullptr;
1636 Type
*GetElementPtrInst::getIndexedType(Type
*Ty
, ArrayRef
<Value
*> IdxList
) {
1637 return getIndexedTypeInternal(Ty
, IdxList
);
1640 Type
*GetElementPtrInst::getIndexedType(Type
*Ty
,
1641 ArrayRef
<Constant
*> IdxList
) {
1642 return getIndexedTypeInternal(Ty
, IdxList
);
1645 Type
*GetElementPtrInst::getIndexedType(Type
*Ty
, ArrayRef
<uint64_t> IdxList
) {
1646 return getIndexedTypeInternal(Ty
, IdxList
);
1649 /// hasAllZeroIndices - Return true if all of the indices of this GEP are
1650 /// zeros. If so, the result pointer and the first operand have the same
1651 /// value, just potentially different types.
1652 bool GetElementPtrInst::hasAllZeroIndices() const {
1653 for (unsigned i
= 1, e
= getNumOperands(); i
!= e
; ++i
) {
1654 if (ConstantInt
*CI
= dyn_cast
<ConstantInt
>(getOperand(i
))) {
1655 if (!CI
->isZero()) return false;
1663 /// hasAllConstantIndices - Return true if all of the indices of this GEP are
1664 /// constant integers. If so, the result pointer and the first operand have
1665 /// a constant offset between them.
1666 bool GetElementPtrInst::hasAllConstantIndices() const {
1667 for (unsigned i
= 1, e
= getNumOperands(); i
!= e
; ++i
) {
1668 if (!isa
<ConstantInt
>(getOperand(i
)))
1674 void GetElementPtrInst::setIsInBounds(bool B
) {
1675 cast
<GEPOperator
>(this)->setIsInBounds(B
);
1678 bool GetElementPtrInst::isInBounds() const {
1679 return cast
<GEPOperator
>(this)->isInBounds();
1682 bool GetElementPtrInst::accumulateConstantOffset(const DataLayout
&DL
,
1683 APInt
&Offset
) const {
1684 // Delegate to the generic GEPOperator implementation.
1685 return cast
<GEPOperator
>(this)->accumulateConstantOffset(DL
, Offset
);
1688 //===----------------------------------------------------------------------===//
1689 // ExtractElementInst Implementation
1690 //===----------------------------------------------------------------------===//
1692 ExtractElementInst::ExtractElementInst(Value
*Val
, Value
*Index
,
1694 Instruction
*InsertBef
)
1695 : Instruction(cast
<VectorType
>(Val
->getType())->getElementType(),
1697 OperandTraits
<ExtractElementInst
>::op_begin(this),
1699 assert(isValidOperands(Val
, Index
) &&
1700 "Invalid extractelement instruction operands!");
1706 ExtractElementInst::ExtractElementInst(Value
*Val
, Value
*Index
,
1708 BasicBlock
*InsertAE
)
1709 : Instruction(cast
<VectorType
>(Val
->getType())->getElementType(),
1711 OperandTraits
<ExtractElementInst
>::op_begin(this),
1713 assert(isValidOperands(Val
, Index
) &&
1714 "Invalid extractelement instruction operands!");
1721 bool ExtractElementInst::isValidOperands(const Value
*Val
, const Value
*Index
) {
1722 if (!Val
->getType()->isVectorTy() || !Index
->getType()->isIntegerTy())
1727 //===----------------------------------------------------------------------===//
1728 // InsertElementInst Implementation
1729 //===----------------------------------------------------------------------===//
1731 InsertElementInst::InsertElementInst(Value
*Vec
, Value
*Elt
, Value
*Index
,
1733 Instruction
*InsertBef
)
1734 : Instruction(Vec
->getType(), InsertElement
,
1735 OperandTraits
<InsertElementInst
>::op_begin(this),
1737 assert(isValidOperands(Vec
, Elt
, Index
) &&
1738 "Invalid insertelement instruction operands!");
1745 InsertElementInst::InsertElementInst(Value
*Vec
, Value
*Elt
, Value
*Index
,
1747 BasicBlock
*InsertAE
)
1748 : Instruction(Vec
->getType(), InsertElement
,
1749 OperandTraits
<InsertElementInst
>::op_begin(this),
1751 assert(isValidOperands(Vec
, Elt
, Index
) &&
1752 "Invalid insertelement instruction operands!");
1760 bool InsertElementInst::isValidOperands(const Value
*Vec
, const Value
*Elt
,
1761 const Value
*Index
) {
1762 if (!Vec
->getType()->isVectorTy())
1763 return false; // First operand of insertelement must be vector type.
1765 if (Elt
->getType() != cast
<VectorType
>(Vec
->getType())->getElementType())
1766 return false;// Second operand of insertelement must be vector element type.
1768 if (!Index
->getType()->isIntegerTy())
1769 return false; // Third operand of insertelement must be i32.
1773 //===----------------------------------------------------------------------===//
1774 // ShuffleVectorInst Implementation
1775 //===----------------------------------------------------------------------===//
1777 ShuffleVectorInst::ShuffleVectorInst(Value
*V1
, Value
*V2
, Value
*Mask
,
1779 Instruction
*InsertBefore
)
1780 : Instruction(VectorType::get(cast
<VectorType
>(V1
->getType())->getElementType(),
1781 cast
<VectorType
>(Mask
->getType())->getNumElements()),
1783 OperandTraits
<ShuffleVectorInst
>::op_begin(this),
1784 OperandTraits
<ShuffleVectorInst
>::operands(this),
1786 assert(isValidOperands(V1
, V2
, Mask
) &&
1787 "Invalid shuffle vector instruction operands!");
1794 ShuffleVectorInst::ShuffleVectorInst(Value
*V1
, Value
*V2
, Value
*Mask
,
1796 BasicBlock
*InsertAtEnd
)
1797 : Instruction(VectorType::get(cast
<VectorType
>(V1
->getType())->getElementType(),
1798 cast
<VectorType
>(Mask
->getType())->getNumElements()),
1800 OperandTraits
<ShuffleVectorInst
>::op_begin(this),
1801 OperandTraits
<ShuffleVectorInst
>::operands(this),
1803 assert(isValidOperands(V1
, V2
, Mask
) &&
1804 "Invalid shuffle vector instruction operands!");
1812 void ShuffleVectorInst::commute() {
1813 int NumOpElts
= Op
<0>()->getType()->getVectorNumElements();
1814 int NumMaskElts
= getMask()->getType()->getVectorNumElements();
1815 SmallVector
<Constant
*, 16> NewMask(NumMaskElts
);
1816 Type
*Int32Ty
= Type::getInt32Ty(getContext());
1817 for (int i
= 0; i
!= NumMaskElts
; ++i
) {
1818 int MaskElt
= getMaskValue(i
);
1819 if (MaskElt
== -1) {
1820 NewMask
[i
] = UndefValue::get(Int32Ty
);
1823 assert(MaskElt
>= 0 && MaskElt
< 2 * NumOpElts
&& "Out-of-range mask");
1824 MaskElt
= (MaskElt
< NumOpElts
) ? MaskElt
+ NumOpElts
: MaskElt
- NumOpElts
;
1825 NewMask
[i
] = ConstantInt::get(Int32Ty
, MaskElt
);
1827 Op
<2>() = ConstantVector::get(NewMask
);
1828 Op
<0>().swap(Op
<1>());
1831 bool ShuffleVectorInst::isValidOperands(const Value
*V1
, const Value
*V2
,
1832 const Value
*Mask
) {
1833 // V1 and V2 must be vectors of the same type.
1834 if (!V1
->getType()->isVectorTy() || V1
->getType() != V2
->getType())
1837 // Mask must be vector of i32.
1838 auto *MaskTy
= dyn_cast
<VectorType
>(Mask
->getType());
1839 if (!MaskTy
|| !MaskTy
->getElementType()->isIntegerTy(32))
1842 // Check to see if Mask is valid.
1843 if (isa
<UndefValue
>(Mask
) || isa
<ConstantAggregateZero
>(Mask
))
1846 if (const auto *MV
= dyn_cast
<ConstantVector
>(Mask
)) {
1847 unsigned V1Size
= cast
<VectorType
>(V1
->getType())->getNumElements();
1848 for (Value
*Op
: MV
->operands()) {
1849 if (auto *CI
= dyn_cast
<ConstantInt
>(Op
)) {
1850 if (CI
->uge(V1Size
*2))
1852 } else if (!isa
<UndefValue
>(Op
)) {
1859 if (const auto *CDS
= dyn_cast
<ConstantDataSequential
>(Mask
)) {
1860 unsigned V1Size
= cast
<VectorType
>(V1
->getType())->getNumElements();
1861 for (unsigned i
= 0, e
= MaskTy
->getNumElements(); i
!= e
; ++i
)
1862 if (CDS
->getElementAsInteger(i
) >= V1Size
*2)
1867 // The bitcode reader can create a place holder for a forward reference
1868 // used as the shuffle mask. When this occurs, the shuffle mask will
1869 // fall into this case and fail. To avoid this error, do this bit of
1870 // ugliness to allow such a mask pass.
1871 if (const auto *CE
= dyn_cast
<ConstantExpr
>(Mask
))
1872 if (CE
->getOpcode() == Instruction::UserOp1
)
1878 int ShuffleVectorInst::getMaskValue(const Constant
*Mask
, unsigned i
) {
1879 assert(i
< Mask
->getType()->getVectorNumElements() && "Index out of range");
1880 if (auto *CDS
= dyn_cast
<ConstantDataSequential
>(Mask
))
1881 return CDS
->getElementAsInteger(i
);
1882 Constant
*C
= Mask
->getAggregateElement(i
);
1883 if (isa
<UndefValue
>(C
))
1885 return cast
<ConstantInt
>(C
)->getZExtValue();
1888 void ShuffleVectorInst::getShuffleMask(const Constant
*Mask
,
1889 SmallVectorImpl
<int> &Result
) {
1890 unsigned NumElts
= Mask
->getType()->getVectorNumElements();
1892 if (auto *CDS
= dyn_cast
<ConstantDataSequential
>(Mask
)) {
1893 for (unsigned i
= 0; i
!= NumElts
; ++i
)
1894 Result
.push_back(CDS
->getElementAsInteger(i
));
1897 for (unsigned i
= 0; i
!= NumElts
; ++i
) {
1898 Constant
*C
= Mask
->getAggregateElement(i
);
1899 Result
.push_back(isa
<UndefValue
>(C
) ? -1 :
1900 cast
<ConstantInt
>(C
)->getZExtValue());
1904 static bool isSingleSourceMaskImpl(ArrayRef
<int> Mask
, int NumOpElts
) {
1905 assert(!Mask
.empty() && "Shuffle mask must contain elements");
1906 bool UsesLHS
= false;
1907 bool UsesRHS
= false;
1908 for (int i
= 0, NumMaskElts
= Mask
.size(); i
< NumMaskElts
; ++i
) {
1911 assert(Mask
[i
] >= 0 && Mask
[i
] < (NumOpElts
* 2) &&
1912 "Out-of-bounds shuffle mask element");
1913 UsesLHS
|= (Mask
[i
] < NumOpElts
);
1914 UsesRHS
|= (Mask
[i
] >= NumOpElts
);
1915 if (UsesLHS
&& UsesRHS
)
1918 assert((UsesLHS
^ UsesRHS
) && "Should have selected from exactly 1 source");
1922 bool ShuffleVectorInst::isSingleSourceMask(ArrayRef
<int> Mask
) {
1923 // We don't have vector operand size information, so assume operands are the
1924 // same size as the mask.
1925 return isSingleSourceMaskImpl(Mask
, Mask
.size());
1928 static bool isIdentityMaskImpl(ArrayRef
<int> Mask
, int NumOpElts
) {
1929 if (!isSingleSourceMaskImpl(Mask
, NumOpElts
))
1931 for (int i
= 0, NumMaskElts
= Mask
.size(); i
< NumMaskElts
; ++i
) {
1934 if (Mask
[i
] != i
&& Mask
[i
] != (NumOpElts
+ i
))
1940 bool ShuffleVectorInst::isIdentityMask(ArrayRef
<int> Mask
) {
1941 // We don't have vector operand size information, so assume operands are the
1942 // same size as the mask.
1943 return isIdentityMaskImpl(Mask
, Mask
.size());
1946 bool ShuffleVectorInst::isReverseMask(ArrayRef
<int> Mask
) {
1947 if (!isSingleSourceMask(Mask
))
1949 for (int i
= 0, NumElts
= Mask
.size(); i
< NumElts
; ++i
) {
1952 if (Mask
[i
] != (NumElts
- 1 - i
) && Mask
[i
] != (NumElts
+ NumElts
- 1 - i
))
1958 bool ShuffleVectorInst::isZeroEltSplatMask(ArrayRef
<int> Mask
) {
1959 if (!isSingleSourceMask(Mask
))
1961 for (int i
= 0, NumElts
= Mask
.size(); i
< NumElts
; ++i
) {
1964 if (Mask
[i
] != 0 && Mask
[i
] != NumElts
)
1970 bool ShuffleVectorInst::isSelectMask(ArrayRef
<int> Mask
) {
1971 // Select is differentiated from identity. It requires using both sources.
1972 if (isSingleSourceMask(Mask
))
1974 for (int i
= 0, NumElts
= Mask
.size(); i
< NumElts
; ++i
) {
1977 if (Mask
[i
] != i
&& Mask
[i
] != (NumElts
+ i
))
1983 bool ShuffleVectorInst::isTransposeMask(ArrayRef
<int> Mask
) {
1984 // Example masks that will return true:
1985 // v1 = <a, b, c, d>
1986 // v2 = <e, f, g, h>
1987 // trn1 = shufflevector v1, v2 <0, 4, 2, 6> = <a, e, c, g>
1988 // trn2 = shufflevector v1, v2 <1, 5, 3, 7> = <b, f, d, h>
1990 // 1. The number of elements in the mask must be a power-of-2 and at least 2.
1991 int NumElts
= Mask
.size();
1992 if (NumElts
< 2 || !isPowerOf2_32(NumElts
))
1995 // 2. The first element of the mask must be either a 0 or a 1.
1996 if (Mask
[0] != 0 && Mask
[0] != 1)
1999 // 3. The difference between the first 2 elements must be equal to the
2000 // number of elements in the mask.
2001 if ((Mask
[1] - Mask
[0]) != NumElts
)
2004 // 4. The difference between consecutive even-numbered and odd-numbered
2005 // elements must be equal to 2.
2006 for (int i
= 2; i
< NumElts
; ++i
) {
2007 int MaskEltVal
= Mask
[i
];
2008 if (MaskEltVal
== -1)
2010 int MaskEltPrevVal
= Mask
[i
- 2];
2011 if (MaskEltVal
- MaskEltPrevVal
!= 2)
2017 bool ShuffleVectorInst::isExtractSubvectorMask(ArrayRef
<int> Mask
,
2018 int NumSrcElts
, int &Index
) {
2019 // Must extract from a single source.
2020 if (!isSingleSourceMaskImpl(Mask
, NumSrcElts
))
2023 // Must be smaller (else this is an Identity shuffle).
2024 if (NumSrcElts
<= (int)Mask
.size())
2027 // Find start of extraction, accounting that we may start with an UNDEF.
2029 for (int i
= 0, e
= Mask
.size(); i
!= e
; ++i
) {
2033 int Offset
= (M
% NumSrcElts
) - i
;
2034 if (0 <= SubIndex
&& SubIndex
!= Offset
)
2039 if (0 <= SubIndex
) {
2046 bool ShuffleVectorInst::isIdentityWithPadding() const {
2047 int NumOpElts
= Op
<0>()->getType()->getVectorNumElements();
2048 int NumMaskElts
= getType()->getVectorNumElements();
2049 if (NumMaskElts
<= NumOpElts
)
2052 // The first part of the mask must choose elements from exactly 1 source op.
2053 SmallVector
<int, 16> Mask
= getShuffleMask();
2054 if (!isIdentityMaskImpl(Mask
, NumOpElts
))
2057 // All extending must be with undef elements.
2058 for (int i
= NumOpElts
; i
< NumMaskElts
; ++i
)
2065 bool ShuffleVectorInst::isIdentityWithExtract() const {
2066 int NumOpElts
= Op
<0>()->getType()->getVectorNumElements();
2067 int NumMaskElts
= getType()->getVectorNumElements();
2068 if (NumMaskElts
>= NumOpElts
)
2071 return isIdentityMaskImpl(getShuffleMask(), NumOpElts
);
2074 bool ShuffleVectorInst::isConcat() const {
2075 // Vector concatenation is differentiated from identity with padding.
2076 if (isa
<UndefValue
>(Op
<0>()) || isa
<UndefValue
>(Op
<1>()))
2079 int NumOpElts
= Op
<0>()->getType()->getVectorNumElements();
2080 int NumMaskElts
= getType()->getVectorNumElements();
2081 if (NumMaskElts
!= NumOpElts
* 2)
2084 // Use the mask length rather than the operands' vector lengths here. We
2085 // already know that the shuffle returns a vector twice as long as the inputs,
2086 // and neither of the inputs are undef vectors. If the mask picks consecutive
2087 // elements from both inputs, then this is a concatenation of the inputs.
2088 return isIdentityMaskImpl(getShuffleMask(), NumMaskElts
);
2091 //===----------------------------------------------------------------------===//
2092 // InsertValueInst Class
2093 //===----------------------------------------------------------------------===//
2095 void InsertValueInst::init(Value
*Agg
, Value
*Val
, ArrayRef
<unsigned> Idxs
,
2096 const Twine
&Name
) {
2097 assert(getNumOperands() == 2 && "NumOperands not initialized?");
2099 // There's no fundamental reason why we require at least one index
2100 // (other than weirdness with &*IdxBegin being invalid; see
2101 // getelementptr's init routine for example). But there's no
2102 // present need to support it.
2103 assert(!Idxs
.empty() && "InsertValueInst must have at least one index");
2105 assert(ExtractValueInst::getIndexedType(Agg
->getType(), Idxs
) ==
2106 Val
->getType() && "Inserted value must match indexed type!");
2110 Indices
.append(Idxs
.begin(), Idxs
.end());
2114 InsertValueInst::InsertValueInst(const InsertValueInst
&IVI
)
2115 : Instruction(IVI
.getType(), InsertValue
,
2116 OperandTraits
<InsertValueInst
>::op_begin(this), 2),
2117 Indices(IVI
.Indices
) {
2118 Op
<0>() = IVI
.getOperand(0);
2119 Op
<1>() = IVI
.getOperand(1);
2120 SubclassOptionalData
= IVI
.SubclassOptionalData
;
2123 //===----------------------------------------------------------------------===//
2124 // ExtractValueInst Class
2125 //===----------------------------------------------------------------------===//
2127 void ExtractValueInst::init(ArrayRef
<unsigned> Idxs
, const Twine
&Name
) {
2128 assert(getNumOperands() == 1 && "NumOperands not initialized?");
2130 // There's no fundamental reason why we require at least one index.
2131 // But there's no present need to support it.
2132 assert(!Idxs
.empty() && "ExtractValueInst must have at least one index");
2134 Indices
.append(Idxs
.begin(), Idxs
.end());
2138 ExtractValueInst::ExtractValueInst(const ExtractValueInst
&EVI
)
2139 : UnaryInstruction(EVI
.getType(), ExtractValue
, EVI
.getOperand(0)),
2140 Indices(EVI
.Indices
) {
2141 SubclassOptionalData
= EVI
.SubclassOptionalData
;
2144 // getIndexedType - Returns the type of the element that would be extracted
2145 // with an extractvalue instruction with the specified parameters.
2147 // A null type is returned if the indices are invalid for the specified
2150 Type
*ExtractValueInst::getIndexedType(Type
*Agg
,
2151 ArrayRef
<unsigned> Idxs
) {
2152 for (unsigned Index
: Idxs
) {
2153 // We can't use CompositeType::indexValid(Index) here.
2154 // indexValid() always returns true for arrays because getelementptr allows
2155 // out-of-bounds indices. Since we don't allow those for extractvalue and
2156 // insertvalue we need to check array indexing manually.
2157 // Since the only other types we can index into are struct types it's just
2158 // as easy to check those manually as well.
2159 if (ArrayType
*AT
= dyn_cast
<ArrayType
>(Agg
)) {
2160 if (Index
>= AT
->getNumElements())
2162 } else if (StructType
*ST
= dyn_cast
<StructType
>(Agg
)) {
2163 if (Index
>= ST
->getNumElements())
2166 // Not a valid type to index into.
2170 Agg
= cast
<CompositeType
>(Agg
)->getTypeAtIndex(Index
);
2172 return const_cast<Type
*>(Agg
);
2175 //===----------------------------------------------------------------------===//
2176 // UnaryOperator Class
2177 //===----------------------------------------------------------------------===//
2179 UnaryOperator::UnaryOperator(UnaryOps iType
, Value
*S
,
2180 Type
*Ty
, const Twine
&Name
,
2181 Instruction
*InsertBefore
)
2182 : UnaryInstruction(Ty
, iType
, S
, InsertBefore
) {
2188 UnaryOperator::UnaryOperator(UnaryOps iType
, Value
*S
,
2189 Type
*Ty
, const Twine
&Name
,
2190 BasicBlock
*InsertAtEnd
)
2191 : UnaryInstruction(Ty
, iType
, S
, InsertAtEnd
) {
2197 UnaryOperator
*UnaryOperator::Create(UnaryOps Op
, Value
*S
,
2199 Instruction
*InsertBefore
) {
2200 return new UnaryOperator(Op
, S
, S
->getType(), Name
, InsertBefore
);
2203 UnaryOperator
*UnaryOperator::Create(UnaryOps Op
, Value
*S
,
2205 BasicBlock
*InsertAtEnd
) {
2206 UnaryOperator
*Res
= Create(Op
, S
, Name
);
2207 InsertAtEnd
->getInstList().push_back(Res
);
2211 void UnaryOperator::AssertOK() {
2212 Value
*LHS
= getOperand(0);
2213 (void)LHS
; // Silence warnings.
2215 switch (getOpcode()) {
2217 assert(getType() == LHS
->getType() &&
2218 "Unary operation should return same type as operand!");
2219 assert(getType()->isFPOrFPVectorTy() &&
2220 "Tried to create a floating-point operation on a "
2221 "non-floating-point type!");
2223 default: llvm_unreachable("Invalid opcode provided");
2228 //===----------------------------------------------------------------------===//
2229 // BinaryOperator Class
2230 //===----------------------------------------------------------------------===//
2232 BinaryOperator::BinaryOperator(BinaryOps iType
, Value
*S1
, Value
*S2
,
2233 Type
*Ty
, const Twine
&Name
,
2234 Instruction
*InsertBefore
)
2235 : Instruction(Ty
, iType
,
2236 OperandTraits
<BinaryOperator
>::op_begin(this),
2237 OperandTraits
<BinaryOperator
>::operands(this),
2245 BinaryOperator::BinaryOperator(BinaryOps iType
, Value
*S1
, Value
*S2
,
2246 Type
*Ty
, const Twine
&Name
,
2247 BasicBlock
*InsertAtEnd
)
2248 : Instruction(Ty
, iType
,
2249 OperandTraits
<BinaryOperator
>::op_begin(this),
2250 OperandTraits
<BinaryOperator
>::operands(this),
2258 void BinaryOperator::AssertOK() {
2259 Value
*LHS
= getOperand(0), *RHS
= getOperand(1);
2260 (void)LHS
; (void)RHS
; // Silence warnings.
2261 assert(LHS
->getType() == RHS
->getType() &&
2262 "Binary operator operand types must match!");
2264 switch (getOpcode()) {
2267 assert(getType() == LHS
->getType() &&
2268 "Arithmetic operation should return same type as operands!");
2269 assert(getType()->isIntOrIntVectorTy() &&
2270 "Tried to create an integer operation on a non-integer type!");
2272 case FAdd
: case FSub
:
2274 assert(getType() == LHS
->getType() &&
2275 "Arithmetic operation should return same type as operands!");
2276 assert(getType()->isFPOrFPVectorTy() &&
2277 "Tried to create a floating-point operation on a "
2278 "non-floating-point type!");
2282 assert(getType() == LHS
->getType() &&
2283 "Arithmetic operation should return same type as operands!");
2284 assert(getType()->isIntOrIntVectorTy() &&
2285 "Incorrect operand type (not integer) for S/UDIV");
2288 assert(getType() == LHS
->getType() &&
2289 "Arithmetic operation should return same type as operands!");
2290 assert(getType()->isFPOrFPVectorTy() &&
2291 "Incorrect operand type (not floating point) for FDIV");
2295 assert(getType() == LHS
->getType() &&
2296 "Arithmetic operation should return same type as operands!");
2297 assert(getType()->isIntOrIntVectorTy() &&
2298 "Incorrect operand type (not integer) for S/UREM");
2301 assert(getType() == LHS
->getType() &&
2302 "Arithmetic operation should return same type as operands!");
2303 assert(getType()->isFPOrFPVectorTy() &&
2304 "Incorrect operand type (not floating point) for FREM");
2309 assert(getType() == LHS
->getType() &&
2310 "Shift operation should return same type as operands!");
2311 assert(getType()->isIntOrIntVectorTy() &&
2312 "Tried to create a shift operation on a non-integral type!");
2316 assert(getType() == LHS
->getType() &&
2317 "Logical operation should return same type as operands!");
2318 assert(getType()->isIntOrIntVectorTy() &&
2319 "Tried to create a logical operation on a non-integral type!");
2321 default: llvm_unreachable("Invalid opcode provided");
2326 BinaryOperator
*BinaryOperator::Create(BinaryOps Op
, Value
*S1
, Value
*S2
,
2328 Instruction
*InsertBefore
) {
2329 assert(S1
->getType() == S2
->getType() &&
2330 "Cannot create binary operator with two operands of differing type!");
2331 return new BinaryOperator(Op
, S1
, S2
, S1
->getType(), Name
, InsertBefore
);
2334 BinaryOperator
*BinaryOperator::Create(BinaryOps Op
, Value
*S1
, Value
*S2
,
2336 BasicBlock
*InsertAtEnd
) {
2337 BinaryOperator
*Res
= Create(Op
, S1
, S2
, Name
);
2338 InsertAtEnd
->getInstList().push_back(Res
);
2342 BinaryOperator
*BinaryOperator::CreateNeg(Value
*Op
, const Twine
&Name
,
2343 Instruction
*InsertBefore
) {
2344 Value
*zero
= ConstantFP::getZeroValueForNegation(Op
->getType());
2345 return new BinaryOperator(Instruction::Sub
,
2347 Op
->getType(), Name
, InsertBefore
);
2350 BinaryOperator
*BinaryOperator::CreateNeg(Value
*Op
, const Twine
&Name
,
2351 BasicBlock
*InsertAtEnd
) {
2352 Value
*zero
= ConstantFP::getZeroValueForNegation(Op
->getType());
2353 return new BinaryOperator(Instruction::Sub
,
2355 Op
->getType(), Name
, InsertAtEnd
);
2358 BinaryOperator
*BinaryOperator::CreateNSWNeg(Value
*Op
, const Twine
&Name
,
2359 Instruction
*InsertBefore
) {
2360 Value
*zero
= ConstantFP::getZeroValueForNegation(Op
->getType());
2361 return BinaryOperator::CreateNSWSub(zero
, Op
, Name
, InsertBefore
);
2364 BinaryOperator
*BinaryOperator::CreateNSWNeg(Value
*Op
, const Twine
&Name
,
2365 BasicBlock
*InsertAtEnd
) {
2366 Value
*zero
= ConstantFP::getZeroValueForNegation(Op
->getType());
2367 return BinaryOperator::CreateNSWSub(zero
, Op
, Name
, InsertAtEnd
);
2370 BinaryOperator
*BinaryOperator::CreateNUWNeg(Value
*Op
, const Twine
&Name
,
2371 Instruction
*InsertBefore
) {
2372 Value
*zero
= ConstantFP::getZeroValueForNegation(Op
->getType());
2373 return BinaryOperator::CreateNUWSub(zero
, Op
, Name
, InsertBefore
);
2376 BinaryOperator
*BinaryOperator::CreateNUWNeg(Value
*Op
, const Twine
&Name
,
2377 BasicBlock
*InsertAtEnd
) {
2378 Value
*zero
= ConstantFP::getZeroValueForNegation(Op
->getType());
2379 return BinaryOperator::CreateNUWSub(zero
, Op
, Name
, InsertAtEnd
);
2382 BinaryOperator
*BinaryOperator::CreateFNeg(Value
*Op
, const Twine
&Name
,
2383 Instruction
*InsertBefore
) {
2384 Value
*zero
= ConstantFP::getZeroValueForNegation(Op
->getType());
2385 return new BinaryOperator(Instruction::FSub
, zero
, Op
,
2386 Op
->getType(), Name
, InsertBefore
);
2389 BinaryOperator
*BinaryOperator::CreateFNeg(Value
*Op
, const Twine
&Name
,
2390 BasicBlock
*InsertAtEnd
) {
2391 Value
*zero
= ConstantFP::getZeroValueForNegation(Op
->getType());
2392 return new BinaryOperator(Instruction::FSub
, zero
, Op
,
2393 Op
->getType(), Name
, InsertAtEnd
);
2396 BinaryOperator
*BinaryOperator::CreateNot(Value
*Op
, const Twine
&Name
,
2397 Instruction
*InsertBefore
) {
2398 Constant
*C
= Constant::getAllOnesValue(Op
->getType());
2399 return new BinaryOperator(Instruction::Xor
, Op
, C
,
2400 Op
->getType(), Name
, InsertBefore
);
2403 BinaryOperator
*BinaryOperator::CreateNot(Value
*Op
, const Twine
&Name
,
2404 BasicBlock
*InsertAtEnd
) {
2405 Constant
*AllOnes
= Constant::getAllOnesValue(Op
->getType());
2406 return new BinaryOperator(Instruction::Xor
, Op
, AllOnes
,
2407 Op
->getType(), Name
, InsertAtEnd
);
2410 // Exchange the two operands to this instruction. This instruction is safe to
2411 // use on any binary instruction and does not modify the semantics of the
2412 // instruction. If the instruction is order-dependent (SetLT f.e.), the opcode
2414 bool BinaryOperator::swapOperands() {
2415 if (!isCommutative())
2416 return true; // Can't commute operands
2417 Op
<0>().swap(Op
<1>());
2421 //===----------------------------------------------------------------------===//
2422 // FPMathOperator Class
2423 //===----------------------------------------------------------------------===//
2425 float FPMathOperator::getFPAccuracy() const {
2427 cast
<Instruction
>(this)->getMetadata(LLVMContext::MD_fpmath
);
2430 ConstantFP
*Accuracy
= mdconst::extract
<ConstantFP
>(MD
->getOperand(0));
2431 return Accuracy
->getValueAPF().convertToFloat();
2434 //===----------------------------------------------------------------------===//
2436 //===----------------------------------------------------------------------===//
2438 // Just determine if this cast only deals with integral->integral conversion.
2439 bool CastInst::isIntegerCast() const {
2440 switch (getOpcode()) {
2441 default: return false;
2442 case Instruction::ZExt
:
2443 case Instruction::SExt
:
2444 case Instruction::Trunc
:
2446 case Instruction::BitCast
:
2447 return getOperand(0)->getType()->isIntegerTy() &&
2448 getType()->isIntegerTy();
2452 bool CastInst::isLosslessCast() const {
2453 // Only BitCast can be lossless, exit fast if we're not BitCast
2454 if (getOpcode() != Instruction::BitCast
)
2457 // Identity cast is always lossless
2458 Type
*SrcTy
= getOperand(0)->getType();
2459 Type
*DstTy
= getType();
2463 // Pointer to pointer is always lossless.
2464 if (SrcTy
->isPointerTy())
2465 return DstTy
->isPointerTy();
2466 return false; // Other types have no identity values
2469 /// This function determines if the CastInst does not require any bits to be
2470 /// changed in order to effect the cast. Essentially, it identifies cases where
2471 /// no code gen is necessary for the cast, hence the name no-op cast. For
2472 /// example, the following are all no-op casts:
2473 /// # bitcast i32* %x to i8*
2474 /// # bitcast <2 x i32> %x to <4 x i16>
2475 /// # ptrtoint i32* %x to i32 ; on 32-bit plaforms only
2476 /// Determine if the described cast is a no-op.
2477 bool CastInst::isNoopCast(Instruction::CastOps Opcode
,
2480 const DataLayout
&DL
) {
2482 default: llvm_unreachable("Invalid CastOp");
2483 case Instruction::Trunc
:
2484 case Instruction::ZExt
:
2485 case Instruction::SExt
:
2486 case Instruction::FPTrunc
:
2487 case Instruction::FPExt
:
2488 case Instruction::UIToFP
:
2489 case Instruction::SIToFP
:
2490 case Instruction::FPToUI
:
2491 case Instruction::FPToSI
:
2492 case Instruction::AddrSpaceCast
:
2493 // TODO: Target informations may give a more accurate answer here.
2495 case Instruction::BitCast
:
2496 return true; // BitCast never modifies bits.
2497 case Instruction::PtrToInt
:
2498 return DL
.getIntPtrType(SrcTy
)->getScalarSizeInBits() ==
2499 DestTy
->getScalarSizeInBits();
2500 case Instruction::IntToPtr
:
2501 return DL
.getIntPtrType(DestTy
)->getScalarSizeInBits() ==
2502 SrcTy
->getScalarSizeInBits();
2506 bool CastInst::isNoopCast(const DataLayout
&DL
) const {
2507 return isNoopCast(getOpcode(), getOperand(0)->getType(), getType(), DL
);
2510 /// This function determines if a pair of casts can be eliminated and what
2511 /// opcode should be used in the elimination. This assumes that there are two
2512 /// instructions like this:
2513 /// * %F = firstOpcode SrcTy %x to MidTy
2514 /// * %S = secondOpcode MidTy %F to DstTy
2515 /// The function returns a resultOpcode so these two casts can be replaced with:
2516 /// * %Replacement = resultOpcode %SrcTy %x to DstTy
2517 /// If no such cast is permitted, the function returns 0.
2518 unsigned CastInst::isEliminableCastPair(
2519 Instruction::CastOps firstOp
, Instruction::CastOps secondOp
,
2520 Type
*SrcTy
, Type
*MidTy
, Type
*DstTy
, Type
*SrcIntPtrTy
, Type
*MidIntPtrTy
,
2521 Type
*DstIntPtrTy
) {
2522 // Define the 144 possibilities for these two cast instructions. The values
2523 // in this matrix determine what to do in a given situation and select the
2524 // case in the switch below. The rows correspond to firstOp, the columns
2525 // correspond to secondOp. In looking at the table below, keep in mind
2526 // the following cast properties:
2528 // Size Compare Source Destination
2529 // Operator Src ? Size Type Sign Type Sign
2530 // -------- ------------ ------------------- ---------------------
2531 // TRUNC > Integer Any Integral Any
2532 // ZEXT < Integral Unsigned Integer Any
2533 // SEXT < Integral Signed Integer Any
2534 // FPTOUI n/a FloatPt n/a Integral Unsigned
2535 // FPTOSI n/a FloatPt n/a Integral Signed
2536 // UITOFP n/a Integral Unsigned FloatPt n/a
2537 // SITOFP n/a Integral Signed FloatPt n/a
2538 // FPTRUNC > FloatPt n/a FloatPt n/a
2539 // FPEXT < FloatPt n/a FloatPt n/a
2540 // PTRTOINT n/a Pointer n/a Integral Unsigned
2541 // INTTOPTR n/a Integral Unsigned Pointer n/a
2542 // BITCAST = FirstClass n/a FirstClass n/a
2543 // ADDRSPCST n/a Pointer n/a Pointer n/a
2545 // NOTE: some transforms are safe, but we consider them to be non-profitable.
2546 // For example, we could merge "fptoui double to i32" + "zext i32 to i64",
2547 // into "fptoui double to i64", but this loses information about the range
2548 // of the produced value (we no longer know the top-part is all zeros).
2549 // Further this conversion is often much more expensive for typical hardware,
2550 // and causes issues when building libgcc. We disallow fptosi+sext for the
2552 const unsigned numCastOps
=
2553 Instruction::CastOpsEnd
- Instruction::CastOpsBegin
;
2554 static const uint8_t CastResults
[numCastOps
][numCastOps
] = {
2555 // T F F U S F F P I B A -+
2556 // R Z S P P I I T P 2 N T S |
2557 // U E E 2 2 2 2 R E I T C C +- secondOp
2558 // N X X U S F F N X N 2 V V |
2559 // C T T I I P P C T T P T T -+
2560 { 1, 0, 0,99,99, 0, 0,99,99,99, 0, 3, 0}, // Trunc -+
2561 { 8, 1, 9,99,99, 2,17,99,99,99, 2, 3, 0}, // ZExt |
2562 { 8, 0, 1,99,99, 0, 2,99,99,99, 0, 3, 0}, // SExt |
2563 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3, 0}, // FPToUI |
2564 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3, 0}, // FPToSI |
2565 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4, 0}, // UIToFP +- firstOp
2566 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4, 0}, // SIToFP |
2567 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4, 0}, // FPTrunc |
2568 { 99,99,99, 2, 2,99,99, 8, 2,99,99, 4, 0}, // FPExt |
2569 { 1, 0, 0,99,99, 0, 0,99,99,99, 7, 3, 0}, // PtrToInt |
2570 { 99,99,99,99,99,99,99,99,99,11,99,15, 0}, // IntToPtr |
2571 { 5, 5, 5, 6, 6, 5, 5, 6, 6,16, 5, 1,14}, // BitCast |
2572 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,13,12}, // AddrSpaceCast -+
2575 // TODO: This logic could be encoded into the table above and handled in the
2577 // If either of the casts are a bitcast from scalar to vector, disallow the
2578 // merging. However, any pair of bitcasts are allowed.
2579 bool IsFirstBitcast
= (firstOp
== Instruction::BitCast
);
2580 bool IsSecondBitcast
= (secondOp
== Instruction::BitCast
);
2581 bool AreBothBitcasts
= IsFirstBitcast
&& IsSecondBitcast
;
2583 // Check if any of the casts convert scalars <-> vectors.
2584 if ((IsFirstBitcast
&& isa
<VectorType
>(SrcTy
) != isa
<VectorType
>(MidTy
)) ||
2585 (IsSecondBitcast
&& isa
<VectorType
>(MidTy
) != isa
<VectorType
>(DstTy
)))
2586 if (!AreBothBitcasts
)
2589 int ElimCase
= CastResults
[firstOp
-Instruction::CastOpsBegin
]
2590 [secondOp
-Instruction::CastOpsBegin
];
2593 // Categorically disallowed.
2596 // Allowed, use first cast's opcode.
2599 // Allowed, use second cast's opcode.
2602 // No-op cast in second op implies firstOp as long as the DestTy
2603 // is integer and we are not converting between a vector and a
2605 if (!SrcTy
->isVectorTy() && DstTy
->isIntegerTy())
2609 // No-op cast in second op implies firstOp as long as the DestTy
2610 // is floating point.
2611 if (DstTy
->isFloatingPointTy())
2615 // No-op cast in first op implies secondOp as long as the SrcTy
2617 if (SrcTy
->isIntegerTy())
2621 // No-op cast in first op implies secondOp as long as the SrcTy
2622 // is a floating point.
2623 if (SrcTy
->isFloatingPointTy())
2627 // Cannot simplify if address spaces are different!
2628 if (SrcTy
->getPointerAddressSpace() != DstTy
->getPointerAddressSpace())
2631 unsigned MidSize
= MidTy
->getScalarSizeInBits();
2632 // We can still fold this without knowing the actual sizes as long we
2633 // know that the intermediate pointer is the largest possible
2635 // FIXME: Is this always true?
2637 return Instruction::BitCast
;
2639 // ptrtoint, inttoptr -> bitcast (ptr -> ptr) if int size is >= ptr size.
2640 if (!SrcIntPtrTy
|| DstIntPtrTy
!= SrcIntPtrTy
)
2642 unsigned PtrSize
= SrcIntPtrTy
->getScalarSizeInBits();
2643 if (MidSize
>= PtrSize
)
2644 return Instruction::BitCast
;
2648 // ext, trunc -> bitcast, if the SrcTy and DstTy are same size
2649 // ext, trunc -> ext, if sizeof(SrcTy) < sizeof(DstTy)
2650 // ext, trunc -> trunc, if sizeof(SrcTy) > sizeof(DstTy)
2651 unsigned SrcSize
= SrcTy
->getScalarSizeInBits();
2652 unsigned DstSize
= DstTy
->getScalarSizeInBits();
2653 if (SrcSize
== DstSize
)
2654 return Instruction::BitCast
;
2655 else if (SrcSize
< DstSize
)
2660 // zext, sext -> zext, because sext can't sign extend after zext
2661 return Instruction::ZExt
;
2663 // inttoptr, ptrtoint -> bitcast if SrcSize<=PtrSize and SrcSize==DstSize
2666 unsigned PtrSize
= MidIntPtrTy
->getScalarSizeInBits();
2667 unsigned SrcSize
= SrcTy
->getScalarSizeInBits();
2668 unsigned DstSize
= DstTy
->getScalarSizeInBits();
2669 if (SrcSize
<= PtrSize
&& SrcSize
== DstSize
)
2670 return Instruction::BitCast
;
2674 // addrspacecast, addrspacecast -> bitcast, if SrcAS == DstAS
2675 // addrspacecast, addrspacecast -> addrspacecast, if SrcAS != DstAS
2676 if (SrcTy
->getPointerAddressSpace() != DstTy
->getPointerAddressSpace())
2677 return Instruction::AddrSpaceCast
;
2678 return Instruction::BitCast
;
2680 // FIXME: this state can be merged with (1), but the following assert
2681 // is useful to check the correcteness of the sequence due to semantic
2682 // change of bitcast.
2684 SrcTy
->isPtrOrPtrVectorTy() &&
2685 MidTy
->isPtrOrPtrVectorTy() &&
2686 DstTy
->isPtrOrPtrVectorTy() &&
2687 SrcTy
->getPointerAddressSpace() != MidTy
->getPointerAddressSpace() &&
2688 MidTy
->getPointerAddressSpace() == DstTy
->getPointerAddressSpace() &&
2689 "Illegal addrspacecast, bitcast sequence!");
2690 // Allowed, use first cast's opcode
2693 // bitcast, addrspacecast -> addrspacecast if the element type of
2694 // bitcast's source is the same as that of addrspacecast's destination.
2695 if (SrcTy
->getScalarType()->getPointerElementType() ==
2696 DstTy
->getScalarType()->getPointerElementType())
2697 return Instruction::AddrSpaceCast
;
2700 // FIXME: this state can be merged with (1), but the following assert
2701 // is useful to check the correcteness of the sequence due to semantic
2702 // change of bitcast.
2704 SrcTy
->isIntOrIntVectorTy() &&
2705 MidTy
->isPtrOrPtrVectorTy() &&
2706 DstTy
->isPtrOrPtrVectorTy() &&
2707 MidTy
->getPointerAddressSpace() == DstTy
->getPointerAddressSpace() &&
2708 "Illegal inttoptr, bitcast sequence!");
2709 // Allowed, use first cast's opcode
2712 // FIXME: this state can be merged with (2), but the following assert
2713 // is useful to check the correcteness of the sequence due to semantic
2714 // change of bitcast.
2716 SrcTy
->isPtrOrPtrVectorTy() &&
2717 MidTy
->isPtrOrPtrVectorTy() &&
2718 DstTy
->isIntOrIntVectorTy() &&
2719 SrcTy
->getPointerAddressSpace() == MidTy
->getPointerAddressSpace() &&
2720 "Illegal bitcast, ptrtoint sequence!");
2721 // Allowed, use second cast's opcode
2724 // (sitofp (zext x)) -> (uitofp x)
2725 return Instruction::UIToFP
;
2727 // Cast combination can't happen (error in input). This is for all cases
2728 // where the MidTy is not the same for the two cast instructions.
2729 llvm_unreachable("Invalid Cast Combination");
2731 llvm_unreachable("Error in CastResults table!!!");
2735 CastInst
*CastInst::Create(Instruction::CastOps op
, Value
*S
, Type
*Ty
,
2736 const Twine
&Name
, Instruction
*InsertBefore
) {
2737 assert(castIsValid(op
, S
, Ty
) && "Invalid cast!");
2738 // Construct and return the appropriate CastInst subclass
2740 case Trunc
: return new TruncInst (S
, Ty
, Name
, InsertBefore
);
2741 case ZExt
: return new ZExtInst (S
, Ty
, Name
, InsertBefore
);
2742 case SExt
: return new SExtInst (S
, Ty
, Name
, InsertBefore
);
2743 case FPTrunc
: return new FPTruncInst (S
, Ty
, Name
, InsertBefore
);
2744 case FPExt
: return new FPExtInst (S
, Ty
, Name
, InsertBefore
);
2745 case UIToFP
: return new UIToFPInst (S
, Ty
, Name
, InsertBefore
);
2746 case SIToFP
: return new SIToFPInst (S
, Ty
, Name
, InsertBefore
);
2747 case FPToUI
: return new FPToUIInst (S
, Ty
, Name
, InsertBefore
);
2748 case FPToSI
: return new FPToSIInst (S
, Ty
, Name
, InsertBefore
);
2749 case PtrToInt
: return new PtrToIntInst (S
, Ty
, Name
, InsertBefore
);
2750 case IntToPtr
: return new IntToPtrInst (S
, Ty
, Name
, InsertBefore
);
2751 case BitCast
: return new BitCastInst (S
, Ty
, Name
, InsertBefore
);
2752 case AddrSpaceCast
: return new AddrSpaceCastInst (S
, Ty
, Name
, InsertBefore
);
2753 default: llvm_unreachable("Invalid opcode provided");
2757 CastInst
*CastInst::Create(Instruction::CastOps op
, Value
*S
, Type
*Ty
,
2758 const Twine
&Name
, BasicBlock
*InsertAtEnd
) {
2759 assert(castIsValid(op
, S
, Ty
) && "Invalid cast!");
2760 // Construct and return the appropriate CastInst subclass
2762 case Trunc
: return new TruncInst (S
, Ty
, Name
, InsertAtEnd
);
2763 case ZExt
: return new ZExtInst (S
, Ty
, Name
, InsertAtEnd
);
2764 case SExt
: return new SExtInst (S
, Ty
, Name
, InsertAtEnd
);
2765 case FPTrunc
: return new FPTruncInst (S
, Ty
, Name
, InsertAtEnd
);
2766 case FPExt
: return new FPExtInst (S
, Ty
, Name
, InsertAtEnd
);
2767 case UIToFP
: return new UIToFPInst (S
, Ty
, Name
, InsertAtEnd
);
2768 case SIToFP
: return new SIToFPInst (S
, Ty
, Name
, InsertAtEnd
);
2769 case FPToUI
: return new FPToUIInst (S
, Ty
, Name
, InsertAtEnd
);
2770 case FPToSI
: return new FPToSIInst (S
, Ty
, Name
, InsertAtEnd
);
2771 case PtrToInt
: return new PtrToIntInst (S
, Ty
, Name
, InsertAtEnd
);
2772 case IntToPtr
: return new IntToPtrInst (S
, Ty
, Name
, InsertAtEnd
);
2773 case BitCast
: return new BitCastInst (S
, Ty
, Name
, InsertAtEnd
);
2774 case AddrSpaceCast
: return new AddrSpaceCastInst (S
, Ty
, Name
, InsertAtEnd
);
2775 default: llvm_unreachable("Invalid opcode provided");
2779 CastInst
*CastInst::CreateZExtOrBitCast(Value
*S
, Type
*Ty
,
2781 Instruction
*InsertBefore
) {
2782 if (S
->getType()->getScalarSizeInBits() == Ty
->getScalarSizeInBits())
2783 return Create(Instruction::BitCast
, S
, Ty
, Name
, InsertBefore
);
2784 return Create(Instruction::ZExt
, S
, Ty
, Name
, InsertBefore
);
2787 CastInst
*CastInst::CreateZExtOrBitCast(Value
*S
, Type
*Ty
,
2789 BasicBlock
*InsertAtEnd
) {
2790 if (S
->getType()->getScalarSizeInBits() == Ty
->getScalarSizeInBits())
2791 return Create(Instruction::BitCast
, S
, Ty
, Name
, InsertAtEnd
);
2792 return Create(Instruction::ZExt
, S
, Ty
, Name
, InsertAtEnd
);
2795 CastInst
*CastInst::CreateSExtOrBitCast(Value
*S
, Type
*Ty
,
2797 Instruction
*InsertBefore
) {
2798 if (S
->getType()->getScalarSizeInBits() == Ty
->getScalarSizeInBits())
2799 return Create(Instruction::BitCast
, S
, Ty
, Name
, InsertBefore
);
2800 return Create(Instruction::SExt
, S
, Ty
, Name
, InsertBefore
);
2803 CastInst
*CastInst::CreateSExtOrBitCast(Value
*S
, Type
*Ty
,
2805 BasicBlock
*InsertAtEnd
) {
2806 if (S
->getType()->getScalarSizeInBits() == Ty
->getScalarSizeInBits())
2807 return Create(Instruction::BitCast
, S
, Ty
, Name
, InsertAtEnd
);
2808 return Create(Instruction::SExt
, S
, Ty
, Name
, InsertAtEnd
);
2811 CastInst
*CastInst::CreateTruncOrBitCast(Value
*S
, Type
*Ty
,
2813 Instruction
*InsertBefore
) {
2814 if (S
->getType()->getScalarSizeInBits() == Ty
->getScalarSizeInBits())
2815 return Create(Instruction::BitCast
, S
, Ty
, Name
, InsertBefore
);
2816 return Create(Instruction::Trunc
, S
, Ty
, Name
, InsertBefore
);
2819 CastInst
*CastInst::CreateTruncOrBitCast(Value
*S
, Type
*Ty
,
2821 BasicBlock
*InsertAtEnd
) {
2822 if (S
->getType()->getScalarSizeInBits() == Ty
->getScalarSizeInBits())
2823 return Create(Instruction::BitCast
, S
, Ty
, Name
, InsertAtEnd
);
2824 return Create(Instruction::Trunc
, S
, Ty
, Name
, InsertAtEnd
);
2827 CastInst
*CastInst::CreatePointerCast(Value
*S
, Type
*Ty
,
2829 BasicBlock
*InsertAtEnd
) {
2830 assert(S
->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
2831 assert((Ty
->isIntOrIntVectorTy() || Ty
->isPtrOrPtrVectorTy()) &&
2833 assert(Ty
->isVectorTy() == S
->getType()->isVectorTy() && "Invalid cast");
2834 assert((!Ty
->isVectorTy() ||
2835 Ty
->getVectorNumElements() == S
->getType()->getVectorNumElements()) &&
2838 if (Ty
->isIntOrIntVectorTy())
2839 return Create(Instruction::PtrToInt
, S
, Ty
, Name
, InsertAtEnd
);
2841 return CreatePointerBitCastOrAddrSpaceCast(S
, Ty
, Name
, InsertAtEnd
);
2844 /// Create a BitCast or a PtrToInt cast instruction
2845 CastInst
*CastInst::CreatePointerCast(Value
*S
, Type
*Ty
,
2847 Instruction
*InsertBefore
) {
2848 assert(S
->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
2849 assert((Ty
->isIntOrIntVectorTy() || Ty
->isPtrOrPtrVectorTy()) &&
2851 assert(Ty
->isVectorTy() == S
->getType()->isVectorTy() && "Invalid cast");
2852 assert((!Ty
->isVectorTy() ||
2853 Ty
->getVectorNumElements() == S
->getType()->getVectorNumElements()) &&
2856 if (Ty
->isIntOrIntVectorTy())
2857 return Create(Instruction::PtrToInt
, S
, Ty
, Name
, InsertBefore
);
2859 return CreatePointerBitCastOrAddrSpaceCast(S
, Ty
, Name
, InsertBefore
);
2862 CastInst
*CastInst::CreatePointerBitCastOrAddrSpaceCast(
2865 BasicBlock
*InsertAtEnd
) {
2866 assert(S
->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
2867 assert(Ty
->isPtrOrPtrVectorTy() && "Invalid cast");
2869 if (S
->getType()->getPointerAddressSpace() != Ty
->getPointerAddressSpace())
2870 return Create(Instruction::AddrSpaceCast
, S
, Ty
, Name
, InsertAtEnd
);
2872 return Create(Instruction::BitCast
, S
, Ty
, Name
, InsertAtEnd
);
2875 CastInst
*CastInst::CreatePointerBitCastOrAddrSpaceCast(
2878 Instruction
*InsertBefore
) {
2879 assert(S
->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
2880 assert(Ty
->isPtrOrPtrVectorTy() && "Invalid cast");
2882 if (S
->getType()->getPointerAddressSpace() != Ty
->getPointerAddressSpace())
2883 return Create(Instruction::AddrSpaceCast
, S
, Ty
, Name
, InsertBefore
);
2885 return Create(Instruction::BitCast
, S
, Ty
, Name
, InsertBefore
);
2888 CastInst
*CastInst::CreateBitOrPointerCast(Value
*S
, Type
*Ty
,
2890 Instruction
*InsertBefore
) {
2891 if (S
->getType()->isPointerTy() && Ty
->isIntegerTy())
2892 return Create(Instruction::PtrToInt
, S
, Ty
, Name
, InsertBefore
);
2893 if (S
->getType()->isIntegerTy() && Ty
->isPointerTy())
2894 return Create(Instruction::IntToPtr
, S
, Ty
, Name
, InsertBefore
);
2896 return Create(Instruction::BitCast
, S
, Ty
, Name
, InsertBefore
);
2899 CastInst
*CastInst::CreateIntegerCast(Value
*C
, Type
*Ty
,
2900 bool isSigned
, const Twine
&Name
,
2901 Instruction
*InsertBefore
) {
2902 assert(C
->getType()->isIntOrIntVectorTy() && Ty
->isIntOrIntVectorTy() &&
2903 "Invalid integer cast");
2904 unsigned SrcBits
= C
->getType()->getScalarSizeInBits();
2905 unsigned DstBits
= Ty
->getScalarSizeInBits();
2906 Instruction::CastOps opcode
=
2907 (SrcBits
== DstBits
? Instruction::BitCast
:
2908 (SrcBits
> DstBits
? Instruction::Trunc
:
2909 (isSigned
? Instruction::SExt
: Instruction::ZExt
)));
2910 return Create(opcode
, C
, Ty
, Name
, InsertBefore
);
2913 CastInst
*CastInst::CreateIntegerCast(Value
*C
, Type
*Ty
,
2914 bool isSigned
, const Twine
&Name
,
2915 BasicBlock
*InsertAtEnd
) {
2916 assert(C
->getType()->isIntOrIntVectorTy() && Ty
->isIntOrIntVectorTy() &&
2918 unsigned SrcBits
= C
->getType()->getScalarSizeInBits();
2919 unsigned DstBits
= Ty
->getScalarSizeInBits();
2920 Instruction::CastOps opcode
=
2921 (SrcBits
== DstBits
? Instruction::BitCast
:
2922 (SrcBits
> DstBits
? Instruction::Trunc
:
2923 (isSigned
? Instruction::SExt
: Instruction::ZExt
)));
2924 return Create(opcode
, C
, Ty
, Name
, InsertAtEnd
);
2927 CastInst
*CastInst::CreateFPCast(Value
*C
, Type
*Ty
,
2929 Instruction
*InsertBefore
) {
2930 assert(C
->getType()->isFPOrFPVectorTy() && Ty
->isFPOrFPVectorTy() &&
2932 unsigned SrcBits
= C
->getType()->getScalarSizeInBits();
2933 unsigned DstBits
= Ty
->getScalarSizeInBits();
2934 Instruction::CastOps opcode
=
2935 (SrcBits
== DstBits
? Instruction::BitCast
:
2936 (SrcBits
> DstBits
? Instruction::FPTrunc
: Instruction::FPExt
));
2937 return Create(opcode
, C
, Ty
, Name
, InsertBefore
);
2940 CastInst
*CastInst::CreateFPCast(Value
*C
, Type
*Ty
,
2942 BasicBlock
*InsertAtEnd
) {
2943 assert(C
->getType()->isFPOrFPVectorTy() && Ty
->isFPOrFPVectorTy() &&
2945 unsigned SrcBits
= C
->getType()->getScalarSizeInBits();
2946 unsigned DstBits
= Ty
->getScalarSizeInBits();
2947 Instruction::CastOps opcode
=
2948 (SrcBits
== DstBits
? Instruction::BitCast
:
2949 (SrcBits
> DstBits
? Instruction::FPTrunc
: Instruction::FPExt
));
2950 return Create(opcode
, C
, Ty
, Name
, InsertAtEnd
);
2953 // Check whether it is valid to call getCastOpcode for these types.
2954 // This routine must be kept in sync with getCastOpcode.
2955 bool CastInst::isCastable(Type
*SrcTy
, Type
*DestTy
) {
2956 if (!SrcTy
->isFirstClassType() || !DestTy
->isFirstClassType())
2959 if (SrcTy
== DestTy
)
2962 if (VectorType
*SrcVecTy
= dyn_cast
<VectorType
>(SrcTy
))
2963 if (VectorType
*DestVecTy
= dyn_cast
<VectorType
>(DestTy
))
2964 if (SrcVecTy
->getNumElements() == DestVecTy
->getNumElements()) {
2965 // An element by element cast. Valid if casting the elements is valid.
2966 SrcTy
= SrcVecTy
->getElementType();
2967 DestTy
= DestVecTy
->getElementType();
2970 // Get the bit sizes, we'll need these
2971 unsigned SrcBits
= SrcTy
->getPrimitiveSizeInBits(); // 0 for ptr
2972 unsigned DestBits
= DestTy
->getPrimitiveSizeInBits(); // 0 for ptr
2974 // Run through the possibilities ...
2975 if (DestTy
->isIntegerTy()) { // Casting to integral
2976 if (SrcTy
->isIntegerTy()) // Casting from integral
2978 if (SrcTy
->isFloatingPointTy()) // Casting from floating pt
2980 if (SrcTy
->isVectorTy()) // Casting from vector
2981 return DestBits
== SrcBits
;
2982 // Casting from something else
2983 return SrcTy
->isPointerTy();
2985 if (DestTy
->isFloatingPointTy()) { // Casting to floating pt
2986 if (SrcTy
->isIntegerTy()) // Casting from integral
2988 if (SrcTy
->isFloatingPointTy()) // Casting from floating pt
2990 if (SrcTy
->isVectorTy()) // Casting from vector
2991 return DestBits
== SrcBits
;
2992 // Casting from something else
2995 if (DestTy
->isVectorTy()) // Casting to vector
2996 return DestBits
== SrcBits
;
2997 if (DestTy
->isPointerTy()) { // Casting to pointer
2998 if (SrcTy
->isPointerTy()) // Casting from pointer
3000 return SrcTy
->isIntegerTy(); // Casting from integral
3002 if (DestTy
->isX86_MMXTy()) {
3003 if (SrcTy
->isVectorTy())
3004 return DestBits
== SrcBits
; // 64-bit vector to MMX
3006 } // Casting to something else
3010 bool CastInst::isBitCastable(Type
*SrcTy
, Type
*DestTy
) {
3011 if (!SrcTy
->isFirstClassType() || !DestTy
->isFirstClassType())
3014 if (SrcTy
== DestTy
)
3017 if (VectorType
*SrcVecTy
= dyn_cast
<VectorType
>(SrcTy
)) {
3018 if (VectorType
*DestVecTy
= dyn_cast
<VectorType
>(DestTy
)) {
3019 if (SrcVecTy
->getNumElements() == DestVecTy
->getNumElements()) {
3020 // An element by element cast. Valid if casting the elements is valid.
3021 SrcTy
= SrcVecTy
->getElementType();
3022 DestTy
= DestVecTy
->getElementType();
3027 if (PointerType
*DestPtrTy
= dyn_cast
<PointerType
>(DestTy
)) {
3028 if (PointerType
*SrcPtrTy
= dyn_cast
<PointerType
>(SrcTy
)) {
3029 return SrcPtrTy
->getAddressSpace() == DestPtrTy
->getAddressSpace();
3033 unsigned SrcBits
= SrcTy
->getPrimitiveSizeInBits(); // 0 for ptr
3034 unsigned DestBits
= DestTy
->getPrimitiveSizeInBits(); // 0 for ptr
3036 // Could still have vectors of pointers if the number of elements doesn't
3038 if (SrcBits
== 0 || DestBits
== 0)
3041 if (SrcBits
!= DestBits
)
3044 if (DestTy
->isX86_MMXTy() || SrcTy
->isX86_MMXTy())
3050 bool CastInst::isBitOrNoopPointerCastable(Type
*SrcTy
, Type
*DestTy
,
3051 const DataLayout
&DL
) {
3052 // ptrtoint and inttoptr are not allowed on non-integral pointers
3053 if (auto *PtrTy
= dyn_cast
<PointerType
>(SrcTy
))
3054 if (auto *IntTy
= dyn_cast
<IntegerType
>(DestTy
))
3055 return (IntTy
->getBitWidth() == DL
.getPointerTypeSizeInBits(PtrTy
) &&
3056 !DL
.isNonIntegralPointerType(PtrTy
));
3057 if (auto *PtrTy
= dyn_cast
<PointerType
>(DestTy
))
3058 if (auto *IntTy
= dyn_cast
<IntegerType
>(SrcTy
))
3059 return (IntTy
->getBitWidth() == DL
.getPointerTypeSizeInBits(PtrTy
) &&
3060 !DL
.isNonIntegralPointerType(PtrTy
));
3062 return isBitCastable(SrcTy
, DestTy
);
3065 // Provide a way to get a "cast" where the cast opcode is inferred from the
3066 // types and size of the operand. This, basically, is a parallel of the
3067 // logic in the castIsValid function below. This axiom should hold:
3068 // castIsValid( getCastOpcode(Val, Ty), Val, Ty)
3069 // should not assert in castIsValid. In other words, this produces a "correct"
3070 // casting opcode for the arguments passed to it.
3071 // This routine must be kept in sync with isCastable.
3072 Instruction::CastOps
3073 CastInst::getCastOpcode(
3074 const Value
*Src
, bool SrcIsSigned
, Type
*DestTy
, bool DestIsSigned
) {
3075 Type
*SrcTy
= Src
->getType();
3077 assert(SrcTy
->isFirstClassType() && DestTy
->isFirstClassType() &&
3078 "Only first class types are castable!");
3080 if (SrcTy
== DestTy
)
3083 // FIXME: Check address space sizes here
3084 if (VectorType
*SrcVecTy
= dyn_cast
<VectorType
>(SrcTy
))
3085 if (VectorType
*DestVecTy
= dyn_cast
<VectorType
>(DestTy
))
3086 if (SrcVecTy
->getNumElements() == DestVecTy
->getNumElements()) {
3087 // An element by element cast. Find the appropriate opcode based on the
3089 SrcTy
= SrcVecTy
->getElementType();
3090 DestTy
= DestVecTy
->getElementType();
3093 // Get the bit sizes, we'll need these
3094 unsigned SrcBits
= SrcTy
->getPrimitiveSizeInBits(); // 0 for ptr
3095 unsigned DestBits
= DestTy
->getPrimitiveSizeInBits(); // 0 for ptr
3097 // Run through the possibilities ...
3098 if (DestTy
->isIntegerTy()) { // Casting to integral
3099 if (SrcTy
->isIntegerTy()) { // Casting from integral
3100 if (DestBits
< SrcBits
)
3101 return Trunc
; // int -> smaller int
3102 else if (DestBits
> SrcBits
) { // its an extension
3104 return SExt
; // signed -> SEXT
3106 return ZExt
; // unsigned -> ZEXT
3108 return BitCast
; // Same size, No-op cast
3110 } else if (SrcTy
->isFloatingPointTy()) { // Casting from floating pt
3112 return FPToSI
; // FP -> sint
3114 return FPToUI
; // FP -> uint
3115 } else if (SrcTy
->isVectorTy()) {
3116 assert(DestBits
== SrcBits
&&
3117 "Casting vector to integer of different width");
3118 return BitCast
; // Same size, no-op cast
3120 assert(SrcTy
->isPointerTy() &&
3121 "Casting from a value that is not first-class type");
3122 return PtrToInt
; // ptr -> int
3124 } else if (DestTy
->isFloatingPointTy()) { // Casting to floating pt
3125 if (SrcTy
->isIntegerTy()) { // Casting from integral
3127 return SIToFP
; // sint -> FP
3129 return UIToFP
; // uint -> FP
3130 } else if (SrcTy
->isFloatingPointTy()) { // Casting from floating pt
3131 if (DestBits
< SrcBits
) {
3132 return FPTrunc
; // FP -> smaller FP
3133 } else if (DestBits
> SrcBits
) {
3134 return FPExt
; // FP -> larger FP
3136 return BitCast
; // same size, no-op cast
3138 } else if (SrcTy
->isVectorTy()) {
3139 assert(DestBits
== SrcBits
&&
3140 "Casting vector to floating point of different width");
3141 return BitCast
; // same size, no-op cast
3143 llvm_unreachable("Casting pointer or non-first class to float");
3144 } else if (DestTy
->isVectorTy()) {
3145 assert(DestBits
== SrcBits
&&
3146 "Illegal cast to vector (wrong type or size)");
3148 } else if (DestTy
->isPointerTy()) {
3149 if (SrcTy
->isPointerTy()) {
3150 if (DestTy
->getPointerAddressSpace() != SrcTy
->getPointerAddressSpace())
3151 return AddrSpaceCast
;
3152 return BitCast
; // ptr -> ptr
3153 } else if (SrcTy
->isIntegerTy()) {
3154 return IntToPtr
; // int -> ptr
3156 llvm_unreachable("Casting pointer to other than pointer or int");
3157 } else if (DestTy
->isX86_MMXTy()) {
3158 if (SrcTy
->isVectorTy()) {
3159 assert(DestBits
== SrcBits
&& "Casting vector of wrong width to X86_MMX");
3160 return BitCast
; // 64-bit vector to MMX
3162 llvm_unreachable("Illegal cast to X86_MMX");
3164 llvm_unreachable("Casting to type that is not first-class");
3167 //===----------------------------------------------------------------------===//
3168 // CastInst SubClass Constructors
3169 //===----------------------------------------------------------------------===//
3171 /// Check that the construction parameters for a CastInst are correct. This
3172 /// could be broken out into the separate constructors but it is useful to have
3173 /// it in one place and to eliminate the redundant code for getting the sizes
3174 /// of the types involved.
3176 CastInst::castIsValid(Instruction::CastOps op
, Value
*S
, Type
*DstTy
) {
3177 // Check for type sanity on the arguments
3178 Type
*SrcTy
= S
->getType();
3180 if (!SrcTy
->isFirstClassType() || !DstTy
->isFirstClassType() ||
3181 SrcTy
->isAggregateType() || DstTy
->isAggregateType())
3184 // Get the size of the types in bits, we'll need this later
3185 unsigned SrcBitSize
= SrcTy
->getScalarSizeInBits();
3186 unsigned DstBitSize
= DstTy
->getScalarSizeInBits();
3188 // If these are vector types, get the lengths of the vectors (using zero for
3189 // scalar types means that checking that vector lengths match also checks that
3190 // scalars are not being converted to vectors or vectors to scalars).
3191 unsigned SrcLength
= SrcTy
->isVectorTy() ?
3192 cast
<VectorType
>(SrcTy
)->getNumElements() : 0;
3193 unsigned DstLength
= DstTy
->isVectorTy() ?
3194 cast
<VectorType
>(DstTy
)->getNumElements() : 0;
3196 // Switch on the opcode provided
3198 default: return false; // This is an input error
3199 case Instruction::Trunc
:
3200 return SrcTy
->isIntOrIntVectorTy() && DstTy
->isIntOrIntVectorTy() &&
3201 SrcLength
== DstLength
&& SrcBitSize
> DstBitSize
;
3202 case Instruction::ZExt
:
3203 return SrcTy
->isIntOrIntVectorTy() && DstTy
->isIntOrIntVectorTy() &&
3204 SrcLength
== DstLength
&& SrcBitSize
< DstBitSize
;
3205 case Instruction::SExt
:
3206 return SrcTy
->isIntOrIntVectorTy() && DstTy
->isIntOrIntVectorTy() &&
3207 SrcLength
== DstLength
&& SrcBitSize
< DstBitSize
;
3208 case Instruction::FPTrunc
:
3209 return SrcTy
->isFPOrFPVectorTy() && DstTy
->isFPOrFPVectorTy() &&
3210 SrcLength
== DstLength
&& SrcBitSize
> DstBitSize
;
3211 case Instruction::FPExt
:
3212 return SrcTy
->isFPOrFPVectorTy() && DstTy
->isFPOrFPVectorTy() &&
3213 SrcLength
== DstLength
&& SrcBitSize
< DstBitSize
;
3214 case Instruction::UIToFP
:
3215 case Instruction::SIToFP
:
3216 return SrcTy
->isIntOrIntVectorTy() && DstTy
->isFPOrFPVectorTy() &&
3217 SrcLength
== DstLength
;
3218 case Instruction::FPToUI
:
3219 case Instruction::FPToSI
:
3220 return SrcTy
->isFPOrFPVectorTy() && DstTy
->isIntOrIntVectorTy() &&
3221 SrcLength
== DstLength
;
3222 case Instruction::PtrToInt
:
3223 if (isa
<VectorType
>(SrcTy
) != isa
<VectorType
>(DstTy
))
3225 if (VectorType
*VT
= dyn_cast
<VectorType
>(SrcTy
))
3226 if (VT
->getNumElements() != cast
<VectorType
>(DstTy
)->getNumElements())
3228 return SrcTy
->isPtrOrPtrVectorTy() && DstTy
->isIntOrIntVectorTy();
3229 case Instruction::IntToPtr
:
3230 if (isa
<VectorType
>(SrcTy
) != isa
<VectorType
>(DstTy
))
3232 if (VectorType
*VT
= dyn_cast
<VectorType
>(SrcTy
))
3233 if (VT
->getNumElements() != cast
<VectorType
>(DstTy
)->getNumElements())
3235 return SrcTy
->isIntOrIntVectorTy() && DstTy
->isPtrOrPtrVectorTy();
3236 case Instruction::BitCast
: {
3237 PointerType
*SrcPtrTy
= dyn_cast
<PointerType
>(SrcTy
->getScalarType());
3238 PointerType
*DstPtrTy
= dyn_cast
<PointerType
>(DstTy
->getScalarType());
3240 // BitCast implies a no-op cast of type only. No bits change.
3241 // However, you can't cast pointers to anything but pointers.
3242 if (!SrcPtrTy
!= !DstPtrTy
)
3245 // For non-pointer cases, the cast is okay if the source and destination bit
3246 // widths are identical.
3248 return SrcTy
->getPrimitiveSizeInBits() == DstTy
->getPrimitiveSizeInBits();
3250 // If both are pointers then the address spaces must match.
3251 if (SrcPtrTy
->getAddressSpace() != DstPtrTy
->getAddressSpace())
3254 // A vector of pointers must have the same number of elements.
3255 VectorType
*SrcVecTy
= dyn_cast
<VectorType
>(SrcTy
);
3256 VectorType
*DstVecTy
= dyn_cast
<VectorType
>(DstTy
);
3257 if (SrcVecTy
&& DstVecTy
)
3258 return (SrcVecTy
->getNumElements() == DstVecTy
->getNumElements());
3260 return SrcVecTy
->getNumElements() == 1;
3262 return DstVecTy
->getNumElements() == 1;
3266 case Instruction::AddrSpaceCast
: {
3267 PointerType
*SrcPtrTy
= dyn_cast
<PointerType
>(SrcTy
->getScalarType());
3271 PointerType
*DstPtrTy
= dyn_cast
<PointerType
>(DstTy
->getScalarType());
3275 if (SrcPtrTy
->getAddressSpace() == DstPtrTy
->getAddressSpace())
3278 if (VectorType
*SrcVecTy
= dyn_cast
<VectorType
>(SrcTy
)) {
3279 if (VectorType
*DstVecTy
= dyn_cast
<VectorType
>(DstTy
))
3280 return (SrcVecTy
->getNumElements() == DstVecTy
->getNumElements());
3290 TruncInst::TruncInst(
3291 Value
*S
, Type
*Ty
, const Twine
&Name
, Instruction
*InsertBefore
3292 ) : CastInst(Ty
, Trunc
, S
, Name
, InsertBefore
) {
3293 assert(castIsValid(getOpcode(), S
, Ty
) && "Illegal Trunc");
3296 TruncInst::TruncInst(
3297 Value
*S
, Type
*Ty
, const Twine
&Name
, BasicBlock
*InsertAtEnd
3298 ) : CastInst(Ty
, Trunc
, S
, Name
, InsertAtEnd
) {
3299 assert(castIsValid(getOpcode(), S
, Ty
) && "Illegal Trunc");
3303 Value
*S
, Type
*Ty
, const Twine
&Name
, Instruction
*InsertBefore
3304 ) : CastInst(Ty
, ZExt
, S
, Name
, InsertBefore
) {
3305 assert(castIsValid(getOpcode(), S
, Ty
) && "Illegal ZExt");
3309 Value
*S
, Type
*Ty
, const Twine
&Name
, BasicBlock
*InsertAtEnd
3310 ) : CastInst(Ty
, ZExt
, S
, Name
, InsertAtEnd
) {
3311 assert(castIsValid(getOpcode(), S
, Ty
) && "Illegal ZExt");
3314 Value
*S
, Type
*Ty
, const Twine
&Name
, Instruction
*InsertBefore
3315 ) : CastInst(Ty
, SExt
, S
, Name
, InsertBefore
) {
3316 assert(castIsValid(getOpcode(), S
, Ty
) && "Illegal SExt");
3320 Value
*S
, Type
*Ty
, const Twine
&Name
, BasicBlock
*InsertAtEnd
3321 ) : CastInst(Ty
, SExt
, S
, Name
, InsertAtEnd
) {
3322 assert(castIsValid(getOpcode(), S
, Ty
) && "Illegal SExt");
3325 FPTruncInst::FPTruncInst(
3326 Value
*S
, Type
*Ty
, const Twine
&Name
, Instruction
*InsertBefore
3327 ) : CastInst(Ty
, FPTrunc
, S
, Name
, InsertBefore
) {
3328 assert(castIsValid(getOpcode(), S
, Ty
) && "Illegal FPTrunc");
3331 FPTruncInst::FPTruncInst(
3332 Value
*S
, Type
*Ty
, const Twine
&Name
, BasicBlock
*InsertAtEnd
3333 ) : CastInst(Ty
, FPTrunc
, S
, Name
, InsertAtEnd
) {
3334 assert(castIsValid(getOpcode(), S
, Ty
) && "Illegal FPTrunc");
3337 FPExtInst::FPExtInst(
3338 Value
*S
, Type
*Ty
, const Twine
&Name
, Instruction
*InsertBefore
3339 ) : CastInst(Ty
, FPExt
, S
, Name
, InsertBefore
) {
3340 assert(castIsValid(getOpcode(), S
, Ty
) && "Illegal FPExt");
3343 FPExtInst::FPExtInst(
3344 Value
*S
, Type
*Ty
, const Twine
&Name
, BasicBlock
*InsertAtEnd
3345 ) : CastInst(Ty
, FPExt
, S
, Name
, InsertAtEnd
) {
3346 assert(castIsValid(getOpcode(), S
, Ty
) && "Illegal FPExt");
3349 UIToFPInst::UIToFPInst(
3350 Value
*S
, Type
*Ty
, const Twine
&Name
, Instruction
*InsertBefore
3351 ) : CastInst(Ty
, UIToFP
, S
, Name
, InsertBefore
) {
3352 assert(castIsValid(getOpcode(), S
, Ty
) && "Illegal UIToFP");
3355 UIToFPInst::UIToFPInst(
3356 Value
*S
, Type
*Ty
, const Twine
&Name
, BasicBlock
*InsertAtEnd
3357 ) : CastInst(Ty
, UIToFP
, S
, Name
, InsertAtEnd
) {
3358 assert(castIsValid(getOpcode(), S
, Ty
) && "Illegal UIToFP");
3361 SIToFPInst::SIToFPInst(
3362 Value
*S
, Type
*Ty
, const Twine
&Name
, Instruction
*InsertBefore
3363 ) : CastInst(Ty
, SIToFP
, S
, Name
, InsertBefore
) {
3364 assert(castIsValid(getOpcode(), S
, Ty
) && "Illegal SIToFP");
3367 SIToFPInst::SIToFPInst(
3368 Value
*S
, Type
*Ty
, const Twine
&Name
, BasicBlock
*InsertAtEnd
3369 ) : CastInst(Ty
, SIToFP
, S
, Name
, InsertAtEnd
) {
3370 assert(castIsValid(getOpcode(), S
, Ty
) && "Illegal SIToFP");
3373 FPToUIInst::FPToUIInst(
3374 Value
*S
, Type
*Ty
, const Twine
&Name
, Instruction
*InsertBefore
3375 ) : CastInst(Ty
, FPToUI
, S
, Name
, InsertBefore
) {
3376 assert(castIsValid(getOpcode(), S
, Ty
) && "Illegal FPToUI");
3379 FPToUIInst::FPToUIInst(
3380 Value
*S
, Type
*Ty
, const Twine
&Name
, BasicBlock
*InsertAtEnd
3381 ) : CastInst(Ty
, FPToUI
, S
, Name
, InsertAtEnd
) {
3382 assert(castIsValid(getOpcode(), S
, Ty
) && "Illegal FPToUI");
3385 FPToSIInst::FPToSIInst(
3386 Value
*S
, Type
*Ty
, const Twine
&Name
, Instruction
*InsertBefore
3387 ) : CastInst(Ty
, FPToSI
, S
, Name
, InsertBefore
) {
3388 assert(castIsValid(getOpcode(), S
, Ty
) && "Illegal FPToSI");
3391 FPToSIInst::FPToSIInst(
3392 Value
*S
, Type
*Ty
, const Twine
&Name
, BasicBlock
*InsertAtEnd
3393 ) : CastInst(Ty
, FPToSI
, S
, Name
, InsertAtEnd
) {
3394 assert(castIsValid(getOpcode(), S
, Ty
) && "Illegal FPToSI");
3397 PtrToIntInst::PtrToIntInst(
3398 Value
*S
, Type
*Ty
, const Twine
&Name
, Instruction
*InsertBefore
3399 ) : CastInst(Ty
, PtrToInt
, S
, Name
, InsertBefore
) {
3400 assert(castIsValid(getOpcode(), S
, Ty
) && "Illegal PtrToInt");
3403 PtrToIntInst::PtrToIntInst(
3404 Value
*S
, Type
*Ty
, const Twine
&Name
, BasicBlock
*InsertAtEnd
3405 ) : CastInst(Ty
, PtrToInt
, S
, Name
, InsertAtEnd
) {
3406 assert(castIsValid(getOpcode(), S
, Ty
) && "Illegal PtrToInt");
3409 IntToPtrInst::IntToPtrInst(
3410 Value
*S
, Type
*Ty
, const Twine
&Name
, Instruction
*InsertBefore
3411 ) : CastInst(Ty
, IntToPtr
, S
, Name
, InsertBefore
) {
3412 assert(castIsValid(getOpcode(), S
, Ty
) && "Illegal IntToPtr");
3415 IntToPtrInst::IntToPtrInst(
3416 Value
*S
, Type
*Ty
, const Twine
&Name
, BasicBlock
*InsertAtEnd
3417 ) : CastInst(Ty
, IntToPtr
, S
, Name
, InsertAtEnd
) {
3418 assert(castIsValid(getOpcode(), S
, Ty
) && "Illegal IntToPtr");
3421 BitCastInst::BitCastInst(
3422 Value
*S
, Type
*Ty
, const Twine
&Name
, Instruction
*InsertBefore
3423 ) : CastInst(Ty
, BitCast
, S
, Name
, InsertBefore
) {
3424 assert(castIsValid(getOpcode(), S
, Ty
) && "Illegal BitCast");
3427 BitCastInst::BitCastInst(
3428 Value
*S
, Type
*Ty
, const Twine
&Name
, BasicBlock
*InsertAtEnd
3429 ) : CastInst(Ty
, BitCast
, S
, Name
, InsertAtEnd
) {
3430 assert(castIsValid(getOpcode(), S
, Ty
) && "Illegal BitCast");
3433 AddrSpaceCastInst::AddrSpaceCastInst(
3434 Value
*S
, Type
*Ty
, const Twine
&Name
, Instruction
*InsertBefore
3435 ) : CastInst(Ty
, AddrSpaceCast
, S
, Name
, InsertBefore
) {
3436 assert(castIsValid(getOpcode(), S
, Ty
) && "Illegal AddrSpaceCast");
3439 AddrSpaceCastInst::AddrSpaceCastInst(
3440 Value
*S
, Type
*Ty
, const Twine
&Name
, BasicBlock
*InsertAtEnd
3441 ) : CastInst(Ty
, AddrSpaceCast
, S
, Name
, InsertAtEnd
) {
3442 assert(castIsValid(getOpcode(), S
, Ty
) && "Illegal AddrSpaceCast");
3445 //===----------------------------------------------------------------------===//
3447 //===----------------------------------------------------------------------===//
3449 CmpInst::CmpInst(Type
*ty
, OtherOps op
, Predicate predicate
, Value
*LHS
,
3450 Value
*RHS
, const Twine
&Name
, Instruction
*InsertBefore
,
3451 Instruction
*FlagsSource
)
3452 : Instruction(ty
, op
,
3453 OperandTraits
<CmpInst
>::op_begin(this),
3454 OperandTraits
<CmpInst
>::operands(this),
3458 setPredicate((Predicate
)predicate
);
3461 copyIRFlags(FlagsSource
);
3464 CmpInst::CmpInst(Type
*ty
, OtherOps op
, Predicate predicate
, Value
*LHS
,
3465 Value
*RHS
, const Twine
&Name
, BasicBlock
*InsertAtEnd
)
3466 : Instruction(ty
, op
,
3467 OperandTraits
<CmpInst
>::op_begin(this),
3468 OperandTraits
<CmpInst
>::operands(this),
3472 setPredicate((Predicate
)predicate
);
3477 CmpInst::Create(OtherOps Op
, Predicate predicate
, Value
*S1
, Value
*S2
,
3478 const Twine
&Name
, Instruction
*InsertBefore
) {
3479 if (Op
== Instruction::ICmp
) {
3481 return new ICmpInst(InsertBefore
, CmpInst::Predicate(predicate
),
3484 return new ICmpInst(CmpInst::Predicate(predicate
),
3489 return new FCmpInst(InsertBefore
, CmpInst::Predicate(predicate
),
3492 return new FCmpInst(CmpInst::Predicate(predicate
),
3497 CmpInst::Create(OtherOps Op
, Predicate predicate
, Value
*S1
, Value
*S2
,
3498 const Twine
&Name
, BasicBlock
*InsertAtEnd
) {
3499 if (Op
== Instruction::ICmp
) {
3500 return new ICmpInst(*InsertAtEnd
, CmpInst::Predicate(predicate
),
3503 return new FCmpInst(*InsertAtEnd
, CmpInst::Predicate(predicate
),
3507 void CmpInst::swapOperands() {
3508 if (ICmpInst
*IC
= dyn_cast
<ICmpInst
>(this))
3511 cast
<FCmpInst
>(this)->swapOperands();
3514 bool CmpInst::isCommutative() const {
3515 if (const ICmpInst
*IC
= dyn_cast
<ICmpInst
>(this))
3516 return IC
->isCommutative();
3517 return cast
<FCmpInst
>(this)->isCommutative();
3520 bool CmpInst::isEquality() const {
3521 if (const ICmpInst
*IC
= dyn_cast
<ICmpInst
>(this))
3522 return IC
->isEquality();
3523 return cast
<FCmpInst
>(this)->isEquality();
3526 CmpInst::Predicate
CmpInst::getInversePredicate(Predicate pred
) {
3528 default: llvm_unreachable("Unknown cmp predicate!");
3529 case ICMP_EQ
: return ICMP_NE
;
3530 case ICMP_NE
: return ICMP_EQ
;
3531 case ICMP_UGT
: return ICMP_ULE
;
3532 case ICMP_ULT
: return ICMP_UGE
;
3533 case ICMP_UGE
: return ICMP_ULT
;
3534 case ICMP_ULE
: return ICMP_UGT
;
3535 case ICMP_SGT
: return ICMP_SLE
;
3536 case ICMP_SLT
: return ICMP_SGE
;
3537 case ICMP_SGE
: return ICMP_SLT
;
3538 case ICMP_SLE
: return ICMP_SGT
;
3540 case FCMP_OEQ
: return FCMP_UNE
;
3541 case FCMP_ONE
: return FCMP_UEQ
;
3542 case FCMP_OGT
: return FCMP_ULE
;
3543 case FCMP_OLT
: return FCMP_UGE
;
3544 case FCMP_OGE
: return FCMP_ULT
;
3545 case FCMP_OLE
: return FCMP_UGT
;
3546 case FCMP_UEQ
: return FCMP_ONE
;
3547 case FCMP_UNE
: return FCMP_OEQ
;
3548 case FCMP_UGT
: return FCMP_OLE
;
3549 case FCMP_ULT
: return FCMP_OGE
;
3550 case FCMP_UGE
: return FCMP_OLT
;
3551 case FCMP_ULE
: return FCMP_OGT
;
3552 case FCMP_ORD
: return FCMP_UNO
;
3553 case FCMP_UNO
: return FCMP_ORD
;
3554 case FCMP_TRUE
: return FCMP_FALSE
;
3555 case FCMP_FALSE
: return FCMP_TRUE
;
3559 StringRef
CmpInst::getPredicateName(Predicate Pred
) {
3561 default: return "unknown";
3562 case FCmpInst::FCMP_FALSE
: return "false";
3563 case FCmpInst::FCMP_OEQ
: return "oeq";
3564 case FCmpInst::FCMP_OGT
: return "ogt";
3565 case FCmpInst::FCMP_OGE
: return "oge";
3566 case FCmpInst::FCMP_OLT
: return "olt";
3567 case FCmpInst::FCMP_OLE
: return "ole";
3568 case FCmpInst::FCMP_ONE
: return "one";
3569 case FCmpInst::FCMP_ORD
: return "ord";
3570 case FCmpInst::FCMP_UNO
: return "uno";
3571 case FCmpInst::FCMP_UEQ
: return "ueq";
3572 case FCmpInst::FCMP_UGT
: return "ugt";
3573 case FCmpInst::FCMP_UGE
: return "uge";
3574 case FCmpInst::FCMP_ULT
: return "ult";
3575 case FCmpInst::FCMP_ULE
: return "ule";
3576 case FCmpInst::FCMP_UNE
: return "une";
3577 case FCmpInst::FCMP_TRUE
: return "true";
3578 case ICmpInst::ICMP_EQ
: return "eq";
3579 case ICmpInst::ICMP_NE
: return "ne";
3580 case ICmpInst::ICMP_SGT
: return "sgt";
3581 case ICmpInst::ICMP_SGE
: return "sge";
3582 case ICmpInst::ICMP_SLT
: return "slt";
3583 case ICmpInst::ICMP_SLE
: return "sle";
3584 case ICmpInst::ICMP_UGT
: return "ugt";
3585 case ICmpInst::ICMP_UGE
: return "uge";
3586 case ICmpInst::ICMP_ULT
: return "ult";
3587 case ICmpInst::ICMP_ULE
: return "ule";
3591 ICmpInst::Predicate
ICmpInst::getSignedPredicate(Predicate pred
) {
3593 default: llvm_unreachable("Unknown icmp predicate!");
3594 case ICMP_EQ
: case ICMP_NE
:
3595 case ICMP_SGT
: case ICMP_SLT
: case ICMP_SGE
: case ICMP_SLE
:
3597 case ICMP_UGT
: return ICMP_SGT
;
3598 case ICMP_ULT
: return ICMP_SLT
;
3599 case ICMP_UGE
: return ICMP_SGE
;
3600 case ICMP_ULE
: return ICMP_SLE
;
3604 ICmpInst::Predicate
ICmpInst::getUnsignedPredicate(Predicate pred
) {
3606 default: llvm_unreachable("Unknown icmp predicate!");
3607 case ICMP_EQ
: case ICMP_NE
:
3608 case ICMP_UGT
: case ICMP_ULT
: case ICMP_UGE
: case ICMP_ULE
:
3610 case ICMP_SGT
: return ICMP_UGT
;
3611 case ICMP_SLT
: return ICMP_ULT
;
3612 case ICMP_SGE
: return ICMP_UGE
;
3613 case ICMP_SLE
: return ICMP_ULE
;
3617 CmpInst::Predicate
CmpInst::getFlippedStrictnessPredicate(Predicate pred
) {
3619 default: llvm_unreachable("Unknown or unsupported cmp predicate!");
3620 case ICMP_SGT
: return ICMP_SGE
;
3621 case ICMP_SLT
: return ICMP_SLE
;
3622 case ICMP_SGE
: return ICMP_SGT
;
3623 case ICMP_SLE
: return ICMP_SLT
;
3624 case ICMP_UGT
: return ICMP_UGE
;
3625 case ICMP_ULT
: return ICMP_ULE
;
3626 case ICMP_UGE
: return ICMP_UGT
;
3627 case ICMP_ULE
: return ICMP_ULT
;
3629 case FCMP_OGT
: return FCMP_OGE
;
3630 case FCMP_OLT
: return FCMP_OLE
;
3631 case FCMP_OGE
: return FCMP_OGT
;
3632 case FCMP_OLE
: return FCMP_OLT
;
3633 case FCMP_UGT
: return FCMP_UGE
;
3634 case FCMP_ULT
: return FCMP_ULE
;
3635 case FCMP_UGE
: return FCMP_UGT
;
3636 case FCMP_ULE
: return FCMP_ULT
;
3640 CmpInst::Predicate
CmpInst::getSwappedPredicate(Predicate pred
) {
3642 default: llvm_unreachable("Unknown cmp predicate!");
3643 case ICMP_EQ
: case ICMP_NE
:
3645 case ICMP_SGT
: return ICMP_SLT
;
3646 case ICMP_SLT
: return ICMP_SGT
;
3647 case ICMP_SGE
: return ICMP_SLE
;
3648 case ICMP_SLE
: return ICMP_SGE
;
3649 case ICMP_UGT
: return ICMP_ULT
;
3650 case ICMP_ULT
: return ICMP_UGT
;
3651 case ICMP_UGE
: return ICMP_ULE
;
3652 case ICMP_ULE
: return ICMP_UGE
;
3654 case FCMP_FALSE
: case FCMP_TRUE
:
3655 case FCMP_OEQ
: case FCMP_ONE
:
3656 case FCMP_UEQ
: case FCMP_UNE
:
3657 case FCMP_ORD
: case FCMP_UNO
:
3659 case FCMP_OGT
: return FCMP_OLT
;
3660 case FCMP_OLT
: return FCMP_OGT
;
3661 case FCMP_OGE
: return FCMP_OLE
;
3662 case FCMP_OLE
: return FCMP_OGE
;
3663 case FCMP_UGT
: return FCMP_ULT
;
3664 case FCMP_ULT
: return FCMP_UGT
;
3665 case FCMP_UGE
: return FCMP_ULE
;
3666 case FCMP_ULE
: return FCMP_UGE
;
3670 CmpInst::Predicate
CmpInst::getNonStrictPredicate(Predicate pred
) {
3672 case ICMP_SGT
: return ICMP_SGE
;
3673 case ICMP_SLT
: return ICMP_SLE
;
3674 case ICMP_UGT
: return ICMP_UGE
;
3675 case ICMP_ULT
: return ICMP_ULE
;
3676 case FCMP_OGT
: return FCMP_OGE
;
3677 case FCMP_OLT
: return FCMP_OLE
;
3678 case FCMP_UGT
: return FCMP_UGE
;
3679 case FCMP_ULT
: return FCMP_ULE
;
3680 default: return pred
;
3684 CmpInst::Predicate
CmpInst::getSignedPredicate(Predicate pred
) {
3685 assert(CmpInst::isUnsigned(pred
) && "Call only with signed predicates!");
3689 llvm_unreachable("Unknown predicate!");
3690 case CmpInst::ICMP_ULT
:
3691 return CmpInst::ICMP_SLT
;
3692 case CmpInst::ICMP_ULE
:
3693 return CmpInst::ICMP_SLE
;
3694 case CmpInst::ICMP_UGT
:
3695 return CmpInst::ICMP_SGT
;
3696 case CmpInst::ICMP_UGE
:
3697 return CmpInst::ICMP_SGE
;
3701 bool CmpInst::isUnsigned(Predicate predicate
) {
3702 switch (predicate
) {
3703 default: return false;
3704 case ICmpInst::ICMP_ULT
: case ICmpInst::ICMP_ULE
: case ICmpInst::ICMP_UGT
:
3705 case ICmpInst::ICMP_UGE
: return true;
3709 bool CmpInst::isSigned(Predicate predicate
) {
3710 switch (predicate
) {
3711 default: return false;
3712 case ICmpInst::ICMP_SLT
: case ICmpInst::ICMP_SLE
: case ICmpInst::ICMP_SGT
:
3713 case ICmpInst::ICMP_SGE
: return true;
3717 bool CmpInst::isOrdered(Predicate predicate
) {
3718 switch (predicate
) {
3719 default: return false;
3720 case FCmpInst::FCMP_OEQ
: case FCmpInst::FCMP_ONE
: case FCmpInst::FCMP_OGT
:
3721 case FCmpInst::FCMP_OLT
: case FCmpInst::FCMP_OGE
: case FCmpInst::FCMP_OLE
:
3722 case FCmpInst::FCMP_ORD
: return true;
3726 bool CmpInst::isUnordered(Predicate predicate
) {
3727 switch (predicate
) {
3728 default: return false;
3729 case FCmpInst::FCMP_UEQ
: case FCmpInst::FCMP_UNE
: case FCmpInst::FCMP_UGT
:
3730 case FCmpInst::FCMP_ULT
: case FCmpInst::FCMP_UGE
: case FCmpInst::FCMP_ULE
:
3731 case FCmpInst::FCMP_UNO
: return true;
3735 bool CmpInst::isTrueWhenEqual(Predicate predicate
) {
3737 default: return false;
3738 case ICMP_EQ
: case ICMP_UGE
: case ICMP_ULE
: case ICMP_SGE
: case ICMP_SLE
:
3739 case FCMP_TRUE
: case FCMP_UEQ
: case FCMP_UGE
: case FCMP_ULE
: return true;
3743 bool CmpInst::isFalseWhenEqual(Predicate predicate
) {
3745 case ICMP_NE
: case ICMP_UGT
: case ICMP_ULT
: case ICMP_SGT
: case ICMP_SLT
:
3746 case FCMP_FALSE
: case FCMP_ONE
: case FCMP_OGT
: case FCMP_OLT
: return true;
3747 default: return false;
3751 bool CmpInst::isImpliedTrueByMatchingCmp(Predicate Pred1
, Predicate Pred2
) {
3752 // If the predicates match, then we know the first condition implies the
3761 // A == B implies A >=u B, A <=u B, A >=s B, and A <=s B are true.
3762 return Pred2
== ICMP_UGE
|| Pred2
== ICMP_ULE
|| Pred2
== ICMP_SGE
||
3764 case ICMP_UGT
: // A >u B implies A != B and A >=u B are true.
3765 return Pred2
== ICMP_NE
|| Pred2
== ICMP_UGE
;
3766 case ICMP_ULT
: // A <u B implies A != B and A <=u B are true.
3767 return Pred2
== ICMP_NE
|| Pred2
== ICMP_ULE
;
3768 case ICMP_SGT
: // A >s B implies A != B and A >=s B are true.
3769 return Pred2
== ICMP_NE
|| Pred2
== ICMP_SGE
;
3770 case ICMP_SLT
: // A <s B implies A != B and A <=s B are true.
3771 return Pred2
== ICMP_NE
|| Pred2
== ICMP_SLE
;
3776 bool CmpInst::isImpliedFalseByMatchingCmp(Predicate Pred1
, Predicate Pred2
) {
3777 return isImpliedTrueByMatchingCmp(Pred1
, getInversePredicate(Pred2
));
3780 //===----------------------------------------------------------------------===//
3781 // SwitchInst Implementation
3782 //===----------------------------------------------------------------------===//
3784 void SwitchInst::init(Value
*Value
, BasicBlock
*Default
, unsigned NumReserved
) {
3785 assert(Value
&& Default
&& NumReserved
);
3786 ReservedSpace
= NumReserved
;
3787 setNumHungOffUseOperands(2);
3788 allocHungoffUses(ReservedSpace
);
3794 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
3795 /// switch on and a default destination. The number of additional cases can
3796 /// be specified here to make memory allocation more efficient. This
3797 /// constructor can also autoinsert before another instruction.
3798 SwitchInst::SwitchInst(Value
*Value
, BasicBlock
*Default
, unsigned NumCases
,
3799 Instruction
*InsertBefore
)
3800 : Instruction(Type::getVoidTy(Value
->getContext()), Instruction::Switch
,
3801 nullptr, 0, InsertBefore
) {
3802 init(Value
, Default
, 2+NumCases
*2);
3805 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
3806 /// switch on and a default destination. The number of additional cases can
3807 /// be specified here to make memory allocation more efficient. This
3808 /// constructor also autoinserts at the end of the specified BasicBlock.
3809 SwitchInst::SwitchInst(Value
*Value
, BasicBlock
*Default
, unsigned NumCases
,
3810 BasicBlock
*InsertAtEnd
)
3811 : Instruction(Type::getVoidTy(Value
->getContext()), Instruction::Switch
,
3812 nullptr, 0, InsertAtEnd
) {
3813 init(Value
, Default
, 2+NumCases
*2);
3816 SwitchInst::SwitchInst(const SwitchInst
&SI
)
3817 : Instruction(SI
.getType(), Instruction::Switch
, nullptr, 0) {
3818 init(SI
.getCondition(), SI
.getDefaultDest(), SI
.getNumOperands());
3819 setNumHungOffUseOperands(SI
.getNumOperands());
3820 Use
*OL
= getOperandList();
3821 const Use
*InOL
= SI
.getOperandList();
3822 for (unsigned i
= 2, E
= SI
.getNumOperands(); i
!= E
; i
+= 2) {
3824 OL
[i
+1] = InOL
[i
+1];
3826 SubclassOptionalData
= SI
.SubclassOptionalData
;
3829 /// addCase - Add an entry to the switch instruction...
3831 void SwitchInst::addCase(ConstantInt
*OnVal
, BasicBlock
*Dest
) {
3832 unsigned NewCaseIdx
= getNumCases();
3833 unsigned OpNo
= getNumOperands();
3834 if (OpNo
+2 > ReservedSpace
)
3835 growOperands(); // Get more space!
3836 // Initialize some new operands.
3837 assert(OpNo
+1 < ReservedSpace
&& "Growing didn't work!");
3838 setNumHungOffUseOperands(OpNo
+2);
3839 CaseHandle
Case(this, NewCaseIdx
);
3840 Case
.setValue(OnVal
);
3841 Case
.setSuccessor(Dest
);
3844 /// removeCase - This method removes the specified case and its successor
3845 /// from the switch instruction.
3846 SwitchInst::CaseIt
SwitchInst::removeCase(CaseIt I
) {
3847 unsigned idx
= I
->getCaseIndex();
3849 assert(2 + idx
*2 < getNumOperands() && "Case index out of range!!!");
3851 unsigned NumOps
= getNumOperands();
3852 Use
*OL
= getOperandList();
3854 // Overwrite this case with the end of the list.
3855 if (2 + (idx
+ 1) * 2 != NumOps
) {
3856 OL
[2 + idx
* 2] = OL
[NumOps
- 2];
3857 OL
[2 + idx
* 2 + 1] = OL
[NumOps
- 1];
3860 // Nuke the last value.
3861 OL
[NumOps
-2].set(nullptr);
3862 OL
[NumOps
-2+1].set(nullptr);
3863 setNumHungOffUseOperands(NumOps
-2);
3865 return CaseIt(this, idx
);
3868 /// growOperands - grow operands - This grows the operand list in response
3869 /// to a push_back style of operation. This grows the number of ops by 3 times.
3871 void SwitchInst::growOperands() {
3872 unsigned e
= getNumOperands();
3873 unsigned NumOps
= e
*3;
3875 ReservedSpace
= NumOps
;
3876 growHungoffUses(ReservedSpace
);
3880 SwitchInstProfUpdateWrapper::getProfBranchWeightsMD(const SwitchInst
&SI
) {
3881 if (MDNode
*ProfileData
= SI
.getMetadata(LLVMContext::MD_prof
))
3882 if (auto *MDName
= dyn_cast
<MDString
>(ProfileData
->getOperand(0)))
3883 if (MDName
->getString() == "branch_weights")
3888 MDNode
*SwitchInstProfUpdateWrapper::buildProfBranchWeightsMD() {
3889 assert(State
== Changed
&& "called only if metadata has changed");
3894 assert(SI
.getNumSuccessors() == Weights
->size() &&
3895 "num of prof branch_weights must accord with num of successors");
3898 all_of(Weights
.getValue(), [](uint32_t W
) { return W
== 0; });
3900 if (AllZeroes
|| Weights
.getValue().size() < 2)
3903 return MDBuilder(SI
.getParent()->getContext()).createBranchWeights(*Weights
);
3906 void SwitchInstProfUpdateWrapper::init() {
3907 MDNode
*ProfileData
= getProfBranchWeightsMD(SI
);
3909 State
= Initialized
;
3913 if (ProfileData
->getNumOperands() != SI
.getNumSuccessors() + 1) {
3915 if (SwitchInstProfUpdateWrapperStrict
)
3916 llvm_unreachable("number of prof branch_weights metadata operands does "
3917 "not correspond to number of succesors");
3921 SmallVector
<uint32_t, 8> Weights
;
3922 for (unsigned CI
= 1, CE
= SI
.getNumSuccessors(); CI
<= CE
; ++CI
) {
3923 ConstantInt
*C
= mdconst::extract
<ConstantInt
>(ProfileData
->getOperand(CI
));
3924 uint32_t CW
= C
->getValue().getZExtValue();
3925 Weights
.push_back(CW
);
3927 State
= Initialized
;
3928 this->Weights
= std::move(Weights
);
3932 SwitchInstProfUpdateWrapper::removeCase(SwitchInst::CaseIt I
) {
3934 assert(SI
.getNumSuccessors() == Weights
->size() &&
3935 "num of prof branch_weights must accord with num of successors");
3937 // Copy the last case to the place of the removed one and shrink.
3938 // This is tightly coupled with the way SwitchInst::removeCase() removes
3939 // the cases in SwitchInst::removeCase(CaseIt).
3940 Weights
.getValue()[I
->getCaseIndex() + 1] = Weights
.getValue().back();
3941 Weights
.getValue().pop_back();
3943 return SI
.removeCase(I
);
3946 void SwitchInstProfUpdateWrapper::addCase(
3947 ConstantInt
*OnVal
, BasicBlock
*Dest
,
3948 SwitchInstProfUpdateWrapper::CaseWeightOpt W
) {
3949 SI
.addCase(OnVal
, Dest
);
3951 if (State
== Invalid
)
3954 if (!Weights
&& W
&& *W
) {
3956 Weights
= SmallVector
<uint32_t, 8>(SI
.getNumSuccessors(), 0);
3957 Weights
.getValue()[SI
.getNumSuccessors() - 1] = *W
;
3958 } else if (Weights
) {
3960 Weights
.getValue().push_back(W
? *W
: 0);
3963 assert(SI
.getNumSuccessors() == Weights
->size() &&
3964 "num of prof branch_weights must accord with num of successors");
3967 SymbolTableList
<Instruction
>::iterator
3968 SwitchInstProfUpdateWrapper::eraseFromParent() {
3969 // Instruction is erased. Mark as unchanged to not touch it in the destructor.
3970 if (State
!= Invalid
) {
3971 State
= Initialized
;
3975 return SI
.eraseFromParent();
3978 SwitchInstProfUpdateWrapper::CaseWeightOpt
3979 SwitchInstProfUpdateWrapper::getSuccessorWeight(unsigned idx
) {
3982 return Weights
.getValue()[idx
];
3985 void SwitchInstProfUpdateWrapper::setSuccessorWeight(
3986 unsigned idx
, SwitchInstProfUpdateWrapper::CaseWeightOpt W
) {
3987 if (!W
|| State
== Invalid
)
3991 Weights
= SmallVector
<uint32_t, 8>(SI
.getNumSuccessors(), 0);
3994 auto &OldW
= Weights
.getValue()[idx
];
4002 SwitchInstProfUpdateWrapper::CaseWeightOpt
4003 SwitchInstProfUpdateWrapper::getSuccessorWeight(const SwitchInst
&SI
,
4005 if (MDNode
*ProfileData
= getProfBranchWeightsMD(SI
))
4006 if (ProfileData
->getNumOperands() == SI
.getNumSuccessors() + 1)
4007 return mdconst::extract
<ConstantInt
>(ProfileData
->getOperand(idx
+ 1))
4014 //===----------------------------------------------------------------------===//
4015 // IndirectBrInst Implementation
4016 //===----------------------------------------------------------------------===//
4018 void IndirectBrInst::init(Value
*Address
, unsigned NumDests
) {
4019 assert(Address
&& Address
->getType()->isPointerTy() &&
4020 "Address of indirectbr must be a pointer");
4021 ReservedSpace
= 1+NumDests
;
4022 setNumHungOffUseOperands(1);
4023 allocHungoffUses(ReservedSpace
);
4029 /// growOperands - grow operands - This grows the operand list in response
4030 /// to a push_back style of operation. This grows the number of ops by 2 times.
4032 void IndirectBrInst::growOperands() {
4033 unsigned e
= getNumOperands();
4034 unsigned NumOps
= e
*2;
4036 ReservedSpace
= NumOps
;
4037 growHungoffUses(ReservedSpace
);
4040 IndirectBrInst::IndirectBrInst(Value
*Address
, unsigned NumCases
,
4041 Instruction
*InsertBefore
)
4042 : Instruction(Type::getVoidTy(Address
->getContext()),
4043 Instruction::IndirectBr
, nullptr, 0, InsertBefore
) {
4044 init(Address
, NumCases
);
4047 IndirectBrInst::IndirectBrInst(Value
*Address
, unsigned NumCases
,
4048 BasicBlock
*InsertAtEnd
)
4049 : Instruction(Type::getVoidTy(Address
->getContext()),
4050 Instruction::IndirectBr
, nullptr, 0, InsertAtEnd
) {
4051 init(Address
, NumCases
);
4054 IndirectBrInst::IndirectBrInst(const IndirectBrInst
&IBI
)
4055 : Instruction(Type::getVoidTy(IBI
.getContext()), Instruction::IndirectBr
,
4056 nullptr, IBI
.getNumOperands()) {
4057 allocHungoffUses(IBI
.getNumOperands());
4058 Use
*OL
= getOperandList();
4059 const Use
*InOL
= IBI
.getOperandList();
4060 for (unsigned i
= 0, E
= IBI
.getNumOperands(); i
!= E
; ++i
)
4062 SubclassOptionalData
= IBI
.SubclassOptionalData
;
4065 /// addDestination - Add a destination.
4067 void IndirectBrInst::addDestination(BasicBlock
*DestBB
) {
4068 unsigned OpNo
= getNumOperands();
4069 if (OpNo
+1 > ReservedSpace
)
4070 growOperands(); // Get more space!
4071 // Initialize some new operands.
4072 assert(OpNo
< ReservedSpace
&& "Growing didn't work!");
4073 setNumHungOffUseOperands(OpNo
+1);
4074 getOperandList()[OpNo
] = DestBB
;
4077 /// removeDestination - This method removes the specified successor from the
4078 /// indirectbr instruction.
4079 void IndirectBrInst::removeDestination(unsigned idx
) {
4080 assert(idx
< getNumOperands()-1 && "Successor index out of range!");
4082 unsigned NumOps
= getNumOperands();
4083 Use
*OL
= getOperandList();
4085 // Replace this value with the last one.
4086 OL
[idx
+1] = OL
[NumOps
-1];
4088 // Nuke the last value.
4089 OL
[NumOps
-1].set(nullptr);
4090 setNumHungOffUseOperands(NumOps
-1);
4093 //===----------------------------------------------------------------------===//
4094 // cloneImpl() implementations
4095 //===----------------------------------------------------------------------===//
4097 // Define these methods here so vtables don't get emitted into every translation
4098 // unit that uses these classes.
4100 GetElementPtrInst
*GetElementPtrInst::cloneImpl() const {
4101 return new (getNumOperands()) GetElementPtrInst(*this);
4104 UnaryOperator
*UnaryOperator::cloneImpl() const {
4105 return Create(getOpcode(), Op
<0>());
4108 BinaryOperator
*BinaryOperator::cloneImpl() const {
4109 return Create(getOpcode(), Op
<0>(), Op
<1>());
4112 FCmpInst
*FCmpInst::cloneImpl() const {
4113 return new FCmpInst(getPredicate(), Op
<0>(), Op
<1>());
4116 ICmpInst
*ICmpInst::cloneImpl() const {
4117 return new ICmpInst(getPredicate(), Op
<0>(), Op
<1>());
4120 ExtractValueInst
*ExtractValueInst::cloneImpl() const {
4121 return new ExtractValueInst(*this);
4124 InsertValueInst
*InsertValueInst::cloneImpl() const {
4125 return new InsertValueInst(*this);
4128 AllocaInst
*AllocaInst::cloneImpl() const {
4129 AllocaInst
*Result
= new AllocaInst(getAllocatedType(),
4130 getType()->getAddressSpace(),
4131 (Value
*)getOperand(0), getAlignment());
4132 Result
->setUsedWithInAlloca(isUsedWithInAlloca());
4133 Result
->setSwiftError(isSwiftError());
4137 LoadInst
*LoadInst::cloneImpl() const {
4138 return new LoadInst(getType(), getOperand(0), Twine(), isVolatile(),
4139 getAlignment(), getOrdering(), getSyncScopeID());
4142 StoreInst
*StoreInst::cloneImpl() const {
4143 return new StoreInst(getOperand(0), getOperand(1), isVolatile(),
4144 getAlignment(), getOrdering(), getSyncScopeID());
4148 AtomicCmpXchgInst
*AtomicCmpXchgInst::cloneImpl() const {
4149 AtomicCmpXchgInst
*Result
=
4150 new AtomicCmpXchgInst(getOperand(0), getOperand(1), getOperand(2),
4151 getSuccessOrdering(), getFailureOrdering(),
4153 Result
->setVolatile(isVolatile());
4154 Result
->setWeak(isWeak());
4158 AtomicRMWInst
*AtomicRMWInst::cloneImpl() const {
4159 AtomicRMWInst
*Result
=
4160 new AtomicRMWInst(getOperation(), getOperand(0), getOperand(1),
4161 getOrdering(), getSyncScopeID());
4162 Result
->setVolatile(isVolatile());
4166 FenceInst
*FenceInst::cloneImpl() const {
4167 return new FenceInst(getContext(), getOrdering(), getSyncScopeID());
4170 TruncInst
*TruncInst::cloneImpl() const {
4171 return new TruncInst(getOperand(0), getType());
4174 ZExtInst
*ZExtInst::cloneImpl() const {
4175 return new ZExtInst(getOperand(0), getType());
4178 SExtInst
*SExtInst::cloneImpl() const {
4179 return new SExtInst(getOperand(0), getType());
4182 FPTruncInst
*FPTruncInst::cloneImpl() const {
4183 return new FPTruncInst(getOperand(0), getType());
4186 FPExtInst
*FPExtInst::cloneImpl() const {
4187 return new FPExtInst(getOperand(0), getType());
4190 UIToFPInst
*UIToFPInst::cloneImpl() const {
4191 return new UIToFPInst(getOperand(0), getType());
4194 SIToFPInst
*SIToFPInst::cloneImpl() const {
4195 return new SIToFPInst(getOperand(0), getType());
4198 FPToUIInst
*FPToUIInst::cloneImpl() const {
4199 return new FPToUIInst(getOperand(0), getType());
4202 FPToSIInst
*FPToSIInst::cloneImpl() const {
4203 return new FPToSIInst(getOperand(0), getType());
4206 PtrToIntInst
*PtrToIntInst::cloneImpl() const {
4207 return new PtrToIntInst(getOperand(0), getType());
4210 IntToPtrInst
*IntToPtrInst::cloneImpl() const {
4211 return new IntToPtrInst(getOperand(0), getType());
4214 BitCastInst
*BitCastInst::cloneImpl() const {
4215 return new BitCastInst(getOperand(0), getType());
4218 AddrSpaceCastInst
*AddrSpaceCastInst::cloneImpl() const {
4219 return new AddrSpaceCastInst(getOperand(0), getType());
4222 CallInst
*CallInst::cloneImpl() const {
4223 if (hasOperandBundles()) {
4224 unsigned DescriptorBytes
= getNumOperandBundles() * sizeof(BundleOpInfo
);
4225 return new(getNumOperands(), DescriptorBytes
) CallInst(*this);
4227 return new(getNumOperands()) CallInst(*this);
4230 SelectInst
*SelectInst::cloneImpl() const {
4231 return SelectInst::Create(getOperand(0), getOperand(1), getOperand(2));
4234 VAArgInst
*VAArgInst::cloneImpl() const {
4235 return new VAArgInst(getOperand(0), getType());
4238 ExtractElementInst
*ExtractElementInst::cloneImpl() const {
4239 return ExtractElementInst::Create(getOperand(0), getOperand(1));
4242 InsertElementInst
*InsertElementInst::cloneImpl() const {
4243 return InsertElementInst::Create(getOperand(0), getOperand(1), getOperand(2));
4246 ShuffleVectorInst
*ShuffleVectorInst::cloneImpl() const {
4247 return new ShuffleVectorInst(getOperand(0), getOperand(1), getOperand(2));
4250 PHINode
*PHINode::cloneImpl() const { return new PHINode(*this); }
4252 LandingPadInst
*LandingPadInst::cloneImpl() const {
4253 return new LandingPadInst(*this);
4256 ReturnInst
*ReturnInst::cloneImpl() const {
4257 return new(getNumOperands()) ReturnInst(*this);
4260 BranchInst
*BranchInst::cloneImpl() const {
4261 return new(getNumOperands()) BranchInst(*this);
4264 SwitchInst
*SwitchInst::cloneImpl() const { return new SwitchInst(*this); }
4266 IndirectBrInst
*IndirectBrInst::cloneImpl() const {
4267 return new IndirectBrInst(*this);
4270 InvokeInst
*InvokeInst::cloneImpl() const {
4271 if (hasOperandBundles()) {
4272 unsigned DescriptorBytes
= getNumOperandBundles() * sizeof(BundleOpInfo
);
4273 return new(getNumOperands(), DescriptorBytes
) InvokeInst(*this);
4275 return new(getNumOperands()) InvokeInst(*this);
4278 CallBrInst
*CallBrInst::cloneImpl() const {
4279 if (hasOperandBundles()) {
4280 unsigned DescriptorBytes
= getNumOperandBundles() * sizeof(BundleOpInfo
);
4281 return new (getNumOperands(), DescriptorBytes
) CallBrInst(*this);
4283 return new (getNumOperands()) CallBrInst(*this);
4286 ResumeInst
*ResumeInst::cloneImpl() const { return new (1) ResumeInst(*this); }
4288 CleanupReturnInst
*CleanupReturnInst::cloneImpl() const {
4289 return new (getNumOperands()) CleanupReturnInst(*this);
4292 CatchReturnInst
*CatchReturnInst::cloneImpl() const {
4293 return new (getNumOperands()) CatchReturnInst(*this);
4296 CatchSwitchInst
*CatchSwitchInst::cloneImpl() const {
4297 return new CatchSwitchInst(*this);
4300 FuncletPadInst
*FuncletPadInst::cloneImpl() const {
4301 return new (getNumOperands()) FuncletPadInst(*this);
4304 UnreachableInst
*UnreachableInst::cloneImpl() const {
4305 LLVMContext
&Context
= getContext();
4306 return new UnreachableInst(Context
);