[Alignment][NFC] Remove AllocaInst::setAlignment(unsigned)
[llvm-core.git] / lib / IR / Instructions.cpp
blob0f000623bdb51e91c6c12d9e49e0d190e4513bc3
1 //===- Instructions.cpp - Implement the LLVM instructions -----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements all of the non-inline methods for the LLVM instruction
10 // classes.
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"
41 #include <algorithm>
42 #include <cassert>
43 #include <cstdint>
44 #include <vector>
46 using namespace llvm;
48 //===----------------------------------------------------------------------===//
49 // AllocaInst Class
50 //===----------------------------------------------------------------------===//
52 Optional<uint64_t>
53 AllocaInst::getAllocationSizeInBits(const DataLayout &DL) const {
54 uint64_t Size = DL.getTypeAllocSizeInBits(getAllocatedType());
55 if (isArrayAllocation()) {
56 auto C = dyn_cast<ConstantInt>(getArraySize());
57 if (!C)
58 return None;
59 Size *= C->getZExtValue();
61 return Size;
64 //===----------------------------------------------------------------------===//
65 // CallSite Class
66 //===----------------------------------------------------------------------===//
68 User::op_iterator CallSite::getCallee() const {
69 return cast<CallBase>(getInstruction())->op_end() - 1;
72 //===----------------------------------------------------------------------===//
73 // SelectInst Class
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())) {
86 // Vector select.
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());
90 if (!ET)
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>";
98 return nullptr;
101 //===----------------------------------------------------------------------===//
102 // PHINode Class
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()));
135 eraseFromParent();
137 return Removed;
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
142 /// times.
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
172 /// non-undefs.
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)
181 return false;
182 ConstantValue = Incoming;
185 return true;
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)
212 OL[I] = InOL[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);
233 setName(NameStr);
234 setCleanup(false);
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();
248 growOperands(1);
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))
268 return false;
269 if (const CallInst *CI = dyn_cast<CallInst>(this))
270 if (CI->isInlineAsm())
271 return false;
272 return true;
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();
280 return false;
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();
287 return false;
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))
298 return true;
300 if (getDereferenceableBytes(AttributeList::ReturnIndex) > 0 &&
301 !NullPointerIsDefined(getCaller(),
302 getType()->getPointerAddressSpace()))
303 return true;
305 return false;
308 Value *CallBase::getReturnedArgOperand() const {
309 unsigned Index;
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) &&
315 Index)
316 return getArgOperand(Index - AttributeList::FirstArgIndex);
318 return nullptr;
321 bool CallBase::hasRetAttr(Attribute::AttrKind Kind) const {
322 if (Attrs.hasAttribute(AttributeList::ReturnIndex, Kind))
323 return true;
325 // Look at the callee, if available.
326 if (const Function *F = getCalledFunction())
327 return F->getAttributes().hasAttribute(AttributeList::ReturnIndex, Kind);
328 return false;
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))
336 return true;
337 if (const Function *F = getCalledFunction())
338 return F->getAttributes().hasParamAttribute(ArgNo, Kind);
339 return false;
342 bool CallBase::hasFnAttrOnCalledFunction(Attribute::AttrKind Kind) const {
343 if (const Function *F = getCalledFunction())
344 return F->getAttributes().hasAttribute(AttributeList::FunctionIndex, Kind);
345 return false;
348 bool CallBase::hasFnAttrOnCalledFunction(StringRef Kind) const {
349 if (const Function *F = getCalledFunction())
350 return F->getAttributes().hasAttribute(AttributeList::FunctionIndex, Kind);
351 return false;
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;
372 BI++;
375 assert(BI == Bundles.end() && "Incorrect allocation?");
377 return It;
380 //===----------------------------------------------------------------------===//
381 // CallInst Implementation
382 //===----------------------------------------------------------------------===//
384 void CallInst::init(FunctionType *FTy, Value *Func, ArrayRef<Value *> Args,
385 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr) {
386 this->FTy = FTy;
387 assert(getNumOperands() == Args.size() + CountBundleInputs(Bundles) + 1 &&
388 "NumOperands not set up?");
389 setCalledOperand(Func);
391 #ifndef NDEBUG
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!");
400 #endif
402 llvm::copy(Args, op_begin());
404 auto It = populateBundleOperandInfos(Bundles, Args.size());
405 (void)It;
406 assert(It + 1 == op_end() && "Should add up!");
408 setName(NameStr);
411 void CallInst::init(FunctionType *FTy, Value *Func, const Twine &NameStr) {
412 this->FTy = FTy;
413 assert(getNumOperands() == 1 && "NumOperands not set up?");
414 setCalledOperand(Func);
416 assert(FTy->getNumParams() == 0 && "Calling a function with bad signature");
418 setName(NameStr);
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());
459 return NewCI;
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)
468 return;
470 auto *ProfDataName = dyn_cast<MDString>(ProfileData->getOperand(0));
471 if (!ProfDataName || (!ProfDataName->getString().equals("branch_weights") &&
472 !ProfDataName->getString().equals("VP")))
473 return;
475 if (T == 0) {
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.");
481 return;
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))
492 ->getValue()
493 .getZExtValue());
494 Val *= APS;
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.
502 APInt Val(128,
503 mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(i + 1))
504 ->getValue()
505 .getZExtValue());
506 Val *= APS;
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,
524 Value *ArraySize,
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*
534 if (!ArraySize)
535 ArraySize = ConstantInt::get(IntPtrTy, 1);
536 else if (ArraySize->getType() != IntPtrTy) {
537 if (InsertBefore)
538 ArraySize = CastInst::CreateIntegerCast(ArraySize, IntPtrTy, false,
539 "", InsertBefore);
540 else
541 ArraySize = CastInst::CreateIntegerCast(ArraySize, IntPtrTy, false,
542 "", InsertAtEnd);
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,
550 false /*ZExt*/);
551 // Malloc arg is constant product of type size and array size
552 AllocSize = ConstantExpr::getMul(Scale, cast<Constant>(AllocSize));
553 } else {
554 // Multiply type size by the array size...
555 if (InsertBefore)
556 AllocSize = BinaryOperator::CreateMul(ArraySize, AllocSize,
557 "mallocsize", InsertBefore);
558 else
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;
570 if (!MallocFunc)
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;
576 if (InsertBefore) {
577 MCall = CallInst::Create(MallocFunc, AllocSize, OpB, "malloccall",
578 InsertBefore);
579 Result = MCall;
580 if (Result->getType() != AllocPtrType)
581 // Create a cast instruction to convert to the right type...
582 Result = new BitCastInst(MCall, AllocPtrType, Name, InsertBefore);
583 } else {
584 MCall = CallInst::Create(MallocFunc, AllocSize, OpB, "malloccall");
585 Result = MCall;
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");
600 return Result;
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
606 /// constant 1.
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,
612 Function *MallocF,
613 const Twine &Name) {
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,
621 Function *MallocF,
622 const Twine &Name) {
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
630 /// constant 1.
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;
669 if (InsertBefore) {
670 if (Source->getType() != IntPtrTy)
671 PtrCast = new BitCastInst(Source, IntPtrTy, "", InsertBefore);
672 Result = CallInst::Create(FreeFunc, PtrCast, Bundles, "", InsertBefore);
673 } else {
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());
682 return Result;
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");
701 return FreeCall;
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");
708 return FreeCall;
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) {
719 this->FTy = FTy;
721 assert((int)getNumOperands() ==
722 ComputeNumOperands(Args.size(), CountBundleInputs(Bundles)) &&
723 "NumOperands not set up?");
724 setNormalDest(IfNormal);
725 setUnwindDest(IfException);
726 setCalledOperand(Fn);
728 #ifndef NDEBUG
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!");
737 #endif
739 llvm::copy(Args, op_begin());
741 auto It = populateBundleOperandInfos(Bundles, Args.size());
742 (void)It;
743 assert(It + 3 == op_end() && "Should add up!");
745 setName(NameStr);
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());
770 return NewII;
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) {
787 this->FTy = FTy;
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);
799 #ifndef NDEBUG
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!");
808 #endif
810 std::copy(Args.begin(), Args.end(), op_begin());
812 auto It = populateBundleOperandInfos(Bundles, Args.size());
813 (void)It;
814 assert(It + 2 + IndirectDests.size() == op_end() && "Should add up!");
816 setName(NameStr);
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;
856 return NewCBI;
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,
875 InsertBefore) {
876 if (retVal)
877 Op<0>() = 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,
883 InsertAtEnd) {
884 if (retVal)
885 Op<0>() = 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) {
905 Op<0>() = Exn;
908 ResumeInst::ResumeInst(Value *Exn, BasicBlock *InsertAtEnd)
909 : Instruction(Type::getVoidTy(Exn->getContext()), Instruction::Resume,
910 OperandTraits<ResumeInst>::op_begin(this), 1, InsertAtEnd) {
911 Op<0>() = Exn;
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) {
930 if (UnwindBB)
931 setInstructionSubclassData(getSubclassDataFromInstruction() | 1);
933 Op<0>() = CleanupPad;
934 if (UnwindBB)
935 Op<1>() = UnwindBB;
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) {
960 Op<0>() = CatchPad;
961 Op<1>() = 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,
975 InsertBefore) {
976 init(CatchPad, BB);
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,
983 InsertAtEnd) {
984 init(CatchPad, BB);
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,
996 InsertBefore) {
997 if (UnwindDest)
998 ++NumReservedValues;
999 init(ParentPad, UnwindDest, NumReservedValues + 1);
1000 setName(NameStr);
1003 CatchSwitchInst::CatchSwitchInst(Value *ParentPad, BasicBlock *UnwindDest,
1004 unsigned NumReservedValues,
1005 const Twine &NameStr, BasicBlock *InsertAtEnd)
1006 : Instruction(ParentPad->getType(), Instruction::CatchSwitch, nullptr, 0,
1007 InsertAtEnd) {
1008 if (UnwindDest)
1009 ++NumReservedValues;
1010 init(ParentPad, UnwindDest, NumReservedValues + 1);
1011 setName(NameStr);
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)
1022 OL[I] = InOL[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;
1034 if (UnwindDest) {
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)
1046 return;
1047 ReservedSpace = (NumOperands + Size / 2) * 2;
1048 growHungoffUses(ReservedSpace);
1051 void CatchSwitchInst::addHandler(BasicBlock *Handler) {
1052 unsigned OpNo = getNumOperands();
1053 growOperands(1);
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.
1065 *EndDst = nullptr;
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);
1078 setName(NameStr);
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,
1095 InsertBefore) {
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,
1104 InsertAtEnd) {
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,
1115 0, InsertBefore) {}
1116 UnreachableInst::UnreachableInst(LLVMContext &Context, BasicBlock *InsertAtEnd)
1117 : Instruction(Type::getVoidTy(Context), Instruction::Unreachable, nullptr,
1118 0, InsertAtEnd) {}
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,
1133 InsertBefore) {
1134 assert(IfTrue && "Branch destination may not be null!");
1135 Op<-1>() = IfTrue;
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,
1142 InsertBefore) {
1143 Op<-1>() = IfTrue;
1144 Op<-2>() = IfFalse;
1145 Op<-3>() = Cond;
1146 #ifndef NDEBUG
1147 AssertOK();
1148 #endif
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!");
1155 Op<-1>() = IfTrue;
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) {
1162 Op<-1>() = IfTrue;
1163 Op<-2>() = IfFalse;
1164 Op<-3>() = Cond;
1165 #ifndef NDEBUG
1166 AssertOK();
1167 #endif
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
1189 // expectations.
1190 swapProfMetadata();
1193 //===----------------------------------------------------------------------===//
1194 // AllocaInst Implementation
1195 //===----------------------------------------------------------------------===//
1197 static Value *getAISize(LLVMContext &Context, Value *Amt) {
1198 if (!Amt)
1199 Amt = ConstantInt::get(Type::getInt32Ty(Context), 1);
1200 else {
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!");
1206 return Amt;
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),
1230 AllocatedType(Ty) {
1231 setAlignment(MaybeAlign(Align));
1232 assert(!Ty->isVoidTy() && "Cannot allocate void!");
1233 setName(Name);
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),
1241 AllocatedType(Ty) {
1242 setAlignment(MaybeAlign(Align));
1243 assert(!Ty->isVoidTy() && "Cannot allocate void!");
1244 setName(Name);
1247 void AllocaInst::setAlignment(MaybeAlign Align) {
1248 assert((!Align || *Align <= MaximumAlignment) &&
1249 "Alignment is greater than MaximumAlignment!");
1250 setInstructionSubclassData((getSubclassDataFromInstruction() & ~31) |
1251 encode(Align));
1252 if (Align)
1253 assert(getAlignment() == Align->value() &&
1254 "Alignment representation error!");
1255 else
1256 assert(getAlignment() == 0 && "Alignment representation error!");
1259 bool AllocaInst::isArrayAllocation() const {
1260 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(0)))
1261 return !CI->isOne();
1262 return true;
1265 /// isStaticAlloca - Return true if this alloca is in the entry block of the
1266 /// function and is a constant size. If so, the code generator will fold it
1267 /// into the prolog/epilog code, so it is basically free.
1268 bool AllocaInst::isStaticAlloca() const {
1269 // Must be constant size.
1270 if (!isa<ConstantInt>(getArraySize())) return false;
1272 // Must be in the entry block.
1273 const BasicBlock *Parent = getParent();
1274 return Parent == &Parent->getParent()->front() && !isUsedWithInAlloca();
1277 //===----------------------------------------------------------------------===//
1278 // LoadInst Implementation
1279 //===----------------------------------------------------------------------===//
1281 void LoadInst::AssertOK() {
1282 assert(getOperand(0)->getType()->isPointerTy() &&
1283 "Ptr must have pointer type.");
1284 assert(!(isAtomic() && getAlignment() == 0) &&
1285 "Alignment required for atomic load");
1288 LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name,
1289 Instruction *InsertBef)
1290 : LoadInst(Ty, Ptr, Name, /*isVolatile=*/false, InsertBef) {}
1292 LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name,
1293 BasicBlock *InsertAE)
1294 : LoadInst(Ty, Ptr, Name, /*isVolatile=*/false, InsertAE) {}
1296 LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile,
1297 Instruction *InsertBef)
1298 : LoadInst(Ty, Ptr, Name, isVolatile, /*Align=*/0, InsertBef) {}
1300 LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile,
1301 BasicBlock *InsertAE)
1302 : LoadInst(Ty, Ptr, Name, isVolatile, /*Align=*/0, InsertAE) {}
1304 LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile,
1305 unsigned Align, Instruction *InsertBef)
1306 : LoadInst(Ty, Ptr, Name, isVolatile, Align, AtomicOrdering::NotAtomic,
1307 SyncScope::System, InsertBef) {}
1309 LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile,
1310 unsigned Align, BasicBlock *InsertAE)
1311 : LoadInst(Ty, Ptr, Name, isVolatile, Align, AtomicOrdering::NotAtomic,
1312 SyncScope::System, InsertAE) {}
1314 LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile,
1315 unsigned Align, AtomicOrdering Order,
1316 SyncScope::ID SSID, Instruction *InsertBef)
1317 : UnaryInstruction(Ty, Load, Ptr, InsertBef) {
1318 assert(Ty == cast<PointerType>(Ptr->getType())->getElementType());
1319 setVolatile(isVolatile);
1320 setAlignment(MaybeAlign(Align));
1321 setAtomic(Order, SSID);
1322 AssertOK();
1323 setName(Name);
1326 LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile,
1327 unsigned Align, AtomicOrdering Order, SyncScope::ID SSID,
1328 BasicBlock *InsertAE)
1329 : UnaryInstruction(Ty, Load, Ptr, InsertAE) {
1330 assert(Ty == cast<PointerType>(Ptr->getType())->getElementType());
1331 setVolatile(isVolatile);
1332 setAlignment(MaybeAlign(Align));
1333 setAtomic(Order, SSID);
1334 AssertOK();
1335 setName(Name);
1338 void LoadInst::setAlignment(MaybeAlign Align) {
1339 assert((!Align || *Align <= MaximumAlignment) &&
1340 "Alignment is greater than MaximumAlignment!");
1341 setInstructionSubclassData((getSubclassDataFromInstruction() & ~(31 << 1)) |
1342 (encode(Align) << 1));
1343 if (Align)
1344 assert(getAlignment() == Align->value() &&
1345 "Alignment representation error!");
1346 else
1347 assert(getAlignment() == 0 && "Alignment representation error!");
1350 //===----------------------------------------------------------------------===//
1351 // StoreInst Implementation
1352 //===----------------------------------------------------------------------===//
1354 void StoreInst::AssertOK() {
1355 assert(getOperand(0) && getOperand(1) && "Both operands must be non-null!");
1356 assert(getOperand(1)->getType()->isPointerTy() &&
1357 "Ptr must have pointer type!");
1358 assert(getOperand(0)->getType() ==
1359 cast<PointerType>(getOperand(1)->getType())->getElementType()
1360 && "Ptr must be a pointer to Val type!");
1361 assert(!(isAtomic() && getAlignment() == 0) &&
1362 "Alignment required for atomic store");
1365 StoreInst::StoreInst(Value *val, Value *addr, Instruction *InsertBefore)
1366 : StoreInst(val, addr, /*isVolatile=*/false, InsertBefore) {}
1368 StoreInst::StoreInst(Value *val, Value *addr, BasicBlock *InsertAtEnd)
1369 : StoreInst(val, addr, /*isVolatile=*/false, InsertAtEnd) {}
1371 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1372 Instruction *InsertBefore)
1373 : StoreInst(val, addr, isVolatile, /*Align=*/0, InsertBefore) {}
1375 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1376 BasicBlock *InsertAtEnd)
1377 : StoreInst(val, addr, isVolatile, /*Align=*/0, InsertAtEnd) {}
1379 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile, unsigned Align,
1380 Instruction *InsertBefore)
1381 : StoreInst(val, addr, isVolatile, Align, AtomicOrdering::NotAtomic,
1382 SyncScope::System, InsertBefore) {}
1384 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile, unsigned Align,
1385 BasicBlock *InsertAtEnd)
1386 : StoreInst(val, addr, isVolatile, Align, AtomicOrdering::NotAtomic,
1387 SyncScope::System, InsertAtEnd) {}
1389 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1390 unsigned Align, AtomicOrdering Order,
1391 SyncScope::ID SSID,
1392 Instruction *InsertBefore)
1393 : Instruction(Type::getVoidTy(val->getContext()), Store,
1394 OperandTraits<StoreInst>::op_begin(this),
1395 OperandTraits<StoreInst>::operands(this),
1396 InsertBefore) {
1397 Op<0>() = val;
1398 Op<1>() = addr;
1399 setVolatile(isVolatile);
1400 setAlignment(Align);
1401 setAtomic(Order, SSID);
1402 AssertOK();
1405 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1406 unsigned Align, AtomicOrdering Order,
1407 SyncScope::ID SSID,
1408 BasicBlock *InsertAtEnd)
1409 : Instruction(Type::getVoidTy(val->getContext()), Store,
1410 OperandTraits<StoreInst>::op_begin(this),
1411 OperandTraits<StoreInst>::operands(this),
1412 InsertAtEnd) {
1413 Op<0>() = val;
1414 Op<1>() = addr;
1415 setVolatile(isVolatile);
1416 setAlignment(Align);
1417 setAtomic(Order, SSID);
1418 AssertOK();
1421 void StoreInst::setAlignment(unsigned Align) {
1422 setAlignment(llvm::MaybeAlign(Align));
1425 void StoreInst::setAlignment(MaybeAlign Align) {
1426 assert((!Align || *Align <= MaximumAlignment) &&
1427 "Alignment is greater than MaximumAlignment!");
1428 setInstructionSubclassData((getSubclassDataFromInstruction() & ~(31 << 1)) |
1429 (encode(Align) << 1));
1430 if (Align)
1431 assert(getAlignment() == Align->value() &&
1432 "Alignment representation error!");
1433 else
1434 assert(getAlignment() == 0 && "Alignment representation error!");
1437 //===----------------------------------------------------------------------===//
1438 // AtomicCmpXchgInst Implementation
1439 //===----------------------------------------------------------------------===//
1441 void AtomicCmpXchgInst::Init(Value *Ptr, Value *Cmp, Value *NewVal,
1442 AtomicOrdering SuccessOrdering,
1443 AtomicOrdering FailureOrdering,
1444 SyncScope::ID SSID) {
1445 Op<0>() = Ptr;
1446 Op<1>() = Cmp;
1447 Op<2>() = NewVal;
1448 setSuccessOrdering(SuccessOrdering);
1449 setFailureOrdering(FailureOrdering);
1450 setSyncScopeID(SSID);
1452 assert(getOperand(0) && getOperand(1) && getOperand(2) &&
1453 "All operands must be non-null!");
1454 assert(getOperand(0)->getType()->isPointerTy() &&
1455 "Ptr must have pointer type!");
1456 assert(getOperand(1)->getType() ==
1457 cast<PointerType>(getOperand(0)->getType())->getElementType()
1458 && "Ptr must be a pointer to Cmp type!");
1459 assert(getOperand(2)->getType() ==
1460 cast<PointerType>(getOperand(0)->getType())->getElementType()
1461 && "Ptr must be a pointer to NewVal type!");
1462 assert(SuccessOrdering != AtomicOrdering::NotAtomic &&
1463 "AtomicCmpXchg instructions must be atomic!");
1464 assert(FailureOrdering != AtomicOrdering::NotAtomic &&
1465 "AtomicCmpXchg instructions must be atomic!");
1466 assert(!isStrongerThan(FailureOrdering, SuccessOrdering) &&
1467 "AtomicCmpXchg failure argument shall be no stronger than the success "
1468 "argument");
1469 assert(FailureOrdering != AtomicOrdering::Release &&
1470 FailureOrdering != AtomicOrdering::AcquireRelease &&
1471 "AtomicCmpXchg failure ordering cannot include release semantics");
1474 AtomicCmpXchgInst::AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal,
1475 AtomicOrdering SuccessOrdering,
1476 AtomicOrdering FailureOrdering,
1477 SyncScope::ID SSID,
1478 Instruction *InsertBefore)
1479 : Instruction(
1480 StructType::get(Cmp->getType(), Type::getInt1Ty(Cmp->getContext())),
1481 AtomicCmpXchg, OperandTraits<AtomicCmpXchgInst>::op_begin(this),
1482 OperandTraits<AtomicCmpXchgInst>::operands(this), InsertBefore) {
1483 Init(Ptr, Cmp, NewVal, SuccessOrdering, FailureOrdering, SSID);
1486 AtomicCmpXchgInst::AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal,
1487 AtomicOrdering SuccessOrdering,
1488 AtomicOrdering FailureOrdering,
1489 SyncScope::ID SSID,
1490 BasicBlock *InsertAtEnd)
1491 : Instruction(
1492 StructType::get(Cmp->getType(), Type::getInt1Ty(Cmp->getContext())),
1493 AtomicCmpXchg, OperandTraits<AtomicCmpXchgInst>::op_begin(this),
1494 OperandTraits<AtomicCmpXchgInst>::operands(this), InsertAtEnd) {
1495 Init(Ptr, Cmp, NewVal, SuccessOrdering, FailureOrdering, SSID);
1498 //===----------------------------------------------------------------------===//
1499 // AtomicRMWInst Implementation
1500 //===----------------------------------------------------------------------===//
1502 void AtomicRMWInst::Init(BinOp Operation, Value *Ptr, Value *Val,
1503 AtomicOrdering Ordering,
1504 SyncScope::ID SSID) {
1505 Op<0>() = Ptr;
1506 Op<1>() = Val;
1507 setOperation(Operation);
1508 setOrdering(Ordering);
1509 setSyncScopeID(SSID);
1511 assert(getOperand(0) && getOperand(1) &&
1512 "All operands must be non-null!");
1513 assert(getOperand(0)->getType()->isPointerTy() &&
1514 "Ptr must have pointer type!");
1515 assert(getOperand(1)->getType() ==
1516 cast<PointerType>(getOperand(0)->getType())->getElementType()
1517 && "Ptr must be a pointer to Val type!");
1518 assert(Ordering != AtomicOrdering::NotAtomic &&
1519 "AtomicRMW instructions must be atomic!");
1522 AtomicRMWInst::AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val,
1523 AtomicOrdering Ordering,
1524 SyncScope::ID SSID,
1525 Instruction *InsertBefore)
1526 : Instruction(Val->getType(), AtomicRMW,
1527 OperandTraits<AtomicRMWInst>::op_begin(this),
1528 OperandTraits<AtomicRMWInst>::operands(this),
1529 InsertBefore) {
1530 Init(Operation, Ptr, Val, Ordering, SSID);
1533 AtomicRMWInst::AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val,
1534 AtomicOrdering Ordering,
1535 SyncScope::ID SSID,
1536 BasicBlock *InsertAtEnd)
1537 : Instruction(Val->getType(), AtomicRMW,
1538 OperandTraits<AtomicRMWInst>::op_begin(this),
1539 OperandTraits<AtomicRMWInst>::operands(this),
1540 InsertAtEnd) {
1541 Init(Operation, Ptr, Val, Ordering, SSID);
1544 StringRef AtomicRMWInst::getOperationName(BinOp Op) {
1545 switch (Op) {
1546 case AtomicRMWInst::Xchg:
1547 return "xchg";
1548 case AtomicRMWInst::Add:
1549 return "add";
1550 case AtomicRMWInst::Sub:
1551 return "sub";
1552 case AtomicRMWInst::And:
1553 return "and";
1554 case AtomicRMWInst::Nand:
1555 return "nand";
1556 case AtomicRMWInst::Or:
1557 return "or";
1558 case AtomicRMWInst::Xor:
1559 return "xor";
1560 case AtomicRMWInst::Max:
1561 return "max";
1562 case AtomicRMWInst::Min:
1563 return "min";
1564 case AtomicRMWInst::UMax:
1565 return "umax";
1566 case AtomicRMWInst::UMin:
1567 return "umin";
1568 case AtomicRMWInst::FAdd:
1569 return "fadd";
1570 case AtomicRMWInst::FSub:
1571 return "fsub";
1572 case AtomicRMWInst::BAD_BINOP:
1573 return "<invalid operation>";
1576 llvm_unreachable("invalid atomicrmw operation");
1579 //===----------------------------------------------------------------------===//
1580 // FenceInst Implementation
1581 //===----------------------------------------------------------------------===//
1583 FenceInst::FenceInst(LLVMContext &C, AtomicOrdering Ordering,
1584 SyncScope::ID SSID,
1585 Instruction *InsertBefore)
1586 : Instruction(Type::getVoidTy(C), Fence, nullptr, 0, InsertBefore) {
1587 setOrdering(Ordering);
1588 setSyncScopeID(SSID);
1591 FenceInst::FenceInst(LLVMContext &C, AtomicOrdering Ordering,
1592 SyncScope::ID SSID,
1593 BasicBlock *InsertAtEnd)
1594 : Instruction(Type::getVoidTy(C), Fence, nullptr, 0, InsertAtEnd) {
1595 setOrdering(Ordering);
1596 setSyncScopeID(SSID);
1599 //===----------------------------------------------------------------------===//
1600 // GetElementPtrInst Implementation
1601 //===----------------------------------------------------------------------===//
1603 void GetElementPtrInst::init(Value *Ptr, ArrayRef<Value *> IdxList,
1604 const Twine &Name) {
1605 assert(getNumOperands() == 1 + IdxList.size() &&
1606 "NumOperands not initialized?");
1607 Op<0>() = Ptr;
1608 llvm::copy(IdxList, op_begin() + 1);
1609 setName(Name);
1612 GetElementPtrInst::GetElementPtrInst(const GetElementPtrInst &GEPI)
1613 : Instruction(GEPI.getType(), GetElementPtr,
1614 OperandTraits<GetElementPtrInst>::op_end(this) -
1615 GEPI.getNumOperands(),
1616 GEPI.getNumOperands()),
1617 SourceElementType(GEPI.SourceElementType),
1618 ResultElementType(GEPI.ResultElementType) {
1619 std::copy(GEPI.op_begin(), GEPI.op_end(), op_begin());
1620 SubclassOptionalData = GEPI.SubclassOptionalData;
1623 /// getIndexedType - Returns the type of the element that would be accessed with
1624 /// a gep instruction with the specified parameters.
1626 /// The Idxs pointer should point to a continuous piece of memory containing the
1627 /// indices, either as Value* or uint64_t.
1629 /// A null type is returned if the indices are invalid for the specified
1630 /// pointer type.
1632 template <typename IndexTy>
1633 static Type *getIndexedTypeInternal(Type *Agg, ArrayRef<IndexTy> IdxList) {
1634 // Handle the special case of the empty set index set, which is always valid.
1635 if (IdxList.empty())
1636 return Agg;
1638 // If there is at least one index, the top level type must be sized, otherwise
1639 // it cannot be 'stepped over'.
1640 if (!Agg->isSized())
1641 return nullptr;
1643 unsigned CurIdx = 1;
1644 for (; CurIdx != IdxList.size(); ++CurIdx) {
1645 CompositeType *CT = dyn_cast<CompositeType>(Agg);
1646 if (!CT || CT->isPointerTy()) return nullptr;
1647 IndexTy Index = IdxList[CurIdx];
1648 if (!CT->indexValid(Index)) return nullptr;
1649 Agg = CT->getTypeAtIndex(Index);
1651 return CurIdx == IdxList.size() ? Agg : nullptr;
1654 Type *GetElementPtrInst::getIndexedType(Type *Ty, ArrayRef<Value *> IdxList) {
1655 return getIndexedTypeInternal(Ty, IdxList);
1658 Type *GetElementPtrInst::getIndexedType(Type *Ty,
1659 ArrayRef<Constant *> IdxList) {
1660 return getIndexedTypeInternal(Ty, IdxList);
1663 Type *GetElementPtrInst::getIndexedType(Type *Ty, ArrayRef<uint64_t> IdxList) {
1664 return getIndexedTypeInternal(Ty, IdxList);
1667 /// hasAllZeroIndices - Return true if all of the indices of this GEP are
1668 /// zeros. If so, the result pointer and the first operand have the same
1669 /// value, just potentially different types.
1670 bool GetElementPtrInst::hasAllZeroIndices() const {
1671 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1672 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(i))) {
1673 if (!CI->isZero()) return false;
1674 } else {
1675 return false;
1678 return true;
1681 /// hasAllConstantIndices - Return true if all of the indices of this GEP are
1682 /// constant integers. If so, the result pointer and the first operand have
1683 /// a constant offset between them.
1684 bool GetElementPtrInst::hasAllConstantIndices() const {
1685 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1686 if (!isa<ConstantInt>(getOperand(i)))
1687 return false;
1689 return true;
1692 void GetElementPtrInst::setIsInBounds(bool B) {
1693 cast<GEPOperator>(this)->setIsInBounds(B);
1696 bool GetElementPtrInst::isInBounds() const {
1697 return cast<GEPOperator>(this)->isInBounds();
1700 bool GetElementPtrInst::accumulateConstantOffset(const DataLayout &DL,
1701 APInt &Offset) const {
1702 // Delegate to the generic GEPOperator implementation.
1703 return cast<GEPOperator>(this)->accumulateConstantOffset(DL, Offset);
1706 //===----------------------------------------------------------------------===//
1707 // ExtractElementInst Implementation
1708 //===----------------------------------------------------------------------===//
1710 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1711 const Twine &Name,
1712 Instruction *InsertBef)
1713 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1714 ExtractElement,
1715 OperandTraits<ExtractElementInst>::op_begin(this),
1716 2, InsertBef) {
1717 assert(isValidOperands(Val, Index) &&
1718 "Invalid extractelement instruction operands!");
1719 Op<0>() = Val;
1720 Op<1>() = Index;
1721 setName(Name);
1724 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1725 const Twine &Name,
1726 BasicBlock *InsertAE)
1727 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1728 ExtractElement,
1729 OperandTraits<ExtractElementInst>::op_begin(this),
1730 2, InsertAE) {
1731 assert(isValidOperands(Val, Index) &&
1732 "Invalid extractelement instruction operands!");
1734 Op<0>() = Val;
1735 Op<1>() = Index;
1736 setName(Name);
1739 bool ExtractElementInst::isValidOperands(const Value *Val, const Value *Index) {
1740 if (!Val->getType()->isVectorTy() || !Index->getType()->isIntegerTy())
1741 return false;
1742 return true;
1745 //===----------------------------------------------------------------------===//
1746 // InsertElementInst Implementation
1747 //===----------------------------------------------------------------------===//
1749 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1750 const Twine &Name,
1751 Instruction *InsertBef)
1752 : Instruction(Vec->getType(), InsertElement,
1753 OperandTraits<InsertElementInst>::op_begin(this),
1754 3, InsertBef) {
1755 assert(isValidOperands(Vec, Elt, Index) &&
1756 "Invalid insertelement instruction operands!");
1757 Op<0>() = Vec;
1758 Op<1>() = Elt;
1759 Op<2>() = Index;
1760 setName(Name);
1763 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1764 const Twine &Name,
1765 BasicBlock *InsertAE)
1766 : Instruction(Vec->getType(), InsertElement,
1767 OperandTraits<InsertElementInst>::op_begin(this),
1768 3, InsertAE) {
1769 assert(isValidOperands(Vec, Elt, Index) &&
1770 "Invalid insertelement instruction operands!");
1772 Op<0>() = Vec;
1773 Op<1>() = Elt;
1774 Op<2>() = Index;
1775 setName(Name);
1778 bool InsertElementInst::isValidOperands(const Value *Vec, const Value *Elt,
1779 const Value *Index) {
1780 if (!Vec->getType()->isVectorTy())
1781 return false; // First operand of insertelement must be vector type.
1783 if (Elt->getType() != cast<VectorType>(Vec->getType())->getElementType())
1784 return false;// Second operand of insertelement must be vector element type.
1786 if (!Index->getType()->isIntegerTy())
1787 return false; // Third operand of insertelement must be i32.
1788 return true;
1791 //===----------------------------------------------------------------------===//
1792 // ShuffleVectorInst Implementation
1793 //===----------------------------------------------------------------------===//
1795 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1796 const Twine &Name,
1797 Instruction *InsertBefore)
1798 : Instruction(VectorType::get(cast<VectorType>(V1->getType())->getElementType(),
1799 cast<VectorType>(Mask->getType())->getNumElements()),
1800 ShuffleVector,
1801 OperandTraits<ShuffleVectorInst>::op_begin(this),
1802 OperandTraits<ShuffleVectorInst>::operands(this),
1803 InsertBefore) {
1804 assert(isValidOperands(V1, V2, Mask) &&
1805 "Invalid shuffle vector instruction operands!");
1806 Op<0>() = V1;
1807 Op<1>() = V2;
1808 Op<2>() = Mask;
1809 setName(Name);
1812 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1813 const Twine &Name,
1814 BasicBlock *InsertAtEnd)
1815 : Instruction(VectorType::get(cast<VectorType>(V1->getType())->getElementType(),
1816 cast<VectorType>(Mask->getType())->getNumElements()),
1817 ShuffleVector,
1818 OperandTraits<ShuffleVectorInst>::op_begin(this),
1819 OperandTraits<ShuffleVectorInst>::operands(this),
1820 InsertAtEnd) {
1821 assert(isValidOperands(V1, V2, Mask) &&
1822 "Invalid shuffle vector instruction operands!");
1824 Op<0>() = V1;
1825 Op<1>() = V2;
1826 Op<2>() = Mask;
1827 setName(Name);
1830 void ShuffleVectorInst::commute() {
1831 int NumOpElts = Op<0>()->getType()->getVectorNumElements();
1832 int NumMaskElts = getMask()->getType()->getVectorNumElements();
1833 SmallVector<Constant*, 16> NewMask(NumMaskElts);
1834 Type *Int32Ty = Type::getInt32Ty(getContext());
1835 for (int i = 0; i != NumMaskElts; ++i) {
1836 int MaskElt = getMaskValue(i);
1837 if (MaskElt == -1) {
1838 NewMask[i] = UndefValue::get(Int32Ty);
1839 continue;
1841 assert(MaskElt >= 0 && MaskElt < 2 * NumOpElts && "Out-of-range mask");
1842 MaskElt = (MaskElt < NumOpElts) ? MaskElt + NumOpElts : MaskElt - NumOpElts;
1843 NewMask[i] = ConstantInt::get(Int32Ty, MaskElt);
1845 Op<2>() = ConstantVector::get(NewMask);
1846 Op<0>().swap(Op<1>());
1849 bool ShuffleVectorInst::isValidOperands(const Value *V1, const Value *V2,
1850 const Value *Mask) {
1851 // V1 and V2 must be vectors of the same type.
1852 if (!V1->getType()->isVectorTy() || V1->getType() != V2->getType())
1853 return false;
1855 // Mask must be vector of i32.
1856 auto *MaskTy = dyn_cast<VectorType>(Mask->getType());
1857 if (!MaskTy || !MaskTy->getElementType()->isIntegerTy(32))
1858 return false;
1860 // Check to see if Mask is valid.
1861 if (isa<UndefValue>(Mask) || isa<ConstantAggregateZero>(Mask))
1862 return true;
1864 if (const auto *MV = dyn_cast<ConstantVector>(Mask)) {
1865 unsigned V1Size = cast<VectorType>(V1->getType())->getNumElements();
1866 for (Value *Op : MV->operands()) {
1867 if (auto *CI = dyn_cast<ConstantInt>(Op)) {
1868 if (CI->uge(V1Size*2))
1869 return false;
1870 } else if (!isa<UndefValue>(Op)) {
1871 return false;
1874 return true;
1877 if (const auto *CDS = dyn_cast<ConstantDataSequential>(Mask)) {
1878 unsigned V1Size = cast<VectorType>(V1->getType())->getNumElements();
1879 for (unsigned i = 0, e = MaskTy->getNumElements(); i != e; ++i)
1880 if (CDS->getElementAsInteger(i) >= V1Size*2)
1881 return false;
1882 return true;
1885 // The bitcode reader can create a place holder for a forward reference
1886 // used as the shuffle mask. When this occurs, the shuffle mask will
1887 // fall into this case and fail. To avoid this error, do this bit of
1888 // ugliness to allow such a mask pass.
1889 if (const auto *CE = dyn_cast<ConstantExpr>(Mask))
1890 if (CE->getOpcode() == Instruction::UserOp1)
1891 return true;
1893 return false;
1896 int ShuffleVectorInst::getMaskValue(const Constant *Mask, unsigned i) {
1897 assert(i < Mask->getType()->getVectorNumElements() && "Index out of range");
1898 if (auto *CDS = dyn_cast<ConstantDataSequential>(Mask))
1899 return CDS->getElementAsInteger(i);
1900 Constant *C = Mask->getAggregateElement(i);
1901 if (isa<UndefValue>(C))
1902 return -1;
1903 return cast<ConstantInt>(C)->getZExtValue();
1906 void ShuffleVectorInst::getShuffleMask(const Constant *Mask,
1907 SmallVectorImpl<int> &Result) {
1908 unsigned NumElts = Mask->getType()->getVectorNumElements();
1910 if (auto *CDS = dyn_cast<ConstantDataSequential>(Mask)) {
1911 for (unsigned i = 0; i != NumElts; ++i)
1912 Result.push_back(CDS->getElementAsInteger(i));
1913 return;
1915 for (unsigned i = 0; i != NumElts; ++i) {
1916 Constant *C = Mask->getAggregateElement(i);
1917 Result.push_back(isa<UndefValue>(C) ? -1 :
1918 cast<ConstantInt>(C)->getZExtValue());
1922 static bool isSingleSourceMaskImpl(ArrayRef<int> Mask, int NumOpElts) {
1923 assert(!Mask.empty() && "Shuffle mask must contain elements");
1924 bool UsesLHS = false;
1925 bool UsesRHS = false;
1926 for (int i = 0, NumMaskElts = Mask.size(); i < NumMaskElts; ++i) {
1927 if (Mask[i] == -1)
1928 continue;
1929 assert(Mask[i] >= 0 && Mask[i] < (NumOpElts * 2) &&
1930 "Out-of-bounds shuffle mask element");
1931 UsesLHS |= (Mask[i] < NumOpElts);
1932 UsesRHS |= (Mask[i] >= NumOpElts);
1933 if (UsesLHS && UsesRHS)
1934 return false;
1936 assert((UsesLHS ^ UsesRHS) && "Should have selected from exactly 1 source");
1937 return true;
1940 bool ShuffleVectorInst::isSingleSourceMask(ArrayRef<int> Mask) {
1941 // We don't have vector operand size information, so assume operands are the
1942 // same size as the mask.
1943 return isSingleSourceMaskImpl(Mask, Mask.size());
1946 static bool isIdentityMaskImpl(ArrayRef<int> Mask, int NumOpElts) {
1947 if (!isSingleSourceMaskImpl(Mask, NumOpElts))
1948 return false;
1949 for (int i = 0, NumMaskElts = Mask.size(); i < NumMaskElts; ++i) {
1950 if (Mask[i] == -1)
1951 continue;
1952 if (Mask[i] != i && Mask[i] != (NumOpElts + i))
1953 return false;
1955 return true;
1958 bool ShuffleVectorInst::isIdentityMask(ArrayRef<int> Mask) {
1959 // We don't have vector operand size information, so assume operands are the
1960 // same size as the mask.
1961 return isIdentityMaskImpl(Mask, Mask.size());
1964 bool ShuffleVectorInst::isReverseMask(ArrayRef<int> Mask) {
1965 if (!isSingleSourceMask(Mask))
1966 return false;
1967 for (int i = 0, NumElts = Mask.size(); i < NumElts; ++i) {
1968 if (Mask[i] == -1)
1969 continue;
1970 if (Mask[i] != (NumElts - 1 - i) && Mask[i] != (NumElts + NumElts - 1 - i))
1971 return false;
1973 return true;
1976 bool ShuffleVectorInst::isZeroEltSplatMask(ArrayRef<int> Mask) {
1977 if (!isSingleSourceMask(Mask))
1978 return false;
1979 for (int i = 0, NumElts = Mask.size(); i < NumElts; ++i) {
1980 if (Mask[i] == -1)
1981 continue;
1982 if (Mask[i] != 0 && Mask[i] != NumElts)
1983 return false;
1985 return true;
1988 bool ShuffleVectorInst::isSelectMask(ArrayRef<int> Mask) {
1989 // Select is differentiated from identity. It requires using both sources.
1990 if (isSingleSourceMask(Mask))
1991 return false;
1992 for (int i = 0, NumElts = Mask.size(); i < NumElts; ++i) {
1993 if (Mask[i] == -1)
1994 continue;
1995 if (Mask[i] != i && Mask[i] != (NumElts + i))
1996 return false;
1998 return true;
2001 bool ShuffleVectorInst::isTransposeMask(ArrayRef<int> Mask) {
2002 // Example masks that will return true:
2003 // v1 = <a, b, c, d>
2004 // v2 = <e, f, g, h>
2005 // trn1 = shufflevector v1, v2 <0, 4, 2, 6> = <a, e, c, g>
2006 // trn2 = shufflevector v1, v2 <1, 5, 3, 7> = <b, f, d, h>
2008 // 1. The number of elements in the mask must be a power-of-2 and at least 2.
2009 int NumElts = Mask.size();
2010 if (NumElts < 2 || !isPowerOf2_32(NumElts))
2011 return false;
2013 // 2. The first element of the mask must be either a 0 or a 1.
2014 if (Mask[0] != 0 && Mask[0] != 1)
2015 return false;
2017 // 3. The difference between the first 2 elements must be equal to the
2018 // number of elements in the mask.
2019 if ((Mask[1] - Mask[0]) != NumElts)
2020 return false;
2022 // 4. The difference between consecutive even-numbered and odd-numbered
2023 // elements must be equal to 2.
2024 for (int i = 2; i < NumElts; ++i) {
2025 int MaskEltVal = Mask[i];
2026 if (MaskEltVal == -1)
2027 return false;
2028 int MaskEltPrevVal = Mask[i - 2];
2029 if (MaskEltVal - MaskEltPrevVal != 2)
2030 return false;
2032 return true;
2035 bool ShuffleVectorInst::isExtractSubvectorMask(ArrayRef<int> Mask,
2036 int NumSrcElts, int &Index) {
2037 // Must extract from a single source.
2038 if (!isSingleSourceMaskImpl(Mask, NumSrcElts))
2039 return false;
2041 // Must be smaller (else this is an Identity shuffle).
2042 if (NumSrcElts <= (int)Mask.size())
2043 return false;
2045 // Find start of extraction, accounting that we may start with an UNDEF.
2046 int SubIndex = -1;
2047 for (int i = 0, e = Mask.size(); i != e; ++i) {
2048 int M = Mask[i];
2049 if (M < 0)
2050 continue;
2051 int Offset = (M % NumSrcElts) - i;
2052 if (0 <= SubIndex && SubIndex != Offset)
2053 return false;
2054 SubIndex = Offset;
2057 if (0 <= SubIndex) {
2058 Index = SubIndex;
2059 return true;
2061 return false;
2064 bool ShuffleVectorInst::isIdentityWithPadding() const {
2065 int NumOpElts = Op<0>()->getType()->getVectorNumElements();
2066 int NumMaskElts = getType()->getVectorNumElements();
2067 if (NumMaskElts <= NumOpElts)
2068 return false;
2070 // The first part of the mask must choose elements from exactly 1 source op.
2071 SmallVector<int, 16> Mask = getShuffleMask();
2072 if (!isIdentityMaskImpl(Mask, NumOpElts))
2073 return false;
2075 // All extending must be with undef elements.
2076 for (int i = NumOpElts; i < NumMaskElts; ++i)
2077 if (Mask[i] != -1)
2078 return false;
2080 return true;
2083 bool ShuffleVectorInst::isIdentityWithExtract() const {
2084 int NumOpElts = Op<0>()->getType()->getVectorNumElements();
2085 int NumMaskElts = getType()->getVectorNumElements();
2086 if (NumMaskElts >= NumOpElts)
2087 return false;
2089 return isIdentityMaskImpl(getShuffleMask(), NumOpElts);
2092 bool ShuffleVectorInst::isConcat() const {
2093 // Vector concatenation is differentiated from identity with padding.
2094 if (isa<UndefValue>(Op<0>()) || isa<UndefValue>(Op<1>()))
2095 return false;
2097 int NumOpElts = Op<0>()->getType()->getVectorNumElements();
2098 int NumMaskElts = getType()->getVectorNumElements();
2099 if (NumMaskElts != NumOpElts * 2)
2100 return false;
2102 // Use the mask length rather than the operands' vector lengths here. We
2103 // already know that the shuffle returns a vector twice as long as the inputs,
2104 // and neither of the inputs are undef vectors. If the mask picks consecutive
2105 // elements from both inputs, then this is a concatenation of the inputs.
2106 return isIdentityMaskImpl(getShuffleMask(), NumMaskElts);
2109 //===----------------------------------------------------------------------===//
2110 // InsertValueInst Class
2111 //===----------------------------------------------------------------------===//
2113 void InsertValueInst::init(Value *Agg, Value *Val, ArrayRef<unsigned> Idxs,
2114 const Twine &Name) {
2115 assert(getNumOperands() == 2 && "NumOperands not initialized?");
2117 // There's no fundamental reason why we require at least one index
2118 // (other than weirdness with &*IdxBegin being invalid; see
2119 // getelementptr's init routine for example). But there's no
2120 // present need to support it.
2121 assert(!Idxs.empty() && "InsertValueInst must have at least one index");
2123 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs) ==
2124 Val->getType() && "Inserted value must match indexed type!");
2125 Op<0>() = Agg;
2126 Op<1>() = Val;
2128 Indices.append(Idxs.begin(), Idxs.end());
2129 setName(Name);
2132 InsertValueInst::InsertValueInst(const InsertValueInst &IVI)
2133 : Instruction(IVI.getType(), InsertValue,
2134 OperandTraits<InsertValueInst>::op_begin(this), 2),
2135 Indices(IVI.Indices) {
2136 Op<0>() = IVI.getOperand(0);
2137 Op<1>() = IVI.getOperand(1);
2138 SubclassOptionalData = IVI.SubclassOptionalData;
2141 //===----------------------------------------------------------------------===//
2142 // ExtractValueInst Class
2143 //===----------------------------------------------------------------------===//
2145 void ExtractValueInst::init(ArrayRef<unsigned> Idxs, const Twine &Name) {
2146 assert(getNumOperands() == 1 && "NumOperands not initialized?");
2148 // There's no fundamental reason why we require at least one index.
2149 // But there's no present need to support it.
2150 assert(!Idxs.empty() && "ExtractValueInst must have at least one index");
2152 Indices.append(Idxs.begin(), Idxs.end());
2153 setName(Name);
2156 ExtractValueInst::ExtractValueInst(const ExtractValueInst &EVI)
2157 : UnaryInstruction(EVI.getType(), ExtractValue, EVI.getOperand(0)),
2158 Indices(EVI.Indices) {
2159 SubclassOptionalData = EVI.SubclassOptionalData;
2162 // getIndexedType - Returns the type of the element that would be extracted
2163 // with an extractvalue instruction with the specified parameters.
2165 // A null type is returned if the indices are invalid for the specified
2166 // pointer type.
2168 Type *ExtractValueInst::getIndexedType(Type *Agg,
2169 ArrayRef<unsigned> Idxs) {
2170 for (unsigned Index : Idxs) {
2171 // We can't use CompositeType::indexValid(Index) here.
2172 // indexValid() always returns true for arrays because getelementptr allows
2173 // out-of-bounds indices. Since we don't allow those for extractvalue and
2174 // insertvalue we need to check array indexing manually.
2175 // Since the only other types we can index into are struct types it's just
2176 // as easy to check those manually as well.
2177 if (ArrayType *AT = dyn_cast<ArrayType>(Agg)) {
2178 if (Index >= AT->getNumElements())
2179 return nullptr;
2180 } else if (StructType *ST = dyn_cast<StructType>(Agg)) {
2181 if (Index >= ST->getNumElements())
2182 return nullptr;
2183 } else {
2184 // Not a valid type to index into.
2185 return nullptr;
2188 Agg = cast<CompositeType>(Agg)->getTypeAtIndex(Index);
2190 return const_cast<Type*>(Agg);
2193 //===----------------------------------------------------------------------===//
2194 // UnaryOperator Class
2195 //===----------------------------------------------------------------------===//
2197 UnaryOperator::UnaryOperator(UnaryOps iType, Value *S,
2198 Type *Ty, const Twine &Name,
2199 Instruction *InsertBefore)
2200 : UnaryInstruction(Ty, iType, S, InsertBefore) {
2201 Op<0>() = S;
2202 setName(Name);
2203 AssertOK();
2206 UnaryOperator::UnaryOperator(UnaryOps iType, Value *S,
2207 Type *Ty, const Twine &Name,
2208 BasicBlock *InsertAtEnd)
2209 : UnaryInstruction(Ty, iType, S, InsertAtEnd) {
2210 Op<0>() = S;
2211 setName(Name);
2212 AssertOK();
2215 UnaryOperator *UnaryOperator::Create(UnaryOps Op, Value *S,
2216 const Twine &Name,
2217 Instruction *InsertBefore) {
2218 return new UnaryOperator(Op, S, S->getType(), Name, InsertBefore);
2221 UnaryOperator *UnaryOperator::Create(UnaryOps Op, Value *S,
2222 const Twine &Name,
2223 BasicBlock *InsertAtEnd) {
2224 UnaryOperator *Res = Create(Op, S, Name);
2225 InsertAtEnd->getInstList().push_back(Res);
2226 return Res;
2229 void UnaryOperator::AssertOK() {
2230 Value *LHS = getOperand(0);
2231 (void)LHS; // Silence warnings.
2232 #ifndef NDEBUG
2233 switch (getOpcode()) {
2234 case FNeg:
2235 assert(getType() == LHS->getType() &&
2236 "Unary operation should return same type as operand!");
2237 assert(getType()->isFPOrFPVectorTy() &&
2238 "Tried to create a floating-point operation on a "
2239 "non-floating-point type!");
2240 break;
2241 default: llvm_unreachable("Invalid opcode provided");
2243 #endif
2246 //===----------------------------------------------------------------------===//
2247 // BinaryOperator Class
2248 //===----------------------------------------------------------------------===//
2250 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
2251 Type *Ty, const Twine &Name,
2252 Instruction *InsertBefore)
2253 : Instruction(Ty, iType,
2254 OperandTraits<BinaryOperator>::op_begin(this),
2255 OperandTraits<BinaryOperator>::operands(this),
2256 InsertBefore) {
2257 Op<0>() = S1;
2258 Op<1>() = S2;
2259 setName(Name);
2260 AssertOK();
2263 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
2264 Type *Ty, const Twine &Name,
2265 BasicBlock *InsertAtEnd)
2266 : Instruction(Ty, iType,
2267 OperandTraits<BinaryOperator>::op_begin(this),
2268 OperandTraits<BinaryOperator>::operands(this),
2269 InsertAtEnd) {
2270 Op<0>() = S1;
2271 Op<1>() = S2;
2272 setName(Name);
2273 AssertOK();
2276 void BinaryOperator::AssertOK() {
2277 Value *LHS = getOperand(0), *RHS = getOperand(1);
2278 (void)LHS; (void)RHS; // Silence warnings.
2279 assert(LHS->getType() == RHS->getType() &&
2280 "Binary operator operand types must match!");
2281 #ifndef NDEBUG
2282 switch (getOpcode()) {
2283 case Add: case Sub:
2284 case Mul:
2285 assert(getType() == LHS->getType() &&
2286 "Arithmetic operation should return same type as operands!");
2287 assert(getType()->isIntOrIntVectorTy() &&
2288 "Tried to create an integer operation on a non-integer type!");
2289 break;
2290 case FAdd: case FSub:
2291 case FMul:
2292 assert(getType() == LHS->getType() &&
2293 "Arithmetic operation should return same type as operands!");
2294 assert(getType()->isFPOrFPVectorTy() &&
2295 "Tried to create a floating-point operation on a "
2296 "non-floating-point type!");
2297 break;
2298 case UDiv:
2299 case SDiv:
2300 assert(getType() == LHS->getType() &&
2301 "Arithmetic operation should return same type as operands!");
2302 assert(getType()->isIntOrIntVectorTy() &&
2303 "Incorrect operand type (not integer) for S/UDIV");
2304 break;
2305 case FDiv:
2306 assert(getType() == LHS->getType() &&
2307 "Arithmetic operation should return same type as operands!");
2308 assert(getType()->isFPOrFPVectorTy() &&
2309 "Incorrect operand type (not floating point) for FDIV");
2310 break;
2311 case URem:
2312 case SRem:
2313 assert(getType() == LHS->getType() &&
2314 "Arithmetic operation should return same type as operands!");
2315 assert(getType()->isIntOrIntVectorTy() &&
2316 "Incorrect operand type (not integer) for S/UREM");
2317 break;
2318 case FRem:
2319 assert(getType() == LHS->getType() &&
2320 "Arithmetic operation should return same type as operands!");
2321 assert(getType()->isFPOrFPVectorTy() &&
2322 "Incorrect operand type (not floating point) for FREM");
2323 break;
2324 case Shl:
2325 case LShr:
2326 case AShr:
2327 assert(getType() == LHS->getType() &&
2328 "Shift operation should return same type as operands!");
2329 assert(getType()->isIntOrIntVectorTy() &&
2330 "Tried to create a shift operation on a non-integral type!");
2331 break;
2332 case And: case Or:
2333 case Xor:
2334 assert(getType() == LHS->getType() &&
2335 "Logical operation should return same type as operands!");
2336 assert(getType()->isIntOrIntVectorTy() &&
2337 "Tried to create a logical operation on a non-integral type!");
2338 break;
2339 default: llvm_unreachable("Invalid opcode provided");
2341 #endif
2344 BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2,
2345 const Twine &Name,
2346 Instruction *InsertBefore) {
2347 assert(S1->getType() == S2->getType() &&
2348 "Cannot create binary operator with two operands of differing type!");
2349 return new BinaryOperator(Op, S1, S2, S1->getType(), Name, InsertBefore);
2352 BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2,
2353 const Twine &Name,
2354 BasicBlock *InsertAtEnd) {
2355 BinaryOperator *Res = Create(Op, S1, S2, Name);
2356 InsertAtEnd->getInstList().push_back(Res);
2357 return Res;
2360 BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const Twine &Name,
2361 Instruction *InsertBefore) {
2362 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
2363 return new BinaryOperator(Instruction::Sub,
2364 zero, Op,
2365 Op->getType(), Name, InsertBefore);
2368 BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const Twine &Name,
2369 BasicBlock *InsertAtEnd) {
2370 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
2371 return new BinaryOperator(Instruction::Sub,
2372 zero, Op,
2373 Op->getType(), Name, InsertAtEnd);
2376 BinaryOperator *BinaryOperator::CreateNSWNeg(Value *Op, const Twine &Name,
2377 Instruction *InsertBefore) {
2378 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
2379 return BinaryOperator::CreateNSWSub(zero, Op, Name, InsertBefore);
2382 BinaryOperator *BinaryOperator::CreateNSWNeg(Value *Op, const Twine &Name,
2383 BasicBlock *InsertAtEnd) {
2384 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
2385 return BinaryOperator::CreateNSWSub(zero, Op, Name, InsertAtEnd);
2388 BinaryOperator *BinaryOperator::CreateNUWNeg(Value *Op, const Twine &Name,
2389 Instruction *InsertBefore) {
2390 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
2391 return BinaryOperator::CreateNUWSub(zero, Op, Name, InsertBefore);
2394 BinaryOperator *BinaryOperator::CreateNUWNeg(Value *Op, const Twine &Name,
2395 BasicBlock *InsertAtEnd) {
2396 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
2397 return BinaryOperator::CreateNUWSub(zero, Op, Name, InsertAtEnd);
2400 BinaryOperator *BinaryOperator::CreateFNeg(Value *Op, const Twine &Name,
2401 Instruction *InsertBefore) {
2402 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
2403 return new BinaryOperator(Instruction::FSub, zero, Op,
2404 Op->getType(), Name, InsertBefore);
2407 BinaryOperator *BinaryOperator::CreateFNeg(Value *Op, const Twine &Name,
2408 BasicBlock *InsertAtEnd) {
2409 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
2410 return new BinaryOperator(Instruction::FSub, zero, Op,
2411 Op->getType(), Name, InsertAtEnd);
2414 BinaryOperator *BinaryOperator::CreateNot(Value *Op, const Twine &Name,
2415 Instruction *InsertBefore) {
2416 Constant *C = Constant::getAllOnesValue(Op->getType());
2417 return new BinaryOperator(Instruction::Xor, Op, C,
2418 Op->getType(), Name, InsertBefore);
2421 BinaryOperator *BinaryOperator::CreateNot(Value *Op, const Twine &Name,
2422 BasicBlock *InsertAtEnd) {
2423 Constant *AllOnes = Constant::getAllOnesValue(Op->getType());
2424 return new BinaryOperator(Instruction::Xor, Op, AllOnes,
2425 Op->getType(), Name, InsertAtEnd);
2428 // Exchange the two operands to this instruction. This instruction is safe to
2429 // use on any binary instruction and does not modify the semantics of the
2430 // instruction. If the instruction is order-dependent (SetLT f.e.), the opcode
2431 // is changed.
2432 bool BinaryOperator::swapOperands() {
2433 if (!isCommutative())
2434 return true; // Can't commute operands
2435 Op<0>().swap(Op<1>());
2436 return false;
2439 //===----------------------------------------------------------------------===//
2440 // FPMathOperator Class
2441 //===----------------------------------------------------------------------===//
2443 float FPMathOperator::getFPAccuracy() const {
2444 const MDNode *MD =
2445 cast<Instruction>(this)->getMetadata(LLVMContext::MD_fpmath);
2446 if (!MD)
2447 return 0.0;
2448 ConstantFP *Accuracy = mdconst::extract<ConstantFP>(MD->getOperand(0));
2449 return Accuracy->getValueAPF().convertToFloat();
2452 //===----------------------------------------------------------------------===//
2453 // CastInst Class
2454 //===----------------------------------------------------------------------===//
2456 // Just determine if this cast only deals with integral->integral conversion.
2457 bool CastInst::isIntegerCast() const {
2458 switch (getOpcode()) {
2459 default: return false;
2460 case Instruction::ZExt:
2461 case Instruction::SExt:
2462 case Instruction::Trunc:
2463 return true;
2464 case Instruction::BitCast:
2465 return getOperand(0)->getType()->isIntegerTy() &&
2466 getType()->isIntegerTy();
2470 bool CastInst::isLosslessCast() const {
2471 // Only BitCast can be lossless, exit fast if we're not BitCast
2472 if (getOpcode() != Instruction::BitCast)
2473 return false;
2475 // Identity cast is always lossless
2476 Type *SrcTy = getOperand(0)->getType();
2477 Type *DstTy = getType();
2478 if (SrcTy == DstTy)
2479 return true;
2481 // Pointer to pointer is always lossless.
2482 if (SrcTy->isPointerTy())
2483 return DstTy->isPointerTy();
2484 return false; // Other types have no identity values
2487 /// This function determines if the CastInst does not require any bits to be
2488 /// changed in order to effect the cast. Essentially, it identifies cases where
2489 /// no code gen is necessary for the cast, hence the name no-op cast. For
2490 /// example, the following are all no-op casts:
2491 /// # bitcast i32* %x to i8*
2492 /// # bitcast <2 x i32> %x to <4 x i16>
2493 /// # ptrtoint i32* %x to i32 ; on 32-bit plaforms only
2494 /// Determine if the described cast is a no-op.
2495 bool CastInst::isNoopCast(Instruction::CastOps Opcode,
2496 Type *SrcTy,
2497 Type *DestTy,
2498 const DataLayout &DL) {
2499 switch (Opcode) {
2500 default: llvm_unreachable("Invalid CastOp");
2501 case Instruction::Trunc:
2502 case Instruction::ZExt:
2503 case Instruction::SExt:
2504 case Instruction::FPTrunc:
2505 case Instruction::FPExt:
2506 case Instruction::UIToFP:
2507 case Instruction::SIToFP:
2508 case Instruction::FPToUI:
2509 case Instruction::FPToSI:
2510 case Instruction::AddrSpaceCast:
2511 // TODO: Target informations may give a more accurate answer here.
2512 return false;
2513 case Instruction::BitCast:
2514 return true; // BitCast never modifies bits.
2515 case Instruction::PtrToInt:
2516 return DL.getIntPtrType(SrcTy)->getScalarSizeInBits() ==
2517 DestTy->getScalarSizeInBits();
2518 case Instruction::IntToPtr:
2519 return DL.getIntPtrType(DestTy)->getScalarSizeInBits() ==
2520 SrcTy->getScalarSizeInBits();
2524 bool CastInst::isNoopCast(const DataLayout &DL) const {
2525 return isNoopCast(getOpcode(), getOperand(0)->getType(), getType(), DL);
2528 /// This function determines if a pair of casts can be eliminated and what
2529 /// opcode should be used in the elimination. This assumes that there are two
2530 /// instructions like this:
2531 /// * %F = firstOpcode SrcTy %x to MidTy
2532 /// * %S = secondOpcode MidTy %F to DstTy
2533 /// The function returns a resultOpcode so these two casts can be replaced with:
2534 /// * %Replacement = resultOpcode %SrcTy %x to DstTy
2535 /// If no such cast is permitted, the function returns 0.
2536 unsigned CastInst::isEliminableCastPair(
2537 Instruction::CastOps firstOp, Instruction::CastOps secondOp,
2538 Type *SrcTy, Type *MidTy, Type *DstTy, Type *SrcIntPtrTy, Type *MidIntPtrTy,
2539 Type *DstIntPtrTy) {
2540 // Define the 144 possibilities for these two cast instructions. The values
2541 // in this matrix determine what to do in a given situation and select the
2542 // case in the switch below. The rows correspond to firstOp, the columns
2543 // correspond to secondOp. In looking at the table below, keep in mind
2544 // the following cast properties:
2546 // Size Compare Source Destination
2547 // Operator Src ? Size Type Sign Type Sign
2548 // -------- ------------ ------------------- ---------------------
2549 // TRUNC > Integer Any Integral Any
2550 // ZEXT < Integral Unsigned Integer Any
2551 // SEXT < Integral Signed Integer Any
2552 // FPTOUI n/a FloatPt n/a Integral Unsigned
2553 // FPTOSI n/a FloatPt n/a Integral Signed
2554 // UITOFP n/a Integral Unsigned FloatPt n/a
2555 // SITOFP n/a Integral Signed FloatPt n/a
2556 // FPTRUNC > FloatPt n/a FloatPt n/a
2557 // FPEXT < FloatPt n/a FloatPt n/a
2558 // PTRTOINT n/a Pointer n/a Integral Unsigned
2559 // INTTOPTR n/a Integral Unsigned Pointer n/a
2560 // BITCAST = FirstClass n/a FirstClass n/a
2561 // ADDRSPCST n/a Pointer n/a Pointer n/a
2563 // NOTE: some transforms are safe, but we consider them to be non-profitable.
2564 // For example, we could merge "fptoui double to i32" + "zext i32 to i64",
2565 // into "fptoui double to i64", but this loses information about the range
2566 // of the produced value (we no longer know the top-part is all zeros).
2567 // Further this conversion is often much more expensive for typical hardware,
2568 // and causes issues when building libgcc. We disallow fptosi+sext for the
2569 // same reason.
2570 const unsigned numCastOps =
2571 Instruction::CastOpsEnd - Instruction::CastOpsBegin;
2572 static const uint8_t CastResults[numCastOps][numCastOps] = {
2573 // T F F U S F F P I B A -+
2574 // R Z S P P I I T P 2 N T S |
2575 // U E E 2 2 2 2 R E I T C C +- secondOp
2576 // N X X U S F F N X N 2 V V |
2577 // C T T I I P P C T T P T T -+
2578 { 1, 0, 0,99,99, 0, 0,99,99,99, 0, 3, 0}, // Trunc -+
2579 { 8, 1, 9,99,99, 2,17,99,99,99, 2, 3, 0}, // ZExt |
2580 { 8, 0, 1,99,99, 0, 2,99,99,99, 0, 3, 0}, // SExt |
2581 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3, 0}, // FPToUI |
2582 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3, 0}, // FPToSI |
2583 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4, 0}, // UIToFP +- firstOp
2584 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4, 0}, // SIToFP |
2585 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4, 0}, // FPTrunc |
2586 { 99,99,99, 2, 2,99,99, 8, 2,99,99, 4, 0}, // FPExt |
2587 { 1, 0, 0,99,99, 0, 0,99,99,99, 7, 3, 0}, // PtrToInt |
2588 { 99,99,99,99,99,99,99,99,99,11,99,15, 0}, // IntToPtr |
2589 { 5, 5, 5, 6, 6, 5, 5, 6, 6,16, 5, 1,14}, // BitCast |
2590 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,13,12}, // AddrSpaceCast -+
2593 // TODO: This logic could be encoded into the table above and handled in the
2594 // switch below.
2595 // If either of the casts are a bitcast from scalar to vector, disallow the
2596 // merging. However, any pair of bitcasts are allowed.
2597 bool IsFirstBitcast = (firstOp == Instruction::BitCast);
2598 bool IsSecondBitcast = (secondOp == Instruction::BitCast);
2599 bool AreBothBitcasts = IsFirstBitcast && IsSecondBitcast;
2601 // Check if any of the casts convert scalars <-> vectors.
2602 if ((IsFirstBitcast && isa<VectorType>(SrcTy) != isa<VectorType>(MidTy)) ||
2603 (IsSecondBitcast && isa<VectorType>(MidTy) != isa<VectorType>(DstTy)))
2604 if (!AreBothBitcasts)
2605 return 0;
2607 int ElimCase = CastResults[firstOp-Instruction::CastOpsBegin]
2608 [secondOp-Instruction::CastOpsBegin];
2609 switch (ElimCase) {
2610 case 0:
2611 // Categorically disallowed.
2612 return 0;
2613 case 1:
2614 // Allowed, use first cast's opcode.
2615 return firstOp;
2616 case 2:
2617 // Allowed, use second cast's opcode.
2618 return secondOp;
2619 case 3:
2620 // No-op cast in second op implies firstOp as long as the DestTy
2621 // is integer and we are not converting between a vector and a
2622 // non-vector type.
2623 if (!SrcTy->isVectorTy() && DstTy->isIntegerTy())
2624 return firstOp;
2625 return 0;
2626 case 4:
2627 // No-op cast in second op implies firstOp as long as the DestTy
2628 // is floating point.
2629 if (DstTy->isFloatingPointTy())
2630 return firstOp;
2631 return 0;
2632 case 5:
2633 // No-op cast in first op implies secondOp as long as the SrcTy
2634 // is an integer.
2635 if (SrcTy->isIntegerTy())
2636 return secondOp;
2637 return 0;
2638 case 6:
2639 // No-op cast in first op implies secondOp as long as the SrcTy
2640 // is a floating point.
2641 if (SrcTy->isFloatingPointTy())
2642 return secondOp;
2643 return 0;
2644 case 7: {
2645 // Cannot simplify if address spaces are different!
2646 if (SrcTy->getPointerAddressSpace() != DstTy->getPointerAddressSpace())
2647 return 0;
2649 unsigned MidSize = MidTy->getScalarSizeInBits();
2650 // We can still fold this without knowing the actual sizes as long we
2651 // know that the intermediate pointer is the largest possible
2652 // pointer size.
2653 // FIXME: Is this always true?
2654 if (MidSize == 64)
2655 return Instruction::BitCast;
2657 // ptrtoint, inttoptr -> bitcast (ptr -> ptr) if int size is >= ptr size.
2658 if (!SrcIntPtrTy || DstIntPtrTy != SrcIntPtrTy)
2659 return 0;
2660 unsigned PtrSize = SrcIntPtrTy->getScalarSizeInBits();
2661 if (MidSize >= PtrSize)
2662 return Instruction::BitCast;
2663 return 0;
2665 case 8: {
2666 // ext, trunc -> bitcast, if the SrcTy and DstTy are same size
2667 // ext, trunc -> ext, if sizeof(SrcTy) < sizeof(DstTy)
2668 // ext, trunc -> trunc, if sizeof(SrcTy) > sizeof(DstTy)
2669 unsigned SrcSize = SrcTy->getScalarSizeInBits();
2670 unsigned DstSize = DstTy->getScalarSizeInBits();
2671 if (SrcSize == DstSize)
2672 return Instruction::BitCast;
2673 else if (SrcSize < DstSize)
2674 return firstOp;
2675 return secondOp;
2677 case 9:
2678 // zext, sext -> zext, because sext can't sign extend after zext
2679 return Instruction::ZExt;
2680 case 11: {
2681 // inttoptr, ptrtoint -> bitcast if SrcSize<=PtrSize and SrcSize==DstSize
2682 if (!MidIntPtrTy)
2683 return 0;
2684 unsigned PtrSize = MidIntPtrTy->getScalarSizeInBits();
2685 unsigned SrcSize = SrcTy->getScalarSizeInBits();
2686 unsigned DstSize = DstTy->getScalarSizeInBits();
2687 if (SrcSize <= PtrSize && SrcSize == DstSize)
2688 return Instruction::BitCast;
2689 return 0;
2691 case 12:
2692 // addrspacecast, addrspacecast -> bitcast, if SrcAS == DstAS
2693 // addrspacecast, addrspacecast -> addrspacecast, if SrcAS != DstAS
2694 if (SrcTy->getPointerAddressSpace() != DstTy->getPointerAddressSpace())
2695 return Instruction::AddrSpaceCast;
2696 return Instruction::BitCast;
2697 case 13:
2698 // FIXME: this state can be merged with (1), but the following assert
2699 // is useful to check the correcteness of the sequence due to semantic
2700 // change of bitcast.
2701 assert(
2702 SrcTy->isPtrOrPtrVectorTy() &&
2703 MidTy->isPtrOrPtrVectorTy() &&
2704 DstTy->isPtrOrPtrVectorTy() &&
2705 SrcTy->getPointerAddressSpace() != MidTy->getPointerAddressSpace() &&
2706 MidTy->getPointerAddressSpace() == DstTy->getPointerAddressSpace() &&
2707 "Illegal addrspacecast, bitcast sequence!");
2708 // Allowed, use first cast's opcode
2709 return firstOp;
2710 case 14:
2711 // bitcast, addrspacecast -> addrspacecast if the element type of
2712 // bitcast's source is the same as that of addrspacecast's destination.
2713 if (SrcTy->getScalarType()->getPointerElementType() ==
2714 DstTy->getScalarType()->getPointerElementType())
2715 return Instruction::AddrSpaceCast;
2716 return 0;
2717 case 15:
2718 // FIXME: this state can be merged with (1), but the following assert
2719 // is useful to check the correcteness of the sequence due to semantic
2720 // change of bitcast.
2721 assert(
2722 SrcTy->isIntOrIntVectorTy() &&
2723 MidTy->isPtrOrPtrVectorTy() &&
2724 DstTy->isPtrOrPtrVectorTy() &&
2725 MidTy->getPointerAddressSpace() == DstTy->getPointerAddressSpace() &&
2726 "Illegal inttoptr, bitcast sequence!");
2727 // Allowed, use first cast's opcode
2728 return firstOp;
2729 case 16:
2730 // FIXME: this state can be merged with (2), but the following assert
2731 // is useful to check the correcteness of the sequence due to semantic
2732 // change of bitcast.
2733 assert(
2734 SrcTy->isPtrOrPtrVectorTy() &&
2735 MidTy->isPtrOrPtrVectorTy() &&
2736 DstTy->isIntOrIntVectorTy() &&
2737 SrcTy->getPointerAddressSpace() == MidTy->getPointerAddressSpace() &&
2738 "Illegal bitcast, ptrtoint sequence!");
2739 // Allowed, use second cast's opcode
2740 return secondOp;
2741 case 17:
2742 // (sitofp (zext x)) -> (uitofp x)
2743 return Instruction::UIToFP;
2744 case 99:
2745 // Cast combination can't happen (error in input). This is for all cases
2746 // where the MidTy is not the same for the two cast instructions.
2747 llvm_unreachable("Invalid Cast Combination");
2748 default:
2749 llvm_unreachable("Error in CastResults table!!!");
2753 CastInst *CastInst::Create(Instruction::CastOps op, Value *S, Type *Ty,
2754 const Twine &Name, Instruction *InsertBefore) {
2755 assert(castIsValid(op, S, Ty) && "Invalid cast!");
2756 // Construct and return the appropriate CastInst subclass
2757 switch (op) {
2758 case Trunc: return new TruncInst (S, Ty, Name, InsertBefore);
2759 case ZExt: return new ZExtInst (S, Ty, Name, InsertBefore);
2760 case SExt: return new SExtInst (S, Ty, Name, InsertBefore);
2761 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertBefore);
2762 case FPExt: return new FPExtInst (S, Ty, Name, InsertBefore);
2763 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertBefore);
2764 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertBefore);
2765 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertBefore);
2766 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertBefore);
2767 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertBefore);
2768 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertBefore);
2769 case BitCast: return new BitCastInst (S, Ty, Name, InsertBefore);
2770 case AddrSpaceCast: return new AddrSpaceCastInst (S, Ty, Name, InsertBefore);
2771 default: llvm_unreachable("Invalid opcode provided");
2775 CastInst *CastInst::Create(Instruction::CastOps op, Value *S, Type *Ty,
2776 const Twine &Name, BasicBlock *InsertAtEnd) {
2777 assert(castIsValid(op, S, Ty) && "Invalid cast!");
2778 // Construct and return the appropriate CastInst subclass
2779 switch (op) {
2780 case Trunc: return new TruncInst (S, Ty, Name, InsertAtEnd);
2781 case ZExt: return new ZExtInst (S, Ty, Name, InsertAtEnd);
2782 case SExt: return new SExtInst (S, Ty, Name, InsertAtEnd);
2783 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertAtEnd);
2784 case FPExt: return new FPExtInst (S, Ty, Name, InsertAtEnd);
2785 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertAtEnd);
2786 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertAtEnd);
2787 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertAtEnd);
2788 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertAtEnd);
2789 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertAtEnd);
2790 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertAtEnd);
2791 case BitCast: return new BitCastInst (S, Ty, Name, InsertAtEnd);
2792 case AddrSpaceCast: return new AddrSpaceCastInst (S, Ty, Name, InsertAtEnd);
2793 default: llvm_unreachable("Invalid opcode provided");
2797 CastInst *CastInst::CreateZExtOrBitCast(Value *S, Type *Ty,
2798 const Twine &Name,
2799 Instruction *InsertBefore) {
2800 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2801 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2802 return Create(Instruction::ZExt, S, Ty, Name, InsertBefore);
2805 CastInst *CastInst::CreateZExtOrBitCast(Value *S, Type *Ty,
2806 const Twine &Name,
2807 BasicBlock *InsertAtEnd) {
2808 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2809 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2810 return Create(Instruction::ZExt, S, Ty, Name, InsertAtEnd);
2813 CastInst *CastInst::CreateSExtOrBitCast(Value *S, Type *Ty,
2814 const Twine &Name,
2815 Instruction *InsertBefore) {
2816 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2817 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2818 return Create(Instruction::SExt, S, Ty, Name, InsertBefore);
2821 CastInst *CastInst::CreateSExtOrBitCast(Value *S, Type *Ty,
2822 const Twine &Name,
2823 BasicBlock *InsertAtEnd) {
2824 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2825 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2826 return Create(Instruction::SExt, S, Ty, Name, InsertAtEnd);
2829 CastInst *CastInst::CreateTruncOrBitCast(Value *S, Type *Ty,
2830 const Twine &Name,
2831 Instruction *InsertBefore) {
2832 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2833 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2834 return Create(Instruction::Trunc, S, Ty, Name, InsertBefore);
2837 CastInst *CastInst::CreateTruncOrBitCast(Value *S, Type *Ty,
2838 const Twine &Name,
2839 BasicBlock *InsertAtEnd) {
2840 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2841 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2842 return Create(Instruction::Trunc, S, Ty, Name, InsertAtEnd);
2845 CastInst *CastInst::CreatePointerCast(Value *S, Type *Ty,
2846 const Twine &Name,
2847 BasicBlock *InsertAtEnd) {
2848 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
2849 assert((Ty->isIntOrIntVectorTy() || Ty->isPtrOrPtrVectorTy()) &&
2850 "Invalid cast");
2851 assert(Ty->isVectorTy() == S->getType()->isVectorTy() && "Invalid cast");
2852 assert((!Ty->isVectorTy() ||
2853 Ty->getVectorNumElements() == S->getType()->getVectorNumElements()) &&
2854 "Invalid cast");
2856 if (Ty->isIntOrIntVectorTy())
2857 return Create(Instruction::PtrToInt, S, Ty, Name, InsertAtEnd);
2859 return CreatePointerBitCastOrAddrSpaceCast(S, Ty, Name, InsertAtEnd);
2862 /// Create a BitCast or a PtrToInt cast instruction
2863 CastInst *CastInst::CreatePointerCast(Value *S, Type *Ty,
2864 const Twine &Name,
2865 Instruction *InsertBefore) {
2866 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
2867 assert((Ty->isIntOrIntVectorTy() || Ty->isPtrOrPtrVectorTy()) &&
2868 "Invalid cast");
2869 assert(Ty->isVectorTy() == S->getType()->isVectorTy() && "Invalid cast");
2870 assert((!Ty->isVectorTy() ||
2871 Ty->getVectorNumElements() == S->getType()->getVectorNumElements()) &&
2872 "Invalid cast");
2874 if (Ty->isIntOrIntVectorTy())
2875 return Create(Instruction::PtrToInt, S, Ty, Name, InsertBefore);
2877 return CreatePointerBitCastOrAddrSpaceCast(S, Ty, Name, InsertBefore);
2880 CastInst *CastInst::CreatePointerBitCastOrAddrSpaceCast(
2881 Value *S, Type *Ty,
2882 const Twine &Name,
2883 BasicBlock *InsertAtEnd) {
2884 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
2885 assert(Ty->isPtrOrPtrVectorTy() && "Invalid cast");
2887 if (S->getType()->getPointerAddressSpace() != Ty->getPointerAddressSpace())
2888 return Create(Instruction::AddrSpaceCast, S, Ty, Name, InsertAtEnd);
2890 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2893 CastInst *CastInst::CreatePointerBitCastOrAddrSpaceCast(
2894 Value *S, Type *Ty,
2895 const Twine &Name,
2896 Instruction *InsertBefore) {
2897 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
2898 assert(Ty->isPtrOrPtrVectorTy() && "Invalid cast");
2900 if (S->getType()->getPointerAddressSpace() != Ty->getPointerAddressSpace())
2901 return Create(Instruction::AddrSpaceCast, S, Ty, Name, InsertBefore);
2903 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2906 CastInst *CastInst::CreateBitOrPointerCast(Value *S, Type *Ty,
2907 const Twine &Name,
2908 Instruction *InsertBefore) {
2909 if (S->getType()->isPointerTy() && Ty->isIntegerTy())
2910 return Create(Instruction::PtrToInt, S, Ty, Name, InsertBefore);
2911 if (S->getType()->isIntegerTy() && Ty->isPointerTy())
2912 return Create(Instruction::IntToPtr, S, Ty, Name, InsertBefore);
2914 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2917 CastInst *CastInst::CreateIntegerCast(Value *C, Type *Ty,
2918 bool isSigned, const Twine &Name,
2919 Instruction *InsertBefore) {
2920 assert(C->getType()->isIntOrIntVectorTy() && Ty->isIntOrIntVectorTy() &&
2921 "Invalid integer cast");
2922 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2923 unsigned DstBits = Ty->getScalarSizeInBits();
2924 Instruction::CastOps opcode =
2925 (SrcBits == DstBits ? Instruction::BitCast :
2926 (SrcBits > DstBits ? Instruction::Trunc :
2927 (isSigned ? Instruction::SExt : Instruction::ZExt)));
2928 return Create(opcode, C, Ty, Name, InsertBefore);
2931 CastInst *CastInst::CreateIntegerCast(Value *C, Type *Ty,
2932 bool isSigned, const Twine &Name,
2933 BasicBlock *InsertAtEnd) {
2934 assert(C->getType()->isIntOrIntVectorTy() && Ty->isIntOrIntVectorTy() &&
2935 "Invalid cast");
2936 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2937 unsigned DstBits = Ty->getScalarSizeInBits();
2938 Instruction::CastOps opcode =
2939 (SrcBits == DstBits ? Instruction::BitCast :
2940 (SrcBits > DstBits ? Instruction::Trunc :
2941 (isSigned ? Instruction::SExt : Instruction::ZExt)));
2942 return Create(opcode, C, Ty, Name, InsertAtEnd);
2945 CastInst *CastInst::CreateFPCast(Value *C, Type *Ty,
2946 const Twine &Name,
2947 Instruction *InsertBefore) {
2948 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
2949 "Invalid cast");
2950 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2951 unsigned DstBits = Ty->getScalarSizeInBits();
2952 Instruction::CastOps opcode =
2953 (SrcBits == DstBits ? Instruction::BitCast :
2954 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
2955 return Create(opcode, C, Ty, Name, InsertBefore);
2958 CastInst *CastInst::CreateFPCast(Value *C, Type *Ty,
2959 const Twine &Name,
2960 BasicBlock *InsertAtEnd) {
2961 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
2962 "Invalid cast");
2963 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2964 unsigned DstBits = Ty->getScalarSizeInBits();
2965 Instruction::CastOps opcode =
2966 (SrcBits == DstBits ? Instruction::BitCast :
2967 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
2968 return Create(opcode, C, Ty, Name, InsertAtEnd);
2971 // Check whether it is valid to call getCastOpcode for these types.
2972 // This routine must be kept in sync with getCastOpcode.
2973 bool CastInst::isCastable(Type *SrcTy, Type *DestTy) {
2974 if (!SrcTy->isFirstClassType() || !DestTy->isFirstClassType())
2975 return false;
2977 if (SrcTy == DestTy)
2978 return true;
2980 if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy))
2981 if (VectorType *DestVecTy = dyn_cast<VectorType>(DestTy))
2982 if (SrcVecTy->getNumElements() == DestVecTy->getNumElements()) {
2983 // An element by element cast. Valid if casting the elements is valid.
2984 SrcTy = SrcVecTy->getElementType();
2985 DestTy = DestVecTy->getElementType();
2988 // Get the bit sizes, we'll need these
2989 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr
2990 unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr
2992 // Run through the possibilities ...
2993 if (DestTy->isIntegerTy()) { // Casting to integral
2994 if (SrcTy->isIntegerTy()) // Casting from integral
2995 return true;
2996 if (SrcTy->isFloatingPointTy()) // Casting from floating pt
2997 return true;
2998 if (SrcTy->isVectorTy()) // Casting from vector
2999 return DestBits == SrcBits;
3000 // Casting from something else
3001 return SrcTy->isPointerTy();
3003 if (DestTy->isFloatingPointTy()) { // Casting to floating pt
3004 if (SrcTy->isIntegerTy()) // Casting from integral
3005 return true;
3006 if (SrcTy->isFloatingPointTy()) // Casting from floating pt
3007 return true;
3008 if (SrcTy->isVectorTy()) // Casting from vector
3009 return DestBits == SrcBits;
3010 // Casting from something else
3011 return false;
3013 if (DestTy->isVectorTy()) // Casting to vector
3014 return DestBits == SrcBits;
3015 if (DestTy->isPointerTy()) { // Casting to pointer
3016 if (SrcTy->isPointerTy()) // Casting from pointer
3017 return true;
3018 return SrcTy->isIntegerTy(); // Casting from integral
3020 if (DestTy->isX86_MMXTy()) {
3021 if (SrcTy->isVectorTy())
3022 return DestBits == SrcBits; // 64-bit vector to MMX
3023 return false;
3024 } // Casting to something else
3025 return false;
3028 bool CastInst::isBitCastable(Type *SrcTy, Type *DestTy) {
3029 if (!SrcTy->isFirstClassType() || !DestTy->isFirstClassType())
3030 return false;
3032 if (SrcTy == DestTy)
3033 return true;
3035 if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy)) {
3036 if (VectorType *DestVecTy = dyn_cast<VectorType>(DestTy)) {
3037 if (SrcVecTy->getNumElements() == DestVecTy->getNumElements()) {
3038 // An element by element cast. Valid if casting the elements is valid.
3039 SrcTy = SrcVecTy->getElementType();
3040 DestTy = DestVecTy->getElementType();
3045 if (PointerType *DestPtrTy = dyn_cast<PointerType>(DestTy)) {
3046 if (PointerType *SrcPtrTy = dyn_cast<PointerType>(SrcTy)) {
3047 return SrcPtrTy->getAddressSpace() == DestPtrTy->getAddressSpace();
3051 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr
3052 unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr
3054 // Could still have vectors of pointers if the number of elements doesn't
3055 // match
3056 if (SrcBits == 0 || DestBits == 0)
3057 return false;
3059 if (SrcBits != DestBits)
3060 return false;
3062 if (DestTy->isX86_MMXTy() || SrcTy->isX86_MMXTy())
3063 return false;
3065 return true;
3068 bool CastInst::isBitOrNoopPointerCastable(Type *SrcTy, Type *DestTy,
3069 const DataLayout &DL) {
3070 // ptrtoint and inttoptr are not allowed on non-integral pointers
3071 if (auto *PtrTy = dyn_cast<PointerType>(SrcTy))
3072 if (auto *IntTy = dyn_cast<IntegerType>(DestTy))
3073 return (IntTy->getBitWidth() == DL.getPointerTypeSizeInBits(PtrTy) &&
3074 !DL.isNonIntegralPointerType(PtrTy));
3075 if (auto *PtrTy = dyn_cast<PointerType>(DestTy))
3076 if (auto *IntTy = dyn_cast<IntegerType>(SrcTy))
3077 return (IntTy->getBitWidth() == DL.getPointerTypeSizeInBits(PtrTy) &&
3078 !DL.isNonIntegralPointerType(PtrTy));
3080 return isBitCastable(SrcTy, DestTy);
3083 // Provide a way to get a "cast" where the cast opcode is inferred from the
3084 // types and size of the operand. This, basically, is a parallel of the
3085 // logic in the castIsValid function below. This axiom should hold:
3086 // castIsValid( getCastOpcode(Val, Ty), Val, Ty)
3087 // should not assert in castIsValid. In other words, this produces a "correct"
3088 // casting opcode for the arguments passed to it.
3089 // This routine must be kept in sync with isCastable.
3090 Instruction::CastOps
3091 CastInst::getCastOpcode(
3092 const Value *Src, bool SrcIsSigned, Type *DestTy, bool DestIsSigned) {
3093 Type *SrcTy = Src->getType();
3095 assert(SrcTy->isFirstClassType() && DestTy->isFirstClassType() &&
3096 "Only first class types are castable!");
3098 if (SrcTy == DestTy)
3099 return BitCast;
3101 // FIXME: Check address space sizes here
3102 if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy))
3103 if (VectorType *DestVecTy = dyn_cast<VectorType>(DestTy))
3104 if (SrcVecTy->getNumElements() == DestVecTy->getNumElements()) {
3105 // An element by element cast. Find the appropriate opcode based on the
3106 // element types.
3107 SrcTy = SrcVecTy->getElementType();
3108 DestTy = DestVecTy->getElementType();
3111 // Get the bit sizes, we'll need these
3112 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr
3113 unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr
3115 // Run through the possibilities ...
3116 if (DestTy->isIntegerTy()) { // Casting to integral
3117 if (SrcTy->isIntegerTy()) { // Casting from integral
3118 if (DestBits < SrcBits)
3119 return Trunc; // int -> smaller int
3120 else if (DestBits > SrcBits) { // its an extension
3121 if (SrcIsSigned)
3122 return SExt; // signed -> SEXT
3123 else
3124 return ZExt; // unsigned -> ZEXT
3125 } else {
3126 return BitCast; // Same size, No-op cast
3128 } else if (SrcTy->isFloatingPointTy()) { // Casting from floating pt
3129 if (DestIsSigned)
3130 return FPToSI; // FP -> sint
3131 else
3132 return FPToUI; // FP -> uint
3133 } else if (SrcTy->isVectorTy()) {
3134 assert(DestBits == SrcBits &&
3135 "Casting vector to integer of different width");
3136 return BitCast; // Same size, no-op cast
3137 } else {
3138 assert(SrcTy->isPointerTy() &&
3139 "Casting from a value that is not first-class type");
3140 return PtrToInt; // ptr -> int
3142 } else if (DestTy->isFloatingPointTy()) { // Casting to floating pt
3143 if (SrcTy->isIntegerTy()) { // Casting from integral
3144 if (SrcIsSigned)
3145 return SIToFP; // sint -> FP
3146 else
3147 return UIToFP; // uint -> FP
3148 } else if (SrcTy->isFloatingPointTy()) { // Casting from floating pt
3149 if (DestBits < SrcBits) {
3150 return FPTrunc; // FP -> smaller FP
3151 } else if (DestBits > SrcBits) {
3152 return FPExt; // FP -> larger FP
3153 } else {
3154 return BitCast; // same size, no-op cast
3156 } else if (SrcTy->isVectorTy()) {
3157 assert(DestBits == SrcBits &&
3158 "Casting vector to floating point of different width");
3159 return BitCast; // same size, no-op cast
3161 llvm_unreachable("Casting pointer or non-first class to float");
3162 } else if (DestTy->isVectorTy()) {
3163 assert(DestBits == SrcBits &&
3164 "Illegal cast to vector (wrong type or size)");
3165 return BitCast;
3166 } else if (DestTy->isPointerTy()) {
3167 if (SrcTy->isPointerTy()) {
3168 if (DestTy->getPointerAddressSpace() != SrcTy->getPointerAddressSpace())
3169 return AddrSpaceCast;
3170 return BitCast; // ptr -> ptr
3171 } else if (SrcTy->isIntegerTy()) {
3172 return IntToPtr; // int -> ptr
3174 llvm_unreachable("Casting pointer to other than pointer or int");
3175 } else if (DestTy->isX86_MMXTy()) {
3176 if (SrcTy->isVectorTy()) {
3177 assert(DestBits == SrcBits && "Casting vector of wrong width to X86_MMX");
3178 return BitCast; // 64-bit vector to MMX
3180 llvm_unreachable("Illegal cast to X86_MMX");
3182 llvm_unreachable("Casting to type that is not first-class");
3185 //===----------------------------------------------------------------------===//
3186 // CastInst SubClass Constructors
3187 //===----------------------------------------------------------------------===//
3189 /// Check that the construction parameters for a CastInst are correct. This
3190 /// could be broken out into the separate constructors but it is useful to have
3191 /// it in one place and to eliminate the redundant code for getting the sizes
3192 /// of the types involved.
3193 bool
3194 CastInst::castIsValid(Instruction::CastOps op, Value *S, Type *DstTy) {
3195 // Check for type sanity on the arguments
3196 Type *SrcTy = S->getType();
3198 if (!SrcTy->isFirstClassType() || !DstTy->isFirstClassType() ||
3199 SrcTy->isAggregateType() || DstTy->isAggregateType())
3200 return false;
3202 // Get the size of the types in bits, we'll need this later
3203 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
3204 unsigned DstBitSize = DstTy->getScalarSizeInBits();
3206 // If these are vector types, get the lengths of the vectors (using zero for
3207 // scalar types means that checking that vector lengths match also checks that
3208 // scalars are not being converted to vectors or vectors to scalars).
3209 unsigned SrcLength = SrcTy->isVectorTy() ?
3210 cast<VectorType>(SrcTy)->getNumElements() : 0;
3211 unsigned DstLength = DstTy->isVectorTy() ?
3212 cast<VectorType>(DstTy)->getNumElements() : 0;
3214 // Switch on the opcode provided
3215 switch (op) {
3216 default: return false; // This is an input error
3217 case Instruction::Trunc:
3218 return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() &&
3219 SrcLength == DstLength && SrcBitSize > DstBitSize;
3220 case Instruction::ZExt:
3221 return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() &&
3222 SrcLength == DstLength && SrcBitSize < DstBitSize;
3223 case Instruction::SExt:
3224 return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() &&
3225 SrcLength == DstLength && SrcBitSize < DstBitSize;
3226 case Instruction::FPTrunc:
3227 return SrcTy->isFPOrFPVectorTy() && DstTy->isFPOrFPVectorTy() &&
3228 SrcLength == DstLength && SrcBitSize > DstBitSize;
3229 case Instruction::FPExt:
3230 return SrcTy->isFPOrFPVectorTy() && DstTy->isFPOrFPVectorTy() &&
3231 SrcLength == DstLength && SrcBitSize < DstBitSize;
3232 case Instruction::UIToFP:
3233 case Instruction::SIToFP:
3234 return SrcTy->isIntOrIntVectorTy() && DstTy->isFPOrFPVectorTy() &&
3235 SrcLength == DstLength;
3236 case Instruction::FPToUI:
3237 case Instruction::FPToSI:
3238 return SrcTy->isFPOrFPVectorTy() && DstTy->isIntOrIntVectorTy() &&
3239 SrcLength == DstLength;
3240 case Instruction::PtrToInt:
3241 if (isa<VectorType>(SrcTy) != isa<VectorType>(DstTy))
3242 return false;
3243 if (VectorType *VT = dyn_cast<VectorType>(SrcTy))
3244 if (VT->getNumElements() != cast<VectorType>(DstTy)->getNumElements())
3245 return false;
3246 return SrcTy->isPtrOrPtrVectorTy() && DstTy->isIntOrIntVectorTy();
3247 case Instruction::IntToPtr:
3248 if (isa<VectorType>(SrcTy) != isa<VectorType>(DstTy))
3249 return false;
3250 if (VectorType *VT = dyn_cast<VectorType>(SrcTy))
3251 if (VT->getNumElements() != cast<VectorType>(DstTy)->getNumElements())
3252 return false;
3253 return SrcTy->isIntOrIntVectorTy() && DstTy->isPtrOrPtrVectorTy();
3254 case Instruction::BitCast: {
3255 PointerType *SrcPtrTy = dyn_cast<PointerType>(SrcTy->getScalarType());
3256 PointerType *DstPtrTy = dyn_cast<PointerType>(DstTy->getScalarType());
3258 // BitCast implies a no-op cast of type only. No bits change.
3259 // However, you can't cast pointers to anything but pointers.
3260 if (!SrcPtrTy != !DstPtrTy)
3261 return false;
3263 // For non-pointer cases, the cast is okay if the source and destination bit
3264 // widths are identical.
3265 if (!SrcPtrTy)
3266 return SrcTy->getPrimitiveSizeInBits() == DstTy->getPrimitiveSizeInBits();
3268 // If both are pointers then the address spaces must match.
3269 if (SrcPtrTy->getAddressSpace() != DstPtrTy->getAddressSpace())
3270 return false;
3272 // A vector of pointers must have the same number of elements.
3273 VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy);
3274 VectorType *DstVecTy = dyn_cast<VectorType>(DstTy);
3275 if (SrcVecTy && DstVecTy)
3276 return (SrcVecTy->getNumElements() == DstVecTy->getNumElements());
3277 if (SrcVecTy)
3278 return SrcVecTy->getNumElements() == 1;
3279 if (DstVecTy)
3280 return DstVecTy->getNumElements() == 1;
3282 return true;
3284 case Instruction::AddrSpaceCast: {
3285 PointerType *SrcPtrTy = dyn_cast<PointerType>(SrcTy->getScalarType());
3286 if (!SrcPtrTy)
3287 return false;
3289 PointerType *DstPtrTy = dyn_cast<PointerType>(DstTy->getScalarType());
3290 if (!DstPtrTy)
3291 return false;
3293 if (SrcPtrTy->getAddressSpace() == DstPtrTy->getAddressSpace())
3294 return false;
3296 if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy)) {
3297 if (VectorType *DstVecTy = dyn_cast<VectorType>(DstTy))
3298 return (SrcVecTy->getNumElements() == DstVecTy->getNumElements());
3300 return false;
3303 return true;
3308 TruncInst::TruncInst(
3309 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3310 ) : CastInst(Ty, Trunc, S, Name, InsertBefore) {
3311 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
3314 TruncInst::TruncInst(
3315 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3316 ) : CastInst(Ty, Trunc, S, Name, InsertAtEnd) {
3317 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
3320 ZExtInst::ZExtInst(
3321 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3322 ) : CastInst(Ty, ZExt, S, Name, InsertBefore) {
3323 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
3326 ZExtInst::ZExtInst(
3327 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3328 ) : CastInst(Ty, ZExt, S, Name, InsertAtEnd) {
3329 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
3331 SExtInst::SExtInst(
3332 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3333 ) : CastInst(Ty, SExt, S, Name, InsertBefore) {
3334 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
3337 SExtInst::SExtInst(
3338 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3339 ) : CastInst(Ty, SExt, S, Name, InsertAtEnd) {
3340 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
3343 FPTruncInst::FPTruncInst(
3344 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3345 ) : CastInst(Ty, FPTrunc, S, Name, InsertBefore) {
3346 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
3349 FPTruncInst::FPTruncInst(
3350 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3351 ) : CastInst(Ty, FPTrunc, S, Name, InsertAtEnd) {
3352 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
3355 FPExtInst::FPExtInst(
3356 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3357 ) : CastInst(Ty, FPExt, S, Name, InsertBefore) {
3358 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
3361 FPExtInst::FPExtInst(
3362 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3363 ) : CastInst(Ty, FPExt, S, Name, InsertAtEnd) {
3364 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
3367 UIToFPInst::UIToFPInst(
3368 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3369 ) : CastInst(Ty, UIToFP, S, Name, InsertBefore) {
3370 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
3373 UIToFPInst::UIToFPInst(
3374 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3375 ) : CastInst(Ty, UIToFP, S, Name, InsertAtEnd) {
3376 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
3379 SIToFPInst::SIToFPInst(
3380 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3381 ) : CastInst(Ty, SIToFP, S, Name, InsertBefore) {
3382 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
3385 SIToFPInst::SIToFPInst(
3386 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3387 ) : CastInst(Ty, SIToFP, S, Name, InsertAtEnd) {
3388 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
3391 FPToUIInst::FPToUIInst(
3392 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3393 ) : CastInst(Ty, FPToUI, S, Name, InsertBefore) {
3394 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
3397 FPToUIInst::FPToUIInst(
3398 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3399 ) : CastInst(Ty, FPToUI, S, Name, InsertAtEnd) {
3400 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
3403 FPToSIInst::FPToSIInst(
3404 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3405 ) : CastInst(Ty, FPToSI, S, Name, InsertBefore) {
3406 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
3409 FPToSIInst::FPToSIInst(
3410 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3411 ) : CastInst(Ty, FPToSI, S, Name, InsertAtEnd) {
3412 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
3415 PtrToIntInst::PtrToIntInst(
3416 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3417 ) : CastInst(Ty, PtrToInt, S, Name, InsertBefore) {
3418 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
3421 PtrToIntInst::PtrToIntInst(
3422 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3423 ) : CastInst(Ty, PtrToInt, S, Name, InsertAtEnd) {
3424 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
3427 IntToPtrInst::IntToPtrInst(
3428 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3429 ) : CastInst(Ty, IntToPtr, S, Name, InsertBefore) {
3430 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
3433 IntToPtrInst::IntToPtrInst(
3434 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3435 ) : CastInst(Ty, IntToPtr, S, Name, InsertAtEnd) {
3436 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
3439 BitCastInst::BitCastInst(
3440 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3441 ) : CastInst(Ty, BitCast, S, Name, InsertBefore) {
3442 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
3445 BitCastInst::BitCastInst(
3446 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3447 ) : CastInst(Ty, BitCast, S, Name, InsertAtEnd) {
3448 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
3451 AddrSpaceCastInst::AddrSpaceCastInst(
3452 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3453 ) : CastInst(Ty, AddrSpaceCast, S, Name, InsertBefore) {
3454 assert(castIsValid(getOpcode(), S, Ty) && "Illegal AddrSpaceCast");
3457 AddrSpaceCastInst::AddrSpaceCastInst(
3458 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3459 ) : CastInst(Ty, AddrSpaceCast, S, Name, InsertAtEnd) {
3460 assert(castIsValid(getOpcode(), S, Ty) && "Illegal AddrSpaceCast");
3463 //===----------------------------------------------------------------------===//
3464 // CmpInst Classes
3465 //===----------------------------------------------------------------------===//
3467 CmpInst::CmpInst(Type *ty, OtherOps op, Predicate predicate, Value *LHS,
3468 Value *RHS, const Twine &Name, Instruction *InsertBefore,
3469 Instruction *FlagsSource)
3470 : Instruction(ty, op,
3471 OperandTraits<CmpInst>::op_begin(this),
3472 OperandTraits<CmpInst>::operands(this),
3473 InsertBefore) {
3474 Op<0>() = LHS;
3475 Op<1>() = RHS;
3476 setPredicate((Predicate)predicate);
3477 setName(Name);
3478 if (FlagsSource)
3479 copyIRFlags(FlagsSource);
3482 CmpInst::CmpInst(Type *ty, OtherOps op, Predicate predicate, Value *LHS,
3483 Value *RHS, const Twine &Name, BasicBlock *InsertAtEnd)
3484 : Instruction(ty, op,
3485 OperandTraits<CmpInst>::op_begin(this),
3486 OperandTraits<CmpInst>::operands(this),
3487 InsertAtEnd) {
3488 Op<0>() = LHS;
3489 Op<1>() = RHS;
3490 setPredicate((Predicate)predicate);
3491 setName(Name);
3494 CmpInst *
3495 CmpInst::Create(OtherOps Op, Predicate predicate, Value *S1, Value *S2,
3496 const Twine &Name, Instruction *InsertBefore) {
3497 if (Op == Instruction::ICmp) {
3498 if (InsertBefore)
3499 return new ICmpInst(InsertBefore, CmpInst::Predicate(predicate),
3500 S1, S2, Name);
3501 else
3502 return new ICmpInst(CmpInst::Predicate(predicate),
3503 S1, S2, Name);
3506 if (InsertBefore)
3507 return new FCmpInst(InsertBefore, CmpInst::Predicate(predicate),
3508 S1, S2, Name);
3509 else
3510 return new FCmpInst(CmpInst::Predicate(predicate),
3511 S1, S2, Name);
3514 CmpInst *
3515 CmpInst::Create(OtherOps Op, Predicate predicate, Value *S1, Value *S2,
3516 const Twine &Name, BasicBlock *InsertAtEnd) {
3517 if (Op == Instruction::ICmp) {
3518 return new ICmpInst(*InsertAtEnd, CmpInst::Predicate(predicate),
3519 S1, S2, Name);
3521 return new FCmpInst(*InsertAtEnd, CmpInst::Predicate(predicate),
3522 S1, S2, Name);
3525 void CmpInst::swapOperands() {
3526 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
3527 IC->swapOperands();
3528 else
3529 cast<FCmpInst>(this)->swapOperands();
3532 bool CmpInst::isCommutative() const {
3533 if (const ICmpInst *IC = dyn_cast<ICmpInst>(this))
3534 return IC->isCommutative();
3535 return cast<FCmpInst>(this)->isCommutative();
3538 bool CmpInst::isEquality() const {
3539 if (const ICmpInst *IC = dyn_cast<ICmpInst>(this))
3540 return IC->isEquality();
3541 return cast<FCmpInst>(this)->isEquality();
3544 CmpInst::Predicate CmpInst::getInversePredicate(Predicate pred) {
3545 switch (pred) {
3546 default: llvm_unreachable("Unknown cmp predicate!");
3547 case ICMP_EQ: return ICMP_NE;
3548 case ICMP_NE: return ICMP_EQ;
3549 case ICMP_UGT: return ICMP_ULE;
3550 case ICMP_ULT: return ICMP_UGE;
3551 case ICMP_UGE: return ICMP_ULT;
3552 case ICMP_ULE: return ICMP_UGT;
3553 case ICMP_SGT: return ICMP_SLE;
3554 case ICMP_SLT: return ICMP_SGE;
3555 case ICMP_SGE: return ICMP_SLT;
3556 case ICMP_SLE: return ICMP_SGT;
3558 case FCMP_OEQ: return FCMP_UNE;
3559 case FCMP_ONE: return FCMP_UEQ;
3560 case FCMP_OGT: return FCMP_ULE;
3561 case FCMP_OLT: return FCMP_UGE;
3562 case FCMP_OGE: return FCMP_ULT;
3563 case FCMP_OLE: return FCMP_UGT;
3564 case FCMP_UEQ: return FCMP_ONE;
3565 case FCMP_UNE: return FCMP_OEQ;
3566 case FCMP_UGT: return FCMP_OLE;
3567 case FCMP_ULT: return FCMP_OGE;
3568 case FCMP_UGE: return FCMP_OLT;
3569 case FCMP_ULE: return FCMP_OGT;
3570 case FCMP_ORD: return FCMP_UNO;
3571 case FCMP_UNO: return FCMP_ORD;
3572 case FCMP_TRUE: return FCMP_FALSE;
3573 case FCMP_FALSE: return FCMP_TRUE;
3577 StringRef CmpInst::getPredicateName(Predicate Pred) {
3578 switch (Pred) {
3579 default: return "unknown";
3580 case FCmpInst::FCMP_FALSE: return "false";
3581 case FCmpInst::FCMP_OEQ: return "oeq";
3582 case FCmpInst::FCMP_OGT: return "ogt";
3583 case FCmpInst::FCMP_OGE: return "oge";
3584 case FCmpInst::FCMP_OLT: return "olt";
3585 case FCmpInst::FCMP_OLE: return "ole";
3586 case FCmpInst::FCMP_ONE: return "one";
3587 case FCmpInst::FCMP_ORD: return "ord";
3588 case FCmpInst::FCMP_UNO: return "uno";
3589 case FCmpInst::FCMP_UEQ: return "ueq";
3590 case FCmpInst::FCMP_UGT: return "ugt";
3591 case FCmpInst::FCMP_UGE: return "uge";
3592 case FCmpInst::FCMP_ULT: return "ult";
3593 case FCmpInst::FCMP_ULE: return "ule";
3594 case FCmpInst::FCMP_UNE: return "une";
3595 case FCmpInst::FCMP_TRUE: return "true";
3596 case ICmpInst::ICMP_EQ: return "eq";
3597 case ICmpInst::ICMP_NE: return "ne";
3598 case ICmpInst::ICMP_SGT: return "sgt";
3599 case ICmpInst::ICMP_SGE: return "sge";
3600 case ICmpInst::ICMP_SLT: return "slt";
3601 case ICmpInst::ICMP_SLE: return "sle";
3602 case ICmpInst::ICMP_UGT: return "ugt";
3603 case ICmpInst::ICMP_UGE: return "uge";
3604 case ICmpInst::ICMP_ULT: return "ult";
3605 case ICmpInst::ICMP_ULE: return "ule";
3609 ICmpInst::Predicate ICmpInst::getSignedPredicate(Predicate pred) {
3610 switch (pred) {
3611 default: llvm_unreachable("Unknown icmp predicate!");
3612 case ICMP_EQ: case ICMP_NE:
3613 case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE:
3614 return pred;
3615 case ICMP_UGT: return ICMP_SGT;
3616 case ICMP_ULT: return ICMP_SLT;
3617 case ICMP_UGE: return ICMP_SGE;
3618 case ICMP_ULE: return ICMP_SLE;
3622 ICmpInst::Predicate ICmpInst::getUnsignedPredicate(Predicate pred) {
3623 switch (pred) {
3624 default: llvm_unreachable("Unknown icmp predicate!");
3625 case ICMP_EQ: case ICMP_NE:
3626 case ICMP_UGT: case ICMP_ULT: case ICMP_UGE: case ICMP_ULE:
3627 return pred;
3628 case ICMP_SGT: return ICMP_UGT;
3629 case ICMP_SLT: return ICMP_ULT;
3630 case ICMP_SGE: return ICMP_UGE;
3631 case ICMP_SLE: return ICMP_ULE;
3635 CmpInst::Predicate CmpInst::getFlippedStrictnessPredicate(Predicate pred) {
3636 switch (pred) {
3637 default: llvm_unreachable("Unknown or unsupported cmp predicate!");
3638 case ICMP_SGT: return ICMP_SGE;
3639 case ICMP_SLT: return ICMP_SLE;
3640 case ICMP_SGE: return ICMP_SGT;
3641 case ICMP_SLE: return ICMP_SLT;
3642 case ICMP_UGT: return ICMP_UGE;
3643 case ICMP_ULT: return ICMP_ULE;
3644 case ICMP_UGE: return ICMP_UGT;
3645 case ICMP_ULE: return ICMP_ULT;
3647 case FCMP_OGT: return FCMP_OGE;
3648 case FCMP_OLT: return FCMP_OLE;
3649 case FCMP_OGE: return FCMP_OGT;
3650 case FCMP_OLE: return FCMP_OLT;
3651 case FCMP_UGT: return FCMP_UGE;
3652 case FCMP_ULT: return FCMP_ULE;
3653 case FCMP_UGE: return FCMP_UGT;
3654 case FCMP_ULE: return FCMP_ULT;
3658 CmpInst::Predicate CmpInst::getSwappedPredicate(Predicate pred) {
3659 switch (pred) {
3660 default: llvm_unreachable("Unknown cmp predicate!");
3661 case ICMP_EQ: case ICMP_NE:
3662 return pred;
3663 case ICMP_SGT: return ICMP_SLT;
3664 case ICMP_SLT: return ICMP_SGT;
3665 case ICMP_SGE: return ICMP_SLE;
3666 case ICMP_SLE: return ICMP_SGE;
3667 case ICMP_UGT: return ICMP_ULT;
3668 case ICMP_ULT: return ICMP_UGT;
3669 case ICMP_UGE: return ICMP_ULE;
3670 case ICMP_ULE: return ICMP_UGE;
3672 case FCMP_FALSE: case FCMP_TRUE:
3673 case FCMP_OEQ: case FCMP_ONE:
3674 case FCMP_UEQ: case FCMP_UNE:
3675 case FCMP_ORD: case FCMP_UNO:
3676 return pred;
3677 case FCMP_OGT: return FCMP_OLT;
3678 case FCMP_OLT: return FCMP_OGT;
3679 case FCMP_OGE: return FCMP_OLE;
3680 case FCMP_OLE: return FCMP_OGE;
3681 case FCMP_UGT: return FCMP_ULT;
3682 case FCMP_ULT: return FCMP_UGT;
3683 case FCMP_UGE: return FCMP_ULE;
3684 case FCMP_ULE: return FCMP_UGE;
3688 CmpInst::Predicate CmpInst::getNonStrictPredicate(Predicate pred) {
3689 switch (pred) {
3690 case ICMP_SGT: return ICMP_SGE;
3691 case ICMP_SLT: return ICMP_SLE;
3692 case ICMP_UGT: return ICMP_UGE;
3693 case ICMP_ULT: return ICMP_ULE;
3694 case FCMP_OGT: return FCMP_OGE;
3695 case FCMP_OLT: return FCMP_OLE;
3696 case FCMP_UGT: return FCMP_UGE;
3697 case FCMP_ULT: return FCMP_ULE;
3698 default: return pred;
3702 CmpInst::Predicate CmpInst::getSignedPredicate(Predicate pred) {
3703 assert(CmpInst::isUnsigned(pred) && "Call only with signed predicates!");
3705 switch (pred) {
3706 default:
3707 llvm_unreachable("Unknown predicate!");
3708 case CmpInst::ICMP_ULT:
3709 return CmpInst::ICMP_SLT;
3710 case CmpInst::ICMP_ULE:
3711 return CmpInst::ICMP_SLE;
3712 case CmpInst::ICMP_UGT:
3713 return CmpInst::ICMP_SGT;
3714 case CmpInst::ICMP_UGE:
3715 return CmpInst::ICMP_SGE;
3719 bool CmpInst::isUnsigned(Predicate predicate) {
3720 switch (predicate) {
3721 default: return false;
3722 case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE: case ICmpInst::ICMP_UGT:
3723 case ICmpInst::ICMP_UGE: return true;
3727 bool CmpInst::isSigned(Predicate predicate) {
3728 switch (predicate) {
3729 default: return false;
3730 case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_SLE: case ICmpInst::ICMP_SGT:
3731 case ICmpInst::ICMP_SGE: return true;
3735 bool CmpInst::isOrdered(Predicate predicate) {
3736 switch (predicate) {
3737 default: return false;
3738 case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_OGT:
3739 case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLE:
3740 case FCmpInst::FCMP_ORD: return true;
3744 bool CmpInst::isUnordered(Predicate predicate) {
3745 switch (predicate) {
3746 default: return false;
3747 case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UNE: case FCmpInst::FCMP_UGT:
3748 case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_UGE: case FCmpInst::FCMP_ULE:
3749 case FCmpInst::FCMP_UNO: return true;
3753 bool CmpInst::isTrueWhenEqual(Predicate predicate) {
3754 switch(predicate) {
3755 default: return false;
3756 case ICMP_EQ: case ICMP_UGE: case ICMP_ULE: case ICMP_SGE: case ICMP_SLE:
3757 case FCMP_TRUE: case FCMP_UEQ: case FCMP_UGE: case FCMP_ULE: return true;
3761 bool CmpInst::isFalseWhenEqual(Predicate predicate) {
3762 switch(predicate) {
3763 case ICMP_NE: case ICMP_UGT: case ICMP_ULT: case ICMP_SGT: case ICMP_SLT:
3764 case FCMP_FALSE: case FCMP_ONE: case FCMP_OGT: case FCMP_OLT: return true;
3765 default: return false;
3769 bool CmpInst::isImpliedTrueByMatchingCmp(Predicate Pred1, Predicate Pred2) {
3770 // If the predicates match, then we know the first condition implies the
3771 // second is true.
3772 if (Pred1 == Pred2)
3773 return true;
3775 switch (Pred1) {
3776 default:
3777 break;
3778 case ICMP_EQ:
3779 // A == B implies A >=u B, A <=u B, A >=s B, and A <=s B are true.
3780 return Pred2 == ICMP_UGE || Pred2 == ICMP_ULE || Pred2 == ICMP_SGE ||
3781 Pred2 == ICMP_SLE;
3782 case ICMP_UGT: // A >u B implies A != B and A >=u B are true.
3783 return Pred2 == ICMP_NE || Pred2 == ICMP_UGE;
3784 case ICMP_ULT: // A <u B implies A != B and A <=u B are true.
3785 return Pred2 == ICMP_NE || Pred2 == ICMP_ULE;
3786 case ICMP_SGT: // A >s B implies A != B and A >=s B are true.
3787 return Pred2 == ICMP_NE || Pred2 == ICMP_SGE;
3788 case ICMP_SLT: // A <s B implies A != B and A <=s B are true.
3789 return Pred2 == ICMP_NE || Pred2 == ICMP_SLE;
3791 return false;
3794 bool CmpInst::isImpliedFalseByMatchingCmp(Predicate Pred1, Predicate Pred2) {
3795 return isImpliedTrueByMatchingCmp(Pred1, getInversePredicate(Pred2));
3798 //===----------------------------------------------------------------------===//
3799 // SwitchInst Implementation
3800 //===----------------------------------------------------------------------===//
3802 void SwitchInst::init(Value *Value, BasicBlock *Default, unsigned NumReserved) {
3803 assert(Value && Default && NumReserved);
3804 ReservedSpace = NumReserved;
3805 setNumHungOffUseOperands(2);
3806 allocHungoffUses(ReservedSpace);
3808 Op<0>() = Value;
3809 Op<1>() = Default;
3812 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
3813 /// switch on and a default destination. The number of additional cases can
3814 /// be specified here to make memory allocation more efficient. This
3815 /// constructor can also autoinsert before another instruction.
3816 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
3817 Instruction *InsertBefore)
3818 : Instruction(Type::getVoidTy(Value->getContext()), Instruction::Switch,
3819 nullptr, 0, InsertBefore) {
3820 init(Value, Default, 2+NumCases*2);
3823 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
3824 /// switch on and a default destination. The number of additional cases can
3825 /// be specified here to make memory allocation more efficient. This
3826 /// constructor also autoinserts at the end of the specified BasicBlock.
3827 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
3828 BasicBlock *InsertAtEnd)
3829 : Instruction(Type::getVoidTy(Value->getContext()), Instruction::Switch,
3830 nullptr, 0, InsertAtEnd) {
3831 init(Value, Default, 2+NumCases*2);
3834 SwitchInst::SwitchInst(const SwitchInst &SI)
3835 : Instruction(SI.getType(), Instruction::Switch, nullptr, 0) {
3836 init(SI.getCondition(), SI.getDefaultDest(), SI.getNumOperands());
3837 setNumHungOffUseOperands(SI.getNumOperands());
3838 Use *OL = getOperandList();
3839 const Use *InOL = SI.getOperandList();
3840 for (unsigned i = 2, E = SI.getNumOperands(); i != E; i += 2) {
3841 OL[i] = InOL[i];
3842 OL[i+1] = InOL[i+1];
3844 SubclassOptionalData = SI.SubclassOptionalData;
3847 /// addCase - Add an entry to the switch instruction...
3849 void SwitchInst::addCase(ConstantInt *OnVal, BasicBlock *Dest) {
3850 unsigned NewCaseIdx = getNumCases();
3851 unsigned OpNo = getNumOperands();
3852 if (OpNo+2 > ReservedSpace)
3853 growOperands(); // Get more space!
3854 // Initialize some new operands.
3855 assert(OpNo+1 < ReservedSpace && "Growing didn't work!");
3856 setNumHungOffUseOperands(OpNo+2);
3857 CaseHandle Case(this, NewCaseIdx);
3858 Case.setValue(OnVal);
3859 Case.setSuccessor(Dest);
3862 /// removeCase - This method removes the specified case and its successor
3863 /// from the switch instruction.
3864 SwitchInst::CaseIt SwitchInst::removeCase(CaseIt I) {
3865 unsigned idx = I->getCaseIndex();
3867 assert(2 + idx*2 < getNumOperands() && "Case index out of range!!!");
3869 unsigned NumOps = getNumOperands();
3870 Use *OL = getOperandList();
3872 // Overwrite this case with the end of the list.
3873 if (2 + (idx + 1) * 2 != NumOps) {
3874 OL[2 + idx * 2] = OL[NumOps - 2];
3875 OL[2 + idx * 2 + 1] = OL[NumOps - 1];
3878 // Nuke the last value.
3879 OL[NumOps-2].set(nullptr);
3880 OL[NumOps-2+1].set(nullptr);
3881 setNumHungOffUseOperands(NumOps-2);
3883 return CaseIt(this, idx);
3886 /// growOperands - grow operands - This grows the operand list in response
3887 /// to a push_back style of operation. This grows the number of ops by 3 times.
3889 void SwitchInst::growOperands() {
3890 unsigned e = getNumOperands();
3891 unsigned NumOps = e*3;
3893 ReservedSpace = NumOps;
3894 growHungoffUses(ReservedSpace);
3897 MDNode *
3898 SwitchInstProfUpdateWrapper::getProfBranchWeightsMD(const SwitchInst &SI) {
3899 if (MDNode *ProfileData = SI.getMetadata(LLVMContext::MD_prof))
3900 if (auto *MDName = dyn_cast<MDString>(ProfileData->getOperand(0)))
3901 if (MDName->getString() == "branch_weights")
3902 return ProfileData;
3903 return nullptr;
3906 MDNode *SwitchInstProfUpdateWrapper::buildProfBranchWeightsMD() {
3907 assert(Changed && "called only if metadata has changed");
3909 if (!Weights)
3910 return nullptr;
3912 assert(SI.getNumSuccessors() == Weights->size() &&
3913 "num of prof branch_weights must accord with num of successors");
3915 bool AllZeroes =
3916 all_of(Weights.getValue(), [](uint32_t W) { return W == 0; });
3918 if (AllZeroes || Weights.getValue().size() < 2)
3919 return nullptr;
3921 return MDBuilder(SI.getParent()->getContext()).createBranchWeights(*Weights);
3924 void SwitchInstProfUpdateWrapper::init() {
3925 MDNode *ProfileData = getProfBranchWeightsMD(SI);
3926 if (!ProfileData)
3927 return;
3929 if (ProfileData->getNumOperands() != SI.getNumSuccessors() + 1) {
3930 llvm_unreachable("number of prof branch_weights metadata operands does "
3931 "not correspond to number of succesors");
3934 SmallVector<uint32_t, 8> Weights;
3935 for (unsigned CI = 1, CE = SI.getNumSuccessors(); CI <= CE; ++CI) {
3936 ConstantInt *C = mdconst::extract<ConstantInt>(ProfileData->getOperand(CI));
3937 uint32_t CW = C->getValue().getZExtValue();
3938 Weights.push_back(CW);
3940 this->Weights = std::move(Weights);
3943 SwitchInst::CaseIt
3944 SwitchInstProfUpdateWrapper::removeCase(SwitchInst::CaseIt I) {
3945 if (Weights) {
3946 assert(SI.getNumSuccessors() == Weights->size() &&
3947 "num of prof branch_weights must accord with num of successors");
3948 Changed = true;
3949 // Copy the last case to the place of the removed one and shrink.
3950 // This is tightly coupled with the way SwitchInst::removeCase() removes
3951 // the cases in SwitchInst::removeCase(CaseIt).
3952 Weights.getValue()[I->getCaseIndex() + 1] = Weights.getValue().back();
3953 Weights.getValue().pop_back();
3955 return SI.removeCase(I);
3958 void SwitchInstProfUpdateWrapper::addCase(
3959 ConstantInt *OnVal, BasicBlock *Dest,
3960 SwitchInstProfUpdateWrapper::CaseWeightOpt W) {
3961 SI.addCase(OnVal, Dest);
3963 if (!Weights && W && *W) {
3964 Changed = true;
3965 Weights = SmallVector<uint32_t, 8>(SI.getNumSuccessors(), 0);
3966 Weights.getValue()[SI.getNumSuccessors() - 1] = *W;
3967 } else if (Weights) {
3968 Changed = true;
3969 Weights.getValue().push_back(W ? *W : 0);
3971 if (Weights)
3972 assert(SI.getNumSuccessors() == Weights->size() &&
3973 "num of prof branch_weights must accord with num of successors");
3976 SymbolTableList<Instruction>::iterator
3977 SwitchInstProfUpdateWrapper::eraseFromParent() {
3978 // Instruction is erased. Mark as unchanged to not touch it in the destructor.
3979 Changed = false;
3980 if (Weights)
3981 Weights->resize(0);
3982 return SI.eraseFromParent();
3985 SwitchInstProfUpdateWrapper::CaseWeightOpt
3986 SwitchInstProfUpdateWrapper::getSuccessorWeight(unsigned idx) {
3987 if (!Weights)
3988 return None;
3989 return Weights.getValue()[idx];
3992 void SwitchInstProfUpdateWrapper::setSuccessorWeight(
3993 unsigned idx, SwitchInstProfUpdateWrapper::CaseWeightOpt W) {
3994 if (!W)
3995 return;
3997 if (!Weights && *W)
3998 Weights = SmallVector<uint32_t, 8>(SI.getNumSuccessors(), 0);
4000 if (Weights) {
4001 auto &OldW = Weights.getValue()[idx];
4002 if (*W != OldW) {
4003 Changed = true;
4004 OldW = *W;
4009 SwitchInstProfUpdateWrapper::CaseWeightOpt
4010 SwitchInstProfUpdateWrapper::getSuccessorWeight(const SwitchInst &SI,
4011 unsigned idx) {
4012 if (MDNode *ProfileData = getProfBranchWeightsMD(SI))
4013 if (ProfileData->getNumOperands() == SI.getNumSuccessors() + 1)
4014 return mdconst::extract<ConstantInt>(ProfileData->getOperand(idx + 1))
4015 ->getValue()
4016 .getZExtValue();
4018 return None;
4021 //===----------------------------------------------------------------------===//
4022 // IndirectBrInst Implementation
4023 //===----------------------------------------------------------------------===//
4025 void IndirectBrInst::init(Value *Address, unsigned NumDests) {
4026 assert(Address && Address->getType()->isPointerTy() &&
4027 "Address of indirectbr must be a pointer");
4028 ReservedSpace = 1+NumDests;
4029 setNumHungOffUseOperands(1);
4030 allocHungoffUses(ReservedSpace);
4032 Op<0>() = Address;
4036 /// growOperands - grow operands - This grows the operand list in response
4037 /// to a push_back style of operation. This grows the number of ops by 2 times.
4039 void IndirectBrInst::growOperands() {
4040 unsigned e = getNumOperands();
4041 unsigned NumOps = e*2;
4043 ReservedSpace = NumOps;
4044 growHungoffUses(ReservedSpace);
4047 IndirectBrInst::IndirectBrInst(Value *Address, unsigned NumCases,
4048 Instruction *InsertBefore)
4049 : Instruction(Type::getVoidTy(Address->getContext()),
4050 Instruction::IndirectBr, nullptr, 0, InsertBefore) {
4051 init(Address, NumCases);
4054 IndirectBrInst::IndirectBrInst(Value *Address, unsigned NumCases,
4055 BasicBlock *InsertAtEnd)
4056 : Instruction(Type::getVoidTy(Address->getContext()),
4057 Instruction::IndirectBr, nullptr, 0, InsertAtEnd) {
4058 init(Address, NumCases);
4061 IndirectBrInst::IndirectBrInst(const IndirectBrInst &IBI)
4062 : Instruction(Type::getVoidTy(IBI.getContext()), Instruction::IndirectBr,
4063 nullptr, IBI.getNumOperands()) {
4064 allocHungoffUses(IBI.getNumOperands());
4065 Use *OL = getOperandList();
4066 const Use *InOL = IBI.getOperandList();
4067 for (unsigned i = 0, E = IBI.getNumOperands(); i != E; ++i)
4068 OL[i] = InOL[i];
4069 SubclassOptionalData = IBI.SubclassOptionalData;
4072 /// addDestination - Add a destination.
4074 void IndirectBrInst::addDestination(BasicBlock *DestBB) {
4075 unsigned OpNo = getNumOperands();
4076 if (OpNo+1 > ReservedSpace)
4077 growOperands(); // Get more space!
4078 // Initialize some new operands.
4079 assert(OpNo < ReservedSpace && "Growing didn't work!");
4080 setNumHungOffUseOperands(OpNo+1);
4081 getOperandList()[OpNo] = DestBB;
4084 /// removeDestination - This method removes the specified successor from the
4085 /// indirectbr instruction.
4086 void IndirectBrInst::removeDestination(unsigned idx) {
4087 assert(idx < getNumOperands()-1 && "Successor index out of range!");
4089 unsigned NumOps = getNumOperands();
4090 Use *OL = getOperandList();
4092 // Replace this value with the last one.
4093 OL[idx+1] = OL[NumOps-1];
4095 // Nuke the last value.
4096 OL[NumOps-1].set(nullptr);
4097 setNumHungOffUseOperands(NumOps-1);
4100 //===----------------------------------------------------------------------===//
4101 // cloneImpl() implementations
4102 //===----------------------------------------------------------------------===//
4104 // Define these methods here so vtables don't get emitted into every translation
4105 // unit that uses these classes.
4107 GetElementPtrInst *GetElementPtrInst::cloneImpl() const {
4108 return new (getNumOperands()) GetElementPtrInst(*this);
4111 UnaryOperator *UnaryOperator::cloneImpl() const {
4112 return Create(getOpcode(), Op<0>());
4115 BinaryOperator *BinaryOperator::cloneImpl() const {
4116 return Create(getOpcode(), Op<0>(), Op<1>());
4119 FCmpInst *FCmpInst::cloneImpl() const {
4120 return new FCmpInst(getPredicate(), Op<0>(), Op<1>());
4123 ICmpInst *ICmpInst::cloneImpl() const {
4124 return new ICmpInst(getPredicate(), Op<0>(), Op<1>());
4127 ExtractValueInst *ExtractValueInst::cloneImpl() const {
4128 return new ExtractValueInst(*this);
4131 InsertValueInst *InsertValueInst::cloneImpl() const {
4132 return new InsertValueInst(*this);
4135 AllocaInst *AllocaInst::cloneImpl() const {
4136 AllocaInst *Result = new AllocaInst(getAllocatedType(),
4137 getType()->getAddressSpace(),
4138 (Value *)getOperand(0), getAlignment());
4139 Result->setUsedWithInAlloca(isUsedWithInAlloca());
4140 Result->setSwiftError(isSwiftError());
4141 return Result;
4144 LoadInst *LoadInst::cloneImpl() const {
4145 return new LoadInst(getType(), getOperand(0), Twine(), isVolatile(),
4146 getAlignment(), getOrdering(), getSyncScopeID());
4149 StoreInst *StoreInst::cloneImpl() const {
4150 return new StoreInst(getOperand(0), getOperand(1), isVolatile(),
4151 getAlignment(), getOrdering(), getSyncScopeID());
4155 AtomicCmpXchgInst *AtomicCmpXchgInst::cloneImpl() const {
4156 AtomicCmpXchgInst *Result =
4157 new AtomicCmpXchgInst(getOperand(0), getOperand(1), getOperand(2),
4158 getSuccessOrdering(), getFailureOrdering(),
4159 getSyncScopeID());
4160 Result->setVolatile(isVolatile());
4161 Result->setWeak(isWeak());
4162 return Result;
4165 AtomicRMWInst *AtomicRMWInst::cloneImpl() const {
4166 AtomicRMWInst *Result =
4167 new AtomicRMWInst(getOperation(), getOperand(0), getOperand(1),
4168 getOrdering(), getSyncScopeID());
4169 Result->setVolatile(isVolatile());
4170 return Result;
4173 FenceInst *FenceInst::cloneImpl() const {
4174 return new FenceInst(getContext(), getOrdering(), getSyncScopeID());
4177 TruncInst *TruncInst::cloneImpl() const {
4178 return new TruncInst(getOperand(0), getType());
4181 ZExtInst *ZExtInst::cloneImpl() const {
4182 return new ZExtInst(getOperand(0), getType());
4185 SExtInst *SExtInst::cloneImpl() const {
4186 return new SExtInst(getOperand(0), getType());
4189 FPTruncInst *FPTruncInst::cloneImpl() const {
4190 return new FPTruncInst(getOperand(0), getType());
4193 FPExtInst *FPExtInst::cloneImpl() const {
4194 return new FPExtInst(getOperand(0), getType());
4197 UIToFPInst *UIToFPInst::cloneImpl() const {
4198 return new UIToFPInst(getOperand(0), getType());
4201 SIToFPInst *SIToFPInst::cloneImpl() const {
4202 return new SIToFPInst(getOperand(0), getType());
4205 FPToUIInst *FPToUIInst::cloneImpl() const {
4206 return new FPToUIInst(getOperand(0), getType());
4209 FPToSIInst *FPToSIInst::cloneImpl() const {
4210 return new FPToSIInst(getOperand(0), getType());
4213 PtrToIntInst *PtrToIntInst::cloneImpl() const {
4214 return new PtrToIntInst(getOperand(0), getType());
4217 IntToPtrInst *IntToPtrInst::cloneImpl() const {
4218 return new IntToPtrInst(getOperand(0), getType());
4221 BitCastInst *BitCastInst::cloneImpl() const {
4222 return new BitCastInst(getOperand(0), getType());
4225 AddrSpaceCastInst *AddrSpaceCastInst::cloneImpl() const {
4226 return new AddrSpaceCastInst(getOperand(0), getType());
4229 CallInst *CallInst::cloneImpl() const {
4230 if (hasOperandBundles()) {
4231 unsigned DescriptorBytes = getNumOperandBundles() * sizeof(BundleOpInfo);
4232 return new(getNumOperands(), DescriptorBytes) CallInst(*this);
4234 return new(getNumOperands()) CallInst(*this);
4237 SelectInst *SelectInst::cloneImpl() const {
4238 return SelectInst::Create(getOperand(0), getOperand(1), getOperand(2));
4241 VAArgInst *VAArgInst::cloneImpl() const {
4242 return new VAArgInst(getOperand(0), getType());
4245 ExtractElementInst *ExtractElementInst::cloneImpl() const {
4246 return ExtractElementInst::Create(getOperand(0), getOperand(1));
4249 InsertElementInst *InsertElementInst::cloneImpl() const {
4250 return InsertElementInst::Create(getOperand(0), getOperand(1), getOperand(2));
4253 ShuffleVectorInst *ShuffleVectorInst::cloneImpl() const {
4254 return new ShuffleVectorInst(getOperand(0), getOperand(1), getOperand(2));
4257 PHINode *PHINode::cloneImpl() const { return new PHINode(*this); }
4259 LandingPadInst *LandingPadInst::cloneImpl() const {
4260 return new LandingPadInst(*this);
4263 ReturnInst *ReturnInst::cloneImpl() const {
4264 return new(getNumOperands()) ReturnInst(*this);
4267 BranchInst *BranchInst::cloneImpl() const {
4268 return new(getNumOperands()) BranchInst(*this);
4271 SwitchInst *SwitchInst::cloneImpl() const { return new SwitchInst(*this); }
4273 IndirectBrInst *IndirectBrInst::cloneImpl() const {
4274 return new IndirectBrInst(*this);
4277 InvokeInst *InvokeInst::cloneImpl() const {
4278 if (hasOperandBundles()) {
4279 unsigned DescriptorBytes = getNumOperandBundles() * sizeof(BundleOpInfo);
4280 return new(getNumOperands(), DescriptorBytes) InvokeInst(*this);
4282 return new(getNumOperands()) InvokeInst(*this);
4285 CallBrInst *CallBrInst::cloneImpl() const {
4286 if (hasOperandBundles()) {
4287 unsigned DescriptorBytes = getNumOperandBundles() * sizeof(BundleOpInfo);
4288 return new (getNumOperands(), DescriptorBytes) CallBrInst(*this);
4290 return new (getNumOperands()) CallBrInst(*this);
4293 ResumeInst *ResumeInst::cloneImpl() const { return new (1) ResumeInst(*this); }
4295 CleanupReturnInst *CleanupReturnInst::cloneImpl() const {
4296 return new (getNumOperands()) CleanupReturnInst(*this);
4299 CatchReturnInst *CatchReturnInst::cloneImpl() const {
4300 return new (getNumOperands()) CatchReturnInst(*this);
4303 CatchSwitchInst *CatchSwitchInst::cloneImpl() const {
4304 return new CatchSwitchInst(*this);
4307 FuncletPadInst *FuncletPadInst::cloneImpl() const {
4308 return new (getNumOperands()) FuncletPadInst(*this);
4311 UnreachableInst *UnreachableInst::cloneImpl() const {
4312 LLVMContext &Context = getContext();
4313 return new UnreachableInst(Context);