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 //===----------------------------------------------------------------------===//
50 //===----------------------------------------------------------------------===//
53 AllocaInst::getAllocationSizeInBits(const DataLayout
&DL
) const {
54 uint64_t Size
= DL
.getTypeAllocSizeInBits(getAllocatedType());
55 if (isArrayAllocation()) {
56 auto C
= dyn_cast
<ConstantInt
>(getArraySize());
59 Size
*= C
->getZExtValue();
64 //===----------------------------------------------------------------------===//
66 //===----------------------------------------------------------------------===//
68 User::op_iterator
CallSite::getCallee() const {
69 return cast
<CallBase
>(getInstruction())->op_end() - 1;
72 //===----------------------------------------------------------------------===//
74 //===----------------------------------------------------------------------===//
76 /// areInvalidOperands - Return a string if the specified operands are invalid
77 /// for a select operation, otherwise return null.
78 const char *SelectInst::areInvalidOperands(Value
*Op0
, Value
*Op1
, Value
*Op2
) {
79 if (Op1
->getType() != Op2
->getType())
80 return "both values to select must have same type";
82 if (Op1
->getType()->isTokenTy())
83 return "select values cannot have token type";
85 if (VectorType
*VT
= dyn_cast
<VectorType
>(Op0
->getType())) {
87 if (VT
->getElementType() != Type::getInt1Ty(Op0
->getContext()))
88 return "vector select condition element type must be i1";
89 VectorType
*ET
= dyn_cast
<VectorType
>(Op1
->getType());
91 return "selected values for vector select must be vectors";
92 if (ET
->getNumElements() != VT
->getNumElements())
93 return "vector select requires selected vectors to have "
94 "the same vector length as select condition";
95 } else if (Op0
->getType() != Type::getInt1Ty(Op0
->getContext())) {
96 return "select condition must be i1 or <n x i1>";
101 //===----------------------------------------------------------------------===//
103 //===----------------------------------------------------------------------===//
105 PHINode::PHINode(const PHINode
&PN
)
106 : Instruction(PN
.getType(), Instruction::PHI
, nullptr, PN
.getNumOperands()),
107 ReservedSpace(PN
.getNumOperands()) {
108 allocHungoffUses(PN
.getNumOperands());
109 std::copy(PN
.op_begin(), PN
.op_end(), op_begin());
110 std::copy(PN
.block_begin(), PN
.block_end(), block_begin());
111 SubclassOptionalData
= PN
.SubclassOptionalData
;
114 // removeIncomingValue - Remove an incoming value. This is useful if a
115 // predecessor basic block is deleted.
116 Value
*PHINode::removeIncomingValue(unsigned Idx
, bool DeletePHIIfEmpty
) {
117 Value
*Removed
= getIncomingValue(Idx
);
119 // Move everything after this operand down.
121 // FIXME: we could just swap with the end of the list, then erase. However,
122 // clients might not expect this to happen. The code as it is thrashes the
123 // use/def lists, which is kinda lame.
124 std::copy(op_begin() + Idx
+ 1, op_end(), op_begin() + Idx
);
125 std::copy(block_begin() + Idx
+ 1, block_end(), block_begin() + Idx
);
127 // Nuke the last value.
128 Op
<-1>().set(nullptr);
129 setNumHungOffUseOperands(getNumOperands() - 1);
131 // If the PHI node is dead, because it has zero entries, nuke it now.
132 if (getNumOperands() == 0 && DeletePHIIfEmpty
) {
133 // If anyone is using this PHI, make them use a dummy value instead...
134 replaceAllUsesWith(UndefValue::get(getType()));
140 /// growOperands - grow operands - This grows the operand list in response
141 /// to a push_back style of operation. This grows the number of ops by 1.5
144 void PHINode::growOperands() {
145 unsigned e
= getNumOperands();
146 unsigned NumOps
= e
+ e
/ 2;
147 if (NumOps
< 2) NumOps
= 2; // 2 op PHI nodes are VERY common.
149 ReservedSpace
= NumOps
;
150 growHungoffUses(ReservedSpace
, /* IsPhi */ true);
153 /// hasConstantValue - If the specified PHI node always merges together the same
154 /// value, return the value, otherwise return null.
155 Value
*PHINode::hasConstantValue() const {
156 // Exploit the fact that phi nodes always have at least one entry.
157 Value
*ConstantValue
= getIncomingValue(0);
158 for (unsigned i
= 1, e
= getNumIncomingValues(); i
!= e
; ++i
)
159 if (getIncomingValue(i
) != ConstantValue
&& getIncomingValue(i
) != this) {
160 if (ConstantValue
!= this)
161 return nullptr; // Incoming values not all the same.
162 // The case where the first value is this PHI.
163 ConstantValue
= getIncomingValue(i
);
165 if (ConstantValue
== this)
166 return UndefValue::get(getType());
167 return ConstantValue
;
170 /// hasConstantOrUndefValue - Whether the specified PHI node always merges
171 /// together the same value, assuming that undefs result in the same value as
173 /// Unlike \ref hasConstantValue, this does not return a value because the
174 /// unique non-undef incoming value need not dominate the PHI node.
175 bool PHINode::hasConstantOrUndefValue() const {
176 Value
*ConstantValue
= nullptr;
177 for (unsigned i
= 0, e
= getNumIncomingValues(); i
!= e
; ++i
) {
178 Value
*Incoming
= getIncomingValue(i
);
179 if (Incoming
!= this && !isa
<UndefValue
>(Incoming
)) {
180 if (ConstantValue
&& ConstantValue
!= Incoming
)
182 ConstantValue
= Incoming
;
188 //===----------------------------------------------------------------------===//
189 // LandingPadInst Implementation
190 //===----------------------------------------------------------------------===//
192 LandingPadInst::LandingPadInst(Type
*RetTy
, unsigned NumReservedValues
,
193 const Twine
&NameStr
, Instruction
*InsertBefore
)
194 : Instruction(RetTy
, Instruction::LandingPad
, nullptr, 0, InsertBefore
) {
195 init(NumReservedValues
, NameStr
);
198 LandingPadInst::LandingPadInst(Type
*RetTy
, unsigned NumReservedValues
,
199 const Twine
&NameStr
, BasicBlock
*InsertAtEnd
)
200 : Instruction(RetTy
, Instruction::LandingPad
, nullptr, 0, InsertAtEnd
) {
201 init(NumReservedValues
, NameStr
);
204 LandingPadInst::LandingPadInst(const LandingPadInst
&LP
)
205 : Instruction(LP
.getType(), Instruction::LandingPad
, nullptr,
206 LP
.getNumOperands()),
207 ReservedSpace(LP
.getNumOperands()) {
208 allocHungoffUses(LP
.getNumOperands());
209 Use
*OL
= getOperandList();
210 const Use
*InOL
= LP
.getOperandList();
211 for (unsigned I
= 0, E
= ReservedSpace
; I
!= E
; ++I
)
214 setCleanup(LP
.isCleanup());
217 LandingPadInst
*LandingPadInst::Create(Type
*RetTy
, unsigned NumReservedClauses
,
218 const Twine
&NameStr
,
219 Instruction
*InsertBefore
) {
220 return new LandingPadInst(RetTy
, NumReservedClauses
, NameStr
, InsertBefore
);
223 LandingPadInst
*LandingPadInst::Create(Type
*RetTy
, unsigned NumReservedClauses
,
224 const Twine
&NameStr
,
225 BasicBlock
*InsertAtEnd
) {
226 return new LandingPadInst(RetTy
, NumReservedClauses
, NameStr
, InsertAtEnd
);
229 void LandingPadInst::init(unsigned NumReservedValues
, const Twine
&NameStr
) {
230 ReservedSpace
= NumReservedValues
;
231 setNumHungOffUseOperands(0);
232 allocHungoffUses(ReservedSpace
);
237 /// growOperands - grow operands - This grows the operand list in response to a
238 /// push_back style of operation. This grows the number of ops by 2 times.
239 void LandingPadInst::growOperands(unsigned Size
) {
240 unsigned e
= getNumOperands();
241 if (ReservedSpace
>= e
+ Size
) return;
242 ReservedSpace
= (std::max(e
, 1U) + Size
/ 2) * 2;
243 growHungoffUses(ReservedSpace
);
246 void LandingPadInst::addClause(Constant
*Val
) {
247 unsigned OpNo
= getNumOperands();
249 assert(OpNo
< ReservedSpace
&& "Growing didn't work!");
250 setNumHungOffUseOperands(getNumOperands() + 1);
251 getOperandList()[OpNo
] = Val
;
254 //===----------------------------------------------------------------------===//
255 // CallBase Implementation
256 //===----------------------------------------------------------------------===//
258 Function
*CallBase::getCaller() { return getParent()->getParent(); }
260 unsigned CallBase::getNumSubclassExtraOperandsDynamic() const {
261 assert(getOpcode() == Instruction::CallBr
&& "Unexpected opcode!");
262 return cast
<CallBrInst
>(this)->getNumIndirectDests() + 1;
265 bool CallBase::isIndirectCall() const {
266 const Value
*V
= getCalledValue();
267 if (isa
<Function
>(V
) || isa
<Constant
>(V
))
269 if (const CallInst
*CI
= dyn_cast
<CallInst
>(this))
270 if (CI
->isInlineAsm())
275 /// Tests if this call site must be tail call optimized. Only a CallInst can
276 /// be tail call optimized.
277 bool CallBase::isMustTailCall() const {
278 if (auto *CI
= dyn_cast
<CallInst
>(this))
279 return CI
->isMustTailCall();
283 /// Tests if this call site is marked as a tail call.
284 bool CallBase::isTailCall() const {
285 if (auto *CI
= dyn_cast
<CallInst
>(this))
286 return CI
->isTailCall();
290 Intrinsic::ID
CallBase::getIntrinsicID() const {
291 if (auto *F
= getCalledFunction())
292 return F
->getIntrinsicID();
293 return Intrinsic::not_intrinsic
;
296 bool CallBase::isReturnNonNull() const {
297 if (hasRetAttr(Attribute::NonNull
))
300 if (getDereferenceableBytes(AttributeList::ReturnIndex
) > 0 &&
301 !NullPointerIsDefined(getCaller(),
302 getType()->getPointerAddressSpace()))
308 Value
*CallBase::getReturnedArgOperand() const {
311 if (Attrs
.hasAttrSomewhere(Attribute::Returned
, &Index
) && Index
)
312 return getArgOperand(Index
- AttributeList::FirstArgIndex
);
313 if (const Function
*F
= getCalledFunction())
314 if (F
->getAttributes().hasAttrSomewhere(Attribute::Returned
, &Index
) &&
316 return getArgOperand(Index
- AttributeList::FirstArgIndex
);
321 bool CallBase::hasRetAttr(Attribute::AttrKind Kind
) const {
322 if (Attrs
.hasAttribute(AttributeList::ReturnIndex
, Kind
))
325 // Look at the callee, if available.
326 if (const Function
*F
= getCalledFunction())
327 return F
->getAttributes().hasAttribute(AttributeList::ReturnIndex
, Kind
);
331 /// Determine whether the argument or parameter has the given attribute.
332 bool CallBase::paramHasAttr(unsigned ArgNo
, Attribute::AttrKind Kind
) const {
333 assert(ArgNo
< getNumArgOperands() && "Param index out of bounds!");
335 if (Attrs
.hasParamAttribute(ArgNo
, Kind
))
337 if (const Function
*F
= getCalledFunction())
338 return F
->getAttributes().hasParamAttribute(ArgNo
, Kind
);
342 bool CallBase::hasFnAttrOnCalledFunction(Attribute::AttrKind Kind
) const {
343 if (const Function
*F
= getCalledFunction())
344 return F
->getAttributes().hasAttribute(AttributeList::FunctionIndex
, Kind
);
348 bool CallBase::hasFnAttrOnCalledFunction(StringRef Kind
) const {
349 if (const Function
*F
= getCalledFunction())
350 return F
->getAttributes().hasAttribute(AttributeList::FunctionIndex
, Kind
);
354 CallBase::op_iterator
355 CallBase::populateBundleOperandInfos(ArrayRef
<OperandBundleDef
> Bundles
,
356 const unsigned BeginIndex
) {
357 auto It
= op_begin() + BeginIndex
;
358 for (auto &B
: Bundles
)
359 It
= std::copy(B
.input_begin(), B
.input_end(), It
);
361 auto *ContextImpl
= getContext().pImpl
;
362 auto BI
= Bundles
.begin();
363 unsigned CurrentIndex
= BeginIndex
;
365 for (auto &BOI
: bundle_op_infos()) {
366 assert(BI
!= Bundles
.end() && "Incorrect allocation?");
368 BOI
.Tag
= ContextImpl
->getOrInsertBundleTag(BI
->getTag());
369 BOI
.Begin
= CurrentIndex
;
370 BOI
.End
= CurrentIndex
+ BI
->input_size();
371 CurrentIndex
= BOI
.End
;
375 assert(BI
== Bundles
.end() && "Incorrect allocation?");
380 //===----------------------------------------------------------------------===//
381 // CallInst Implementation
382 //===----------------------------------------------------------------------===//
384 void CallInst::init(FunctionType
*FTy
, Value
*Func
, ArrayRef
<Value
*> Args
,
385 ArrayRef
<OperandBundleDef
> Bundles
, const Twine
&NameStr
) {
387 assert(getNumOperands() == Args
.size() + CountBundleInputs(Bundles
) + 1 &&
388 "NumOperands not set up?");
389 setCalledOperand(Func
);
392 assert((Args
.size() == FTy
->getNumParams() ||
393 (FTy
->isVarArg() && Args
.size() > FTy
->getNumParams())) &&
394 "Calling a function with bad signature!");
396 for (unsigned i
= 0; i
!= Args
.size(); ++i
)
397 assert((i
>= FTy
->getNumParams() ||
398 FTy
->getParamType(i
) == Args
[i
]->getType()) &&
399 "Calling a function with a bad signature!");
402 llvm::copy(Args
, op_begin());
404 auto It
= populateBundleOperandInfos(Bundles
, Args
.size());
406 assert(It
+ 1 == op_end() && "Should add up!");
411 void CallInst::init(FunctionType
*FTy
, Value
*Func
, const Twine
&NameStr
) {
413 assert(getNumOperands() == 1 && "NumOperands not set up?");
414 setCalledOperand(Func
);
416 assert(FTy
->getNumParams() == 0 && "Calling a function with bad signature");
421 CallInst::CallInst(FunctionType
*Ty
, Value
*Func
, const Twine
&Name
,
422 Instruction
*InsertBefore
)
423 : CallBase(Ty
->getReturnType(), Instruction::Call
,
424 OperandTraits
<CallBase
>::op_end(this) - 1, 1, InsertBefore
) {
425 init(Ty
, Func
, Name
);
428 CallInst::CallInst(FunctionType
*Ty
, Value
*Func
, const Twine
&Name
,
429 BasicBlock
*InsertAtEnd
)
430 : CallBase(Ty
->getReturnType(), Instruction::Call
,
431 OperandTraits
<CallBase
>::op_end(this) - 1, 1, InsertAtEnd
) {
432 init(Ty
, Func
, Name
);
435 CallInst::CallInst(const CallInst
&CI
)
436 : CallBase(CI
.Attrs
, CI
.FTy
, CI
.getType(), Instruction::Call
,
437 OperandTraits
<CallBase
>::op_end(this) - CI
.getNumOperands(),
438 CI
.getNumOperands()) {
439 setTailCallKind(CI
.getTailCallKind());
440 setCallingConv(CI
.getCallingConv());
442 std::copy(CI
.op_begin(), CI
.op_end(), op_begin());
443 std::copy(CI
.bundle_op_info_begin(), CI
.bundle_op_info_end(),
444 bundle_op_info_begin());
445 SubclassOptionalData
= CI
.SubclassOptionalData
;
448 CallInst
*CallInst::Create(CallInst
*CI
, ArrayRef
<OperandBundleDef
> OpB
,
449 Instruction
*InsertPt
) {
450 std::vector
<Value
*> Args(CI
->arg_begin(), CI
->arg_end());
452 auto *NewCI
= CallInst::Create(CI
->getFunctionType(), CI
->getCalledValue(),
453 Args
, OpB
, CI
->getName(), InsertPt
);
454 NewCI
->setTailCallKind(CI
->getTailCallKind());
455 NewCI
->setCallingConv(CI
->getCallingConv());
456 NewCI
->SubclassOptionalData
= CI
->SubclassOptionalData
;
457 NewCI
->setAttributes(CI
->getAttributes());
458 NewCI
->setDebugLoc(CI
->getDebugLoc());
462 // Update profile weight for call instruction by scaling it using the ratio
463 // of S/T. The meaning of "branch_weights" meta data for call instruction is
464 // transfered to represent call count.
465 void CallInst::updateProfWeight(uint64_t S
, uint64_t T
) {
466 auto *ProfileData
= getMetadata(LLVMContext::MD_prof
);
467 if (ProfileData
== nullptr)
470 auto *ProfDataName
= dyn_cast
<MDString
>(ProfileData
->getOperand(0));
471 if (!ProfDataName
|| (!ProfDataName
->getString().equals("branch_weights") &&
472 !ProfDataName
->getString().equals("VP")))
476 LLVM_DEBUG(dbgs() << "Attempting to update profile weights will result in "
477 "div by 0. Ignoring. Likely the function "
478 << getParent()->getParent()->getName()
479 << " has 0 entry count, and contains call instructions "
480 "with non-zero prof info.");
484 MDBuilder
MDB(getContext());
485 SmallVector
<Metadata
*, 3> Vals
;
486 Vals
.push_back(ProfileData
->getOperand(0));
487 APInt
APS(128, S
), APT(128, T
);
488 if (ProfDataName
->getString().equals("branch_weights") &&
489 ProfileData
->getNumOperands() > 0) {
490 // Using APInt::div may be expensive, but most cases should fit 64 bits.
491 APInt
Val(128, mdconst::dyn_extract
<ConstantInt
>(ProfileData
->getOperand(1))
495 Vals
.push_back(MDB
.createConstant(ConstantInt::get(
496 Type::getInt64Ty(getContext()), Val
.udiv(APT
).getLimitedValue())));
497 } else if (ProfDataName
->getString().equals("VP"))
498 for (unsigned i
= 1; i
< ProfileData
->getNumOperands(); i
+= 2) {
499 // The first value is the key of the value profile, which will not change.
500 Vals
.push_back(ProfileData
->getOperand(i
));
501 // Using APInt::div may be expensive, but most cases should fit 64 bits.
503 mdconst::dyn_extract
<ConstantInt
>(ProfileData
->getOperand(i
+ 1))
507 Vals
.push_back(MDB
.createConstant(
508 ConstantInt::get(Type::getInt64Ty(getContext()),
509 Val
.udiv(APT
).getLimitedValue())));
511 setMetadata(LLVMContext::MD_prof
, MDNode::get(getContext(), Vals
));
514 /// IsConstantOne - Return true only if val is constant int 1
515 static bool IsConstantOne(Value
*val
) {
516 assert(val
&& "IsConstantOne does not work with nullptr val");
517 const ConstantInt
*CVal
= dyn_cast
<ConstantInt
>(val
);
518 return CVal
&& CVal
->isOne();
521 static Instruction
*createMalloc(Instruction
*InsertBefore
,
522 BasicBlock
*InsertAtEnd
, Type
*IntPtrTy
,
523 Type
*AllocTy
, Value
*AllocSize
,
525 ArrayRef
<OperandBundleDef
> OpB
,
526 Function
*MallocF
, const Twine
&Name
) {
527 assert(((!InsertBefore
&& InsertAtEnd
) || (InsertBefore
&& !InsertAtEnd
)) &&
528 "createMalloc needs either InsertBefore or InsertAtEnd");
530 // malloc(type) becomes:
531 // bitcast (i8* malloc(typeSize)) to type*
532 // malloc(type, arraySize) becomes:
533 // bitcast (i8* malloc(typeSize*arraySize)) to type*
535 ArraySize
= ConstantInt::get(IntPtrTy
, 1);
536 else if (ArraySize
->getType() != IntPtrTy
) {
538 ArraySize
= CastInst::CreateIntegerCast(ArraySize
, IntPtrTy
, false,
541 ArraySize
= CastInst::CreateIntegerCast(ArraySize
, IntPtrTy
, false,
545 if (!IsConstantOne(ArraySize
)) {
546 if (IsConstantOne(AllocSize
)) {
547 AllocSize
= ArraySize
; // Operand * 1 = Operand
548 } else if (Constant
*CO
= dyn_cast
<Constant
>(ArraySize
)) {
549 Constant
*Scale
= ConstantExpr::getIntegerCast(CO
, IntPtrTy
,
551 // Malloc arg is constant product of type size and array size
552 AllocSize
= ConstantExpr::getMul(Scale
, cast
<Constant
>(AllocSize
));
554 // Multiply type size by the array size...
556 AllocSize
= BinaryOperator::CreateMul(ArraySize
, AllocSize
,
557 "mallocsize", InsertBefore
);
559 AllocSize
= BinaryOperator::CreateMul(ArraySize
, AllocSize
,
560 "mallocsize", InsertAtEnd
);
564 assert(AllocSize
->getType() == IntPtrTy
&& "malloc arg is wrong size");
565 // Create the call to Malloc.
566 BasicBlock
*BB
= InsertBefore
? InsertBefore
->getParent() : InsertAtEnd
;
567 Module
*M
= BB
->getParent()->getParent();
568 Type
*BPTy
= Type::getInt8PtrTy(BB
->getContext());
569 FunctionCallee MallocFunc
= MallocF
;
571 // prototype malloc as "void *malloc(size_t)"
572 MallocFunc
= M
->getOrInsertFunction("malloc", BPTy
, IntPtrTy
);
573 PointerType
*AllocPtrType
= PointerType::getUnqual(AllocTy
);
574 CallInst
*MCall
= nullptr;
575 Instruction
*Result
= nullptr;
577 MCall
= CallInst::Create(MallocFunc
, AllocSize
, OpB
, "malloccall",
580 if (Result
->getType() != AllocPtrType
)
581 // Create a cast instruction to convert to the right type...
582 Result
= new BitCastInst(MCall
, AllocPtrType
, Name
, InsertBefore
);
584 MCall
= CallInst::Create(MallocFunc
, AllocSize
, OpB
, "malloccall");
586 if (Result
->getType() != AllocPtrType
) {
587 InsertAtEnd
->getInstList().push_back(MCall
);
588 // Create a cast instruction to convert to the right type...
589 Result
= new BitCastInst(MCall
, AllocPtrType
, Name
);
592 MCall
->setTailCall();
593 if (Function
*F
= dyn_cast
<Function
>(MallocFunc
.getCallee())) {
594 MCall
->setCallingConv(F
->getCallingConv());
595 if (!F
->returnDoesNotAlias())
596 F
->setReturnDoesNotAlias();
598 assert(!MCall
->getType()->isVoidTy() && "Malloc has void return type");
603 /// CreateMalloc - Generate the IR for a call to malloc:
604 /// 1. Compute the malloc call's argument as the specified type's size,
605 /// possibly multiplied by the array size if the array size is not
607 /// 2. Call malloc with that argument.
608 /// 3. Bitcast the result of the malloc call to the specified type.
609 Instruction
*CallInst::CreateMalloc(Instruction
*InsertBefore
,
610 Type
*IntPtrTy
, Type
*AllocTy
,
611 Value
*AllocSize
, Value
*ArraySize
,
614 return createMalloc(InsertBefore
, nullptr, IntPtrTy
, AllocTy
, AllocSize
,
615 ArraySize
, None
, MallocF
, Name
);
617 Instruction
*CallInst::CreateMalloc(Instruction
*InsertBefore
,
618 Type
*IntPtrTy
, Type
*AllocTy
,
619 Value
*AllocSize
, Value
*ArraySize
,
620 ArrayRef
<OperandBundleDef
> OpB
,
623 return createMalloc(InsertBefore
, nullptr, IntPtrTy
, AllocTy
, AllocSize
,
624 ArraySize
, OpB
, MallocF
, Name
);
627 /// CreateMalloc - Generate the IR for a call to malloc:
628 /// 1. Compute the malloc call's argument as the specified type's size,
629 /// possibly multiplied by the array size if the array size is not
631 /// 2. Call malloc with that argument.
632 /// 3. Bitcast the result of the malloc call to the specified type.
633 /// Note: This function does not add the bitcast to the basic block, that is the
634 /// responsibility of the caller.
635 Instruction
*CallInst::CreateMalloc(BasicBlock
*InsertAtEnd
,
636 Type
*IntPtrTy
, Type
*AllocTy
,
637 Value
*AllocSize
, Value
*ArraySize
,
638 Function
*MallocF
, const Twine
&Name
) {
639 return createMalloc(nullptr, InsertAtEnd
, IntPtrTy
, AllocTy
, AllocSize
,
640 ArraySize
, None
, MallocF
, Name
);
642 Instruction
*CallInst::CreateMalloc(BasicBlock
*InsertAtEnd
,
643 Type
*IntPtrTy
, Type
*AllocTy
,
644 Value
*AllocSize
, Value
*ArraySize
,
645 ArrayRef
<OperandBundleDef
> OpB
,
646 Function
*MallocF
, const Twine
&Name
) {
647 return createMalloc(nullptr, InsertAtEnd
, IntPtrTy
, AllocTy
, AllocSize
,
648 ArraySize
, OpB
, MallocF
, Name
);
651 static Instruction
*createFree(Value
*Source
,
652 ArrayRef
<OperandBundleDef
> Bundles
,
653 Instruction
*InsertBefore
,
654 BasicBlock
*InsertAtEnd
) {
655 assert(((!InsertBefore
&& InsertAtEnd
) || (InsertBefore
&& !InsertAtEnd
)) &&
656 "createFree needs either InsertBefore or InsertAtEnd");
657 assert(Source
->getType()->isPointerTy() &&
658 "Can not free something of nonpointer type!");
660 BasicBlock
*BB
= InsertBefore
? InsertBefore
->getParent() : InsertAtEnd
;
661 Module
*M
= BB
->getParent()->getParent();
663 Type
*VoidTy
= Type::getVoidTy(M
->getContext());
664 Type
*IntPtrTy
= Type::getInt8PtrTy(M
->getContext());
665 // prototype free as "void free(void*)"
666 FunctionCallee FreeFunc
= M
->getOrInsertFunction("free", VoidTy
, IntPtrTy
);
667 CallInst
*Result
= nullptr;
668 Value
*PtrCast
= Source
;
670 if (Source
->getType() != IntPtrTy
)
671 PtrCast
= new BitCastInst(Source
, IntPtrTy
, "", InsertBefore
);
672 Result
= CallInst::Create(FreeFunc
, PtrCast
, Bundles
, "", InsertBefore
);
674 if (Source
->getType() != IntPtrTy
)
675 PtrCast
= new BitCastInst(Source
, IntPtrTy
, "", InsertAtEnd
);
676 Result
= CallInst::Create(FreeFunc
, PtrCast
, Bundles
, "");
678 Result
->setTailCall();
679 if (Function
*F
= dyn_cast
<Function
>(FreeFunc
.getCallee()))
680 Result
->setCallingConv(F
->getCallingConv());
685 /// CreateFree - Generate the IR for a call to the builtin free function.
686 Instruction
*CallInst::CreateFree(Value
*Source
, Instruction
*InsertBefore
) {
687 return createFree(Source
, None
, InsertBefore
, nullptr);
689 Instruction
*CallInst::CreateFree(Value
*Source
,
690 ArrayRef
<OperandBundleDef
> Bundles
,
691 Instruction
*InsertBefore
) {
692 return createFree(Source
, Bundles
, InsertBefore
, nullptr);
695 /// CreateFree - Generate the IR for a call to the builtin free function.
696 /// Note: This function does not add the call to the basic block, that is the
697 /// responsibility of the caller.
698 Instruction
*CallInst::CreateFree(Value
*Source
, BasicBlock
*InsertAtEnd
) {
699 Instruction
*FreeCall
= createFree(Source
, None
, nullptr, InsertAtEnd
);
700 assert(FreeCall
&& "CreateFree did not create a CallInst");
703 Instruction
*CallInst::CreateFree(Value
*Source
,
704 ArrayRef
<OperandBundleDef
> Bundles
,
705 BasicBlock
*InsertAtEnd
) {
706 Instruction
*FreeCall
= createFree(Source
, Bundles
, nullptr, InsertAtEnd
);
707 assert(FreeCall
&& "CreateFree did not create a CallInst");
711 //===----------------------------------------------------------------------===//
712 // InvokeInst Implementation
713 //===----------------------------------------------------------------------===//
715 void InvokeInst::init(FunctionType
*FTy
, Value
*Fn
, BasicBlock
*IfNormal
,
716 BasicBlock
*IfException
, ArrayRef
<Value
*> Args
,
717 ArrayRef
<OperandBundleDef
> Bundles
,
718 const Twine
&NameStr
) {
721 assert((int)getNumOperands() ==
722 ComputeNumOperands(Args
.size(), CountBundleInputs(Bundles
)) &&
723 "NumOperands not set up?");
724 setNormalDest(IfNormal
);
725 setUnwindDest(IfException
);
726 setCalledOperand(Fn
);
729 assert(((Args
.size() == FTy
->getNumParams()) ||
730 (FTy
->isVarArg() && Args
.size() > FTy
->getNumParams())) &&
731 "Invoking a function with bad signature");
733 for (unsigned i
= 0, e
= Args
.size(); i
!= e
; i
++)
734 assert((i
>= FTy
->getNumParams() ||
735 FTy
->getParamType(i
) == Args
[i
]->getType()) &&
736 "Invoking a function with a bad signature!");
739 llvm::copy(Args
, op_begin());
741 auto It
= populateBundleOperandInfos(Bundles
, Args
.size());
743 assert(It
+ 3 == op_end() && "Should add up!");
748 InvokeInst::InvokeInst(const InvokeInst
&II
)
749 : CallBase(II
.Attrs
, II
.FTy
, II
.getType(), Instruction::Invoke
,
750 OperandTraits
<CallBase
>::op_end(this) - II
.getNumOperands(),
751 II
.getNumOperands()) {
752 setCallingConv(II
.getCallingConv());
753 std::copy(II
.op_begin(), II
.op_end(), op_begin());
754 std::copy(II
.bundle_op_info_begin(), II
.bundle_op_info_end(),
755 bundle_op_info_begin());
756 SubclassOptionalData
= II
.SubclassOptionalData
;
759 InvokeInst
*InvokeInst::Create(InvokeInst
*II
, ArrayRef
<OperandBundleDef
> OpB
,
760 Instruction
*InsertPt
) {
761 std::vector
<Value
*> Args(II
->arg_begin(), II
->arg_end());
763 auto *NewII
= InvokeInst::Create(II
->getFunctionType(), II
->getCalledValue(),
764 II
->getNormalDest(), II
->getUnwindDest(),
765 Args
, OpB
, II
->getName(), InsertPt
);
766 NewII
->setCallingConv(II
->getCallingConv());
767 NewII
->SubclassOptionalData
= II
->SubclassOptionalData
;
768 NewII
->setAttributes(II
->getAttributes());
769 NewII
->setDebugLoc(II
->getDebugLoc());
774 LandingPadInst
*InvokeInst::getLandingPadInst() const {
775 return cast
<LandingPadInst
>(getUnwindDest()->getFirstNonPHI());
778 //===----------------------------------------------------------------------===//
779 // CallBrInst Implementation
780 //===----------------------------------------------------------------------===//
782 void CallBrInst::init(FunctionType
*FTy
, Value
*Fn
, BasicBlock
*Fallthrough
,
783 ArrayRef
<BasicBlock
*> IndirectDests
,
784 ArrayRef
<Value
*> Args
,
785 ArrayRef
<OperandBundleDef
> Bundles
,
786 const Twine
&NameStr
) {
789 assert((int)getNumOperands() ==
790 ComputeNumOperands(Args
.size(), IndirectDests
.size(),
791 CountBundleInputs(Bundles
)) &&
792 "NumOperands not set up?");
793 NumIndirectDests
= IndirectDests
.size();
794 setDefaultDest(Fallthrough
);
795 for (unsigned i
= 0; i
!= NumIndirectDests
; ++i
)
796 setIndirectDest(i
, IndirectDests
[i
]);
797 setCalledOperand(Fn
);
800 assert(((Args
.size() == FTy
->getNumParams()) ||
801 (FTy
->isVarArg() && Args
.size() > FTy
->getNumParams())) &&
802 "Calling a function with bad signature");
804 for (unsigned i
= 0, e
= Args
.size(); i
!= e
; i
++)
805 assert((i
>= FTy
->getNumParams() ||
806 FTy
->getParamType(i
) == Args
[i
]->getType()) &&
807 "Calling a function with a bad signature!");
810 std::copy(Args
.begin(), Args
.end(), op_begin());
812 auto It
= populateBundleOperandInfos(Bundles
, Args
.size());
814 assert(It
+ 2 + IndirectDests
.size() == op_end() && "Should add up!");
819 void CallBrInst::updateArgBlockAddresses(unsigned i
, BasicBlock
*B
) {
820 assert(getNumIndirectDests() > i
&& "IndirectDest # out of range for callbr");
821 if (BasicBlock
*OldBB
= getIndirectDest(i
)) {
822 BlockAddress
*Old
= BlockAddress::get(OldBB
);
823 BlockAddress
*New
= BlockAddress::get(B
);
824 for (unsigned ArgNo
= 0, e
= getNumArgOperands(); ArgNo
!= e
; ++ArgNo
)
825 if (dyn_cast
<BlockAddress
>(getArgOperand(ArgNo
)) == Old
)
826 setArgOperand(ArgNo
, New
);
830 CallBrInst::CallBrInst(const CallBrInst
&CBI
)
831 : CallBase(CBI
.Attrs
, CBI
.FTy
, CBI
.getType(), Instruction::CallBr
,
832 OperandTraits
<CallBase
>::op_end(this) - CBI
.getNumOperands(),
833 CBI
.getNumOperands()) {
834 setCallingConv(CBI
.getCallingConv());
835 std::copy(CBI
.op_begin(), CBI
.op_end(), op_begin());
836 std::copy(CBI
.bundle_op_info_begin(), CBI
.bundle_op_info_end(),
837 bundle_op_info_begin());
838 SubclassOptionalData
= CBI
.SubclassOptionalData
;
839 NumIndirectDests
= CBI
.NumIndirectDests
;
842 CallBrInst
*CallBrInst::Create(CallBrInst
*CBI
, ArrayRef
<OperandBundleDef
> OpB
,
843 Instruction
*InsertPt
) {
844 std::vector
<Value
*> Args(CBI
->arg_begin(), CBI
->arg_end());
846 auto *NewCBI
= CallBrInst::Create(CBI
->getFunctionType(),
847 CBI
->getCalledValue(),
848 CBI
->getDefaultDest(),
849 CBI
->getIndirectDests(),
850 Args
, OpB
, CBI
->getName(), InsertPt
);
851 NewCBI
->setCallingConv(CBI
->getCallingConv());
852 NewCBI
->SubclassOptionalData
= CBI
->SubclassOptionalData
;
853 NewCBI
->setAttributes(CBI
->getAttributes());
854 NewCBI
->setDebugLoc(CBI
->getDebugLoc());
855 NewCBI
->NumIndirectDests
= CBI
->NumIndirectDests
;
859 //===----------------------------------------------------------------------===//
860 // ReturnInst Implementation
861 //===----------------------------------------------------------------------===//
863 ReturnInst::ReturnInst(const ReturnInst
&RI
)
864 : Instruction(Type::getVoidTy(RI
.getContext()), Instruction::Ret
,
865 OperandTraits
<ReturnInst
>::op_end(this) - RI
.getNumOperands(),
866 RI
.getNumOperands()) {
867 if (RI
.getNumOperands())
868 Op
<0>() = RI
.Op
<0>();
869 SubclassOptionalData
= RI
.SubclassOptionalData
;
872 ReturnInst::ReturnInst(LLVMContext
&C
, Value
*retVal
, Instruction
*InsertBefore
)
873 : Instruction(Type::getVoidTy(C
), Instruction::Ret
,
874 OperandTraits
<ReturnInst
>::op_end(this) - !!retVal
, !!retVal
,
880 ReturnInst::ReturnInst(LLVMContext
&C
, Value
*retVal
, BasicBlock
*InsertAtEnd
)
881 : Instruction(Type::getVoidTy(C
), Instruction::Ret
,
882 OperandTraits
<ReturnInst
>::op_end(this) - !!retVal
, !!retVal
,
888 ReturnInst::ReturnInst(LLVMContext
&Context
, BasicBlock
*InsertAtEnd
)
889 : Instruction(Type::getVoidTy(Context
), Instruction::Ret
,
890 OperandTraits
<ReturnInst
>::op_end(this), 0, InsertAtEnd
) {}
892 //===----------------------------------------------------------------------===//
893 // ResumeInst Implementation
894 //===----------------------------------------------------------------------===//
896 ResumeInst::ResumeInst(const ResumeInst
&RI
)
897 : Instruction(Type::getVoidTy(RI
.getContext()), Instruction::Resume
,
898 OperandTraits
<ResumeInst
>::op_begin(this), 1) {
899 Op
<0>() = RI
.Op
<0>();
902 ResumeInst::ResumeInst(Value
*Exn
, Instruction
*InsertBefore
)
903 : Instruction(Type::getVoidTy(Exn
->getContext()), Instruction::Resume
,
904 OperandTraits
<ResumeInst
>::op_begin(this), 1, InsertBefore
) {
908 ResumeInst::ResumeInst(Value
*Exn
, BasicBlock
*InsertAtEnd
)
909 : Instruction(Type::getVoidTy(Exn
->getContext()), Instruction::Resume
,
910 OperandTraits
<ResumeInst
>::op_begin(this), 1, InsertAtEnd
) {
914 //===----------------------------------------------------------------------===//
915 // CleanupReturnInst Implementation
916 //===----------------------------------------------------------------------===//
918 CleanupReturnInst::CleanupReturnInst(const CleanupReturnInst
&CRI
)
919 : Instruction(CRI
.getType(), Instruction::CleanupRet
,
920 OperandTraits
<CleanupReturnInst
>::op_end(this) -
921 CRI
.getNumOperands(),
922 CRI
.getNumOperands()) {
923 setInstructionSubclassData(CRI
.getSubclassDataFromInstruction());
924 Op
<0>() = CRI
.Op
<0>();
925 if (CRI
.hasUnwindDest())
926 Op
<1>() = CRI
.Op
<1>();
929 void CleanupReturnInst::init(Value
*CleanupPad
, BasicBlock
*UnwindBB
) {
931 setInstructionSubclassData(getSubclassDataFromInstruction() | 1);
933 Op
<0>() = CleanupPad
;
938 CleanupReturnInst::CleanupReturnInst(Value
*CleanupPad
, BasicBlock
*UnwindBB
,
939 unsigned Values
, Instruction
*InsertBefore
)
940 : Instruction(Type::getVoidTy(CleanupPad
->getContext()),
941 Instruction::CleanupRet
,
942 OperandTraits
<CleanupReturnInst
>::op_end(this) - Values
,
943 Values
, InsertBefore
) {
944 init(CleanupPad
, UnwindBB
);
947 CleanupReturnInst::CleanupReturnInst(Value
*CleanupPad
, BasicBlock
*UnwindBB
,
948 unsigned Values
, BasicBlock
*InsertAtEnd
)
949 : Instruction(Type::getVoidTy(CleanupPad
->getContext()),
950 Instruction::CleanupRet
,
951 OperandTraits
<CleanupReturnInst
>::op_end(this) - Values
,
952 Values
, InsertAtEnd
) {
953 init(CleanupPad
, UnwindBB
);
956 //===----------------------------------------------------------------------===//
957 // CatchReturnInst Implementation
958 //===----------------------------------------------------------------------===//
959 void CatchReturnInst::init(Value
*CatchPad
, BasicBlock
*BB
) {
964 CatchReturnInst::CatchReturnInst(const CatchReturnInst
&CRI
)
965 : Instruction(Type::getVoidTy(CRI
.getContext()), Instruction::CatchRet
,
966 OperandTraits
<CatchReturnInst
>::op_begin(this), 2) {
967 Op
<0>() = CRI
.Op
<0>();
968 Op
<1>() = CRI
.Op
<1>();
971 CatchReturnInst::CatchReturnInst(Value
*CatchPad
, BasicBlock
*BB
,
972 Instruction
*InsertBefore
)
973 : Instruction(Type::getVoidTy(BB
->getContext()), Instruction::CatchRet
,
974 OperandTraits
<CatchReturnInst
>::op_begin(this), 2,
979 CatchReturnInst::CatchReturnInst(Value
*CatchPad
, BasicBlock
*BB
,
980 BasicBlock
*InsertAtEnd
)
981 : Instruction(Type::getVoidTy(BB
->getContext()), Instruction::CatchRet
,
982 OperandTraits
<CatchReturnInst
>::op_begin(this), 2,
987 //===----------------------------------------------------------------------===//
988 // CatchSwitchInst Implementation
989 //===----------------------------------------------------------------------===//
991 CatchSwitchInst::CatchSwitchInst(Value
*ParentPad
, BasicBlock
*UnwindDest
,
992 unsigned NumReservedValues
,
993 const Twine
&NameStr
,
994 Instruction
*InsertBefore
)
995 : Instruction(ParentPad
->getType(), Instruction::CatchSwitch
, nullptr, 0,
999 init(ParentPad
, UnwindDest
, NumReservedValues
+ 1);
1003 CatchSwitchInst::CatchSwitchInst(Value
*ParentPad
, BasicBlock
*UnwindDest
,
1004 unsigned NumReservedValues
,
1005 const Twine
&NameStr
, BasicBlock
*InsertAtEnd
)
1006 : Instruction(ParentPad
->getType(), Instruction::CatchSwitch
, nullptr, 0,
1009 ++NumReservedValues
;
1010 init(ParentPad
, UnwindDest
, NumReservedValues
+ 1);
1014 CatchSwitchInst::CatchSwitchInst(const CatchSwitchInst
&CSI
)
1015 : Instruction(CSI
.getType(), Instruction::CatchSwitch
, nullptr,
1016 CSI
.getNumOperands()) {
1017 init(CSI
.getParentPad(), CSI
.getUnwindDest(), CSI
.getNumOperands());
1018 setNumHungOffUseOperands(ReservedSpace
);
1019 Use
*OL
= getOperandList();
1020 const Use
*InOL
= CSI
.getOperandList();
1021 for (unsigned I
= 1, E
= ReservedSpace
; I
!= E
; ++I
)
1025 void CatchSwitchInst::init(Value
*ParentPad
, BasicBlock
*UnwindDest
,
1026 unsigned NumReservedValues
) {
1027 assert(ParentPad
&& NumReservedValues
);
1029 ReservedSpace
= NumReservedValues
;
1030 setNumHungOffUseOperands(UnwindDest
? 2 : 1);
1031 allocHungoffUses(ReservedSpace
);
1033 Op
<0>() = ParentPad
;
1035 setInstructionSubclassData(getSubclassDataFromInstruction() | 1);
1036 setUnwindDest(UnwindDest
);
1040 /// growOperands - grow operands - This grows the operand list in response to a
1041 /// push_back style of operation. This grows the number of ops by 2 times.
1042 void CatchSwitchInst::growOperands(unsigned Size
) {
1043 unsigned NumOperands
= getNumOperands();
1044 assert(NumOperands
>= 1);
1045 if (ReservedSpace
>= NumOperands
+ Size
)
1047 ReservedSpace
= (NumOperands
+ Size
/ 2) * 2;
1048 growHungoffUses(ReservedSpace
);
1051 void CatchSwitchInst::addHandler(BasicBlock
*Handler
) {
1052 unsigned OpNo
= getNumOperands();
1054 assert(OpNo
< ReservedSpace
&& "Growing didn't work!");
1055 setNumHungOffUseOperands(getNumOperands() + 1);
1056 getOperandList()[OpNo
] = Handler
;
1059 void CatchSwitchInst::removeHandler(handler_iterator HI
) {
1060 // Move all subsequent handlers up one.
1061 Use
*EndDst
= op_end() - 1;
1062 for (Use
*CurDst
= HI
.getCurrent(); CurDst
!= EndDst
; ++CurDst
)
1063 *CurDst
= *(CurDst
+ 1);
1064 // Null out the last handler use.
1067 setNumHungOffUseOperands(getNumOperands() - 1);
1070 //===----------------------------------------------------------------------===//
1071 // FuncletPadInst Implementation
1072 //===----------------------------------------------------------------------===//
1073 void FuncletPadInst::init(Value
*ParentPad
, ArrayRef
<Value
*> Args
,
1074 const Twine
&NameStr
) {
1075 assert(getNumOperands() == 1 + Args
.size() && "NumOperands not set up?");
1076 llvm::copy(Args
, op_begin());
1077 setParentPad(ParentPad
);
1081 FuncletPadInst::FuncletPadInst(const FuncletPadInst
&FPI
)
1082 : Instruction(FPI
.getType(), FPI
.getOpcode(),
1083 OperandTraits
<FuncletPadInst
>::op_end(this) -
1084 FPI
.getNumOperands(),
1085 FPI
.getNumOperands()) {
1086 std::copy(FPI
.op_begin(), FPI
.op_end(), op_begin());
1087 setParentPad(FPI
.getParentPad());
1090 FuncletPadInst::FuncletPadInst(Instruction::FuncletPadOps Op
, Value
*ParentPad
,
1091 ArrayRef
<Value
*> Args
, unsigned Values
,
1092 const Twine
&NameStr
, Instruction
*InsertBefore
)
1093 : Instruction(ParentPad
->getType(), Op
,
1094 OperandTraits
<FuncletPadInst
>::op_end(this) - Values
, Values
,
1096 init(ParentPad
, Args
, NameStr
);
1099 FuncletPadInst::FuncletPadInst(Instruction::FuncletPadOps Op
, Value
*ParentPad
,
1100 ArrayRef
<Value
*> Args
, unsigned Values
,
1101 const Twine
&NameStr
, BasicBlock
*InsertAtEnd
)
1102 : Instruction(ParentPad
->getType(), Op
,
1103 OperandTraits
<FuncletPadInst
>::op_end(this) - Values
, Values
,
1105 init(ParentPad
, Args
, NameStr
);
1108 //===----------------------------------------------------------------------===//
1109 // UnreachableInst Implementation
1110 //===----------------------------------------------------------------------===//
1112 UnreachableInst::UnreachableInst(LLVMContext
&Context
,
1113 Instruction
*InsertBefore
)
1114 : Instruction(Type::getVoidTy(Context
), Instruction::Unreachable
, nullptr,
1116 UnreachableInst::UnreachableInst(LLVMContext
&Context
, BasicBlock
*InsertAtEnd
)
1117 : Instruction(Type::getVoidTy(Context
), Instruction::Unreachable
, nullptr,
1120 //===----------------------------------------------------------------------===//
1121 // BranchInst Implementation
1122 //===----------------------------------------------------------------------===//
1124 void BranchInst::AssertOK() {
1125 if (isConditional())
1126 assert(getCondition()->getType()->isIntegerTy(1) &&
1127 "May only branch on boolean predicates!");
1130 BranchInst::BranchInst(BasicBlock
*IfTrue
, Instruction
*InsertBefore
)
1131 : Instruction(Type::getVoidTy(IfTrue
->getContext()), Instruction::Br
,
1132 OperandTraits
<BranchInst
>::op_end(this) - 1, 1,
1134 assert(IfTrue
&& "Branch destination may not be null!");
1138 BranchInst::BranchInst(BasicBlock
*IfTrue
, BasicBlock
*IfFalse
, Value
*Cond
,
1139 Instruction
*InsertBefore
)
1140 : Instruction(Type::getVoidTy(IfTrue
->getContext()), Instruction::Br
,
1141 OperandTraits
<BranchInst
>::op_end(this) - 3, 3,
1151 BranchInst::BranchInst(BasicBlock
*IfTrue
, BasicBlock
*InsertAtEnd
)
1152 : Instruction(Type::getVoidTy(IfTrue
->getContext()), Instruction::Br
,
1153 OperandTraits
<BranchInst
>::op_end(this) - 1, 1, InsertAtEnd
) {
1154 assert(IfTrue
&& "Branch destination may not be null!");
1158 BranchInst::BranchInst(BasicBlock
*IfTrue
, BasicBlock
*IfFalse
, Value
*Cond
,
1159 BasicBlock
*InsertAtEnd
)
1160 : Instruction(Type::getVoidTy(IfTrue
->getContext()), Instruction::Br
,
1161 OperandTraits
<BranchInst
>::op_end(this) - 3, 3, InsertAtEnd
) {
1170 BranchInst::BranchInst(const BranchInst
&BI
)
1171 : Instruction(Type::getVoidTy(BI
.getContext()), Instruction::Br
,
1172 OperandTraits
<BranchInst
>::op_end(this) - BI
.getNumOperands(),
1173 BI
.getNumOperands()) {
1174 Op
<-1>() = BI
.Op
<-1>();
1175 if (BI
.getNumOperands() != 1) {
1176 assert(BI
.getNumOperands() == 3 && "BR can have 1 or 3 operands!");
1177 Op
<-3>() = BI
.Op
<-3>();
1178 Op
<-2>() = BI
.Op
<-2>();
1180 SubclassOptionalData
= BI
.SubclassOptionalData
;
1183 void BranchInst::swapSuccessors() {
1184 assert(isConditional() &&
1185 "Cannot swap successors of an unconditional branch");
1186 Op
<-1>().swap(Op
<-2>());
1188 // Update profile metadata if present and it matches our structural
1193 //===----------------------------------------------------------------------===//
1194 // AllocaInst Implementation
1195 //===----------------------------------------------------------------------===//
1197 static Value
*getAISize(LLVMContext
&Context
, Value
*Amt
) {
1199 Amt
= ConstantInt::get(Type::getInt32Ty(Context
), 1);
1201 assert(!isa
<BasicBlock
>(Amt
) &&
1202 "Passed basic block into allocation size parameter! Use other ctor");
1203 assert(Amt
->getType()->isIntegerTy() &&
1204 "Allocation array size is not an integer!");
1209 AllocaInst::AllocaInst(Type
*Ty
, unsigned AddrSpace
, const Twine
&Name
,
1210 Instruction
*InsertBefore
)
1211 : AllocaInst(Ty
, AddrSpace
, /*ArraySize=*/nullptr, Name
, InsertBefore
) {}
1213 AllocaInst::AllocaInst(Type
*Ty
, unsigned AddrSpace
, const Twine
&Name
,
1214 BasicBlock
*InsertAtEnd
)
1215 : AllocaInst(Ty
, AddrSpace
, /*ArraySize=*/nullptr, Name
, InsertAtEnd
) {}
1217 AllocaInst::AllocaInst(Type
*Ty
, unsigned AddrSpace
, Value
*ArraySize
,
1218 const Twine
&Name
, Instruction
*InsertBefore
)
1219 : AllocaInst(Ty
, AddrSpace
, ArraySize
, /*Align=*/0, Name
, InsertBefore
) {}
1221 AllocaInst::AllocaInst(Type
*Ty
, unsigned AddrSpace
, Value
*ArraySize
,
1222 const Twine
&Name
, BasicBlock
*InsertAtEnd
)
1223 : AllocaInst(Ty
, AddrSpace
, ArraySize
, /*Align=*/0, Name
, InsertAtEnd
) {}
1225 AllocaInst::AllocaInst(Type
*Ty
, unsigned AddrSpace
, Value
*ArraySize
,
1226 unsigned Align
, const Twine
&Name
,
1227 Instruction
*InsertBefore
)
1228 : UnaryInstruction(PointerType::get(Ty
, AddrSpace
), Alloca
,
1229 getAISize(Ty
->getContext(), ArraySize
), InsertBefore
),
1231 setAlignment(Align
);
1232 assert(!Ty
->isVoidTy() && "Cannot allocate void!");
1236 AllocaInst::AllocaInst(Type
*Ty
, unsigned AddrSpace
, Value
*ArraySize
,
1237 unsigned Align
, const Twine
&Name
,
1238 BasicBlock
*InsertAtEnd
)
1239 : UnaryInstruction(PointerType::get(Ty
, AddrSpace
), Alloca
,
1240 getAISize(Ty
->getContext(), ArraySize
), InsertAtEnd
),
1242 setAlignment(Align
);
1243 assert(!Ty
->isVoidTy() && "Cannot allocate void!");
1247 void AllocaInst::setAlignment(unsigned Align
) {
1248 setAlignment(llvm::MaybeAlign(Align
));
1251 void AllocaInst::setAlignment(MaybeAlign Align
) {
1252 assert((!Align
|| *Align
<= MaximumAlignment
) &&
1253 "Alignment is greater than MaximumAlignment!");
1254 setInstructionSubclassData((getSubclassDataFromInstruction() & ~31) |
1257 assert(getAlignment() == Align
->value() &&
1258 "Alignment representation error!");
1260 assert(getAlignment() == 0 && "Alignment representation error!");
1263 bool AllocaInst::isArrayAllocation() const {
1264 if (ConstantInt
*CI
= dyn_cast
<ConstantInt
>(getOperand(0)))
1265 return !CI
->isOne();
1269 /// isStaticAlloca - Return true if this alloca is in the entry block of the
1270 /// function and is a constant size. If so, the code generator will fold it
1271 /// into the prolog/epilog code, so it is basically free.
1272 bool AllocaInst::isStaticAlloca() const {
1273 // Must be constant size.
1274 if (!isa
<ConstantInt
>(getArraySize())) return false;
1276 // Must be in the entry block.
1277 const BasicBlock
*Parent
= getParent();
1278 return Parent
== &Parent
->getParent()->front() && !isUsedWithInAlloca();
1281 //===----------------------------------------------------------------------===//
1282 // LoadInst Implementation
1283 //===----------------------------------------------------------------------===//
1285 void LoadInst::AssertOK() {
1286 assert(getOperand(0)->getType()->isPointerTy() &&
1287 "Ptr must have pointer type.");
1288 assert(!(isAtomic() && getAlignment() == 0) &&
1289 "Alignment required for atomic load");
1292 LoadInst::LoadInst(Type
*Ty
, Value
*Ptr
, const Twine
&Name
,
1293 Instruction
*InsertBef
)
1294 : LoadInst(Ty
, Ptr
, Name
, /*isVolatile=*/false, InsertBef
) {}
1296 LoadInst::LoadInst(Type
*Ty
, Value
*Ptr
, const Twine
&Name
,
1297 BasicBlock
*InsertAE
)
1298 : LoadInst(Ty
, Ptr
, Name
, /*isVolatile=*/false, InsertAE
) {}
1300 LoadInst::LoadInst(Type
*Ty
, Value
*Ptr
, const Twine
&Name
, bool isVolatile
,
1301 Instruction
*InsertBef
)
1302 : LoadInst(Ty
, Ptr
, Name
, isVolatile
, /*Align=*/0, InsertBef
) {}
1304 LoadInst::LoadInst(Type
*Ty
, Value
*Ptr
, const Twine
&Name
, bool isVolatile
,
1305 BasicBlock
*InsertAE
)
1306 : LoadInst(Ty
, Ptr
, Name
, isVolatile
, /*Align=*/0, InsertAE
) {}
1308 LoadInst::LoadInst(Type
*Ty
, Value
*Ptr
, const Twine
&Name
, bool isVolatile
,
1309 unsigned Align
, Instruction
*InsertBef
)
1310 : LoadInst(Ty
, Ptr
, Name
, isVolatile
, Align
, AtomicOrdering::NotAtomic
,
1311 SyncScope::System
, InsertBef
) {}
1313 LoadInst::LoadInst(Type
*Ty
, Value
*Ptr
, const Twine
&Name
, bool isVolatile
,
1314 unsigned Align
, BasicBlock
*InsertAE
)
1315 : LoadInst(Ty
, Ptr
, Name
, isVolatile
, Align
, AtomicOrdering::NotAtomic
,
1316 SyncScope::System
, InsertAE
) {}
1318 LoadInst::LoadInst(Type
*Ty
, Value
*Ptr
, const Twine
&Name
, bool isVolatile
,
1319 unsigned Align
, AtomicOrdering Order
,
1320 SyncScope::ID SSID
, Instruction
*InsertBef
)
1321 : UnaryInstruction(Ty
, Load
, Ptr
, InsertBef
) {
1322 assert(Ty
== cast
<PointerType
>(Ptr
->getType())->getElementType());
1323 setVolatile(isVolatile
);
1324 setAlignment(Align
);
1325 setAtomic(Order
, SSID
);
1330 LoadInst::LoadInst(Type
*Ty
, Value
*Ptr
, const Twine
&Name
, bool isVolatile
,
1331 unsigned Align
, AtomicOrdering Order
, SyncScope::ID SSID
,
1332 BasicBlock
*InsertAE
)
1333 : UnaryInstruction(Ty
, Load
, Ptr
, InsertAE
) {
1334 assert(Ty
== cast
<PointerType
>(Ptr
->getType())->getElementType());
1335 setVolatile(isVolatile
);
1336 setAlignment(Align
);
1337 setAtomic(Order
, SSID
);
1342 void LoadInst::setAlignment(unsigned Align
) {
1343 setAlignment(llvm::MaybeAlign(Align
));
1346 void LoadInst::setAlignment(MaybeAlign Align
) {
1347 assert((!Align
|| *Align
<= MaximumAlignment
) &&
1348 "Alignment is greater than MaximumAlignment!");
1349 setInstructionSubclassData((getSubclassDataFromInstruction() & ~(31 << 1)) |
1350 (encode(Align
) << 1));
1352 assert(getAlignment() == Align
->value() &&
1353 "Alignment representation error!");
1355 assert(getAlignment() == 0 && "Alignment representation error!");
1358 //===----------------------------------------------------------------------===//
1359 // StoreInst Implementation
1360 //===----------------------------------------------------------------------===//
1362 void StoreInst::AssertOK() {
1363 assert(getOperand(0) && getOperand(1) && "Both operands must be non-null!");
1364 assert(getOperand(1)->getType()->isPointerTy() &&
1365 "Ptr must have pointer type!");
1366 assert(getOperand(0)->getType() ==
1367 cast
<PointerType
>(getOperand(1)->getType())->getElementType()
1368 && "Ptr must be a pointer to Val type!");
1369 assert(!(isAtomic() && getAlignment() == 0) &&
1370 "Alignment required for atomic store");
1373 StoreInst::StoreInst(Value
*val
, Value
*addr
, Instruction
*InsertBefore
)
1374 : StoreInst(val
, addr
, /*isVolatile=*/false, InsertBefore
) {}
1376 StoreInst::StoreInst(Value
*val
, Value
*addr
, BasicBlock
*InsertAtEnd
)
1377 : StoreInst(val
, addr
, /*isVolatile=*/false, InsertAtEnd
) {}
1379 StoreInst::StoreInst(Value
*val
, Value
*addr
, bool isVolatile
,
1380 Instruction
*InsertBefore
)
1381 : StoreInst(val
, addr
, isVolatile
, /*Align=*/0, InsertBefore
) {}
1383 StoreInst::StoreInst(Value
*val
, Value
*addr
, bool isVolatile
,
1384 BasicBlock
*InsertAtEnd
)
1385 : StoreInst(val
, addr
, isVolatile
, /*Align=*/0, InsertAtEnd
) {}
1387 StoreInst::StoreInst(Value
*val
, Value
*addr
, bool isVolatile
, unsigned Align
,
1388 Instruction
*InsertBefore
)
1389 : StoreInst(val
, addr
, isVolatile
, Align
, AtomicOrdering::NotAtomic
,
1390 SyncScope::System
, InsertBefore
) {}
1392 StoreInst::StoreInst(Value
*val
, Value
*addr
, bool isVolatile
, unsigned Align
,
1393 BasicBlock
*InsertAtEnd
)
1394 : StoreInst(val
, addr
, isVolatile
, Align
, AtomicOrdering::NotAtomic
,
1395 SyncScope::System
, InsertAtEnd
) {}
1397 StoreInst::StoreInst(Value
*val
, Value
*addr
, bool isVolatile
,
1398 unsigned Align
, AtomicOrdering Order
,
1400 Instruction
*InsertBefore
)
1401 : Instruction(Type::getVoidTy(val
->getContext()), Store
,
1402 OperandTraits
<StoreInst
>::op_begin(this),
1403 OperandTraits
<StoreInst
>::operands(this),
1407 setVolatile(isVolatile
);
1408 setAlignment(Align
);
1409 setAtomic(Order
, SSID
);
1413 StoreInst::StoreInst(Value
*val
, Value
*addr
, bool isVolatile
,
1414 unsigned Align
, AtomicOrdering Order
,
1416 BasicBlock
*InsertAtEnd
)
1417 : Instruction(Type::getVoidTy(val
->getContext()), Store
,
1418 OperandTraits
<StoreInst
>::op_begin(this),
1419 OperandTraits
<StoreInst
>::operands(this),
1423 setVolatile(isVolatile
);
1424 setAlignment(Align
);
1425 setAtomic(Order
, SSID
);
1429 void StoreInst::setAlignment(unsigned Align
) {
1430 setAlignment(llvm::MaybeAlign(Align
));
1433 void StoreInst::setAlignment(MaybeAlign Align
) {
1434 assert((!Align
|| *Align
<= MaximumAlignment
) &&
1435 "Alignment is greater than MaximumAlignment!");
1436 setInstructionSubclassData((getSubclassDataFromInstruction() & ~(31 << 1)) |
1437 (encode(Align
) << 1));
1439 assert(getAlignment() == Align
->value() &&
1440 "Alignment representation error!");
1442 assert(getAlignment() == 0 && "Alignment representation error!");
1445 //===----------------------------------------------------------------------===//
1446 // AtomicCmpXchgInst Implementation
1447 //===----------------------------------------------------------------------===//
1449 void AtomicCmpXchgInst::Init(Value
*Ptr
, Value
*Cmp
, Value
*NewVal
,
1450 AtomicOrdering SuccessOrdering
,
1451 AtomicOrdering FailureOrdering
,
1452 SyncScope::ID SSID
) {
1456 setSuccessOrdering(SuccessOrdering
);
1457 setFailureOrdering(FailureOrdering
);
1458 setSyncScopeID(SSID
);
1460 assert(getOperand(0) && getOperand(1) && getOperand(2) &&
1461 "All operands must be non-null!");
1462 assert(getOperand(0)->getType()->isPointerTy() &&
1463 "Ptr must have pointer type!");
1464 assert(getOperand(1)->getType() ==
1465 cast
<PointerType
>(getOperand(0)->getType())->getElementType()
1466 && "Ptr must be a pointer to Cmp type!");
1467 assert(getOperand(2)->getType() ==
1468 cast
<PointerType
>(getOperand(0)->getType())->getElementType()
1469 && "Ptr must be a pointer to NewVal type!");
1470 assert(SuccessOrdering
!= AtomicOrdering::NotAtomic
&&
1471 "AtomicCmpXchg instructions must be atomic!");
1472 assert(FailureOrdering
!= AtomicOrdering::NotAtomic
&&
1473 "AtomicCmpXchg instructions must be atomic!");
1474 assert(!isStrongerThan(FailureOrdering
, SuccessOrdering
) &&
1475 "AtomicCmpXchg failure argument shall be no stronger than the success "
1477 assert(FailureOrdering
!= AtomicOrdering::Release
&&
1478 FailureOrdering
!= AtomicOrdering::AcquireRelease
&&
1479 "AtomicCmpXchg failure ordering cannot include release semantics");
1482 AtomicCmpXchgInst::AtomicCmpXchgInst(Value
*Ptr
, Value
*Cmp
, Value
*NewVal
,
1483 AtomicOrdering SuccessOrdering
,
1484 AtomicOrdering FailureOrdering
,
1486 Instruction
*InsertBefore
)
1488 StructType::get(Cmp
->getType(), Type::getInt1Ty(Cmp
->getContext())),
1489 AtomicCmpXchg
, OperandTraits
<AtomicCmpXchgInst
>::op_begin(this),
1490 OperandTraits
<AtomicCmpXchgInst
>::operands(this), InsertBefore
) {
1491 Init(Ptr
, Cmp
, NewVal
, SuccessOrdering
, FailureOrdering
, SSID
);
1494 AtomicCmpXchgInst::AtomicCmpXchgInst(Value
*Ptr
, Value
*Cmp
, Value
*NewVal
,
1495 AtomicOrdering SuccessOrdering
,
1496 AtomicOrdering FailureOrdering
,
1498 BasicBlock
*InsertAtEnd
)
1500 StructType::get(Cmp
->getType(), Type::getInt1Ty(Cmp
->getContext())),
1501 AtomicCmpXchg
, OperandTraits
<AtomicCmpXchgInst
>::op_begin(this),
1502 OperandTraits
<AtomicCmpXchgInst
>::operands(this), InsertAtEnd
) {
1503 Init(Ptr
, Cmp
, NewVal
, SuccessOrdering
, FailureOrdering
, SSID
);
1506 //===----------------------------------------------------------------------===//
1507 // AtomicRMWInst Implementation
1508 //===----------------------------------------------------------------------===//
1510 void AtomicRMWInst::Init(BinOp Operation
, Value
*Ptr
, Value
*Val
,
1511 AtomicOrdering Ordering
,
1512 SyncScope::ID SSID
) {
1515 setOperation(Operation
);
1516 setOrdering(Ordering
);
1517 setSyncScopeID(SSID
);
1519 assert(getOperand(0) && getOperand(1) &&
1520 "All operands must be non-null!");
1521 assert(getOperand(0)->getType()->isPointerTy() &&
1522 "Ptr must have pointer type!");
1523 assert(getOperand(1)->getType() ==
1524 cast
<PointerType
>(getOperand(0)->getType())->getElementType()
1525 && "Ptr must be a pointer to Val type!");
1526 assert(Ordering
!= AtomicOrdering::NotAtomic
&&
1527 "AtomicRMW instructions must be atomic!");
1530 AtomicRMWInst::AtomicRMWInst(BinOp Operation
, Value
*Ptr
, Value
*Val
,
1531 AtomicOrdering Ordering
,
1533 Instruction
*InsertBefore
)
1534 : Instruction(Val
->getType(), AtomicRMW
,
1535 OperandTraits
<AtomicRMWInst
>::op_begin(this),
1536 OperandTraits
<AtomicRMWInst
>::operands(this),
1538 Init(Operation
, Ptr
, Val
, Ordering
, SSID
);
1541 AtomicRMWInst::AtomicRMWInst(BinOp Operation
, Value
*Ptr
, Value
*Val
,
1542 AtomicOrdering Ordering
,
1544 BasicBlock
*InsertAtEnd
)
1545 : Instruction(Val
->getType(), AtomicRMW
,
1546 OperandTraits
<AtomicRMWInst
>::op_begin(this),
1547 OperandTraits
<AtomicRMWInst
>::operands(this),
1549 Init(Operation
, Ptr
, Val
, Ordering
, SSID
);
1552 StringRef
AtomicRMWInst::getOperationName(BinOp Op
) {
1554 case AtomicRMWInst::Xchg
:
1556 case AtomicRMWInst::Add
:
1558 case AtomicRMWInst::Sub
:
1560 case AtomicRMWInst::And
:
1562 case AtomicRMWInst::Nand
:
1564 case AtomicRMWInst::Or
:
1566 case AtomicRMWInst::Xor
:
1568 case AtomicRMWInst::Max
:
1570 case AtomicRMWInst::Min
:
1572 case AtomicRMWInst::UMax
:
1574 case AtomicRMWInst::UMin
:
1576 case AtomicRMWInst::FAdd
:
1578 case AtomicRMWInst::FSub
:
1580 case AtomicRMWInst::BAD_BINOP
:
1581 return "<invalid operation>";
1584 llvm_unreachable("invalid atomicrmw operation");
1587 //===----------------------------------------------------------------------===//
1588 // FenceInst Implementation
1589 //===----------------------------------------------------------------------===//
1591 FenceInst::FenceInst(LLVMContext
&C
, AtomicOrdering Ordering
,
1593 Instruction
*InsertBefore
)
1594 : Instruction(Type::getVoidTy(C
), Fence
, nullptr, 0, InsertBefore
) {
1595 setOrdering(Ordering
);
1596 setSyncScopeID(SSID
);
1599 FenceInst::FenceInst(LLVMContext
&C
, AtomicOrdering Ordering
,
1601 BasicBlock
*InsertAtEnd
)
1602 : Instruction(Type::getVoidTy(C
), Fence
, nullptr, 0, InsertAtEnd
) {
1603 setOrdering(Ordering
);
1604 setSyncScopeID(SSID
);
1607 //===----------------------------------------------------------------------===//
1608 // GetElementPtrInst Implementation
1609 //===----------------------------------------------------------------------===//
1611 void GetElementPtrInst::init(Value
*Ptr
, ArrayRef
<Value
*> IdxList
,
1612 const Twine
&Name
) {
1613 assert(getNumOperands() == 1 + IdxList
.size() &&
1614 "NumOperands not initialized?");
1616 llvm::copy(IdxList
, op_begin() + 1);
1620 GetElementPtrInst::GetElementPtrInst(const GetElementPtrInst
&GEPI
)
1621 : Instruction(GEPI
.getType(), GetElementPtr
,
1622 OperandTraits
<GetElementPtrInst
>::op_end(this) -
1623 GEPI
.getNumOperands(),
1624 GEPI
.getNumOperands()),
1625 SourceElementType(GEPI
.SourceElementType
),
1626 ResultElementType(GEPI
.ResultElementType
) {
1627 std::copy(GEPI
.op_begin(), GEPI
.op_end(), op_begin());
1628 SubclassOptionalData
= GEPI
.SubclassOptionalData
;
1631 /// getIndexedType - Returns the type of the element that would be accessed with
1632 /// a gep instruction with the specified parameters.
1634 /// The Idxs pointer should point to a continuous piece of memory containing the
1635 /// indices, either as Value* or uint64_t.
1637 /// A null type is returned if the indices are invalid for the specified
1640 template <typename IndexTy
>
1641 static Type
*getIndexedTypeInternal(Type
*Agg
, ArrayRef
<IndexTy
> IdxList
) {
1642 // Handle the special case of the empty set index set, which is always valid.
1643 if (IdxList
.empty())
1646 // If there is at least one index, the top level type must be sized, otherwise
1647 // it cannot be 'stepped over'.
1648 if (!Agg
->isSized())
1651 unsigned CurIdx
= 1;
1652 for (; CurIdx
!= IdxList
.size(); ++CurIdx
) {
1653 CompositeType
*CT
= dyn_cast
<CompositeType
>(Agg
);
1654 if (!CT
|| CT
->isPointerTy()) return nullptr;
1655 IndexTy Index
= IdxList
[CurIdx
];
1656 if (!CT
->indexValid(Index
)) return nullptr;
1657 Agg
= CT
->getTypeAtIndex(Index
);
1659 return CurIdx
== IdxList
.size() ? Agg
: nullptr;
1662 Type
*GetElementPtrInst::getIndexedType(Type
*Ty
, ArrayRef
<Value
*> IdxList
) {
1663 return getIndexedTypeInternal(Ty
, IdxList
);
1666 Type
*GetElementPtrInst::getIndexedType(Type
*Ty
,
1667 ArrayRef
<Constant
*> IdxList
) {
1668 return getIndexedTypeInternal(Ty
, IdxList
);
1671 Type
*GetElementPtrInst::getIndexedType(Type
*Ty
, ArrayRef
<uint64_t> IdxList
) {
1672 return getIndexedTypeInternal(Ty
, IdxList
);
1675 /// hasAllZeroIndices - Return true if all of the indices of this GEP are
1676 /// zeros. If so, the result pointer and the first operand have the same
1677 /// value, just potentially different types.
1678 bool GetElementPtrInst::hasAllZeroIndices() const {
1679 for (unsigned i
= 1, e
= getNumOperands(); i
!= e
; ++i
) {
1680 if (ConstantInt
*CI
= dyn_cast
<ConstantInt
>(getOperand(i
))) {
1681 if (!CI
->isZero()) return false;
1689 /// hasAllConstantIndices - Return true if all of the indices of this GEP are
1690 /// constant integers. If so, the result pointer and the first operand have
1691 /// a constant offset between them.
1692 bool GetElementPtrInst::hasAllConstantIndices() const {
1693 for (unsigned i
= 1, e
= getNumOperands(); i
!= e
; ++i
) {
1694 if (!isa
<ConstantInt
>(getOperand(i
)))
1700 void GetElementPtrInst::setIsInBounds(bool B
) {
1701 cast
<GEPOperator
>(this)->setIsInBounds(B
);
1704 bool GetElementPtrInst::isInBounds() const {
1705 return cast
<GEPOperator
>(this)->isInBounds();
1708 bool GetElementPtrInst::accumulateConstantOffset(const DataLayout
&DL
,
1709 APInt
&Offset
) const {
1710 // Delegate to the generic GEPOperator implementation.
1711 return cast
<GEPOperator
>(this)->accumulateConstantOffset(DL
, Offset
);
1714 //===----------------------------------------------------------------------===//
1715 // ExtractElementInst Implementation
1716 //===----------------------------------------------------------------------===//
1718 ExtractElementInst::ExtractElementInst(Value
*Val
, Value
*Index
,
1720 Instruction
*InsertBef
)
1721 : Instruction(cast
<VectorType
>(Val
->getType())->getElementType(),
1723 OperandTraits
<ExtractElementInst
>::op_begin(this),
1725 assert(isValidOperands(Val
, Index
) &&
1726 "Invalid extractelement instruction operands!");
1732 ExtractElementInst::ExtractElementInst(Value
*Val
, Value
*Index
,
1734 BasicBlock
*InsertAE
)
1735 : Instruction(cast
<VectorType
>(Val
->getType())->getElementType(),
1737 OperandTraits
<ExtractElementInst
>::op_begin(this),
1739 assert(isValidOperands(Val
, Index
) &&
1740 "Invalid extractelement instruction operands!");
1747 bool ExtractElementInst::isValidOperands(const Value
*Val
, const Value
*Index
) {
1748 if (!Val
->getType()->isVectorTy() || !Index
->getType()->isIntegerTy())
1753 //===----------------------------------------------------------------------===//
1754 // InsertElementInst Implementation
1755 //===----------------------------------------------------------------------===//
1757 InsertElementInst::InsertElementInst(Value
*Vec
, Value
*Elt
, Value
*Index
,
1759 Instruction
*InsertBef
)
1760 : Instruction(Vec
->getType(), InsertElement
,
1761 OperandTraits
<InsertElementInst
>::op_begin(this),
1763 assert(isValidOperands(Vec
, Elt
, Index
) &&
1764 "Invalid insertelement instruction operands!");
1771 InsertElementInst::InsertElementInst(Value
*Vec
, Value
*Elt
, Value
*Index
,
1773 BasicBlock
*InsertAE
)
1774 : Instruction(Vec
->getType(), InsertElement
,
1775 OperandTraits
<InsertElementInst
>::op_begin(this),
1777 assert(isValidOperands(Vec
, Elt
, Index
) &&
1778 "Invalid insertelement instruction operands!");
1786 bool InsertElementInst::isValidOperands(const Value
*Vec
, const Value
*Elt
,
1787 const Value
*Index
) {
1788 if (!Vec
->getType()->isVectorTy())
1789 return false; // First operand of insertelement must be vector type.
1791 if (Elt
->getType() != cast
<VectorType
>(Vec
->getType())->getElementType())
1792 return false;// Second operand of insertelement must be vector element type.
1794 if (!Index
->getType()->isIntegerTy())
1795 return false; // Third operand of insertelement must be i32.
1799 //===----------------------------------------------------------------------===//
1800 // ShuffleVectorInst Implementation
1801 //===----------------------------------------------------------------------===//
1803 ShuffleVectorInst::ShuffleVectorInst(Value
*V1
, Value
*V2
, Value
*Mask
,
1805 Instruction
*InsertBefore
)
1806 : Instruction(VectorType::get(cast
<VectorType
>(V1
->getType())->getElementType(),
1807 cast
<VectorType
>(Mask
->getType())->getNumElements()),
1809 OperandTraits
<ShuffleVectorInst
>::op_begin(this),
1810 OperandTraits
<ShuffleVectorInst
>::operands(this),
1812 assert(isValidOperands(V1
, V2
, Mask
) &&
1813 "Invalid shuffle vector instruction operands!");
1820 ShuffleVectorInst::ShuffleVectorInst(Value
*V1
, Value
*V2
, Value
*Mask
,
1822 BasicBlock
*InsertAtEnd
)
1823 : Instruction(VectorType::get(cast
<VectorType
>(V1
->getType())->getElementType(),
1824 cast
<VectorType
>(Mask
->getType())->getNumElements()),
1826 OperandTraits
<ShuffleVectorInst
>::op_begin(this),
1827 OperandTraits
<ShuffleVectorInst
>::operands(this),
1829 assert(isValidOperands(V1
, V2
, Mask
) &&
1830 "Invalid shuffle vector instruction operands!");
1838 void ShuffleVectorInst::commute() {
1839 int NumOpElts
= Op
<0>()->getType()->getVectorNumElements();
1840 int NumMaskElts
= getMask()->getType()->getVectorNumElements();
1841 SmallVector
<Constant
*, 16> NewMask(NumMaskElts
);
1842 Type
*Int32Ty
= Type::getInt32Ty(getContext());
1843 for (int i
= 0; i
!= NumMaskElts
; ++i
) {
1844 int MaskElt
= getMaskValue(i
);
1845 if (MaskElt
== -1) {
1846 NewMask
[i
] = UndefValue::get(Int32Ty
);
1849 assert(MaskElt
>= 0 && MaskElt
< 2 * NumOpElts
&& "Out-of-range mask");
1850 MaskElt
= (MaskElt
< NumOpElts
) ? MaskElt
+ NumOpElts
: MaskElt
- NumOpElts
;
1851 NewMask
[i
] = ConstantInt::get(Int32Ty
, MaskElt
);
1853 Op
<2>() = ConstantVector::get(NewMask
);
1854 Op
<0>().swap(Op
<1>());
1857 bool ShuffleVectorInst::isValidOperands(const Value
*V1
, const Value
*V2
,
1858 const Value
*Mask
) {
1859 // V1 and V2 must be vectors of the same type.
1860 if (!V1
->getType()->isVectorTy() || V1
->getType() != V2
->getType())
1863 // Mask must be vector of i32.
1864 auto *MaskTy
= dyn_cast
<VectorType
>(Mask
->getType());
1865 if (!MaskTy
|| !MaskTy
->getElementType()->isIntegerTy(32))
1868 // Check to see if Mask is valid.
1869 if (isa
<UndefValue
>(Mask
) || isa
<ConstantAggregateZero
>(Mask
))
1872 if (const auto *MV
= dyn_cast
<ConstantVector
>(Mask
)) {
1873 unsigned V1Size
= cast
<VectorType
>(V1
->getType())->getNumElements();
1874 for (Value
*Op
: MV
->operands()) {
1875 if (auto *CI
= dyn_cast
<ConstantInt
>(Op
)) {
1876 if (CI
->uge(V1Size
*2))
1878 } else if (!isa
<UndefValue
>(Op
)) {
1885 if (const auto *CDS
= dyn_cast
<ConstantDataSequential
>(Mask
)) {
1886 unsigned V1Size
= cast
<VectorType
>(V1
->getType())->getNumElements();
1887 for (unsigned i
= 0, e
= MaskTy
->getNumElements(); i
!= e
; ++i
)
1888 if (CDS
->getElementAsInteger(i
) >= V1Size
*2)
1893 // The bitcode reader can create a place holder for a forward reference
1894 // used as the shuffle mask. When this occurs, the shuffle mask will
1895 // fall into this case and fail. To avoid this error, do this bit of
1896 // ugliness to allow such a mask pass.
1897 if (const auto *CE
= dyn_cast
<ConstantExpr
>(Mask
))
1898 if (CE
->getOpcode() == Instruction::UserOp1
)
1904 int ShuffleVectorInst::getMaskValue(const Constant
*Mask
, unsigned i
) {
1905 assert(i
< Mask
->getType()->getVectorNumElements() && "Index out of range");
1906 if (auto *CDS
= dyn_cast
<ConstantDataSequential
>(Mask
))
1907 return CDS
->getElementAsInteger(i
);
1908 Constant
*C
= Mask
->getAggregateElement(i
);
1909 if (isa
<UndefValue
>(C
))
1911 return cast
<ConstantInt
>(C
)->getZExtValue();
1914 void ShuffleVectorInst::getShuffleMask(const Constant
*Mask
,
1915 SmallVectorImpl
<int> &Result
) {
1916 unsigned NumElts
= Mask
->getType()->getVectorNumElements();
1918 if (auto *CDS
= dyn_cast
<ConstantDataSequential
>(Mask
)) {
1919 for (unsigned i
= 0; i
!= NumElts
; ++i
)
1920 Result
.push_back(CDS
->getElementAsInteger(i
));
1923 for (unsigned i
= 0; i
!= NumElts
; ++i
) {
1924 Constant
*C
= Mask
->getAggregateElement(i
);
1925 Result
.push_back(isa
<UndefValue
>(C
) ? -1 :
1926 cast
<ConstantInt
>(C
)->getZExtValue());
1930 static bool isSingleSourceMaskImpl(ArrayRef
<int> Mask
, int NumOpElts
) {
1931 assert(!Mask
.empty() && "Shuffle mask must contain elements");
1932 bool UsesLHS
= false;
1933 bool UsesRHS
= false;
1934 for (int i
= 0, NumMaskElts
= Mask
.size(); i
< NumMaskElts
; ++i
) {
1937 assert(Mask
[i
] >= 0 && Mask
[i
] < (NumOpElts
* 2) &&
1938 "Out-of-bounds shuffle mask element");
1939 UsesLHS
|= (Mask
[i
] < NumOpElts
);
1940 UsesRHS
|= (Mask
[i
] >= NumOpElts
);
1941 if (UsesLHS
&& UsesRHS
)
1944 assert((UsesLHS
^ UsesRHS
) && "Should have selected from exactly 1 source");
1948 bool ShuffleVectorInst::isSingleSourceMask(ArrayRef
<int> Mask
) {
1949 // We don't have vector operand size information, so assume operands are the
1950 // same size as the mask.
1951 return isSingleSourceMaskImpl(Mask
, Mask
.size());
1954 static bool isIdentityMaskImpl(ArrayRef
<int> Mask
, int NumOpElts
) {
1955 if (!isSingleSourceMaskImpl(Mask
, NumOpElts
))
1957 for (int i
= 0, NumMaskElts
= Mask
.size(); i
< NumMaskElts
; ++i
) {
1960 if (Mask
[i
] != i
&& Mask
[i
] != (NumOpElts
+ i
))
1966 bool ShuffleVectorInst::isIdentityMask(ArrayRef
<int> Mask
) {
1967 // We don't have vector operand size information, so assume operands are the
1968 // same size as the mask.
1969 return isIdentityMaskImpl(Mask
, Mask
.size());
1972 bool ShuffleVectorInst::isReverseMask(ArrayRef
<int> Mask
) {
1973 if (!isSingleSourceMask(Mask
))
1975 for (int i
= 0, NumElts
= Mask
.size(); i
< NumElts
; ++i
) {
1978 if (Mask
[i
] != (NumElts
- 1 - i
) && Mask
[i
] != (NumElts
+ NumElts
- 1 - i
))
1984 bool ShuffleVectorInst::isZeroEltSplatMask(ArrayRef
<int> Mask
) {
1985 if (!isSingleSourceMask(Mask
))
1987 for (int i
= 0, NumElts
= Mask
.size(); i
< NumElts
; ++i
) {
1990 if (Mask
[i
] != 0 && Mask
[i
] != NumElts
)
1996 bool ShuffleVectorInst::isSelectMask(ArrayRef
<int> Mask
) {
1997 // Select is differentiated from identity. It requires using both sources.
1998 if (isSingleSourceMask(Mask
))
2000 for (int i
= 0, NumElts
= Mask
.size(); i
< NumElts
; ++i
) {
2003 if (Mask
[i
] != i
&& Mask
[i
] != (NumElts
+ i
))
2009 bool ShuffleVectorInst::isTransposeMask(ArrayRef
<int> Mask
) {
2010 // Example masks that will return true:
2011 // v1 = <a, b, c, d>
2012 // v2 = <e, f, g, h>
2013 // trn1 = shufflevector v1, v2 <0, 4, 2, 6> = <a, e, c, g>
2014 // trn2 = shufflevector v1, v2 <1, 5, 3, 7> = <b, f, d, h>
2016 // 1. The number of elements in the mask must be a power-of-2 and at least 2.
2017 int NumElts
= Mask
.size();
2018 if (NumElts
< 2 || !isPowerOf2_32(NumElts
))
2021 // 2. The first element of the mask must be either a 0 or a 1.
2022 if (Mask
[0] != 0 && Mask
[0] != 1)
2025 // 3. The difference between the first 2 elements must be equal to the
2026 // number of elements in the mask.
2027 if ((Mask
[1] - Mask
[0]) != NumElts
)
2030 // 4. The difference between consecutive even-numbered and odd-numbered
2031 // elements must be equal to 2.
2032 for (int i
= 2; i
< NumElts
; ++i
) {
2033 int MaskEltVal
= Mask
[i
];
2034 if (MaskEltVal
== -1)
2036 int MaskEltPrevVal
= Mask
[i
- 2];
2037 if (MaskEltVal
- MaskEltPrevVal
!= 2)
2043 bool ShuffleVectorInst::isExtractSubvectorMask(ArrayRef
<int> Mask
,
2044 int NumSrcElts
, int &Index
) {
2045 // Must extract from a single source.
2046 if (!isSingleSourceMaskImpl(Mask
, NumSrcElts
))
2049 // Must be smaller (else this is an Identity shuffle).
2050 if (NumSrcElts
<= (int)Mask
.size())
2053 // Find start of extraction, accounting that we may start with an UNDEF.
2055 for (int i
= 0, e
= Mask
.size(); i
!= e
; ++i
) {
2059 int Offset
= (M
% NumSrcElts
) - i
;
2060 if (0 <= SubIndex
&& SubIndex
!= Offset
)
2065 if (0 <= SubIndex
) {
2072 bool ShuffleVectorInst::isIdentityWithPadding() const {
2073 int NumOpElts
= Op
<0>()->getType()->getVectorNumElements();
2074 int NumMaskElts
= getType()->getVectorNumElements();
2075 if (NumMaskElts
<= NumOpElts
)
2078 // The first part of the mask must choose elements from exactly 1 source op.
2079 SmallVector
<int, 16> Mask
= getShuffleMask();
2080 if (!isIdentityMaskImpl(Mask
, NumOpElts
))
2083 // All extending must be with undef elements.
2084 for (int i
= NumOpElts
; i
< NumMaskElts
; ++i
)
2091 bool ShuffleVectorInst::isIdentityWithExtract() const {
2092 int NumOpElts
= Op
<0>()->getType()->getVectorNumElements();
2093 int NumMaskElts
= getType()->getVectorNumElements();
2094 if (NumMaskElts
>= NumOpElts
)
2097 return isIdentityMaskImpl(getShuffleMask(), NumOpElts
);
2100 bool ShuffleVectorInst::isConcat() const {
2101 // Vector concatenation is differentiated from identity with padding.
2102 if (isa
<UndefValue
>(Op
<0>()) || isa
<UndefValue
>(Op
<1>()))
2105 int NumOpElts
= Op
<0>()->getType()->getVectorNumElements();
2106 int NumMaskElts
= getType()->getVectorNumElements();
2107 if (NumMaskElts
!= NumOpElts
* 2)
2110 // Use the mask length rather than the operands' vector lengths here. We
2111 // already know that the shuffle returns a vector twice as long as the inputs,
2112 // and neither of the inputs are undef vectors. If the mask picks consecutive
2113 // elements from both inputs, then this is a concatenation of the inputs.
2114 return isIdentityMaskImpl(getShuffleMask(), NumMaskElts
);
2117 //===----------------------------------------------------------------------===//
2118 // InsertValueInst Class
2119 //===----------------------------------------------------------------------===//
2121 void InsertValueInst::init(Value
*Agg
, Value
*Val
, ArrayRef
<unsigned> Idxs
,
2122 const Twine
&Name
) {
2123 assert(getNumOperands() == 2 && "NumOperands not initialized?");
2125 // There's no fundamental reason why we require at least one index
2126 // (other than weirdness with &*IdxBegin being invalid; see
2127 // getelementptr's init routine for example). But there's no
2128 // present need to support it.
2129 assert(!Idxs
.empty() && "InsertValueInst must have at least one index");
2131 assert(ExtractValueInst::getIndexedType(Agg
->getType(), Idxs
) ==
2132 Val
->getType() && "Inserted value must match indexed type!");
2136 Indices
.append(Idxs
.begin(), Idxs
.end());
2140 InsertValueInst::InsertValueInst(const InsertValueInst
&IVI
)
2141 : Instruction(IVI
.getType(), InsertValue
,
2142 OperandTraits
<InsertValueInst
>::op_begin(this), 2),
2143 Indices(IVI
.Indices
) {
2144 Op
<0>() = IVI
.getOperand(0);
2145 Op
<1>() = IVI
.getOperand(1);
2146 SubclassOptionalData
= IVI
.SubclassOptionalData
;
2149 //===----------------------------------------------------------------------===//
2150 // ExtractValueInst Class
2151 //===----------------------------------------------------------------------===//
2153 void ExtractValueInst::init(ArrayRef
<unsigned> Idxs
, const Twine
&Name
) {
2154 assert(getNumOperands() == 1 && "NumOperands not initialized?");
2156 // There's no fundamental reason why we require at least one index.
2157 // But there's no present need to support it.
2158 assert(!Idxs
.empty() && "ExtractValueInst must have at least one index");
2160 Indices
.append(Idxs
.begin(), Idxs
.end());
2164 ExtractValueInst::ExtractValueInst(const ExtractValueInst
&EVI
)
2165 : UnaryInstruction(EVI
.getType(), ExtractValue
, EVI
.getOperand(0)),
2166 Indices(EVI
.Indices
) {
2167 SubclassOptionalData
= EVI
.SubclassOptionalData
;
2170 // getIndexedType - Returns the type of the element that would be extracted
2171 // with an extractvalue instruction with the specified parameters.
2173 // A null type is returned if the indices are invalid for the specified
2176 Type
*ExtractValueInst::getIndexedType(Type
*Agg
,
2177 ArrayRef
<unsigned> Idxs
) {
2178 for (unsigned Index
: Idxs
) {
2179 // We can't use CompositeType::indexValid(Index) here.
2180 // indexValid() always returns true for arrays because getelementptr allows
2181 // out-of-bounds indices. Since we don't allow those for extractvalue and
2182 // insertvalue we need to check array indexing manually.
2183 // Since the only other types we can index into are struct types it's just
2184 // as easy to check those manually as well.
2185 if (ArrayType
*AT
= dyn_cast
<ArrayType
>(Agg
)) {
2186 if (Index
>= AT
->getNumElements())
2188 } else if (StructType
*ST
= dyn_cast
<StructType
>(Agg
)) {
2189 if (Index
>= ST
->getNumElements())
2192 // Not a valid type to index into.
2196 Agg
= cast
<CompositeType
>(Agg
)->getTypeAtIndex(Index
);
2198 return const_cast<Type
*>(Agg
);
2201 //===----------------------------------------------------------------------===//
2202 // UnaryOperator Class
2203 //===----------------------------------------------------------------------===//
2205 UnaryOperator::UnaryOperator(UnaryOps iType
, Value
*S
,
2206 Type
*Ty
, const Twine
&Name
,
2207 Instruction
*InsertBefore
)
2208 : UnaryInstruction(Ty
, iType
, S
, InsertBefore
) {
2214 UnaryOperator::UnaryOperator(UnaryOps iType
, Value
*S
,
2215 Type
*Ty
, const Twine
&Name
,
2216 BasicBlock
*InsertAtEnd
)
2217 : UnaryInstruction(Ty
, iType
, S
, InsertAtEnd
) {
2223 UnaryOperator
*UnaryOperator::Create(UnaryOps Op
, Value
*S
,
2225 Instruction
*InsertBefore
) {
2226 return new UnaryOperator(Op
, S
, S
->getType(), Name
, InsertBefore
);
2229 UnaryOperator
*UnaryOperator::Create(UnaryOps Op
, Value
*S
,
2231 BasicBlock
*InsertAtEnd
) {
2232 UnaryOperator
*Res
= Create(Op
, S
, Name
);
2233 InsertAtEnd
->getInstList().push_back(Res
);
2237 void UnaryOperator::AssertOK() {
2238 Value
*LHS
= getOperand(0);
2239 (void)LHS
; // Silence warnings.
2241 switch (getOpcode()) {
2243 assert(getType() == LHS
->getType() &&
2244 "Unary operation should return same type as operand!");
2245 assert(getType()->isFPOrFPVectorTy() &&
2246 "Tried to create a floating-point operation on a "
2247 "non-floating-point type!");
2249 default: llvm_unreachable("Invalid opcode provided");
2254 //===----------------------------------------------------------------------===//
2255 // BinaryOperator Class
2256 //===----------------------------------------------------------------------===//
2258 BinaryOperator::BinaryOperator(BinaryOps iType
, Value
*S1
, Value
*S2
,
2259 Type
*Ty
, const Twine
&Name
,
2260 Instruction
*InsertBefore
)
2261 : Instruction(Ty
, iType
,
2262 OperandTraits
<BinaryOperator
>::op_begin(this),
2263 OperandTraits
<BinaryOperator
>::operands(this),
2271 BinaryOperator::BinaryOperator(BinaryOps iType
, Value
*S1
, Value
*S2
,
2272 Type
*Ty
, const Twine
&Name
,
2273 BasicBlock
*InsertAtEnd
)
2274 : Instruction(Ty
, iType
,
2275 OperandTraits
<BinaryOperator
>::op_begin(this),
2276 OperandTraits
<BinaryOperator
>::operands(this),
2284 void BinaryOperator::AssertOK() {
2285 Value
*LHS
= getOperand(0), *RHS
= getOperand(1);
2286 (void)LHS
; (void)RHS
; // Silence warnings.
2287 assert(LHS
->getType() == RHS
->getType() &&
2288 "Binary operator operand types must match!");
2290 switch (getOpcode()) {
2293 assert(getType() == LHS
->getType() &&
2294 "Arithmetic operation should return same type as operands!");
2295 assert(getType()->isIntOrIntVectorTy() &&
2296 "Tried to create an integer operation on a non-integer type!");
2298 case FAdd
: case FSub
:
2300 assert(getType() == LHS
->getType() &&
2301 "Arithmetic operation should return same type as operands!");
2302 assert(getType()->isFPOrFPVectorTy() &&
2303 "Tried to create a floating-point operation on a "
2304 "non-floating-point type!");
2308 assert(getType() == LHS
->getType() &&
2309 "Arithmetic operation should return same type as operands!");
2310 assert(getType()->isIntOrIntVectorTy() &&
2311 "Incorrect operand type (not integer) for S/UDIV");
2314 assert(getType() == LHS
->getType() &&
2315 "Arithmetic operation should return same type as operands!");
2316 assert(getType()->isFPOrFPVectorTy() &&
2317 "Incorrect operand type (not floating point) for FDIV");
2321 assert(getType() == LHS
->getType() &&
2322 "Arithmetic operation should return same type as operands!");
2323 assert(getType()->isIntOrIntVectorTy() &&
2324 "Incorrect operand type (not integer) for S/UREM");
2327 assert(getType() == LHS
->getType() &&
2328 "Arithmetic operation should return same type as operands!");
2329 assert(getType()->isFPOrFPVectorTy() &&
2330 "Incorrect operand type (not floating point) for FREM");
2335 assert(getType() == LHS
->getType() &&
2336 "Shift operation should return same type as operands!");
2337 assert(getType()->isIntOrIntVectorTy() &&
2338 "Tried to create a shift operation on a non-integral type!");
2342 assert(getType() == LHS
->getType() &&
2343 "Logical operation should return same type as operands!");
2344 assert(getType()->isIntOrIntVectorTy() &&
2345 "Tried to create a logical operation on a non-integral type!");
2347 default: llvm_unreachable("Invalid opcode provided");
2352 BinaryOperator
*BinaryOperator::Create(BinaryOps Op
, Value
*S1
, Value
*S2
,
2354 Instruction
*InsertBefore
) {
2355 assert(S1
->getType() == S2
->getType() &&
2356 "Cannot create binary operator with two operands of differing type!");
2357 return new BinaryOperator(Op
, S1
, S2
, S1
->getType(), Name
, InsertBefore
);
2360 BinaryOperator
*BinaryOperator::Create(BinaryOps Op
, Value
*S1
, Value
*S2
,
2362 BasicBlock
*InsertAtEnd
) {
2363 BinaryOperator
*Res
= Create(Op
, S1
, S2
, Name
);
2364 InsertAtEnd
->getInstList().push_back(Res
);
2368 BinaryOperator
*BinaryOperator::CreateNeg(Value
*Op
, const Twine
&Name
,
2369 Instruction
*InsertBefore
) {
2370 Value
*zero
= ConstantFP::getZeroValueForNegation(Op
->getType());
2371 return new BinaryOperator(Instruction::Sub
,
2373 Op
->getType(), Name
, InsertBefore
);
2376 BinaryOperator
*BinaryOperator::CreateNeg(Value
*Op
, const Twine
&Name
,
2377 BasicBlock
*InsertAtEnd
) {
2378 Value
*zero
= ConstantFP::getZeroValueForNegation(Op
->getType());
2379 return new BinaryOperator(Instruction::Sub
,
2381 Op
->getType(), Name
, InsertAtEnd
);
2384 BinaryOperator
*BinaryOperator::CreateNSWNeg(Value
*Op
, const Twine
&Name
,
2385 Instruction
*InsertBefore
) {
2386 Value
*zero
= ConstantFP::getZeroValueForNegation(Op
->getType());
2387 return BinaryOperator::CreateNSWSub(zero
, Op
, Name
, InsertBefore
);
2390 BinaryOperator
*BinaryOperator::CreateNSWNeg(Value
*Op
, const Twine
&Name
,
2391 BasicBlock
*InsertAtEnd
) {
2392 Value
*zero
= ConstantFP::getZeroValueForNegation(Op
->getType());
2393 return BinaryOperator::CreateNSWSub(zero
, Op
, Name
, InsertAtEnd
);
2396 BinaryOperator
*BinaryOperator::CreateNUWNeg(Value
*Op
, const Twine
&Name
,
2397 Instruction
*InsertBefore
) {
2398 Value
*zero
= ConstantFP::getZeroValueForNegation(Op
->getType());
2399 return BinaryOperator::CreateNUWSub(zero
, Op
, Name
, InsertBefore
);
2402 BinaryOperator
*BinaryOperator::CreateNUWNeg(Value
*Op
, const Twine
&Name
,
2403 BasicBlock
*InsertAtEnd
) {
2404 Value
*zero
= ConstantFP::getZeroValueForNegation(Op
->getType());
2405 return BinaryOperator::CreateNUWSub(zero
, Op
, Name
, InsertAtEnd
);
2408 BinaryOperator
*BinaryOperator::CreateFNeg(Value
*Op
, const Twine
&Name
,
2409 Instruction
*InsertBefore
) {
2410 Value
*zero
= ConstantFP::getZeroValueForNegation(Op
->getType());
2411 return new BinaryOperator(Instruction::FSub
, zero
, Op
,
2412 Op
->getType(), Name
, InsertBefore
);
2415 BinaryOperator
*BinaryOperator::CreateFNeg(Value
*Op
, const Twine
&Name
,
2416 BasicBlock
*InsertAtEnd
) {
2417 Value
*zero
= ConstantFP::getZeroValueForNegation(Op
->getType());
2418 return new BinaryOperator(Instruction::FSub
, zero
, Op
,
2419 Op
->getType(), Name
, InsertAtEnd
);
2422 BinaryOperator
*BinaryOperator::CreateNot(Value
*Op
, const Twine
&Name
,
2423 Instruction
*InsertBefore
) {
2424 Constant
*C
= Constant::getAllOnesValue(Op
->getType());
2425 return new BinaryOperator(Instruction::Xor
, Op
, C
,
2426 Op
->getType(), Name
, InsertBefore
);
2429 BinaryOperator
*BinaryOperator::CreateNot(Value
*Op
, const Twine
&Name
,
2430 BasicBlock
*InsertAtEnd
) {
2431 Constant
*AllOnes
= Constant::getAllOnesValue(Op
->getType());
2432 return new BinaryOperator(Instruction::Xor
, Op
, AllOnes
,
2433 Op
->getType(), Name
, InsertAtEnd
);
2436 // Exchange the two operands to this instruction. This instruction is safe to
2437 // use on any binary instruction and does not modify the semantics of the
2438 // instruction. If the instruction is order-dependent (SetLT f.e.), the opcode
2440 bool BinaryOperator::swapOperands() {
2441 if (!isCommutative())
2442 return true; // Can't commute operands
2443 Op
<0>().swap(Op
<1>());
2447 //===----------------------------------------------------------------------===//
2448 // FPMathOperator Class
2449 //===----------------------------------------------------------------------===//
2451 float FPMathOperator::getFPAccuracy() const {
2453 cast
<Instruction
>(this)->getMetadata(LLVMContext::MD_fpmath
);
2456 ConstantFP
*Accuracy
= mdconst::extract
<ConstantFP
>(MD
->getOperand(0));
2457 return Accuracy
->getValueAPF().convertToFloat();
2460 //===----------------------------------------------------------------------===//
2462 //===----------------------------------------------------------------------===//
2464 // Just determine if this cast only deals with integral->integral conversion.
2465 bool CastInst::isIntegerCast() const {
2466 switch (getOpcode()) {
2467 default: return false;
2468 case Instruction::ZExt
:
2469 case Instruction::SExt
:
2470 case Instruction::Trunc
:
2472 case Instruction::BitCast
:
2473 return getOperand(0)->getType()->isIntegerTy() &&
2474 getType()->isIntegerTy();
2478 bool CastInst::isLosslessCast() const {
2479 // Only BitCast can be lossless, exit fast if we're not BitCast
2480 if (getOpcode() != Instruction::BitCast
)
2483 // Identity cast is always lossless
2484 Type
*SrcTy
= getOperand(0)->getType();
2485 Type
*DstTy
= getType();
2489 // Pointer to pointer is always lossless.
2490 if (SrcTy
->isPointerTy())
2491 return DstTy
->isPointerTy();
2492 return false; // Other types have no identity values
2495 /// This function determines if the CastInst does not require any bits to be
2496 /// changed in order to effect the cast. Essentially, it identifies cases where
2497 /// no code gen is necessary for the cast, hence the name no-op cast. For
2498 /// example, the following are all no-op casts:
2499 /// # bitcast i32* %x to i8*
2500 /// # bitcast <2 x i32> %x to <4 x i16>
2501 /// # ptrtoint i32* %x to i32 ; on 32-bit plaforms only
2502 /// Determine if the described cast is a no-op.
2503 bool CastInst::isNoopCast(Instruction::CastOps Opcode
,
2506 const DataLayout
&DL
) {
2508 default: llvm_unreachable("Invalid CastOp");
2509 case Instruction::Trunc
:
2510 case Instruction::ZExt
:
2511 case Instruction::SExt
:
2512 case Instruction::FPTrunc
:
2513 case Instruction::FPExt
:
2514 case Instruction::UIToFP
:
2515 case Instruction::SIToFP
:
2516 case Instruction::FPToUI
:
2517 case Instruction::FPToSI
:
2518 case Instruction::AddrSpaceCast
:
2519 // TODO: Target informations may give a more accurate answer here.
2521 case Instruction::BitCast
:
2522 return true; // BitCast never modifies bits.
2523 case Instruction::PtrToInt
:
2524 return DL
.getIntPtrType(SrcTy
)->getScalarSizeInBits() ==
2525 DestTy
->getScalarSizeInBits();
2526 case Instruction::IntToPtr
:
2527 return DL
.getIntPtrType(DestTy
)->getScalarSizeInBits() ==
2528 SrcTy
->getScalarSizeInBits();
2532 bool CastInst::isNoopCast(const DataLayout
&DL
) const {
2533 return isNoopCast(getOpcode(), getOperand(0)->getType(), getType(), DL
);
2536 /// This function determines if a pair of casts can be eliminated and what
2537 /// opcode should be used in the elimination. This assumes that there are two
2538 /// instructions like this:
2539 /// * %F = firstOpcode SrcTy %x to MidTy
2540 /// * %S = secondOpcode MidTy %F to DstTy
2541 /// The function returns a resultOpcode so these two casts can be replaced with:
2542 /// * %Replacement = resultOpcode %SrcTy %x to DstTy
2543 /// If no such cast is permitted, the function returns 0.
2544 unsigned CastInst::isEliminableCastPair(
2545 Instruction::CastOps firstOp
, Instruction::CastOps secondOp
,
2546 Type
*SrcTy
, Type
*MidTy
, Type
*DstTy
, Type
*SrcIntPtrTy
, Type
*MidIntPtrTy
,
2547 Type
*DstIntPtrTy
) {
2548 // Define the 144 possibilities for these two cast instructions. The values
2549 // in this matrix determine what to do in a given situation and select the
2550 // case in the switch below. The rows correspond to firstOp, the columns
2551 // correspond to secondOp. In looking at the table below, keep in mind
2552 // the following cast properties:
2554 // Size Compare Source Destination
2555 // Operator Src ? Size Type Sign Type Sign
2556 // -------- ------------ ------------------- ---------------------
2557 // TRUNC > Integer Any Integral Any
2558 // ZEXT < Integral Unsigned Integer Any
2559 // SEXT < Integral Signed Integer Any
2560 // FPTOUI n/a FloatPt n/a Integral Unsigned
2561 // FPTOSI n/a FloatPt n/a Integral Signed
2562 // UITOFP n/a Integral Unsigned FloatPt n/a
2563 // SITOFP n/a Integral Signed FloatPt n/a
2564 // FPTRUNC > FloatPt n/a FloatPt n/a
2565 // FPEXT < FloatPt n/a FloatPt n/a
2566 // PTRTOINT n/a Pointer n/a Integral Unsigned
2567 // INTTOPTR n/a Integral Unsigned Pointer n/a
2568 // BITCAST = FirstClass n/a FirstClass n/a
2569 // ADDRSPCST n/a Pointer n/a Pointer n/a
2571 // NOTE: some transforms are safe, but we consider them to be non-profitable.
2572 // For example, we could merge "fptoui double to i32" + "zext i32 to i64",
2573 // into "fptoui double to i64", but this loses information about the range
2574 // of the produced value (we no longer know the top-part is all zeros).
2575 // Further this conversion is often much more expensive for typical hardware,
2576 // and causes issues when building libgcc. We disallow fptosi+sext for the
2578 const unsigned numCastOps
=
2579 Instruction::CastOpsEnd
- Instruction::CastOpsBegin
;
2580 static const uint8_t CastResults
[numCastOps
][numCastOps
] = {
2581 // T F F U S F F P I B A -+
2582 // R Z S P P I I T P 2 N T S |
2583 // U E E 2 2 2 2 R E I T C C +- secondOp
2584 // N X X U S F F N X N 2 V V |
2585 // C T T I I P P C T T P T T -+
2586 { 1, 0, 0,99,99, 0, 0,99,99,99, 0, 3, 0}, // Trunc -+
2587 { 8, 1, 9,99,99, 2,17,99,99,99, 2, 3, 0}, // ZExt |
2588 { 8, 0, 1,99,99, 0, 2,99,99,99, 0, 3, 0}, // SExt |
2589 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3, 0}, // FPToUI |
2590 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3, 0}, // FPToSI |
2591 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4, 0}, // UIToFP +- firstOp
2592 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4, 0}, // SIToFP |
2593 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4, 0}, // FPTrunc |
2594 { 99,99,99, 2, 2,99,99, 8, 2,99,99, 4, 0}, // FPExt |
2595 { 1, 0, 0,99,99, 0, 0,99,99,99, 7, 3, 0}, // PtrToInt |
2596 { 99,99,99,99,99,99,99,99,99,11,99,15, 0}, // IntToPtr |
2597 { 5, 5, 5, 6, 6, 5, 5, 6, 6,16, 5, 1,14}, // BitCast |
2598 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,13,12}, // AddrSpaceCast -+
2601 // TODO: This logic could be encoded into the table above and handled in the
2603 // If either of the casts are a bitcast from scalar to vector, disallow the
2604 // merging. However, any pair of bitcasts are allowed.
2605 bool IsFirstBitcast
= (firstOp
== Instruction::BitCast
);
2606 bool IsSecondBitcast
= (secondOp
== Instruction::BitCast
);
2607 bool AreBothBitcasts
= IsFirstBitcast
&& IsSecondBitcast
;
2609 // Check if any of the casts convert scalars <-> vectors.
2610 if ((IsFirstBitcast
&& isa
<VectorType
>(SrcTy
) != isa
<VectorType
>(MidTy
)) ||
2611 (IsSecondBitcast
&& isa
<VectorType
>(MidTy
) != isa
<VectorType
>(DstTy
)))
2612 if (!AreBothBitcasts
)
2615 int ElimCase
= CastResults
[firstOp
-Instruction::CastOpsBegin
]
2616 [secondOp
-Instruction::CastOpsBegin
];
2619 // Categorically disallowed.
2622 // Allowed, use first cast's opcode.
2625 // Allowed, use second cast's opcode.
2628 // No-op cast in second op implies firstOp as long as the DestTy
2629 // is integer and we are not converting between a vector and a
2631 if (!SrcTy
->isVectorTy() && DstTy
->isIntegerTy())
2635 // No-op cast in second op implies firstOp as long as the DestTy
2636 // is floating point.
2637 if (DstTy
->isFloatingPointTy())
2641 // No-op cast in first op implies secondOp as long as the SrcTy
2643 if (SrcTy
->isIntegerTy())
2647 // No-op cast in first op implies secondOp as long as the SrcTy
2648 // is a floating point.
2649 if (SrcTy
->isFloatingPointTy())
2653 // Cannot simplify if address spaces are different!
2654 if (SrcTy
->getPointerAddressSpace() != DstTy
->getPointerAddressSpace())
2657 unsigned MidSize
= MidTy
->getScalarSizeInBits();
2658 // We can still fold this without knowing the actual sizes as long we
2659 // know that the intermediate pointer is the largest possible
2661 // FIXME: Is this always true?
2663 return Instruction::BitCast
;
2665 // ptrtoint, inttoptr -> bitcast (ptr -> ptr) if int size is >= ptr size.
2666 if (!SrcIntPtrTy
|| DstIntPtrTy
!= SrcIntPtrTy
)
2668 unsigned PtrSize
= SrcIntPtrTy
->getScalarSizeInBits();
2669 if (MidSize
>= PtrSize
)
2670 return Instruction::BitCast
;
2674 // ext, trunc -> bitcast, if the SrcTy and DstTy are same size
2675 // ext, trunc -> ext, if sizeof(SrcTy) < sizeof(DstTy)
2676 // ext, trunc -> trunc, if sizeof(SrcTy) > sizeof(DstTy)
2677 unsigned SrcSize
= SrcTy
->getScalarSizeInBits();
2678 unsigned DstSize
= DstTy
->getScalarSizeInBits();
2679 if (SrcSize
== DstSize
)
2680 return Instruction::BitCast
;
2681 else if (SrcSize
< DstSize
)
2686 // zext, sext -> zext, because sext can't sign extend after zext
2687 return Instruction::ZExt
;
2689 // inttoptr, ptrtoint -> bitcast if SrcSize<=PtrSize and SrcSize==DstSize
2692 unsigned PtrSize
= MidIntPtrTy
->getScalarSizeInBits();
2693 unsigned SrcSize
= SrcTy
->getScalarSizeInBits();
2694 unsigned DstSize
= DstTy
->getScalarSizeInBits();
2695 if (SrcSize
<= PtrSize
&& SrcSize
== DstSize
)
2696 return Instruction::BitCast
;
2700 // addrspacecast, addrspacecast -> bitcast, if SrcAS == DstAS
2701 // addrspacecast, addrspacecast -> addrspacecast, if SrcAS != DstAS
2702 if (SrcTy
->getPointerAddressSpace() != DstTy
->getPointerAddressSpace())
2703 return Instruction::AddrSpaceCast
;
2704 return Instruction::BitCast
;
2706 // FIXME: this state can be merged with (1), but the following assert
2707 // is useful to check the correcteness of the sequence due to semantic
2708 // change of bitcast.
2710 SrcTy
->isPtrOrPtrVectorTy() &&
2711 MidTy
->isPtrOrPtrVectorTy() &&
2712 DstTy
->isPtrOrPtrVectorTy() &&
2713 SrcTy
->getPointerAddressSpace() != MidTy
->getPointerAddressSpace() &&
2714 MidTy
->getPointerAddressSpace() == DstTy
->getPointerAddressSpace() &&
2715 "Illegal addrspacecast, bitcast sequence!");
2716 // Allowed, use first cast's opcode
2719 // bitcast, addrspacecast -> addrspacecast if the element type of
2720 // bitcast's source is the same as that of addrspacecast's destination.
2721 if (SrcTy
->getScalarType()->getPointerElementType() ==
2722 DstTy
->getScalarType()->getPointerElementType())
2723 return Instruction::AddrSpaceCast
;
2726 // FIXME: this state can be merged with (1), but the following assert
2727 // is useful to check the correcteness of the sequence due to semantic
2728 // change of bitcast.
2730 SrcTy
->isIntOrIntVectorTy() &&
2731 MidTy
->isPtrOrPtrVectorTy() &&
2732 DstTy
->isPtrOrPtrVectorTy() &&
2733 MidTy
->getPointerAddressSpace() == DstTy
->getPointerAddressSpace() &&
2734 "Illegal inttoptr, bitcast sequence!");
2735 // Allowed, use first cast's opcode
2738 // FIXME: this state can be merged with (2), but the following assert
2739 // is useful to check the correcteness of the sequence due to semantic
2740 // change of bitcast.
2742 SrcTy
->isPtrOrPtrVectorTy() &&
2743 MidTy
->isPtrOrPtrVectorTy() &&
2744 DstTy
->isIntOrIntVectorTy() &&
2745 SrcTy
->getPointerAddressSpace() == MidTy
->getPointerAddressSpace() &&
2746 "Illegal bitcast, ptrtoint sequence!");
2747 // Allowed, use second cast's opcode
2750 // (sitofp (zext x)) -> (uitofp x)
2751 return Instruction::UIToFP
;
2753 // Cast combination can't happen (error in input). This is for all cases
2754 // where the MidTy is not the same for the two cast instructions.
2755 llvm_unreachable("Invalid Cast Combination");
2757 llvm_unreachable("Error in CastResults table!!!");
2761 CastInst
*CastInst::Create(Instruction::CastOps op
, Value
*S
, Type
*Ty
,
2762 const Twine
&Name
, Instruction
*InsertBefore
) {
2763 assert(castIsValid(op
, S
, Ty
) && "Invalid cast!");
2764 // Construct and return the appropriate CastInst subclass
2766 case Trunc
: return new TruncInst (S
, Ty
, Name
, InsertBefore
);
2767 case ZExt
: return new ZExtInst (S
, Ty
, Name
, InsertBefore
);
2768 case SExt
: return new SExtInst (S
, Ty
, Name
, InsertBefore
);
2769 case FPTrunc
: return new FPTruncInst (S
, Ty
, Name
, InsertBefore
);
2770 case FPExt
: return new FPExtInst (S
, Ty
, Name
, InsertBefore
);
2771 case UIToFP
: return new UIToFPInst (S
, Ty
, Name
, InsertBefore
);
2772 case SIToFP
: return new SIToFPInst (S
, Ty
, Name
, InsertBefore
);
2773 case FPToUI
: return new FPToUIInst (S
, Ty
, Name
, InsertBefore
);
2774 case FPToSI
: return new FPToSIInst (S
, Ty
, Name
, InsertBefore
);
2775 case PtrToInt
: return new PtrToIntInst (S
, Ty
, Name
, InsertBefore
);
2776 case IntToPtr
: return new IntToPtrInst (S
, Ty
, Name
, InsertBefore
);
2777 case BitCast
: return new BitCastInst (S
, Ty
, Name
, InsertBefore
);
2778 case AddrSpaceCast
: return new AddrSpaceCastInst (S
, Ty
, Name
, InsertBefore
);
2779 default: llvm_unreachable("Invalid opcode provided");
2783 CastInst
*CastInst::Create(Instruction::CastOps op
, Value
*S
, Type
*Ty
,
2784 const Twine
&Name
, BasicBlock
*InsertAtEnd
) {
2785 assert(castIsValid(op
, S
, Ty
) && "Invalid cast!");
2786 // Construct and return the appropriate CastInst subclass
2788 case Trunc
: return new TruncInst (S
, Ty
, Name
, InsertAtEnd
);
2789 case ZExt
: return new ZExtInst (S
, Ty
, Name
, InsertAtEnd
);
2790 case SExt
: return new SExtInst (S
, Ty
, Name
, InsertAtEnd
);
2791 case FPTrunc
: return new FPTruncInst (S
, Ty
, Name
, InsertAtEnd
);
2792 case FPExt
: return new FPExtInst (S
, Ty
, Name
, InsertAtEnd
);
2793 case UIToFP
: return new UIToFPInst (S
, Ty
, Name
, InsertAtEnd
);
2794 case SIToFP
: return new SIToFPInst (S
, Ty
, Name
, InsertAtEnd
);
2795 case FPToUI
: return new FPToUIInst (S
, Ty
, Name
, InsertAtEnd
);
2796 case FPToSI
: return new FPToSIInst (S
, Ty
, Name
, InsertAtEnd
);
2797 case PtrToInt
: return new PtrToIntInst (S
, Ty
, Name
, InsertAtEnd
);
2798 case IntToPtr
: return new IntToPtrInst (S
, Ty
, Name
, InsertAtEnd
);
2799 case BitCast
: return new BitCastInst (S
, Ty
, Name
, InsertAtEnd
);
2800 case AddrSpaceCast
: return new AddrSpaceCastInst (S
, Ty
, Name
, InsertAtEnd
);
2801 default: llvm_unreachable("Invalid opcode provided");
2805 CastInst
*CastInst::CreateZExtOrBitCast(Value
*S
, Type
*Ty
,
2807 Instruction
*InsertBefore
) {
2808 if (S
->getType()->getScalarSizeInBits() == Ty
->getScalarSizeInBits())
2809 return Create(Instruction::BitCast
, S
, Ty
, Name
, InsertBefore
);
2810 return Create(Instruction::ZExt
, S
, Ty
, Name
, InsertBefore
);
2813 CastInst
*CastInst::CreateZExtOrBitCast(Value
*S
, Type
*Ty
,
2815 BasicBlock
*InsertAtEnd
) {
2816 if (S
->getType()->getScalarSizeInBits() == Ty
->getScalarSizeInBits())
2817 return Create(Instruction::BitCast
, S
, Ty
, Name
, InsertAtEnd
);
2818 return Create(Instruction::ZExt
, S
, Ty
, Name
, InsertAtEnd
);
2821 CastInst
*CastInst::CreateSExtOrBitCast(Value
*S
, Type
*Ty
,
2823 Instruction
*InsertBefore
) {
2824 if (S
->getType()->getScalarSizeInBits() == Ty
->getScalarSizeInBits())
2825 return Create(Instruction::BitCast
, S
, Ty
, Name
, InsertBefore
);
2826 return Create(Instruction::SExt
, S
, Ty
, Name
, InsertBefore
);
2829 CastInst
*CastInst::CreateSExtOrBitCast(Value
*S
, Type
*Ty
,
2831 BasicBlock
*InsertAtEnd
) {
2832 if (S
->getType()->getScalarSizeInBits() == Ty
->getScalarSizeInBits())
2833 return Create(Instruction::BitCast
, S
, Ty
, Name
, InsertAtEnd
);
2834 return Create(Instruction::SExt
, S
, Ty
, Name
, InsertAtEnd
);
2837 CastInst
*CastInst::CreateTruncOrBitCast(Value
*S
, Type
*Ty
,
2839 Instruction
*InsertBefore
) {
2840 if (S
->getType()->getScalarSizeInBits() == Ty
->getScalarSizeInBits())
2841 return Create(Instruction::BitCast
, S
, Ty
, Name
, InsertBefore
);
2842 return Create(Instruction::Trunc
, S
, Ty
, Name
, InsertBefore
);
2845 CastInst
*CastInst::CreateTruncOrBitCast(Value
*S
, Type
*Ty
,
2847 BasicBlock
*InsertAtEnd
) {
2848 if (S
->getType()->getScalarSizeInBits() == Ty
->getScalarSizeInBits())
2849 return Create(Instruction::BitCast
, S
, Ty
, Name
, InsertAtEnd
);
2850 return Create(Instruction::Trunc
, S
, Ty
, Name
, InsertAtEnd
);
2853 CastInst
*CastInst::CreatePointerCast(Value
*S
, Type
*Ty
,
2855 BasicBlock
*InsertAtEnd
) {
2856 assert(S
->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
2857 assert((Ty
->isIntOrIntVectorTy() || Ty
->isPtrOrPtrVectorTy()) &&
2859 assert(Ty
->isVectorTy() == S
->getType()->isVectorTy() && "Invalid cast");
2860 assert((!Ty
->isVectorTy() ||
2861 Ty
->getVectorNumElements() == S
->getType()->getVectorNumElements()) &&
2864 if (Ty
->isIntOrIntVectorTy())
2865 return Create(Instruction::PtrToInt
, S
, Ty
, Name
, InsertAtEnd
);
2867 return CreatePointerBitCastOrAddrSpaceCast(S
, Ty
, Name
, InsertAtEnd
);
2870 /// Create a BitCast or a PtrToInt cast instruction
2871 CastInst
*CastInst::CreatePointerCast(Value
*S
, Type
*Ty
,
2873 Instruction
*InsertBefore
) {
2874 assert(S
->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
2875 assert((Ty
->isIntOrIntVectorTy() || Ty
->isPtrOrPtrVectorTy()) &&
2877 assert(Ty
->isVectorTy() == S
->getType()->isVectorTy() && "Invalid cast");
2878 assert((!Ty
->isVectorTy() ||
2879 Ty
->getVectorNumElements() == S
->getType()->getVectorNumElements()) &&
2882 if (Ty
->isIntOrIntVectorTy())
2883 return Create(Instruction::PtrToInt
, S
, Ty
, Name
, InsertBefore
);
2885 return CreatePointerBitCastOrAddrSpaceCast(S
, Ty
, Name
, InsertBefore
);
2888 CastInst
*CastInst::CreatePointerBitCastOrAddrSpaceCast(
2891 BasicBlock
*InsertAtEnd
) {
2892 assert(S
->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
2893 assert(Ty
->isPtrOrPtrVectorTy() && "Invalid cast");
2895 if (S
->getType()->getPointerAddressSpace() != Ty
->getPointerAddressSpace())
2896 return Create(Instruction::AddrSpaceCast
, S
, Ty
, Name
, InsertAtEnd
);
2898 return Create(Instruction::BitCast
, S
, Ty
, Name
, InsertAtEnd
);
2901 CastInst
*CastInst::CreatePointerBitCastOrAddrSpaceCast(
2904 Instruction
*InsertBefore
) {
2905 assert(S
->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
2906 assert(Ty
->isPtrOrPtrVectorTy() && "Invalid cast");
2908 if (S
->getType()->getPointerAddressSpace() != Ty
->getPointerAddressSpace())
2909 return Create(Instruction::AddrSpaceCast
, S
, Ty
, Name
, InsertBefore
);
2911 return Create(Instruction::BitCast
, S
, Ty
, Name
, InsertBefore
);
2914 CastInst
*CastInst::CreateBitOrPointerCast(Value
*S
, Type
*Ty
,
2916 Instruction
*InsertBefore
) {
2917 if (S
->getType()->isPointerTy() && Ty
->isIntegerTy())
2918 return Create(Instruction::PtrToInt
, S
, Ty
, Name
, InsertBefore
);
2919 if (S
->getType()->isIntegerTy() && Ty
->isPointerTy())
2920 return Create(Instruction::IntToPtr
, S
, Ty
, Name
, InsertBefore
);
2922 return Create(Instruction::BitCast
, S
, Ty
, Name
, InsertBefore
);
2925 CastInst
*CastInst::CreateIntegerCast(Value
*C
, Type
*Ty
,
2926 bool isSigned
, const Twine
&Name
,
2927 Instruction
*InsertBefore
) {
2928 assert(C
->getType()->isIntOrIntVectorTy() && Ty
->isIntOrIntVectorTy() &&
2929 "Invalid integer cast");
2930 unsigned SrcBits
= C
->getType()->getScalarSizeInBits();
2931 unsigned DstBits
= Ty
->getScalarSizeInBits();
2932 Instruction::CastOps opcode
=
2933 (SrcBits
== DstBits
? Instruction::BitCast
:
2934 (SrcBits
> DstBits
? Instruction::Trunc
:
2935 (isSigned
? Instruction::SExt
: Instruction::ZExt
)));
2936 return Create(opcode
, C
, Ty
, Name
, InsertBefore
);
2939 CastInst
*CastInst::CreateIntegerCast(Value
*C
, Type
*Ty
,
2940 bool isSigned
, const Twine
&Name
,
2941 BasicBlock
*InsertAtEnd
) {
2942 assert(C
->getType()->isIntOrIntVectorTy() && Ty
->isIntOrIntVectorTy() &&
2944 unsigned SrcBits
= C
->getType()->getScalarSizeInBits();
2945 unsigned DstBits
= Ty
->getScalarSizeInBits();
2946 Instruction::CastOps opcode
=
2947 (SrcBits
== DstBits
? Instruction::BitCast
:
2948 (SrcBits
> DstBits
? Instruction::Trunc
:
2949 (isSigned
? Instruction::SExt
: Instruction::ZExt
)));
2950 return Create(opcode
, C
, Ty
, Name
, InsertAtEnd
);
2953 CastInst
*CastInst::CreateFPCast(Value
*C
, Type
*Ty
,
2955 Instruction
*InsertBefore
) {
2956 assert(C
->getType()->isFPOrFPVectorTy() && Ty
->isFPOrFPVectorTy() &&
2958 unsigned SrcBits
= C
->getType()->getScalarSizeInBits();
2959 unsigned DstBits
= Ty
->getScalarSizeInBits();
2960 Instruction::CastOps opcode
=
2961 (SrcBits
== DstBits
? Instruction::BitCast
:
2962 (SrcBits
> DstBits
? Instruction::FPTrunc
: Instruction::FPExt
));
2963 return Create(opcode
, C
, Ty
, Name
, InsertBefore
);
2966 CastInst
*CastInst::CreateFPCast(Value
*C
, Type
*Ty
,
2968 BasicBlock
*InsertAtEnd
) {
2969 assert(C
->getType()->isFPOrFPVectorTy() && Ty
->isFPOrFPVectorTy() &&
2971 unsigned SrcBits
= C
->getType()->getScalarSizeInBits();
2972 unsigned DstBits
= Ty
->getScalarSizeInBits();
2973 Instruction::CastOps opcode
=
2974 (SrcBits
== DstBits
? Instruction::BitCast
:
2975 (SrcBits
> DstBits
? Instruction::FPTrunc
: Instruction::FPExt
));
2976 return Create(opcode
, C
, Ty
, Name
, InsertAtEnd
);
2979 // Check whether it is valid to call getCastOpcode for these types.
2980 // This routine must be kept in sync with getCastOpcode.
2981 bool CastInst::isCastable(Type
*SrcTy
, Type
*DestTy
) {
2982 if (!SrcTy
->isFirstClassType() || !DestTy
->isFirstClassType())
2985 if (SrcTy
== DestTy
)
2988 if (VectorType
*SrcVecTy
= dyn_cast
<VectorType
>(SrcTy
))
2989 if (VectorType
*DestVecTy
= dyn_cast
<VectorType
>(DestTy
))
2990 if (SrcVecTy
->getNumElements() == DestVecTy
->getNumElements()) {
2991 // An element by element cast. Valid if casting the elements is valid.
2992 SrcTy
= SrcVecTy
->getElementType();
2993 DestTy
= DestVecTy
->getElementType();
2996 // Get the bit sizes, we'll need these
2997 unsigned SrcBits
= SrcTy
->getPrimitiveSizeInBits(); // 0 for ptr
2998 unsigned DestBits
= DestTy
->getPrimitiveSizeInBits(); // 0 for ptr
3000 // Run through the possibilities ...
3001 if (DestTy
->isIntegerTy()) { // Casting to integral
3002 if (SrcTy
->isIntegerTy()) // Casting from integral
3004 if (SrcTy
->isFloatingPointTy()) // Casting from floating pt
3006 if (SrcTy
->isVectorTy()) // Casting from vector
3007 return DestBits
== SrcBits
;
3008 // Casting from something else
3009 return SrcTy
->isPointerTy();
3011 if (DestTy
->isFloatingPointTy()) { // Casting to floating pt
3012 if (SrcTy
->isIntegerTy()) // Casting from integral
3014 if (SrcTy
->isFloatingPointTy()) // Casting from floating pt
3016 if (SrcTy
->isVectorTy()) // Casting from vector
3017 return DestBits
== SrcBits
;
3018 // Casting from something else
3021 if (DestTy
->isVectorTy()) // Casting to vector
3022 return DestBits
== SrcBits
;
3023 if (DestTy
->isPointerTy()) { // Casting to pointer
3024 if (SrcTy
->isPointerTy()) // Casting from pointer
3026 return SrcTy
->isIntegerTy(); // Casting from integral
3028 if (DestTy
->isX86_MMXTy()) {
3029 if (SrcTy
->isVectorTy())
3030 return DestBits
== SrcBits
; // 64-bit vector to MMX
3032 } // Casting to something else
3036 bool CastInst::isBitCastable(Type
*SrcTy
, Type
*DestTy
) {
3037 if (!SrcTy
->isFirstClassType() || !DestTy
->isFirstClassType())
3040 if (SrcTy
== DestTy
)
3043 if (VectorType
*SrcVecTy
= dyn_cast
<VectorType
>(SrcTy
)) {
3044 if (VectorType
*DestVecTy
= dyn_cast
<VectorType
>(DestTy
)) {
3045 if (SrcVecTy
->getNumElements() == DestVecTy
->getNumElements()) {
3046 // An element by element cast. Valid if casting the elements is valid.
3047 SrcTy
= SrcVecTy
->getElementType();
3048 DestTy
= DestVecTy
->getElementType();
3053 if (PointerType
*DestPtrTy
= dyn_cast
<PointerType
>(DestTy
)) {
3054 if (PointerType
*SrcPtrTy
= dyn_cast
<PointerType
>(SrcTy
)) {
3055 return SrcPtrTy
->getAddressSpace() == DestPtrTy
->getAddressSpace();
3059 unsigned SrcBits
= SrcTy
->getPrimitiveSizeInBits(); // 0 for ptr
3060 unsigned DestBits
= DestTy
->getPrimitiveSizeInBits(); // 0 for ptr
3062 // Could still have vectors of pointers if the number of elements doesn't
3064 if (SrcBits
== 0 || DestBits
== 0)
3067 if (SrcBits
!= DestBits
)
3070 if (DestTy
->isX86_MMXTy() || SrcTy
->isX86_MMXTy())
3076 bool CastInst::isBitOrNoopPointerCastable(Type
*SrcTy
, Type
*DestTy
,
3077 const DataLayout
&DL
) {
3078 // ptrtoint and inttoptr are not allowed on non-integral pointers
3079 if (auto *PtrTy
= dyn_cast
<PointerType
>(SrcTy
))
3080 if (auto *IntTy
= dyn_cast
<IntegerType
>(DestTy
))
3081 return (IntTy
->getBitWidth() == DL
.getPointerTypeSizeInBits(PtrTy
) &&
3082 !DL
.isNonIntegralPointerType(PtrTy
));
3083 if (auto *PtrTy
= dyn_cast
<PointerType
>(DestTy
))
3084 if (auto *IntTy
= dyn_cast
<IntegerType
>(SrcTy
))
3085 return (IntTy
->getBitWidth() == DL
.getPointerTypeSizeInBits(PtrTy
) &&
3086 !DL
.isNonIntegralPointerType(PtrTy
));
3088 return isBitCastable(SrcTy
, DestTy
);
3091 // Provide a way to get a "cast" where the cast opcode is inferred from the
3092 // types and size of the operand. This, basically, is a parallel of the
3093 // logic in the castIsValid function below. This axiom should hold:
3094 // castIsValid( getCastOpcode(Val, Ty), Val, Ty)
3095 // should not assert in castIsValid. In other words, this produces a "correct"
3096 // casting opcode for the arguments passed to it.
3097 // This routine must be kept in sync with isCastable.
3098 Instruction::CastOps
3099 CastInst::getCastOpcode(
3100 const Value
*Src
, bool SrcIsSigned
, Type
*DestTy
, bool DestIsSigned
) {
3101 Type
*SrcTy
= Src
->getType();
3103 assert(SrcTy
->isFirstClassType() && DestTy
->isFirstClassType() &&
3104 "Only first class types are castable!");
3106 if (SrcTy
== DestTy
)
3109 // FIXME: Check address space sizes here
3110 if (VectorType
*SrcVecTy
= dyn_cast
<VectorType
>(SrcTy
))
3111 if (VectorType
*DestVecTy
= dyn_cast
<VectorType
>(DestTy
))
3112 if (SrcVecTy
->getNumElements() == DestVecTy
->getNumElements()) {
3113 // An element by element cast. Find the appropriate opcode based on the
3115 SrcTy
= SrcVecTy
->getElementType();
3116 DestTy
= DestVecTy
->getElementType();
3119 // Get the bit sizes, we'll need these
3120 unsigned SrcBits
= SrcTy
->getPrimitiveSizeInBits(); // 0 for ptr
3121 unsigned DestBits
= DestTy
->getPrimitiveSizeInBits(); // 0 for ptr
3123 // Run through the possibilities ...
3124 if (DestTy
->isIntegerTy()) { // Casting to integral
3125 if (SrcTy
->isIntegerTy()) { // Casting from integral
3126 if (DestBits
< SrcBits
)
3127 return Trunc
; // int -> smaller int
3128 else if (DestBits
> SrcBits
) { // its an extension
3130 return SExt
; // signed -> SEXT
3132 return ZExt
; // unsigned -> ZEXT
3134 return BitCast
; // Same size, No-op cast
3136 } else if (SrcTy
->isFloatingPointTy()) { // Casting from floating pt
3138 return FPToSI
; // FP -> sint
3140 return FPToUI
; // FP -> uint
3141 } else if (SrcTy
->isVectorTy()) {
3142 assert(DestBits
== SrcBits
&&
3143 "Casting vector to integer of different width");
3144 return BitCast
; // Same size, no-op cast
3146 assert(SrcTy
->isPointerTy() &&
3147 "Casting from a value that is not first-class type");
3148 return PtrToInt
; // ptr -> int
3150 } else if (DestTy
->isFloatingPointTy()) { // Casting to floating pt
3151 if (SrcTy
->isIntegerTy()) { // Casting from integral
3153 return SIToFP
; // sint -> FP
3155 return UIToFP
; // uint -> FP
3156 } else if (SrcTy
->isFloatingPointTy()) { // Casting from floating pt
3157 if (DestBits
< SrcBits
) {
3158 return FPTrunc
; // FP -> smaller FP
3159 } else if (DestBits
> SrcBits
) {
3160 return FPExt
; // FP -> larger FP
3162 return BitCast
; // same size, no-op cast
3164 } else if (SrcTy
->isVectorTy()) {
3165 assert(DestBits
== SrcBits
&&
3166 "Casting vector to floating point of different width");
3167 return BitCast
; // same size, no-op cast
3169 llvm_unreachable("Casting pointer or non-first class to float");
3170 } else if (DestTy
->isVectorTy()) {
3171 assert(DestBits
== SrcBits
&&
3172 "Illegal cast to vector (wrong type or size)");
3174 } else if (DestTy
->isPointerTy()) {
3175 if (SrcTy
->isPointerTy()) {
3176 if (DestTy
->getPointerAddressSpace() != SrcTy
->getPointerAddressSpace())
3177 return AddrSpaceCast
;
3178 return BitCast
; // ptr -> ptr
3179 } else if (SrcTy
->isIntegerTy()) {
3180 return IntToPtr
; // int -> ptr
3182 llvm_unreachable("Casting pointer to other than pointer or int");
3183 } else if (DestTy
->isX86_MMXTy()) {
3184 if (SrcTy
->isVectorTy()) {
3185 assert(DestBits
== SrcBits
&& "Casting vector of wrong width to X86_MMX");
3186 return BitCast
; // 64-bit vector to MMX
3188 llvm_unreachable("Illegal cast to X86_MMX");
3190 llvm_unreachable("Casting to type that is not first-class");
3193 //===----------------------------------------------------------------------===//
3194 // CastInst SubClass Constructors
3195 //===----------------------------------------------------------------------===//
3197 /// Check that the construction parameters for a CastInst are correct. This
3198 /// could be broken out into the separate constructors but it is useful to have
3199 /// it in one place and to eliminate the redundant code for getting the sizes
3200 /// of the types involved.
3202 CastInst::castIsValid(Instruction::CastOps op
, Value
*S
, Type
*DstTy
) {
3203 // Check for type sanity on the arguments
3204 Type
*SrcTy
= S
->getType();
3206 if (!SrcTy
->isFirstClassType() || !DstTy
->isFirstClassType() ||
3207 SrcTy
->isAggregateType() || DstTy
->isAggregateType())
3210 // Get the size of the types in bits, we'll need this later
3211 unsigned SrcBitSize
= SrcTy
->getScalarSizeInBits();
3212 unsigned DstBitSize
= DstTy
->getScalarSizeInBits();
3214 // If these are vector types, get the lengths of the vectors (using zero for
3215 // scalar types means that checking that vector lengths match also checks that
3216 // scalars are not being converted to vectors or vectors to scalars).
3217 unsigned SrcLength
= SrcTy
->isVectorTy() ?
3218 cast
<VectorType
>(SrcTy
)->getNumElements() : 0;
3219 unsigned DstLength
= DstTy
->isVectorTy() ?
3220 cast
<VectorType
>(DstTy
)->getNumElements() : 0;
3222 // Switch on the opcode provided
3224 default: return false; // This is an input error
3225 case Instruction::Trunc
:
3226 return SrcTy
->isIntOrIntVectorTy() && DstTy
->isIntOrIntVectorTy() &&
3227 SrcLength
== DstLength
&& SrcBitSize
> DstBitSize
;
3228 case Instruction::ZExt
:
3229 return SrcTy
->isIntOrIntVectorTy() && DstTy
->isIntOrIntVectorTy() &&
3230 SrcLength
== DstLength
&& SrcBitSize
< DstBitSize
;
3231 case Instruction::SExt
:
3232 return SrcTy
->isIntOrIntVectorTy() && DstTy
->isIntOrIntVectorTy() &&
3233 SrcLength
== DstLength
&& SrcBitSize
< DstBitSize
;
3234 case Instruction::FPTrunc
:
3235 return SrcTy
->isFPOrFPVectorTy() && DstTy
->isFPOrFPVectorTy() &&
3236 SrcLength
== DstLength
&& SrcBitSize
> DstBitSize
;
3237 case Instruction::FPExt
:
3238 return SrcTy
->isFPOrFPVectorTy() && DstTy
->isFPOrFPVectorTy() &&
3239 SrcLength
== DstLength
&& SrcBitSize
< DstBitSize
;
3240 case Instruction::UIToFP
:
3241 case Instruction::SIToFP
:
3242 return SrcTy
->isIntOrIntVectorTy() && DstTy
->isFPOrFPVectorTy() &&
3243 SrcLength
== DstLength
;
3244 case Instruction::FPToUI
:
3245 case Instruction::FPToSI
:
3246 return SrcTy
->isFPOrFPVectorTy() && DstTy
->isIntOrIntVectorTy() &&
3247 SrcLength
== DstLength
;
3248 case Instruction::PtrToInt
:
3249 if (isa
<VectorType
>(SrcTy
) != isa
<VectorType
>(DstTy
))
3251 if (VectorType
*VT
= dyn_cast
<VectorType
>(SrcTy
))
3252 if (VT
->getNumElements() != cast
<VectorType
>(DstTy
)->getNumElements())
3254 return SrcTy
->isPtrOrPtrVectorTy() && DstTy
->isIntOrIntVectorTy();
3255 case Instruction::IntToPtr
:
3256 if (isa
<VectorType
>(SrcTy
) != isa
<VectorType
>(DstTy
))
3258 if (VectorType
*VT
= dyn_cast
<VectorType
>(SrcTy
))
3259 if (VT
->getNumElements() != cast
<VectorType
>(DstTy
)->getNumElements())
3261 return SrcTy
->isIntOrIntVectorTy() && DstTy
->isPtrOrPtrVectorTy();
3262 case Instruction::BitCast
: {
3263 PointerType
*SrcPtrTy
= dyn_cast
<PointerType
>(SrcTy
->getScalarType());
3264 PointerType
*DstPtrTy
= dyn_cast
<PointerType
>(DstTy
->getScalarType());
3266 // BitCast implies a no-op cast of type only. No bits change.
3267 // However, you can't cast pointers to anything but pointers.
3268 if (!SrcPtrTy
!= !DstPtrTy
)
3271 // For non-pointer cases, the cast is okay if the source and destination bit
3272 // widths are identical.
3274 return SrcTy
->getPrimitiveSizeInBits() == DstTy
->getPrimitiveSizeInBits();
3276 // If both are pointers then the address spaces must match.
3277 if (SrcPtrTy
->getAddressSpace() != DstPtrTy
->getAddressSpace())
3280 // A vector of pointers must have the same number of elements.
3281 VectorType
*SrcVecTy
= dyn_cast
<VectorType
>(SrcTy
);
3282 VectorType
*DstVecTy
= dyn_cast
<VectorType
>(DstTy
);
3283 if (SrcVecTy
&& DstVecTy
)
3284 return (SrcVecTy
->getNumElements() == DstVecTy
->getNumElements());
3286 return SrcVecTy
->getNumElements() == 1;
3288 return DstVecTy
->getNumElements() == 1;
3292 case Instruction::AddrSpaceCast
: {
3293 PointerType
*SrcPtrTy
= dyn_cast
<PointerType
>(SrcTy
->getScalarType());
3297 PointerType
*DstPtrTy
= dyn_cast
<PointerType
>(DstTy
->getScalarType());
3301 if (SrcPtrTy
->getAddressSpace() == DstPtrTy
->getAddressSpace())
3304 if (VectorType
*SrcVecTy
= dyn_cast
<VectorType
>(SrcTy
)) {
3305 if (VectorType
*DstVecTy
= dyn_cast
<VectorType
>(DstTy
))
3306 return (SrcVecTy
->getNumElements() == DstVecTy
->getNumElements());
3316 TruncInst::TruncInst(
3317 Value
*S
, Type
*Ty
, const Twine
&Name
, Instruction
*InsertBefore
3318 ) : CastInst(Ty
, Trunc
, S
, Name
, InsertBefore
) {
3319 assert(castIsValid(getOpcode(), S
, Ty
) && "Illegal Trunc");
3322 TruncInst::TruncInst(
3323 Value
*S
, Type
*Ty
, const Twine
&Name
, BasicBlock
*InsertAtEnd
3324 ) : CastInst(Ty
, Trunc
, S
, Name
, InsertAtEnd
) {
3325 assert(castIsValid(getOpcode(), S
, Ty
) && "Illegal Trunc");
3329 Value
*S
, Type
*Ty
, const Twine
&Name
, Instruction
*InsertBefore
3330 ) : CastInst(Ty
, ZExt
, S
, Name
, InsertBefore
) {
3331 assert(castIsValid(getOpcode(), S
, Ty
) && "Illegal ZExt");
3335 Value
*S
, Type
*Ty
, const Twine
&Name
, BasicBlock
*InsertAtEnd
3336 ) : CastInst(Ty
, ZExt
, S
, Name
, InsertAtEnd
) {
3337 assert(castIsValid(getOpcode(), S
, Ty
) && "Illegal ZExt");
3340 Value
*S
, Type
*Ty
, const Twine
&Name
, Instruction
*InsertBefore
3341 ) : CastInst(Ty
, SExt
, S
, Name
, InsertBefore
) {
3342 assert(castIsValid(getOpcode(), S
, Ty
) && "Illegal SExt");
3346 Value
*S
, Type
*Ty
, const Twine
&Name
, BasicBlock
*InsertAtEnd
3347 ) : CastInst(Ty
, SExt
, S
, Name
, InsertAtEnd
) {
3348 assert(castIsValid(getOpcode(), S
, Ty
) && "Illegal SExt");
3351 FPTruncInst::FPTruncInst(
3352 Value
*S
, Type
*Ty
, const Twine
&Name
, Instruction
*InsertBefore
3353 ) : CastInst(Ty
, FPTrunc
, S
, Name
, InsertBefore
) {
3354 assert(castIsValid(getOpcode(), S
, Ty
) && "Illegal FPTrunc");
3357 FPTruncInst::FPTruncInst(
3358 Value
*S
, Type
*Ty
, const Twine
&Name
, BasicBlock
*InsertAtEnd
3359 ) : CastInst(Ty
, FPTrunc
, S
, Name
, InsertAtEnd
) {
3360 assert(castIsValid(getOpcode(), S
, Ty
) && "Illegal FPTrunc");
3363 FPExtInst::FPExtInst(
3364 Value
*S
, Type
*Ty
, const Twine
&Name
, Instruction
*InsertBefore
3365 ) : CastInst(Ty
, FPExt
, S
, Name
, InsertBefore
) {
3366 assert(castIsValid(getOpcode(), S
, Ty
) && "Illegal FPExt");
3369 FPExtInst::FPExtInst(
3370 Value
*S
, Type
*Ty
, const Twine
&Name
, BasicBlock
*InsertAtEnd
3371 ) : CastInst(Ty
, FPExt
, S
, Name
, InsertAtEnd
) {
3372 assert(castIsValid(getOpcode(), S
, Ty
) && "Illegal FPExt");
3375 UIToFPInst::UIToFPInst(
3376 Value
*S
, Type
*Ty
, const Twine
&Name
, Instruction
*InsertBefore
3377 ) : CastInst(Ty
, UIToFP
, S
, Name
, InsertBefore
) {
3378 assert(castIsValid(getOpcode(), S
, Ty
) && "Illegal UIToFP");
3381 UIToFPInst::UIToFPInst(
3382 Value
*S
, Type
*Ty
, const Twine
&Name
, BasicBlock
*InsertAtEnd
3383 ) : CastInst(Ty
, UIToFP
, S
, Name
, InsertAtEnd
) {
3384 assert(castIsValid(getOpcode(), S
, Ty
) && "Illegal UIToFP");
3387 SIToFPInst::SIToFPInst(
3388 Value
*S
, Type
*Ty
, const Twine
&Name
, Instruction
*InsertBefore
3389 ) : CastInst(Ty
, SIToFP
, S
, Name
, InsertBefore
) {
3390 assert(castIsValid(getOpcode(), S
, Ty
) && "Illegal SIToFP");
3393 SIToFPInst::SIToFPInst(
3394 Value
*S
, Type
*Ty
, const Twine
&Name
, BasicBlock
*InsertAtEnd
3395 ) : CastInst(Ty
, SIToFP
, S
, Name
, InsertAtEnd
) {
3396 assert(castIsValid(getOpcode(), S
, Ty
) && "Illegal SIToFP");
3399 FPToUIInst::FPToUIInst(
3400 Value
*S
, Type
*Ty
, const Twine
&Name
, Instruction
*InsertBefore
3401 ) : CastInst(Ty
, FPToUI
, S
, Name
, InsertBefore
) {
3402 assert(castIsValid(getOpcode(), S
, Ty
) && "Illegal FPToUI");
3405 FPToUIInst::FPToUIInst(
3406 Value
*S
, Type
*Ty
, const Twine
&Name
, BasicBlock
*InsertAtEnd
3407 ) : CastInst(Ty
, FPToUI
, S
, Name
, InsertAtEnd
) {
3408 assert(castIsValid(getOpcode(), S
, Ty
) && "Illegal FPToUI");
3411 FPToSIInst::FPToSIInst(
3412 Value
*S
, Type
*Ty
, const Twine
&Name
, Instruction
*InsertBefore
3413 ) : CastInst(Ty
, FPToSI
, S
, Name
, InsertBefore
) {
3414 assert(castIsValid(getOpcode(), S
, Ty
) && "Illegal FPToSI");
3417 FPToSIInst::FPToSIInst(
3418 Value
*S
, Type
*Ty
, const Twine
&Name
, BasicBlock
*InsertAtEnd
3419 ) : CastInst(Ty
, FPToSI
, S
, Name
, InsertAtEnd
) {
3420 assert(castIsValid(getOpcode(), S
, Ty
) && "Illegal FPToSI");
3423 PtrToIntInst::PtrToIntInst(
3424 Value
*S
, Type
*Ty
, const Twine
&Name
, Instruction
*InsertBefore
3425 ) : CastInst(Ty
, PtrToInt
, S
, Name
, InsertBefore
) {
3426 assert(castIsValid(getOpcode(), S
, Ty
) && "Illegal PtrToInt");
3429 PtrToIntInst::PtrToIntInst(
3430 Value
*S
, Type
*Ty
, const Twine
&Name
, BasicBlock
*InsertAtEnd
3431 ) : CastInst(Ty
, PtrToInt
, S
, Name
, InsertAtEnd
) {
3432 assert(castIsValid(getOpcode(), S
, Ty
) && "Illegal PtrToInt");
3435 IntToPtrInst::IntToPtrInst(
3436 Value
*S
, Type
*Ty
, const Twine
&Name
, Instruction
*InsertBefore
3437 ) : CastInst(Ty
, IntToPtr
, S
, Name
, InsertBefore
) {
3438 assert(castIsValid(getOpcode(), S
, Ty
) && "Illegal IntToPtr");
3441 IntToPtrInst::IntToPtrInst(
3442 Value
*S
, Type
*Ty
, const Twine
&Name
, BasicBlock
*InsertAtEnd
3443 ) : CastInst(Ty
, IntToPtr
, S
, Name
, InsertAtEnd
) {
3444 assert(castIsValid(getOpcode(), S
, Ty
) && "Illegal IntToPtr");
3447 BitCastInst::BitCastInst(
3448 Value
*S
, Type
*Ty
, const Twine
&Name
, Instruction
*InsertBefore
3449 ) : CastInst(Ty
, BitCast
, S
, Name
, InsertBefore
) {
3450 assert(castIsValid(getOpcode(), S
, Ty
) && "Illegal BitCast");
3453 BitCastInst::BitCastInst(
3454 Value
*S
, Type
*Ty
, const Twine
&Name
, BasicBlock
*InsertAtEnd
3455 ) : CastInst(Ty
, BitCast
, S
, Name
, InsertAtEnd
) {
3456 assert(castIsValid(getOpcode(), S
, Ty
) && "Illegal BitCast");
3459 AddrSpaceCastInst::AddrSpaceCastInst(
3460 Value
*S
, Type
*Ty
, const Twine
&Name
, Instruction
*InsertBefore
3461 ) : CastInst(Ty
, AddrSpaceCast
, S
, Name
, InsertBefore
) {
3462 assert(castIsValid(getOpcode(), S
, Ty
) && "Illegal AddrSpaceCast");
3465 AddrSpaceCastInst::AddrSpaceCastInst(
3466 Value
*S
, Type
*Ty
, const Twine
&Name
, BasicBlock
*InsertAtEnd
3467 ) : CastInst(Ty
, AddrSpaceCast
, S
, Name
, InsertAtEnd
) {
3468 assert(castIsValid(getOpcode(), S
, Ty
) && "Illegal AddrSpaceCast");
3471 //===----------------------------------------------------------------------===//
3473 //===----------------------------------------------------------------------===//
3475 CmpInst::CmpInst(Type
*ty
, OtherOps op
, Predicate predicate
, Value
*LHS
,
3476 Value
*RHS
, const Twine
&Name
, Instruction
*InsertBefore
,
3477 Instruction
*FlagsSource
)
3478 : Instruction(ty
, op
,
3479 OperandTraits
<CmpInst
>::op_begin(this),
3480 OperandTraits
<CmpInst
>::operands(this),
3484 setPredicate((Predicate
)predicate
);
3487 copyIRFlags(FlagsSource
);
3490 CmpInst::CmpInst(Type
*ty
, OtherOps op
, Predicate predicate
, Value
*LHS
,
3491 Value
*RHS
, const Twine
&Name
, BasicBlock
*InsertAtEnd
)
3492 : Instruction(ty
, op
,
3493 OperandTraits
<CmpInst
>::op_begin(this),
3494 OperandTraits
<CmpInst
>::operands(this),
3498 setPredicate((Predicate
)predicate
);
3503 CmpInst::Create(OtherOps Op
, Predicate predicate
, Value
*S1
, Value
*S2
,
3504 const Twine
&Name
, Instruction
*InsertBefore
) {
3505 if (Op
== Instruction::ICmp
) {
3507 return new ICmpInst(InsertBefore
, CmpInst::Predicate(predicate
),
3510 return new ICmpInst(CmpInst::Predicate(predicate
),
3515 return new FCmpInst(InsertBefore
, CmpInst::Predicate(predicate
),
3518 return new FCmpInst(CmpInst::Predicate(predicate
),
3523 CmpInst::Create(OtherOps Op
, Predicate predicate
, Value
*S1
, Value
*S2
,
3524 const Twine
&Name
, BasicBlock
*InsertAtEnd
) {
3525 if (Op
== Instruction::ICmp
) {
3526 return new ICmpInst(*InsertAtEnd
, CmpInst::Predicate(predicate
),
3529 return new FCmpInst(*InsertAtEnd
, CmpInst::Predicate(predicate
),
3533 void CmpInst::swapOperands() {
3534 if (ICmpInst
*IC
= dyn_cast
<ICmpInst
>(this))
3537 cast
<FCmpInst
>(this)->swapOperands();
3540 bool CmpInst::isCommutative() const {
3541 if (const ICmpInst
*IC
= dyn_cast
<ICmpInst
>(this))
3542 return IC
->isCommutative();
3543 return cast
<FCmpInst
>(this)->isCommutative();
3546 bool CmpInst::isEquality() const {
3547 if (const ICmpInst
*IC
= dyn_cast
<ICmpInst
>(this))
3548 return IC
->isEquality();
3549 return cast
<FCmpInst
>(this)->isEquality();
3552 CmpInst::Predicate
CmpInst::getInversePredicate(Predicate pred
) {
3554 default: llvm_unreachable("Unknown cmp predicate!");
3555 case ICMP_EQ
: return ICMP_NE
;
3556 case ICMP_NE
: return ICMP_EQ
;
3557 case ICMP_UGT
: return ICMP_ULE
;
3558 case ICMP_ULT
: return ICMP_UGE
;
3559 case ICMP_UGE
: return ICMP_ULT
;
3560 case ICMP_ULE
: return ICMP_UGT
;
3561 case ICMP_SGT
: return ICMP_SLE
;
3562 case ICMP_SLT
: return ICMP_SGE
;
3563 case ICMP_SGE
: return ICMP_SLT
;
3564 case ICMP_SLE
: return ICMP_SGT
;
3566 case FCMP_OEQ
: return FCMP_UNE
;
3567 case FCMP_ONE
: return FCMP_UEQ
;
3568 case FCMP_OGT
: return FCMP_ULE
;
3569 case FCMP_OLT
: return FCMP_UGE
;
3570 case FCMP_OGE
: return FCMP_ULT
;
3571 case FCMP_OLE
: return FCMP_UGT
;
3572 case FCMP_UEQ
: return FCMP_ONE
;
3573 case FCMP_UNE
: return FCMP_OEQ
;
3574 case FCMP_UGT
: return FCMP_OLE
;
3575 case FCMP_ULT
: return FCMP_OGE
;
3576 case FCMP_UGE
: return FCMP_OLT
;
3577 case FCMP_ULE
: return FCMP_OGT
;
3578 case FCMP_ORD
: return FCMP_UNO
;
3579 case FCMP_UNO
: return FCMP_ORD
;
3580 case FCMP_TRUE
: return FCMP_FALSE
;
3581 case FCMP_FALSE
: return FCMP_TRUE
;
3585 StringRef
CmpInst::getPredicateName(Predicate Pred
) {
3587 default: return "unknown";
3588 case FCmpInst::FCMP_FALSE
: return "false";
3589 case FCmpInst::FCMP_OEQ
: return "oeq";
3590 case FCmpInst::FCMP_OGT
: return "ogt";
3591 case FCmpInst::FCMP_OGE
: return "oge";
3592 case FCmpInst::FCMP_OLT
: return "olt";
3593 case FCmpInst::FCMP_OLE
: return "ole";
3594 case FCmpInst::FCMP_ONE
: return "one";
3595 case FCmpInst::FCMP_ORD
: return "ord";
3596 case FCmpInst::FCMP_UNO
: return "uno";
3597 case FCmpInst::FCMP_UEQ
: return "ueq";
3598 case FCmpInst::FCMP_UGT
: return "ugt";
3599 case FCmpInst::FCMP_UGE
: return "uge";
3600 case FCmpInst::FCMP_ULT
: return "ult";
3601 case FCmpInst::FCMP_ULE
: return "ule";
3602 case FCmpInst::FCMP_UNE
: return "une";
3603 case FCmpInst::FCMP_TRUE
: return "true";
3604 case ICmpInst::ICMP_EQ
: return "eq";
3605 case ICmpInst::ICMP_NE
: return "ne";
3606 case ICmpInst::ICMP_SGT
: return "sgt";
3607 case ICmpInst::ICMP_SGE
: return "sge";
3608 case ICmpInst::ICMP_SLT
: return "slt";
3609 case ICmpInst::ICMP_SLE
: return "sle";
3610 case ICmpInst::ICMP_UGT
: return "ugt";
3611 case ICmpInst::ICMP_UGE
: return "uge";
3612 case ICmpInst::ICMP_ULT
: return "ult";
3613 case ICmpInst::ICMP_ULE
: return "ule";
3617 ICmpInst::Predicate
ICmpInst::getSignedPredicate(Predicate pred
) {
3619 default: llvm_unreachable("Unknown icmp predicate!");
3620 case ICMP_EQ
: case ICMP_NE
:
3621 case ICMP_SGT
: case ICMP_SLT
: case ICMP_SGE
: case ICMP_SLE
:
3623 case ICMP_UGT
: return ICMP_SGT
;
3624 case ICMP_ULT
: return ICMP_SLT
;
3625 case ICMP_UGE
: return ICMP_SGE
;
3626 case ICMP_ULE
: return ICMP_SLE
;
3630 ICmpInst::Predicate
ICmpInst::getUnsignedPredicate(Predicate pred
) {
3632 default: llvm_unreachable("Unknown icmp predicate!");
3633 case ICMP_EQ
: case ICMP_NE
:
3634 case ICMP_UGT
: case ICMP_ULT
: case ICMP_UGE
: case ICMP_ULE
:
3636 case ICMP_SGT
: return ICMP_UGT
;
3637 case ICMP_SLT
: return ICMP_ULT
;
3638 case ICMP_SGE
: return ICMP_UGE
;
3639 case ICMP_SLE
: return ICMP_ULE
;
3643 CmpInst::Predicate
CmpInst::getFlippedStrictnessPredicate(Predicate pred
) {
3645 default: llvm_unreachable("Unknown or unsupported cmp predicate!");
3646 case ICMP_SGT
: return ICMP_SGE
;
3647 case ICMP_SLT
: return ICMP_SLE
;
3648 case ICMP_SGE
: return ICMP_SGT
;
3649 case ICMP_SLE
: return ICMP_SLT
;
3650 case ICMP_UGT
: return ICMP_UGE
;
3651 case ICMP_ULT
: return ICMP_ULE
;
3652 case ICMP_UGE
: return ICMP_UGT
;
3653 case ICMP_ULE
: return ICMP_ULT
;
3655 case FCMP_OGT
: return FCMP_OGE
;
3656 case FCMP_OLT
: return FCMP_OLE
;
3657 case FCMP_OGE
: return FCMP_OGT
;
3658 case FCMP_OLE
: return FCMP_OLT
;
3659 case FCMP_UGT
: return FCMP_UGE
;
3660 case FCMP_ULT
: return FCMP_ULE
;
3661 case FCMP_UGE
: return FCMP_UGT
;
3662 case FCMP_ULE
: return FCMP_ULT
;
3666 CmpInst::Predicate
CmpInst::getSwappedPredicate(Predicate pred
) {
3668 default: llvm_unreachable("Unknown cmp predicate!");
3669 case ICMP_EQ
: case ICMP_NE
:
3671 case ICMP_SGT
: return ICMP_SLT
;
3672 case ICMP_SLT
: return ICMP_SGT
;
3673 case ICMP_SGE
: return ICMP_SLE
;
3674 case ICMP_SLE
: return ICMP_SGE
;
3675 case ICMP_UGT
: return ICMP_ULT
;
3676 case ICMP_ULT
: return ICMP_UGT
;
3677 case ICMP_UGE
: return ICMP_ULE
;
3678 case ICMP_ULE
: return ICMP_UGE
;
3680 case FCMP_FALSE
: case FCMP_TRUE
:
3681 case FCMP_OEQ
: case FCMP_ONE
:
3682 case FCMP_UEQ
: case FCMP_UNE
:
3683 case FCMP_ORD
: case FCMP_UNO
:
3685 case FCMP_OGT
: return FCMP_OLT
;
3686 case FCMP_OLT
: return FCMP_OGT
;
3687 case FCMP_OGE
: return FCMP_OLE
;
3688 case FCMP_OLE
: return FCMP_OGE
;
3689 case FCMP_UGT
: return FCMP_ULT
;
3690 case FCMP_ULT
: return FCMP_UGT
;
3691 case FCMP_UGE
: return FCMP_ULE
;
3692 case FCMP_ULE
: return FCMP_UGE
;
3696 CmpInst::Predicate
CmpInst::getNonStrictPredicate(Predicate pred
) {
3698 case ICMP_SGT
: return ICMP_SGE
;
3699 case ICMP_SLT
: return ICMP_SLE
;
3700 case ICMP_UGT
: return ICMP_UGE
;
3701 case ICMP_ULT
: return ICMP_ULE
;
3702 case FCMP_OGT
: return FCMP_OGE
;
3703 case FCMP_OLT
: return FCMP_OLE
;
3704 case FCMP_UGT
: return FCMP_UGE
;
3705 case FCMP_ULT
: return FCMP_ULE
;
3706 default: return pred
;
3710 CmpInst::Predicate
CmpInst::getSignedPredicate(Predicate pred
) {
3711 assert(CmpInst::isUnsigned(pred
) && "Call only with signed predicates!");
3715 llvm_unreachable("Unknown predicate!");
3716 case CmpInst::ICMP_ULT
:
3717 return CmpInst::ICMP_SLT
;
3718 case CmpInst::ICMP_ULE
:
3719 return CmpInst::ICMP_SLE
;
3720 case CmpInst::ICMP_UGT
:
3721 return CmpInst::ICMP_SGT
;
3722 case CmpInst::ICMP_UGE
:
3723 return CmpInst::ICMP_SGE
;
3727 bool CmpInst::isUnsigned(Predicate predicate
) {
3728 switch (predicate
) {
3729 default: return false;
3730 case ICmpInst::ICMP_ULT
: case ICmpInst::ICMP_ULE
: case ICmpInst::ICMP_UGT
:
3731 case ICmpInst::ICMP_UGE
: return true;
3735 bool CmpInst::isSigned(Predicate predicate
) {
3736 switch (predicate
) {
3737 default: return false;
3738 case ICmpInst::ICMP_SLT
: case ICmpInst::ICMP_SLE
: case ICmpInst::ICMP_SGT
:
3739 case ICmpInst::ICMP_SGE
: return true;
3743 bool CmpInst::isOrdered(Predicate predicate
) {
3744 switch (predicate
) {
3745 default: return false;
3746 case FCmpInst::FCMP_OEQ
: case FCmpInst::FCMP_ONE
: case FCmpInst::FCMP_OGT
:
3747 case FCmpInst::FCMP_OLT
: case FCmpInst::FCMP_OGE
: case FCmpInst::FCMP_OLE
:
3748 case FCmpInst::FCMP_ORD
: return true;
3752 bool CmpInst::isUnordered(Predicate predicate
) {
3753 switch (predicate
) {
3754 default: return false;
3755 case FCmpInst::FCMP_UEQ
: case FCmpInst::FCMP_UNE
: case FCmpInst::FCMP_UGT
:
3756 case FCmpInst::FCMP_ULT
: case FCmpInst::FCMP_UGE
: case FCmpInst::FCMP_ULE
:
3757 case FCmpInst::FCMP_UNO
: return true;
3761 bool CmpInst::isTrueWhenEqual(Predicate predicate
) {
3763 default: return false;
3764 case ICMP_EQ
: case ICMP_UGE
: case ICMP_ULE
: case ICMP_SGE
: case ICMP_SLE
:
3765 case FCMP_TRUE
: case FCMP_UEQ
: case FCMP_UGE
: case FCMP_ULE
: return true;
3769 bool CmpInst::isFalseWhenEqual(Predicate predicate
) {
3771 case ICMP_NE
: case ICMP_UGT
: case ICMP_ULT
: case ICMP_SGT
: case ICMP_SLT
:
3772 case FCMP_FALSE
: case FCMP_ONE
: case FCMP_OGT
: case FCMP_OLT
: return true;
3773 default: return false;
3777 bool CmpInst::isImpliedTrueByMatchingCmp(Predicate Pred1
, Predicate Pred2
) {
3778 // If the predicates match, then we know the first condition implies the
3787 // A == B implies A >=u B, A <=u B, A >=s B, and A <=s B are true.
3788 return Pred2
== ICMP_UGE
|| Pred2
== ICMP_ULE
|| Pred2
== ICMP_SGE
||
3790 case ICMP_UGT
: // A >u B implies A != B and A >=u B are true.
3791 return Pred2
== ICMP_NE
|| Pred2
== ICMP_UGE
;
3792 case ICMP_ULT
: // A <u B implies A != B and A <=u B are true.
3793 return Pred2
== ICMP_NE
|| Pred2
== ICMP_ULE
;
3794 case ICMP_SGT
: // A >s B implies A != B and A >=s B are true.
3795 return Pred2
== ICMP_NE
|| Pred2
== ICMP_SGE
;
3796 case ICMP_SLT
: // A <s B implies A != B and A <=s B are true.
3797 return Pred2
== ICMP_NE
|| Pred2
== ICMP_SLE
;
3802 bool CmpInst::isImpliedFalseByMatchingCmp(Predicate Pred1
, Predicate Pred2
) {
3803 return isImpliedTrueByMatchingCmp(Pred1
, getInversePredicate(Pred2
));
3806 //===----------------------------------------------------------------------===//
3807 // SwitchInst Implementation
3808 //===----------------------------------------------------------------------===//
3810 void SwitchInst::init(Value
*Value
, BasicBlock
*Default
, unsigned NumReserved
) {
3811 assert(Value
&& Default
&& NumReserved
);
3812 ReservedSpace
= NumReserved
;
3813 setNumHungOffUseOperands(2);
3814 allocHungoffUses(ReservedSpace
);
3820 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
3821 /// switch on and a default destination. The number of additional cases can
3822 /// be specified here to make memory allocation more efficient. This
3823 /// constructor can also autoinsert before another instruction.
3824 SwitchInst::SwitchInst(Value
*Value
, BasicBlock
*Default
, unsigned NumCases
,
3825 Instruction
*InsertBefore
)
3826 : Instruction(Type::getVoidTy(Value
->getContext()), Instruction::Switch
,
3827 nullptr, 0, InsertBefore
) {
3828 init(Value
, Default
, 2+NumCases
*2);
3831 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
3832 /// switch on and a default destination. The number of additional cases can
3833 /// be specified here to make memory allocation more efficient. This
3834 /// constructor also autoinserts at the end of the specified BasicBlock.
3835 SwitchInst::SwitchInst(Value
*Value
, BasicBlock
*Default
, unsigned NumCases
,
3836 BasicBlock
*InsertAtEnd
)
3837 : Instruction(Type::getVoidTy(Value
->getContext()), Instruction::Switch
,
3838 nullptr, 0, InsertAtEnd
) {
3839 init(Value
, Default
, 2+NumCases
*2);
3842 SwitchInst::SwitchInst(const SwitchInst
&SI
)
3843 : Instruction(SI
.getType(), Instruction::Switch
, nullptr, 0) {
3844 init(SI
.getCondition(), SI
.getDefaultDest(), SI
.getNumOperands());
3845 setNumHungOffUseOperands(SI
.getNumOperands());
3846 Use
*OL
= getOperandList();
3847 const Use
*InOL
= SI
.getOperandList();
3848 for (unsigned i
= 2, E
= SI
.getNumOperands(); i
!= E
; i
+= 2) {
3850 OL
[i
+1] = InOL
[i
+1];
3852 SubclassOptionalData
= SI
.SubclassOptionalData
;
3855 /// addCase - Add an entry to the switch instruction...
3857 void SwitchInst::addCase(ConstantInt
*OnVal
, BasicBlock
*Dest
) {
3858 unsigned NewCaseIdx
= getNumCases();
3859 unsigned OpNo
= getNumOperands();
3860 if (OpNo
+2 > ReservedSpace
)
3861 growOperands(); // Get more space!
3862 // Initialize some new operands.
3863 assert(OpNo
+1 < ReservedSpace
&& "Growing didn't work!");
3864 setNumHungOffUseOperands(OpNo
+2);
3865 CaseHandle
Case(this, NewCaseIdx
);
3866 Case
.setValue(OnVal
);
3867 Case
.setSuccessor(Dest
);
3870 /// removeCase - This method removes the specified case and its successor
3871 /// from the switch instruction.
3872 SwitchInst::CaseIt
SwitchInst::removeCase(CaseIt I
) {
3873 unsigned idx
= I
->getCaseIndex();
3875 assert(2 + idx
*2 < getNumOperands() && "Case index out of range!!!");
3877 unsigned NumOps
= getNumOperands();
3878 Use
*OL
= getOperandList();
3880 // Overwrite this case with the end of the list.
3881 if (2 + (idx
+ 1) * 2 != NumOps
) {
3882 OL
[2 + idx
* 2] = OL
[NumOps
- 2];
3883 OL
[2 + idx
* 2 + 1] = OL
[NumOps
- 1];
3886 // Nuke the last value.
3887 OL
[NumOps
-2].set(nullptr);
3888 OL
[NumOps
-2+1].set(nullptr);
3889 setNumHungOffUseOperands(NumOps
-2);
3891 return CaseIt(this, idx
);
3894 /// growOperands - grow operands - This grows the operand list in response
3895 /// to a push_back style of operation. This grows the number of ops by 3 times.
3897 void SwitchInst::growOperands() {
3898 unsigned e
= getNumOperands();
3899 unsigned NumOps
= e
*3;
3901 ReservedSpace
= NumOps
;
3902 growHungoffUses(ReservedSpace
);
3906 SwitchInstProfUpdateWrapper::getProfBranchWeightsMD(const SwitchInst
&SI
) {
3907 if (MDNode
*ProfileData
= SI
.getMetadata(LLVMContext::MD_prof
))
3908 if (auto *MDName
= dyn_cast
<MDString
>(ProfileData
->getOperand(0)))
3909 if (MDName
->getString() == "branch_weights")
3914 MDNode
*SwitchInstProfUpdateWrapper::buildProfBranchWeightsMD() {
3915 assert(Changed
&& "called only if metadata has changed");
3920 assert(SI
.getNumSuccessors() == Weights
->size() &&
3921 "num of prof branch_weights must accord with num of successors");
3924 all_of(Weights
.getValue(), [](uint32_t W
) { return W
== 0; });
3926 if (AllZeroes
|| Weights
.getValue().size() < 2)
3929 return MDBuilder(SI
.getParent()->getContext()).createBranchWeights(*Weights
);
3932 void SwitchInstProfUpdateWrapper::init() {
3933 MDNode
*ProfileData
= getProfBranchWeightsMD(SI
);
3937 if (ProfileData
->getNumOperands() != SI
.getNumSuccessors() + 1) {
3938 llvm_unreachable("number of prof branch_weights metadata operands does "
3939 "not correspond to number of succesors");
3942 SmallVector
<uint32_t, 8> Weights
;
3943 for (unsigned CI
= 1, CE
= SI
.getNumSuccessors(); CI
<= CE
; ++CI
) {
3944 ConstantInt
*C
= mdconst::extract
<ConstantInt
>(ProfileData
->getOperand(CI
));
3945 uint32_t CW
= C
->getValue().getZExtValue();
3946 Weights
.push_back(CW
);
3948 this->Weights
= std::move(Weights
);
3952 SwitchInstProfUpdateWrapper::removeCase(SwitchInst::CaseIt I
) {
3954 assert(SI
.getNumSuccessors() == Weights
->size() &&
3955 "num of prof branch_weights must accord with num of successors");
3957 // Copy the last case to the place of the removed one and shrink.
3958 // This is tightly coupled with the way SwitchInst::removeCase() removes
3959 // the cases in SwitchInst::removeCase(CaseIt).
3960 Weights
.getValue()[I
->getCaseIndex() + 1] = Weights
.getValue().back();
3961 Weights
.getValue().pop_back();
3963 return SI
.removeCase(I
);
3966 void SwitchInstProfUpdateWrapper::addCase(
3967 ConstantInt
*OnVal
, BasicBlock
*Dest
,
3968 SwitchInstProfUpdateWrapper::CaseWeightOpt W
) {
3969 SI
.addCase(OnVal
, Dest
);
3971 if (!Weights
&& W
&& *W
) {
3973 Weights
= SmallVector
<uint32_t, 8>(SI
.getNumSuccessors(), 0);
3974 Weights
.getValue()[SI
.getNumSuccessors() - 1] = *W
;
3975 } else if (Weights
) {
3977 Weights
.getValue().push_back(W
? *W
: 0);
3980 assert(SI
.getNumSuccessors() == Weights
->size() &&
3981 "num of prof branch_weights must accord with num of successors");
3984 SymbolTableList
<Instruction
>::iterator
3985 SwitchInstProfUpdateWrapper::eraseFromParent() {
3986 // Instruction is erased. Mark as unchanged to not touch it in the destructor.
3990 return SI
.eraseFromParent();
3993 SwitchInstProfUpdateWrapper::CaseWeightOpt
3994 SwitchInstProfUpdateWrapper::getSuccessorWeight(unsigned idx
) {
3997 return Weights
.getValue()[idx
];
4000 void SwitchInstProfUpdateWrapper::setSuccessorWeight(
4001 unsigned idx
, SwitchInstProfUpdateWrapper::CaseWeightOpt W
) {
4006 Weights
= SmallVector
<uint32_t, 8>(SI
.getNumSuccessors(), 0);
4009 auto &OldW
= Weights
.getValue()[idx
];
4017 SwitchInstProfUpdateWrapper::CaseWeightOpt
4018 SwitchInstProfUpdateWrapper::getSuccessorWeight(const SwitchInst
&SI
,
4020 if (MDNode
*ProfileData
= getProfBranchWeightsMD(SI
))
4021 if (ProfileData
->getNumOperands() == SI
.getNumSuccessors() + 1)
4022 return mdconst::extract
<ConstantInt
>(ProfileData
->getOperand(idx
+ 1))
4029 //===----------------------------------------------------------------------===//
4030 // IndirectBrInst Implementation
4031 //===----------------------------------------------------------------------===//
4033 void IndirectBrInst::init(Value
*Address
, unsigned NumDests
) {
4034 assert(Address
&& Address
->getType()->isPointerTy() &&
4035 "Address of indirectbr must be a pointer");
4036 ReservedSpace
= 1+NumDests
;
4037 setNumHungOffUseOperands(1);
4038 allocHungoffUses(ReservedSpace
);
4044 /// growOperands - grow operands - This grows the operand list in response
4045 /// to a push_back style of operation. This grows the number of ops by 2 times.
4047 void IndirectBrInst::growOperands() {
4048 unsigned e
= getNumOperands();
4049 unsigned NumOps
= e
*2;
4051 ReservedSpace
= NumOps
;
4052 growHungoffUses(ReservedSpace
);
4055 IndirectBrInst::IndirectBrInst(Value
*Address
, unsigned NumCases
,
4056 Instruction
*InsertBefore
)
4057 : Instruction(Type::getVoidTy(Address
->getContext()),
4058 Instruction::IndirectBr
, nullptr, 0, InsertBefore
) {
4059 init(Address
, NumCases
);
4062 IndirectBrInst::IndirectBrInst(Value
*Address
, unsigned NumCases
,
4063 BasicBlock
*InsertAtEnd
)
4064 : Instruction(Type::getVoidTy(Address
->getContext()),
4065 Instruction::IndirectBr
, nullptr, 0, InsertAtEnd
) {
4066 init(Address
, NumCases
);
4069 IndirectBrInst::IndirectBrInst(const IndirectBrInst
&IBI
)
4070 : Instruction(Type::getVoidTy(IBI
.getContext()), Instruction::IndirectBr
,
4071 nullptr, IBI
.getNumOperands()) {
4072 allocHungoffUses(IBI
.getNumOperands());
4073 Use
*OL
= getOperandList();
4074 const Use
*InOL
= IBI
.getOperandList();
4075 for (unsigned i
= 0, E
= IBI
.getNumOperands(); i
!= E
; ++i
)
4077 SubclassOptionalData
= IBI
.SubclassOptionalData
;
4080 /// addDestination - Add a destination.
4082 void IndirectBrInst::addDestination(BasicBlock
*DestBB
) {
4083 unsigned OpNo
= getNumOperands();
4084 if (OpNo
+1 > ReservedSpace
)
4085 growOperands(); // Get more space!
4086 // Initialize some new operands.
4087 assert(OpNo
< ReservedSpace
&& "Growing didn't work!");
4088 setNumHungOffUseOperands(OpNo
+1);
4089 getOperandList()[OpNo
] = DestBB
;
4092 /// removeDestination - This method removes the specified successor from the
4093 /// indirectbr instruction.
4094 void IndirectBrInst::removeDestination(unsigned idx
) {
4095 assert(idx
< getNumOperands()-1 && "Successor index out of range!");
4097 unsigned NumOps
= getNumOperands();
4098 Use
*OL
= getOperandList();
4100 // Replace this value with the last one.
4101 OL
[idx
+1] = OL
[NumOps
-1];
4103 // Nuke the last value.
4104 OL
[NumOps
-1].set(nullptr);
4105 setNumHungOffUseOperands(NumOps
-1);
4108 //===----------------------------------------------------------------------===//
4109 // cloneImpl() implementations
4110 //===----------------------------------------------------------------------===//
4112 // Define these methods here so vtables don't get emitted into every translation
4113 // unit that uses these classes.
4115 GetElementPtrInst
*GetElementPtrInst::cloneImpl() const {
4116 return new (getNumOperands()) GetElementPtrInst(*this);
4119 UnaryOperator
*UnaryOperator::cloneImpl() const {
4120 return Create(getOpcode(), Op
<0>());
4123 BinaryOperator
*BinaryOperator::cloneImpl() const {
4124 return Create(getOpcode(), Op
<0>(), Op
<1>());
4127 FCmpInst
*FCmpInst::cloneImpl() const {
4128 return new FCmpInst(getPredicate(), Op
<0>(), Op
<1>());
4131 ICmpInst
*ICmpInst::cloneImpl() const {
4132 return new ICmpInst(getPredicate(), Op
<0>(), Op
<1>());
4135 ExtractValueInst
*ExtractValueInst::cloneImpl() const {
4136 return new ExtractValueInst(*this);
4139 InsertValueInst
*InsertValueInst::cloneImpl() const {
4140 return new InsertValueInst(*this);
4143 AllocaInst
*AllocaInst::cloneImpl() const {
4144 AllocaInst
*Result
= new AllocaInst(getAllocatedType(),
4145 getType()->getAddressSpace(),
4146 (Value
*)getOperand(0), getAlignment());
4147 Result
->setUsedWithInAlloca(isUsedWithInAlloca());
4148 Result
->setSwiftError(isSwiftError());
4152 LoadInst
*LoadInst::cloneImpl() const {
4153 return new LoadInst(getType(), getOperand(0), Twine(), isVolatile(),
4154 getAlignment(), getOrdering(), getSyncScopeID());
4157 StoreInst
*StoreInst::cloneImpl() const {
4158 return new StoreInst(getOperand(0), getOperand(1), isVolatile(),
4159 getAlignment(), getOrdering(), getSyncScopeID());
4163 AtomicCmpXchgInst
*AtomicCmpXchgInst::cloneImpl() const {
4164 AtomicCmpXchgInst
*Result
=
4165 new AtomicCmpXchgInst(getOperand(0), getOperand(1), getOperand(2),
4166 getSuccessOrdering(), getFailureOrdering(),
4168 Result
->setVolatile(isVolatile());
4169 Result
->setWeak(isWeak());
4173 AtomicRMWInst
*AtomicRMWInst::cloneImpl() const {
4174 AtomicRMWInst
*Result
=
4175 new AtomicRMWInst(getOperation(), getOperand(0), getOperand(1),
4176 getOrdering(), getSyncScopeID());
4177 Result
->setVolatile(isVolatile());
4181 FenceInst
*FenceInst::cloneImpl() const {
4182 return new FenceInst(getContext(), getOrdering(), getSyncScopeID());
4185 TruncInst
*TruncInst::cloneImpl() const {
4186 return new TruncInst(getOperand(0), getType());
4189 ZExtInst
*ZExtInst::cloneImpl() const {
4190 return new ZExtInst(getOperand(0), getType());
4193 SExtInst
*SExtInst::cloneImpl() const {
4194 return new SExtInst(getOperand(0), getType());
4197 FPTruncInst
*FPTruncInst::cloneImpl() const {
4198 return new FPTruncInst(getOperand(0), getType());
4201 FPExtInst
*FPExtInst::cloneImpl() const {
4202 return new FPExtInst(getOperand(0), getType());
4205 UIToFPInst
*UIToFPInst::cloneImpl() const {
4206 return new UIToFPInst(getOperand(0), getType());
4209 SIToFPInst
*SIToFPInst::cloneImpl() const {
4210 return new SIToFPInst(getOperand(0), getType());
4213 FPToUIInst
*FPToUIInst::cloneImpl() const {
4214 return new FPToUIInst(getOperand(0), getType());
4217 FPToSIInst
*FPToSIInst::cloneImpl() const {
4218 return new FPToSIInst(getOperand(0), getType());
4221 PtrToIntInst
*PtrToIntInst::cloneImpl() const {
4222 return new PtrToIntInst(getOperand(0), getType());
4225 IntToPtrInst
*IntToPtrInst::cloneImpl() const {
4226 return new IntToPtrInst(getOperand(0), getType());
4229 BitCastInst
*BitCastInst::cloneImpl() const {
4230 return new BitCastInst(getOperand(0), getType());
4233 AddrSpaceCastInst
*AddrSpaceCastInst::cloneImpl() const {
4234 return new AddrSpaceCastInst(getOperand(0), getType());
4237 CallInst
*CallInst::cloneImpl() const {
4238 if (hasOperandBundles()) {
4239 unsigned DescriptorBytes
= getNumOperandBundles() * sizeof(BundleOpInfo
);
4240 return new(getNumOperands(), DescriptorBytes
) CallInst(*this);
4242 return new(getNumOperands()) CallInst(*this);
4245 SelectInst
*SelectInst::cloneImpl() const {
4246 return SelectInst::Create(getOperand(0), getOperand(1), getOperand(2));
4249 VAArgInst
*VAArgInst::cloneImpl() const {
4250 return new VAArgInst(getOperand(0), getType());
4253 ExtractElementInst
*ExtractElementInst::cloneImpl() const {
4254 return ExtractElementInst::Create(getOperand(0), getOperand(1));
4257 InsertElementInst
*InsertElementInst::cloneImpl() const {
4258 return InsertElementInst::Create(getOperand(0), getOperand(1), getOperand(2));
4261 ShuffleVectorInst
*ShuffleVectorInst::cloneImpl() const {
4262 return new ShuffleVectorInst(getOperand(0), getOperand(1), getOperand(2));
4265 PHINode
*PHINode::cloneImpl() const { return new PHINode(*this); }
4267 LandingPadInst
*LandingPadInst::cloneImpl() const {
4268 return new LandingPadInst(*this);
4271 ReturnInst
*ReturnInst::cloneImpl() const {
4272 return new(getNumOperands()) ReturnInst(*this);
4275 BranchInst
*BranchInst::cloneImpl() const {
4276 return new(getNumOperands()) BranchInst(*this);
4279 SwitchInst
*SwitchInst::cloneImpl() const { return new SwitchInst(*this); }
4281 IndirectBrInst
*IndirectBrInst::cloneImpl() const {
4282 return new IndirectBrInst(*this);
4285 InvokeInst
*InvokeInst::cloneImpl() const {
4286 if (hasOperandBundles()) {
4287 unsigned DescriptorBytes
= getNumOperandBundles() * sizeof(BundleOpInfo
);
4288 return new(getNumOperands(), DescriptorBytes
) InvokeInst(*this);
4290 return new(getNumOperands()) InvokeInst(*this);
4293 CallBrInst
*CallBrInst::cloneImpl() const {
4294 if (hasOperandBundles()) {
4295 unsigned DescriptorBytes
= getNumOperandBundles() * sizeof(BundleOpInfo
);
4296 return new (getNumOperands(), DescriptorBytes
) CallBrInst(*this);
4298 return new (getNumOperands()) CallBrInst(*this);
4301 ResumeInst
*ResumeInst::cloneImpl() const { return new (1) ResumeInst(*this); }
4303 CleanupReturnInst
*CleanupReturnInst::cloneImpl() const {
4304 return new (getNumOperands()) CleanupReturnInst(*this);
4307 CatchReturnInst
*CatchReturnInst::cloneImpl() const {
4308 return new (getNumOperands()) CatchReturnInst(*this);
4311 CatchSwitchInst
*CatchSwitchInst::cloneImpl() const {
4312 return new CatchSwitchInst(*this);
4315 FuncletPadInst
*FuncletPadInst::cloneImpl() const {
4316 return new (getNumOperands()) FuncletPadInst(*this);
4319 UnreachableInst
*UnreachableInst::cloneImpl() const {
4320 LLVMContext
&Context
= getContext();
4321 return new UnreachableInst(Context
);