[Alignment][NFC] Convert LoadInst to MaybeAlign
[llvm-core.git] / lib / IR / Instructions.cpp
blob397717151fe5accde2552937dde834d10d5ec965
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 "llvm/Support/TypeSize.h"
42 #include <algorithm>
43 #include <cassert>
44 #include <cstdint>
45 #include <vector>
47 using namespace llvm;
49 //===----------------------------------------------------------------------===//
50 // AllocaInst Class
51 //===----------------------------------------------------------------------===//
53 Optional<uint64_t>
54 AllocaInst::getAllocationSizeInBits(const DataLayout &DL) const {
55 uint64_t Size = DL.getTypeAllocSizeInBits(getAllocatedType());
56 if (isArrayAllocation()) {
57 auto C = dyn_cast<ConstantInt>(getArraySize());
58 if (!C)
59 return None;
60 Size *= C->getZExtValue();
62 return Size;
65 //===----------------------------------------------------------------------===//
66 // CallSite Class
67 //===----------------------------------------------------------------------===//
69 User::op_iterator CallSite::getCallee() const {
70 return cast<CallBase>(getInstruction())->op_end() - 1;
73 //===----------------------------------------------------------------------===//
74 // SelectInst Class
75 //===----------------------------------------------------------------------===//
77 /// areInvalidOperands - Return a string if the specified operands are invalid
78 /// for a select operation, otherwise return null.
79 const char *SelectInst::areInvalidOperands(Value *Op0, Value *Op1, Value *Op2) {
80 if (Op1->getType() != Op2->getType())
81 return "both values to select must have same type";
83 if (Op1->getType()->isTokenTy())
84 return "select values cannot have token type";
86 if (VectorType *VT = dyn_cast<VectorType>(Op0->getType())) {
87 // Vector select.
88 if (VT->getElementType() != Type::getInt1Ty(Op0->getContext()))
89 return "vector select condition element type must be i1";
90 VectorType *ET = dyn_cast<VectorType>(Op1->getType());
91 if (!ET)
92 return "selected values for vector select must be vectors";
93 if (ET->getNumElements() != VT->getNumElements())
94 return "vector select requires selected vectors to have "
95 "the same vector length as select condition";
96 } else if (Op0->getType() != Type::getInt1Ty(Op0->getContext())) {
97 return "select condition must be i1 or <n x i1>";
99 return nullptr;
102 //===----------------------------------------------------------------------===//
103 // PHINode Class
104 //===----------------------------------------------------------------------===//
106 PHINode::PHINode(const PHINode &PN)
107 : Instruction(PN.getType(), Instruction::PHI, nullptr, PN.getNumOperands()),
108 ReservedSpace(PN.getNumOperands()) {
109 allocHungoffUses(PN.getNumOperands());
110 std::copy(PN.op_begin(), PN.op_end(), op_begin());
111 std::copy(PN.block_begin(), PN.block_end(), block_begin());
112 SubclassOptionalData = PN.SubclassOptionalData;
115 // removeIncomingValue - Remove an incoming value. This is useful if a
116 // predecessor basic block is deleted.
117 Value *PHINode::removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty) {
118 Value *Removed = getIncomingValue(Idx);
120 // Move everything after this operand down.
122 // FIXME: we could just swap with the end of the list, then erase. However,
123 // clients might not expect this to happen. The code as it is thrashes the
124 // use/def lists, which is kinda lame.
125 std::copy(op_begin() + Idx + 1, op_end(), op_begin() + Idx);
126 std::copy(block_begin() + Idx + 1, block_end(), block_begin() + Idx);
128 // Nuke the last value.
129 Op<-1>().set(nullptr);
130 setNumHungOffUseOperands(getNumOperands() - 1);
132 // If the PHI node is dead, because it has zero entries, nuke it now.
133 if (getNumOperands() == 0 && DeletePHIIfEmpty) {
134 // If anyone is using this PHI, make them use a dummy value instead...
135 replaceAllUsesWith(UndefValue::get(getType()));
136 eraseFromParent();
138 return Removed;
141 /// growOperands - grow operands - This grows the operand list in response
142 /// to a push_back style of operation. This grows the number of ops by 1.5
143 /// times.
145 void PHINode::growOperands() {
146 unsigned e = getNumOperands();
147 unsigned NumOps = e + e / 2;
148 if (NumOps < 2) NumOps = 2; // 2 op PHI nodes are VERY common.
150 ReservedSpace = NumOps;
151 growHungoffUses(ReservedSpace, /* IsPhi */ true);
154 /// hasConstantValue - If the specified PHI node always merges together the same
155 /// value, return the value, otherwise return null.
156 Value *PHINode::hasConstantValue() const {
157 // Exploit the fact that phi nodes always have at least one entry.
158 Value *ConstantValue = getIncomingValue(0);
159 for (unsigned i = 1, e = getNumIncomingValues(); i != e; ++i)
160 if (getIncomingValue(i) != ConstantValue && getIncomingValue(i) != this) {
161 if (ConstantValue != this)
162 return nullptr; // Incoming values not all the same.
163 // The case where the first value is this PHI.
164 ConstantValue = getIncomingValue(i);
166 if (ConstantValue == this)
167 return UndefValue::get(getType());
168 return ConstantValue;
171 /// hasConstantOrUndefValue - Whether the specified PHI node always merges
172 /// together the same value, assuming that undefs result in the same value as
173 /// non-undefs.
174 /// Unlike \ref hasConstantValue, this does not return a value because the
175 /// unique non-undef incoming value need not dominate the PHI node.
176 bool PHINode::hasConstantOrUndefValue() const {
177 Value *ConstantValue = nullptr;
178 for (unsigned i = 0, e = getNumIncomingValues(); i != e; ++i) {
179 Value *Incoming = getIncomingValue(i);
180 if (Incoming != this && !isa<UndefValue>(Incoming)) {
181 if (ConstantValue && ConstantValue != Incoming)
182 return false;
183 ConstantValue = Incoming;
186 return true;
189 //===----------------------------------------------------------------------===//
190 // LandingPadInst Implementation
191 //===----------------------------------------------------------------------===//
193 LandingPadInst::LandingPadInst(Type *RetTy, unsigned NumReservedValues,
194 const Twine &NameStr, Instruction *InsertBefore)
195 : Instruction(RetTy, Instruction::LandingPad, nullptr, 0, InsertBefore) {
196 init(NumReservedValues, NameStr);
199 LandingPadInst::LandingPadInst(Type *RetTy, unsigned NumReservedValues,
200 const Twine &NameStr, BasicBlock *InsertAtEnd)
201 : Instruction(RetTy, Instruction::LandingPad, nullptr, 0, InsertAtEnd) {
202 init(NumReservedValues, NameStr);
205 LandingPadInst::LandingPadInst(const LandingPadInst &LP)
206 : Instruction(LP.getType(), Instruction::LandingPad, nullptr,
207 LP.getNumOperands()),
208 ReservedSpace(LP.getNumOperands()) {
209 allocHungoffUses(LP.getNumOperands());
210 Use *OL = getOperandList();
211 const Use *InOL = LP.getOperandList();
212 for (unsigned I = 0, E = ReservedSpace; I != E; ++I)
213 OL[I] = InOL[I];
215 setCleanup(LP.isCleanup());
218 LandingPadInst *LandingPadInst::Create(Type *RetTy, unsigned NumReservedClauses,
219 const Twine &NameStr,
220 Instruction *InsertBefore) {
221 return new LandingPadInst(RetTy, NumReservedClauses, NameStr, InsertBefore);
224 LandingPadInst *LandingPadInst::Create(Type *RetTy, unsigned NumReservedClauses,
225 const Twine &NameStr,
226 BasicBlock *InsertAtEnd) {
227 return new LandingPadInst(RetTy, NumReservedClauses, NameStr, InsertAtEnd);
230 void LandingPadInst::init(unsigned NumReservedValues, const Twine &NameStr) {
231 ReservedSpace = NumReservedValues;
232 setNumHungOffUseOperands(0);
233 allocHungoffUses(ReservedSpace);
234 setName(NameStr);
235 setCleanup(false);
238 /// growOperands - grow operands - This grows the operand list in response to a
239 /// push_back style of operation. This grows the number of ops by 2 times.
240 void LandingPadInst::growOperands(unsigned Size) {
241 unsigned e = getNumOperands();
242 if (ReservedSpace >= e + Size) return;
243 ReservedSpace = (std::max(e, 1U) + Size / 2) * 2;
244 growHungoffUses(ReservedSpace);
247 void LandingPadInst::addClause(Constant *Val) {
248 unsigned OpNo = getNumOperands();
249 growOperands(1);
250 assert(OpNo < ReservedSpace && "Growing didn't work!");
251 setNumHungOffUseOperands(getNumOperands() + 1);
252 getOperandList()[OpNo] = Val;
255 //===----------------------------------------------------------------------===//
256 // CallBase Implementation
257 //===----------------------------------------------------------------------===//
259 Function *CallBase::getCaller() { return getParent()->getParent(); }
261 unsigned CallBase::getNumSubclassExtraOperandsDynamic() const {
262 assert(getOpcode() == Instruction::CallBr && "Unexpected opcode!");
263 return cast<CallBrInst>(this)->getNumIndirectDests() + 1;
266 bool CallBase::isIndirectCall() const {
267 const Value *V = getCalledValue();
268 if (isa<Function>(V) || isa<Constant>(V))
269 return false;
270 if (const CallInst *CI = dyn_cast<CallInst>(this))
271 if (CI->isInlineAsm())
272 return false;
273 return true;
276 /// Tests if this call site must be tail call optimized. Only a CallInst can
277 /// be tail call optimized.
278 bool CallBase::isMustTailCall() const {
279 if (auto *CI = dyn_cast<CallInst>(this))
280 return CI->isMustTailCall();
281 return false;
284 /// Tests if this call site is marked as a tail call.
285 bool CallBase::isTailCall() const {
286 if (auto *CI = dyn_cast<CallInst>(this))
287 return CI->isTailCall();
288 return false;
291 Intrinsic::ID CallBase::getIntrinsicID() const {
292 if (auto *F = getCalledFunction())
293 return F->getIntrinsicID();
294 return Intrinsic::not_intrinsic;
297 bool CallBase::isReturnNonNull() const {
298 if (hasRetAttr(Attribute::NonNull))
299 return true;
301 if (getDereferenceableBytes(AttributeList::ReturnIndex) > 0 &&
302 !NullPointerIsDefined(getCaller(),
303 getType()->getPointerAddressSpace()))
304 return true;
306 return false;
309 Value *CallBase::getReturnedArgOperand() const {
310 unsigned Index;
312 if (Attrs.hasAttrSomewhere(Attribute::Returned, &Index) && Index)
313 return getArgOperand(Index - AttributeList::FirstArgIndex);
314 if (const Function *F = getCalledFunction())
315 if (F->getAttributes().hasAttrSomewhere(Attribute::Returned, &Index) &&
316 Index)
317 return getArgOperand(Index - AttributeList::FirstArgIndex);
319 return nullptr;
322 bool CallBase::hasRetAttr(Attribute::AttrKind Kind) const {
323 if (Attrs.hasAttribute(AttributeList::ReturnIndex, Kind))
324 return true;
326 // Look at the callee, if available.
327 if (const Function *F = getCalledFunction())
328 return F->getAttributes().hasAttribute(AttributeList::ReturnIndex, Kind);
329 return false;
332 /// Determine whether the argument or parameter has the given attribute.
333 bool CallBase::paramHasAttr(unsigned ArgNo, Attribute::AttrKind Kind) const {
334 assert(ArgNo < getNumArgOperands() && "Param index out of bounds!");
336 if (Attrs.hasParamAttribute(ArgNo, Kind))
337 return true;
338 if (const Function *F = getCalledFunction())
339 return F->getAttributes().hasParamAttribute(ArgNo, Kind);
340 return false;
343 bool CallBase::hasFnAttrOnCalledFunction(Attribute::AttrKind Kind) const {
344 if (const Function *F = getCalledFunction())
345 return F->getAttributes().hasAttribute(AttributeList::FunctionIndex, Kind);
346 return false;
349 bool CallBase::hasFnAttrOnCalledFunction(StringRef Kind) const {
350 if (const Function *F = getCalledFunction())
351 return F->getAttributes().hasAttribute(AttributeList::FunctionIndex, Kind);
352 return false;
355 CallBase::op_iterator
356 CallBase::populateBundleOperandInfos(ArrayRef<OperandBundleDef> Bundles,
357 const unsigned BeginIndex) {
358 auto It = op_begin() + BeginIndex;
359 for (auto &B : Bundles)
360 It = std::copy(B.input_begin(), B.input_end(), It);
362 auto *ContextImpl = getContext().pImpl;
363 auto BI = Bundles.begin();
364 unsigned CurrentIndex = BeginIndex;
366 for (auto &BOI : bundle_op_infos()) {
367 assert(BI != Bundles.end() && "Incorrect allocation?");
369 BOI.Tag = ContextImpl->getOrInsertBundleTag(BI->getTag());
370 BOI.Begin = CurrentIndex;
371 BOI.End = CurrentIndex + BI->input_size();
372 CurrentIndex = BOI.End;
373 BI++;
376 assert(BI == Bundles.end() && "Incorrect allocation?");
378 return It;
381 //===----------------------------------------------------------------------===//
382 // CallInst Implementation
383 //===----------------------------------------------------------------------===//
385 void CallInst::init(FunctionType *FTy, Value *Func, ArrayRef<Value *> Args,
386 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr) {
387 this->FTy = FTy;
388 assert(getNumOperands() == Args.size() + CountBundleInputs(Bundles) + 1 &&
389 "NumOperands not set up?");
390 setCalledOperand(Func);
392 #ifndef NDEBUG
393 assert((Args.size() == FTy->getNumParams() ||
394 (FTy->isVarArg() && Args.size() > FTy->getNumParams())) &&
395 "Calling a function with bad signature!");
397 for (unsigned i = 0; i != Args.size(); ++i)
398 assert((i >= FTy->getNumParams() ||
399 FTy->getParamType(i) == Args[i]->getType()) &&
400 "Calling a function with a bad signature!");
401 #endif
403 llvm::copy(Args, op_begin());
405 auto It = populateBundleOperandInfos(Bundles, Args.size());
406 (void)It;
407 assert(It + 1 == op_end() && "Should add up!");
409 setName(NameStr);
412 void CallInst::init(FunctionType *FTy, Value *Func, const Twine &NameStr) {
413 this->FTy = FTy;
414 assert(getNumOperands() == 1 && "NumOperands not set up?");
415 setCalledOperand(Func);
417 assert(FTy->getNumParams() == 0 && "Calling a function with bad signature");
419 setName(NameStr);
422 CallInst::CallInst(FunctionType *Ty, Value *Func, const Twine &Name,
423 Instruction *InsertBefore)
424 : CallBase(Ty->getReturnType(), Instruction::Call,
425 OperandTraits<CallBase>::op_end(this) - 1, 1, InsertBefore) {
426 init(Ty, Func, Name);
429 CallInst::CallInst(FunctionType *Ty, Value *Func, const Twine &Name,
430 BasicBlock *InsertAtEnd)
431 : CallBase(Ty->getReturnType(), Instruction::Call,
432 OperandTraits<CallBase>::op_end(this) - 1, 1, InsertAtEnd) {
433 init(Ty, Func, Name);
436 CallInst::CallInst(const CallInst &CI)
437 : CallBase(CI.Attrs, CI.FTy, CI.getType(), Instruction::Call,
438 OperandTraits<CallBase>::op_end(this) - CI.getNumOperands(),
439 CI.getNumOperands()) {
440 setTailCallKind(CI.getTailCallKind());
441 setCallingConv(CI.getCallingConv());
443 std::copy(CI.op_begin(), CI.op_end(), op_begin());
444 std::copy(CI.bundle_op_info_begin(), CI.bundle_op_info_end(),
445 bundle_op_info_begin());
446 SubclassOptionalData = CI.SubclassOptionalData;
449 CallInst *CallInst::Create(CallInst *CI, ArrayRef<OperandBundleDef> OpB,
450 Instruction *InsertPt) {
451 std::vector<Value *> Args(CI->arg_begin(), CI->arg_end());
453 auto *NewCI = CallInst::Create(CI->getFunctionType(), CI->getCalledValue(),
454 Args, OpB, CI->getName(), InsertPt);
455 NewCI->setTailCallKind(CI->getTailCallKind());
456 NewCI->setCallingConv(CI->getCallingConv());
457 NewCI->SubclassOptionalData = CI->SubclassOptionalData;
458 NewCI->setAttributes(CI->getAttributes());
459 NewCI->setDebugLoc(CI->getDebugLoc());
460 return NewCI;
463 // Update profile weight for call instruction by scaling it using the ratio
464 // of S/T. The meaning of "branch_weights" meta data for call instruction is
465 // transfered to represent call count.
466 void CallInst::updateProfWeight(uint64_t S, uint64_t T) {
467 auto *ProfileData = getMetadata(LLVMContext::MD_prof);
468 if (ProfileData == nullptr)
469 return;
471 auto *ProfDataName = dyn_cast<MDString>(ProfileData->getOperand(0));
472 if (!ProfDataName || (!ProfDataName->getString().equals("branch_weights") &&
473 !ProfDataName->getString().equals("VP")))
474 return;
476 if (T == 0) {
477 LLVM_DEBUG(dbgs() << "Attempting to update profile weights will result in "
478 "div by 0. Ignoring. Likely the function "
479 << getParent()->getParent()->getName()
480 << " has 0 entry count, and contains call instructions "
481 "with non-zero prof info.");
482 return;
485 MDBuilder MDB(getContext());
486 SmallVector<Metadata *, 3> Vals;
487 Vals.push_back(ProfileData->getOperand(0));
488 APInt APS(128, S), APT(128, T);
489 if (ProfDataName->getString().equals("branch_weights") &&
490 ProfileData->getNumOperands() > 0) {
491 // Using APInt::div may be expensive, but most cases should fit 64 bits.
492 APInt Val(128, mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(1))
493 ->getValue()
494 .getZExtValue());
495 Val *= APS;
496 Vals.push_back(MDB.createConstant(ConstantInt::get(
497 Type::getInt64Ty(getContext()), Val.udiv(APT).getLimitedValue())));
498 } else if (ProfDataName->getString().equals("VP"))
499 for (unsigned i = 1; i < ProfileData->getNumOperands(); i += 2) {
500 // The first value is the key of the value profile, which will not change.
501 Vals.push_back(ProfileData->getOperand(i));
502 // Using APInt::div may be expensive, but most cases should fit 64 bits.
503 APInt Val(128,
504 mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(i + 1))
505 ->getValue()
506 .getZExtValue());
507 Val *= APS;
508 Vals.push_back(MDB.createConstant(
509 ConstantInt::get(Type::getInt64Ty(getContext()),
510 Val.udiv(APT).getLimitedValue())));
512 setMetadata(LLVMContext::MD_prof, MDNode::get(getContext(), Vals));
515 /// IsConstantOne - Return true only if val is constant int 1
516 static bool IsConstantOne(Value *val) {
517 assert(val && "IsConstantOne does not work with nullptr val");
518 const ConstantInt *CVal = dyn_cast<ConstantInt>(val);
519 return CVal && CVal->isOne();
522 static Instruction *createMalloc(Instruction *InsertBefore,
523 BasicBlock *InsertAtEnd, Type *IntPtrTy,
524 Type *AllocTy, Value *AllocSize,
525 Value *ArraySize,
526 ArrayRef<OperandBundleDef> OpB,
527 Function *MallocF, const Twine &Name) {
528 assert(((!InsertBefore && InsertAtEnd) || (InsertBefore && !InsertAtEnd)) &&
529 "createMalloc needs either InsertBefore or InsertAtEnd");
531 // malloc(type) becomes:
532 // bitcast (i8* malloc(typeSize)) to type*
533 // malloc(type, arraySize) becomes:
534 // bitcast (i8* malloc(typeSize*arraySize)) to type*
535 if (!ArraySize)
536 ArraySize = ConstantInt::get(IntPtrTy, 1);
537 else if (ArraySize->getType() != IntPtrTy) {
538 if (InsertBefore)
539 ArraySize = CastInst::CreateIntegerCast(ArraySize, IntPtrTy, false,
540 "", InsertBefore);
541 else
542 ArraySize = CastInst::CreateIntegerCast(ArraySize, IntPtrTy, false,
543 "", InsertAtEnd);
546 if (!IsConstantOne(ArraySize)) {
547 if (IsConstantOne(AllocSize)) {
548 AllocSize = ArraySize; // Operand * 1 = Operand
549 } else if (Constant *CO = dyn_cast<Constant>(ArraySize)) {
550 Constant *Scale = ConstantExpr::getIntegerCast(CO, IntPtrTy,
551 false /*ZExt*/);
552 // Malloc arg is constant product of type size and array size
553 AllocSize = ConstantExpr::getMul(Scale, cast<Constant>(AllocSize));
554 } else {
555 // Multiply type size by the array size...
556 if (InsertBefore)
557 AllocSize = BinaryOperator::CreateMul(ArraySize, AllocSize,
558 "mallocsize", InsertBefore);
559 else
560 AllocSize = BinaryOperator::CreateMul(ArraySize, AllocSize,
561 "mallocsize", InsertAtEnd);
565 assert(AllocSize->getType() == IntPtrTy && "malloc arg is wrong size");
566 // Create the call to Malloc.
567 BasicBlock *BB = InsertBefore ? InsertBefore->getParent() : InsertAtEnd;
568 Module *M = BB->getParent()->getParent();
569 Type *BPTy = Type::getInt8PtrTy(BB->getContext());
570 FunctionCallee MallocFunc = MallocF;
571 if (!MallocFunc)
572 // prototype malloc as "void *malloc(size_t)"
573 MallocFunc = M->getOrInsertFunction("malloc", BPTy, IntPtrTy);
574 PointerType *AllocPtrType = PointerType::getUnqual(AllocTy);
575 CallInst *MCall = nullptr;
576 Instruction *Result = nullptr;
577 if (InsertBefore) {
578 MCall = CallInst::Create(MallocFunc, AllocSize, OpB, "malloccall",
579 InsertBefore);
580 Result = MCall;
581 if (Result->getType() != AllocPtrType)
582 // Create a cast instruction to convert to the right type...
583 Result = new BitCastInst(MCall, AllocPtrType, Name, InsertBefore);
584 } else {
585 MCall = CallInst::Create(MallocFunc, AllocSize, OpB, "malloccall");
586 Result = MCall;
587 if (Result->getType() != AllocPtrType) {
588 InsertAtEnd->getInstList().push_back(MCall);
589 // Create a cast instruction to convert to the right type...
590 Result = new BitCastInst(MCall, AllocPtrType, Name);
593 MCall->setTailCall();
594 if (Function *F = dyn_cast<Function>(MallocFunc.getCallee())) {
595 MCall->setCallingConv(F->getCallingConv());
596 if (!F->returnDoesNotAlias())
597 F->setReturnDoesNotAlias();
599 assert(!MCall->getType()->isVoidTy() && "Malloc has void return type");
601 return Result;
604 /// CreateMalloc - Generate the IR for a call to malloc:
605 /// 1. Compute the malloc call's argument as the specified type's size,
606 /// possibly multiplied by the array size if the array size is not
607 /// constant 1.
608 /// 2. Call malloc with that argument.
609 /// 3. Bitcast the result of the malloc call to the specified type.
610 Instruction *CallInst::CreateMalloc(Instruction *InsertBefore,
611 Type *IntPtrTy, Type *AllocTy,
612 Value *AllocSize, Value *ArraySize,
613 Function *MallocF,
614 const Twine &Name) {
615 return createMalloc(InsertBefore, nullptr, IntPtrTy, AllocTy, AllocSize,
616 ArraySize, None, MallocF, Name);
618 Instruction *CallInst::CreateMalloc(Instruction *InsertBefore,
619 Type *IntPtrTy, Type *AllocTy,
620 Value *AllocSize, Value *ArraySize,
621 ArrayRef<OperandBundleDef> OpB,
622 Function *MallocF,
623 const Twine &Name) {
624 return createMalloc(InsertBefore, nullptr, IntPtrTy, AllocTy, AllocSize,
625 ArraySize, OpB, MallocF, Name);
628 /// CreateMalloc - Generate the IR for a call to malloc:
629 /// 1. Compute the malloc call's argument as the specified type's size,
630 /// possibly multiplied by the array size if the array size is not
631 /// constant 1.
632 /// 2. Call malloc with that argument.
633 /// 3. Bitcast the result of the malloc call to the specified type.
634 /// Note: This function does not add the bitcast to the basic block, that is the
635 /// responsibility of the caller.
636 Instruction *CallInst::CreateMalloc(BasicBlock *InsertAtEnd,
637 Type *IntPtrTy, Type *AllocTy,
638 Value *AllocSize, Value *ArraySize,
639 Function *MallocF, const Twine &Name) {
640 return createMalloc(nullptr, InsertAtEnd, IntPtrTy, AllocTy, AllocSize,
641 ArraySize, None, MallocF, Name);
643 Instruction *CallInst::CreateMalloc(BasicBlock *InsertAtEnd,
644 Type *IntPtrTy, Type *AllocTy,
645 Value *AllocSize, Value *ArraySize,
646 ArrayRef<OperandBundleDef> OpB,
647 Function *MallocF, const Twine &Name) {
648 return createMalloc(nullptr, InsertAtEnd, IntPtrTy, AllocTy, AllocSize,
649 ArraySize, OpB, MallocF, Name);
652 static Instruction *createFree(Value *Source,
653 ArrayRef<OperandBundleDef> Bundles,
654 Instruction *InsertBefore,
655 BasicBlock *InsertAtEnd) {
656 assert(((!InsertBefore && InsertAtEnd) || (InsertBefore && !InsertAtEnd)) &&
657 "createFree needs either InsertBefore or InsertAtEnd");
658 assert(Source->getType()->isPointerTy() &&
659 "Can not free something of nonpointer type!");
661 BasicBlock *BB = InsertBefore ? InsertBefore->getParent() : InsertAtEnd;
662 Module *M = BB->getParent()->getParent();
664 Type *VoidTy = Type::getVoidTy(M->getContext());
665 Type *IntPtrTy = Type::getInt8PtrTy(M->getContext());
666 // prototype free as "void free(void*)"
667 FunctionCallee FreeFunc = M->getOrInsertFunction("free", VoidTy, IntPtrTy);
668 CallInst *Result = nullptr;
669 Value *PtrCast = Source;
670 if (InsertBefore) {
671 if (Source->getType() != IntPtrTy)
672 PtrCast = new BitCastInst(Source, IntPtrTy, "", InsertBefore);
673 Result = CallInst::Create(FreeFunc, PtrCast, Bundles, "", InsertBefore);
674 } else {
675 if (Source->getType() != IntPtrTy)
676 PtrCast = new BitCastInst(Source, IntPtrTy, "", InsertAtEnd);
677 Result = CallInst::Create(FreeFunc, PtrCast, Bundles, "");
679 Result->setTailCall();
680 if (Function *F = dyn_cast<Function>(FreeFunc.getCallee()))
681 Result->setCallingConv(F->getCallingConv());
683 return Result;
686 /// CreateFree - Generate the IR for a call to the builtin free function.
687 Instruction *CallInst::CreateFree(Value *Source, Instruction *InsertBefore) {
688 return createFree(Source, None, InsertBefore, nullptr);
690 Instruction *CallInst::CreateFree(Value *Source,
691 ArrayRef<OperandBundleDef> Bundles,
692 Instruction *InsertBefore) {
693 return createFree(Source, Bundles, InsertBefore, nullptr);
696 /// CreateFree - Generate the IR for a call to the builtin free function.
697 /// Note: This function does not add the call to the basic block, that is the
698 /// responsibility of the caller.
699 Instruction *CallInst::CreateFree(Value *Source, BasicBlock *InsertAtEnd) {
700 Instruction *FreeCall = createFree(Source, None, nullptr, InsertAtEnd);
701 assert(FreeCall && "CreateFree did not create a CallInst");
702 return FreeCall;
704 Instruction *CallInst::CreateFree(Value *Source,
705 ArrayRef<OperandBundleDef> Bundles,
706 BasicBlock *InsertAtEnd) {
707 Instruction *FreeCall = createFree(Source, Bundles, nullptr, InsertAtEnd);
708 assert(FreeCall && "CreateFree did not create a CallInst");
709 return FreeCall;
712 //===----------------------------------------------------------------------===//
713 // InvokeInst Implementation
714 //===----------------------------------------------------------------------===//
716 void InvokeInst::init(FunctionType *FTy, Value *Fn, BasicBlock *IfNormal,
717 BasicBlock *IfException, ArrayRef<Value *> Args,
718 ArrayRef<OperandBundleDef> Bundles,
719 const Twine &NameStr) {
720 this->FTy = FTy;
722 assert((int)getNumOperands() ==
723 ComputeNumOperands(Args.size(), CountBundleInputs(Bundles)) &&
724 "NumOperands not set up?");
725 setNormalDest(IfNormal);
726 setUnwindDest(IfException);
727 setCalledOperand(Fn);
729 #ifndef NDEBUG
730 assert(((Args.size() == FTy->getNumParams()) ||
731 (FTy->isVarArg() && Args.size() > FTy->getNumParams())) &&
732 "Invoking a function with bad signature");
734 for (unsigned i = 0, e = Args.size(); i != e; i++)
735 assert((i >= FTy->getNumParams() ||
736 FTy->getParamType(i) == Args[i]->getType()) &&
737 "Invoking a function with a bad signature!");
738 #endif
740 llvm::copy(Args, op_begin());
742 auto It = populateBundleOperandInfos(Bundles, Args.size());
743 (void)It;
744 assert(It + 3 == op_end() && "Should add up!");
746 setName(NameStr);
749 InvokeInst::InvokeInst(const InvokeInst &II)
750 : CallBase(II.Attrs, II.FTy, II.getType(), Instruction::Invoke,
751 OperandTraits<CallBase>::op_end(this) - II.getNumOperands(),
752 II.getNumOperands()) {
753 setCallingConv(II.getCallingConv());
754 std::copy(II.op_begin(), II.op_end(), op_begin());
755 std::copy(II.bundle_op_info_begin(), II.bundle_op_info_end(),
756 bundle_op_info_begin());
757 SubclassOptionalData = II.SubclassOptionalData;
760 InvokeInst *InvokeInst::Create(InvokeInst *II, ArrayRef<OperandBundleDef> OpB,
761 Instruction *InsertPt) {
762 std::vector<Value *> Args(II->arg_begin(), II->arg_end());
764 auto *NewII = InvokeInst::Create(II->getFunctionType(), II->getCalledValue(),
765 II->getNormalDest(), II->getUnwindDest(),
766 Args, OpB, II->getName(), InsertPt);
767 NewII->setCallingConv(II->getCallingConv());
768 NewII->SubclassOptionalData = II->SubclassOptionalData;
769 NewII->setAttributes(II->getAttributes());
770 NewII->setDebugLoc(II->getDebugLoc());
771 return NewII;
775 LandingPadInst *InvokeInst::getLandingPadInst() const {
776 return cast<LandingPadInst>(getUnwindDest()->getFirstNonPHI());
779 //===----------------------------------------------------------------------===//
780 // CallBrInst Implementation
781 //===----------------------------------------------------------------------===//
783 void CallBrInst::init(FunctionType *FTy, Value *Fn, BasicBlock *Fallthrough,
784 ArrayRef<BasicBlock *> IndirectDests,
785 ArrayRef<Value *> Args,
786 ArrayRef<OperandBundleDef> Bundles,
787 const Twine &NameStr) {
788 this->FTy = FTy;
790 assert((int)getNumOperands() ==
791 ComputeNumOperands(Args.size(), IndirectDests.size(),
792 CountBundleInputs(Bundles)) &&
793 "NumOperands not set up?");
794 NumIndirectDests = IndirectDests.size();
795 setDefaultDest(Fallthrough);
796 for (unsigned i = 0; i != NumIndirectDests; ++i)
797 setIndirectDest(i, IndirectDests[i]);
798 setCalledOperand(Fn);
800 #ifndef NDEBUG
801 assert(((Args.size() == FTy->getNumParams()) ||
802 (FTy->isVarArg() && Args.size() > FTy->getNumParams())) &&
803 "Calling a function with bad signature");
805 for (unsigned i = 0, e = Args.size(); i != e; i++)
806 assert((i >= FTy->getNumParams() ||
807 FTy->getParamType(i) == Args[i]->getType()) &&
808 "Calling a function with a bad signature!");
809 #endif
811 std::copy(Args.begin(), Args.end(), op_begin());
813 auto It = populateBundleOperandInfos(Bundles, Args.size());
814 (void)It;
815 assert(It + 2 + IndirectDests.size() == op_end() && "Should add up!");
817 setName(NameStr);
820 void CallBrInst::updateArgBlockAddresses(unsigned i, BasicBlock *B) {
821 assert(getNumIndirectDests() > i && "IndirectDest # out of range for callbr");
822 if (BasicBlock *OldBB = getIndirectDest(i)) {
823 BlockAddress *Old = BlockAddress::get(OldBB);
824 BlockAddress *New = BlockAddress::get(B);
825 for (unsigned ArgNo = 0, e = getNumArgOperands(); ArgNo != e; ++ArgNo)
826 if (dyn_cast<BlockAddress>(getArgOperand(ArgNo)) == Old)
827 setArgOperand(ArgNo, New);
831 CallBrInst::CallBrInst(const CallBrInst &CBI)
832 : CallBase(CBI.Attrs, CBI.FTy, CBI.getType(), Instruction::CallBr,
833 OperandTraits<CallBase>::op_end(this) - CBI.getNumOperands(),
834 CBI.getNumOperands()) {
835 setCallingConv(CBI.getCallingConv());
836 std::copy(CBI.op_begin(), CBI.op_end(), op_begin());
837 std::copy(CBI.bundle_op_info_begin(), CBI.bundle_op_info_end(),
838 bundle_op_info_begin());
839 SubclassOptionalData = CBI.SubclassOptionalData;
840 NumIndirectDests = CBI.NumIndirectDests;
843 CallBrInst *CallBrInst::Create(CallBrInst *CBI, ArrayRef<OperandBundleDef> OpB,
844 Instruction *InsertPt) {
845 std::vector<Value *> Args(CBI->arg_begin(), CBI->arg_end());
847 auto *NewCBI = CallBrInst::Create(CBI->getFunctionType(),
848 CBI->getCalledValue(),
849 CBI->getDefaultDest(),
850 CBI->getIndirectDests(),
851 Args, OpB, CBI->getName(), InsertPt);
852 NewCBI->setCallingConv(CBI->getCallingConv());
853 NewCBI->SubclassOptionalData = CBI->SubclassOptionalData;
854 NewCBI->setAttributes(CBI->getAttributes());
855 NewCBI->setDebugLoc(CBI->getDebugLoc());
856 NewCBI->NumIndirectDests = CBI->NumIndirectDests;
857 return NewCBI;
860 //===----------------------------------------------------------------------===//
861 // ReturnInst Implementation
862 //===----------------------------------------------------------------------===//
864 ReturnInst::ReturnInst(const ReturnInst &RI)
865 : Instruction(Type::getVoidTy(RI.getContext()), Instruction::Ret,
866 OperandTraits<ReturnInst>::op_end(this) - RI.getNumOperands(),
867 RI.getNumOperands()) {
868 if (RI.getNumOperands())
869 Op<0>() = RI.Op<0>();
870 SubclassOptionalData = RI.SubclassOptionalData;
873 ReturnInst::ReturnInst(LLVMContext &C, Value *retVal, Instruction *InsertBefore)
874 : Instruction(Type::getVoidTy(C), Instruction::Ret,
875 OperandTraits<ReturnInst>::op_end(this) - !!retVal, !!retVal,
876 InsertBefore) {
877 if (retVal)
878 Op<0>() = retVal;
881 ReturnInst::ReturnInst(LLVMContext &C, Value *retVal, BasicBlock *InsertAtEnd)
882 : Instruction(Type::getVoidTy(C), Instruction::Ret,
883 OperandTraits<ReturnInst>::op_end(this) - !!retVal, !!retVal,
884 InsertAtEnd) {
885 if (retVal)
886 Op<0>() = retVal;
889 ReturnInst::ReturnInst(LLVMContext &Context, BasicBlock *InsertAtEnd)
890 : Instruction(Type::getVoidTy(Context), Instruction::Ret,
891 OperandTraits<ReturnInst>::op_end(this), 0, InsertAtEnd) {}
893 //===----------------------------------------------------------------------===//
894 // ResumeInst Implementation
895 //===----------------------------------------------------------------------===//
897 ResumeInst::ResumeInst(const ResumeInst &RI)
898 : Instruction(Type::getVoidTy(RI.getContext()), Instruction::Resume,
899 OperandTraits<ResumeInst>::op_begin(this), 1) {
900 Op<0>() = RI.Op<0>();
903 ResumeInst::ResumeInst(Value *Exn, Instruction *InsertBefore)
904 : Instruction(Type::getVoidTy(Exn->getContext()), Instruction::Resume,
905 OperandTraits<ResumeInst>::op_begin(this), 1, InsertBefore) {
906 Op<0>() = Exn;
909 ResumeInst::ResumeInst(Value *Exn, BasicBlock *InsertAtEnd)
910 : Instruction(Type::getVoidTy(Exn->getContext()), Instruction::Resume,
911 OperandTraits<ResumeInst>::op_begin(this), 1, InsertAtEnd) {
912 Op<0>() = Exn;
915 //===----------------------------------------------------------------------===//
916 // CleanupReturnInst Implementation
917 //===----------------------------------------------------------------------===//
919 CleanupReturnInst::CleanupReturnInst(const CleanupReturnInst &CRI)
920 : Instruction(CRI.getType(), Instruction::CleanupRet,
921 OperandTraits<CleanupReturnInst>::op_end(this) -
922 CRI.getNumOperands(),
923 CRI.getNumOperands()) {
924 setInstructionSubclassData(CRI.getSubclassDataFromInstruction());
925 Op<0>() = CRI.Op<0>();
926 if (CRI.hasUnwindDest())
927 Op<1>() = CRI.Op<1>();
930 void CleanupReturnInst::init(Value *CleanupPad, BasicBlock *UnwindBB) {
931 if (UnwindBB)
932 setInstructionSubclassData(getSubclassDataFromInstruction() | 1);
934 Op<0>() = CleanupPad;
935 if (UnwindBB)
936 Op<1>() = UnwindBB;
939 CleanupReturnInst::CleanupReturnInst(Value *CleanupPad, BasicBlock *UnwindBB,
940 unsigned Values, Instruction *InsertBefore)
941 : Instruction(Type::getVoidTy(CleanupPad->getContext()),
942 Instruction::CleanupRet,
943 OperandTraits<CleanupReturnInst>::op_end(this) - Values,
944 Values, InsertBefore) {
945 init(CleanupPad, UnwindBB);
948 CleanupReturnInst::CleanupReturnInst(Value *CleanupPad, BasicBlock *UnwindBB,
949 unsigned Values, BasicBlock *InsertAtEnd)
950 : Instruction(Type::getVoidTy(CleanupPad->getContext()),
951 Instruction::CleanupRet,
952 OperandTraits<CleanupReturnInst>::op_end(this) - Values,
953 Values, InsertAtEnd) {
954 init(CleanupPad, UnwindBB);
957 //===----------------------------------------------------------------------===//
958 // CatchReturnInst Implementation
959 //===----------------------------------------------------------------------===//
960 void CatchReturnInst::init(Value *CatchPad, BasicBlock *BB) {
961 Op<0>() = CatchPad;
962 Op<1>() = BB;
965 CatchReturnInst::CatchReturnInst(const CatchReturnInst &CRI)
966 : Instruction(Type::getVoidTy(CRI.getContext()), Instruction::CatchRet,
967 OperandTraits<CatchReturnInst>::op_begin(this), 2) {
968 Op<0>() = CRI.Op<0>();
969 Op<1>() = CRI.Op<1>();
972 CatchReturnInst::CatchReturnInst(Value *CatchPad, BasicBlock *BB,
973 Instruction *InsertBefore)
974 : Instruction(Type::getVoidTy(BB->getContext()), Instruction::CatchRet,
975 OperandTraits<CatchReturnInst>::op_begin(this), 2,
976 InsertBefore) {
977 init(CatchPad, BB);
980 CatchReturnInst::CatchReturnInst(Value *CatchPad, BasicBlock *BB,
981 BasicBlock *InsertAtEnd)
982 : Instruction(Type::getVoidTy(BB->getContext()), Instruction::CatchRet,
983 OperandTraits<CatchReturnInst>::op_begin(this), 2,
984 InsertAtEnd) {
985 init(CatchPad, BB);
988 //===----------------------------------------------------------------------===//
989 // CatchSwitchInst Implementation
990 //===----------------------------------------------------------------------===//
992 CatchSwitchInst::CatchSwitchInst(Value *ParentPad, BasicBlock *UnwindDest,
993 unsigned NumReservedValues,
994 const Twine &NameStr,
995 Instruction *InsertBefore)
996 : Instruction(ParentPad->getType(), Instruction::CatchSwitch, nullptr, 0,
997 InsertBefore) {
998 if (UnwindDest)
999 ++NumReservedValues;
1000 init(ParentPad, UnwindDest, NumReservedValues + 1);
1001 setName(NameStr);
1004 CatchSwitchInst::CatchSwitchInst(Value *ParentPad, BasicBlock *UnwindDest,
1005 unsigned NumReservedValues,
1006 const Twine &NameStr, BasicBlock *InsertAtEnd)
1007 : Instruction(ParentPad->getType(), Instruction::CatchSwitch, nullptr, 0,
1008 InsertAtEnd) {
1009 if (UnwindDest)
1010 ++NumReservedValues;
1011 init(ParentPad, UnwindDest, NumReservedValues + 1);
1012 setName(NameStr);
1015 CatchSwitchInst::CatchSwitchInst(const CatchSwitchInst &CSI)
1016 : Instruction(CSI.getType(), Instruction::CatchSwitch, nullptr,
1017 CSI.getNumOperands()) {
1018 init(CSI.getParentPad(), CSI.getUnwindDest(), CSI.getNumOperands());
1019 setNumHungOffUseOperands(ReservedSpace);
1020 Use *OL = getOperandList();
1021 const Use *InOL = CSI.getOperandList();
1022 for (unsigned I = 1, E = ReservedSpace; I != E; ++I)
1023 OL[I] = InOL[I];
1026 void CatchSwitchInst::init(Value *ParentPad, BasicBlock *UnwindDest,
1027 unsigned NumReservedValues) {
1028 assert(ParentPad && NumReservedValues);
1030 ReservedSpace = NumReservedValues;
1031 setNumHungOffUseOperands(UnwindDest ? 2 : 1);
1032 allocHungoffUses(ReservedSpace);
1034 Op<0>() = ParentPad;
1035 if (UnwindDest) {
1036 setInstructionSubclassData(getSubclassDataFromInstruction() | 1);
1037 setUnwindDest(UnwindDest);
1041 /// growOperands - grow operands - This grows the operand list in response to a
1042 /// push_back style of operation. This grows the number of ops by 2 times.
1043 void CatchSwitchInst::growOperands(unsigned Size) {
1044 unsigned NumOperands = getNumOperands();
1045 assert(NumOperands >= 1);
1046 if (ReservedSpace >= NumOperands + Size)
1047 return;
1048 ReservedSpace = (NumOperands + Size / 2) * 2;
1049 growHungoffUses(ReservedSpace);
1052 void CatchSwitchInst::addHandler(BasicBlock *Handler) {
1053 unsigned OpNo = getNumOperands();
1054 growOperands(1);
1055 assert(OpNo < ReservedSpace && "Growing didn't work!");
1056 setNumHungOffUseOperands(getNumOperands() + 1);
1057 getOperandList()[OpNo] = Handler;
1060 void CatchSwitchInst::removeHandler(handler_iterator HI) {
1061 // Move all subsequent handlers up one.
1062 Use *EndDst = op_end() - 1;
1063 for (Use *CurDst = HI.getCurrent(); CurDst != EndDst; ++CurDst)
1064 *CurDst = *(CurDst + 1);
1065 // Null out the last handler use.
1066 *EndDst = nullptr;
1068 setNumHungOffUseOperands(getNumOperands() - 1);
1071 //===----------------------------------------------------------------------===//
1072 // FuncletPadInst Implementation
1073 //===----------------------------------------------------------------------===//
1074 void FuncletPadInst::init(Value *ParentPad, ArrayRef<Value *> Args,
1075 const Twine &NameStr) {
1076 assert(getNumOperands() == 1 + Args.size() && "NumOperands not set up?");
1077 llvm::copy(Args, op_begin());
1078 setParentPad(ParentPad);
1079 setName(NameStr);
1082 FuncletPadInst::FuncletPadInst(const FuncletPadInst &FPI)
1083 : Instruction(FPI.getType(), FPI.getOpcode(),
1084 OperandTraits<FuncletPadInst>::op_end(this) -
1085 FPI.getNumOperands(),
1086 FPI.getNumOperands()) {
1087 std::copy(FPI.op_begin(), FPI.op_end(), op_begin());
1088 setParentPad(FPI.getParentPad());
1091 FuncletPadInst::FuncletPadInst(Instruction::FuncletPadOps Op, Value *ParentPad,
1092 ArrayRef<Value *> Args, unsigned Values,
1093 const Twine &NameStr, Instruction *InsertBefore)
1094 : Instruction(ParentPad->getType(), Op,
1095 OperandTraits<FuncletPadInst>::op_end(this) - Values, Values,
1096 InsertBefore) {
1097 init(ParentPad, Args, NameStr);
1100 FuncletPadInst::FuncletPadInst(Instruction::FuncletPadOps Op, Value *ParentPad,
1101 ArrayRef<Value *> Args, unsigned Values,
1102 const Twine &NameStr, BasicBlock *InsertAtEnd)
1103 : Instruction(ParentPad->getType(), Op,
1104 OperandTraits<FuncletPadInst>::op_end(this) - Values, Values,
1105 InsertAtEnd) {
1106 init(ParentPad, Args, NameStr);
1109 //===----------------------------------------------------------------------===//
1110 // UnreachableInst Implementation
1111 //===----------------------------------------------------------------------===//
1113 UnreachableInst::UnreachableInst(LLVMContext &Context,
1114 Instruction *InsertBefore)
1115 : Instruction(Type::getVoidTy(Context), Instruction::Unreachable, nullptr,
1116 0, InsertBefore) {}
1117 UnreachableInst::UnreachableInst(LLVMContext &Context, BasicBlock *InsertAtEnd)
1118 : Instruction(Type::getVoidTy(Context), Instruction::Unreachable, nullptr,
1119 0, InsertAtEnd) {}
1121 //===----------------------------------------------------------------------===//
1122 // BranchInst Implementation
1123 //===----------------------------------------------------------------------===//
1125 void BranchInst::AssertOK() {
1126 if (isConditional())
1127 assert(getCondition()->getType()->isIntegerTy(1) &&
1128 "May only branch on boolean predicates!");
1131 BranchInst::BranchInst(BasicBlock *IfTrue, Instruction *InsertBefore)
1132 : Instruction(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
1133 OperandTraits<BranchInst>::op_end(this) - 1, 1,
1134 InsertBefore) {
1135 assert(IfTrue && "Branch destination may not be null!");
1136 Op<-1>() = IfTrue;
1139 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
1140 Instruction *InsertBefore)
1141 : Instruction(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
1142 OperandTraits<BranchInst>::op_end(this) - 3, 3,
1143 InsertBefore) {
1144 Op<-1>() = IfTrue;
1145 Op<-2>() = IfFalse;
1146 Op<-3>() = Cond;
1147 #ifndef NDEBUG
1148 AssertOK();
1149 #endif
1152 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *InsertAtEnd)
1153 : Instruction(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
1154 OperandTraits<BranchInst>::op_end(this) - 1, 1, InsertAtEnd) {
1155 assert(IfTrue && "Branch destination may not be null!");
1156 Op<-1>() = IfTrue;
1159 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
1160 BasicBlock *InsertAtEnd)
1161 : Instruction(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
1162 OperandTraits<BranchInst>::op_end(this) - 3, 3, InsertAtEnd) {
1163 Op<-1>() = IfTrue;
1164 Op<-2>() = IfFalse;
1165 Op<-3>() = Cond;
1166 #ifndef NDEBUG
1167 AssertOK();
1168 #endif
1171 BranchInst::BranchInst(const BranchInst &BI)
1172 : Instruction(Type::getVoidTy(BI.getContext()), Instruction::Br,
1173 OperandTraits<BranchInst>::op_end(this) - BI.getNumOperands(),
1174 BI.getNumOperands()) {
1175 Op<-1>() = BI.Op<-1>();
1176 if (BI.getNumOperands() != 1) {
1177 assert(BI.getNumOperands() == 3 && "BR can have 1 or 3 operands!");
1178 Op<-3>() = BI.Op<-3>();
1179 Op<-2>() = BI.Op<-2>();
1181 SubclassOptionalData = BI.SubclassOptionalData;
1184 void BranchInst::swapSuccessors() {
1185 assert(isConditional() &&
1186 "Cannot swap successors of an unconditional branch");
1187 Op<-1>().swap(Op<-2>());
1189 // Update profile metadata if present and it matches our structural
1190 // expectations.
1191 swapProfMetadata();
1194 //===----------------------------------------------------------------------===//
1195 // AllocaInst Implementation
1196 //===----------------------------------------------------------------------===//
1198 static Value *getAISize(LLVMContext &Context, Value *Amt) {
1199 if (!Amt)
1200 Amt = ConstantInt::get(Type::getInt32Ty(Context), 1);
1201 else {
1202 assert(!isa<BasicBlock>(Amt) &&
1203 "Passed basic block into allocation size parameter! Use other ctor");
1204 assert(Amt->getType()->isIntegerTy() &&
1205 "Allocation array size is not an integer!");
1207 return Amt;
1210 AllocaInst::AllocaInst(Type *Ty, unsigned AddrSpace, const Twine &Name,
1211 Instruction *InsertBefore)
1212 : AllocaInst(Ty, AddrSpace, /*ArraySize=*/nullptr, Name, InsertBefore) {}
1214 AllocaInst::AllocaInst(Type *Ty, unsigned AddrSpace, const Twine &Name,
1215 BasicBlock *InsertAtEnd)
1216 : AllocaInst(Ty, AddrSpace, /*ArraySize=*/nullptr, Name, InsertAtEnd) {}
1218 AllocaInst::AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize,
1219 const Twine &Name, Instruction *InsertBefore)
1220 : AllocaInst(Ty, AddrSpace, ArraySize, /*Align=*/0, Name, InsertBefore) {}
1222 AllocaInst::AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize,
1223 const Twine &Name, BasicBlock *InsertAtEnd)
1224 : AllocaInst(Ty, AddrSpace, ArraySize, /*Align=*/0, Name, InsertAtEnd) {}
1226 AllocaInst::AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize,
1227 unsigned Align, const Twine &Name,
1228 Instruction *InsertBefore)
1229 : UnaryInstruction(PointerType::get(Ty, AddrSpace), Alloca,
1230 getAISize(Ty->getContext(), ArraySize), InsertBefore),
1231 AllocatedType(Ty) {
1232 setAlignment(MaybeAlign(Align));
1233 assert(!Ty->isVoidTy() && "Cannot allocate void!");
1234 setName(Name);
1237 AllocaInst::AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize,
1238 unsigned Align, const Twine &Name,
1239 BasicBlock *InsertAtEnd)
1240 : UnaryInstruction(PointerType::get(Ty, AddrSpace), Alloca,
1241 getAISize(Ty->getContext(), ArraySize), InsertAtEnd),
1242 AllocatedType(Ty) {
1243 setAlignment(MaybeAlign(Align));
1244 assert(!Ty->isVoidTy() && "Cannot allocate void!");
1245 setName(Name);
1248 void AllocaInst::setAlignment(MaybeAlign Align) {
1249 assert((!Align || *Align <= MaximumAlignment) &&
1250 "Alignment is greater than MaximumAlignment!");
1251 setInstructionSubclassData((getSubclassDataFromInstruction() & ~31) |
1252 encode(Align));
1253 if (Align)
1254 assert(getAlignment() == Align->value() &&
1255 "Alignment representation error!");
1256 else
1257 assert(getAlignment() == 0 && "Alignment representation error!");
1260 bool AllocaInst::isArrayAllocation() const {
1261 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(0)))
1262 return !CI->isOne();
1263 return true;
1266 /// isStaticAlloca - Return true if this alloca is in the entry block of the
1267 /// function and is a constant size. If so, the code generator will fold it
1268 /// into the prolog/epilog code, so it is basically free.
1269 bool AllocaInst::isStaticAlloca() const {
1270 // Must be constant size.
1271 if (!isa<ConstantInt>(getArraySize())) return false;
1273 // Must be in the entry block.
1274 const BasicBlock *Parent = getParent();
1275 return Parent == &Parent->getParent()->front() && !isUsedWithInAlloca();
1278 //===----------------------------------------------------------------------===//
1279 // LoadInst Implementation
1280 //===----------------------------------------------------------------------===//
1282 void LoadInst::AssertOK() {
1283 assert(getOperand(0)->getType()->isPointerTy() &&
1284 "Ptr must have pointer type.");
1285 assert(!(isAtomic() && getAlignment() == 0) &&
1286 "Alignment required for atomic load");
1289 LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name,
1290 Instruction *InsertBef)
1291 : LoadInst(Ty, Ptr, Name, /*isVolatile=*/false, InsertBef) {}
1293 LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name,
1294 BasicBlock *InsertAE)
1295 : LoadInst(Ty, Ptr, Name, /*isVolatile=*/false, InsertAE) {}
1297 LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile,
1298 Instruction *InsertBef)
1299 : LoadInst(Ty, Ptr, Name, isVolatile, /*Align=*/None, InsertBef) {}
1301 LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile,
1302 BasicBlock *InsertAE)
1303 : LoadInst(Ty, Ptr, Name, isVolatile, /*Align=*/None, InsertAE) {}
1305 LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile,
1306 MaybeAlign Align, Instruction *InsertBef)
1307 : LoadInst(Ty, Ptr, Name, isVolatile, Align, AtomicOrdering::NotAtomic,
1308 SyncScope::System, InsertBef) {}
1310 LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile,
1311 MaybeAlign Align, BasicBlock *InsertAE)
1312 : LoadInst(Ty, Ptr, Name, isVolatile, Align, AtomicOrdering::NotAtomic,
1313 SyncScope::System, InsertAE) {}
1315 LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile,
1316 MaybeAlign Align, AtomicOrdering Order, SyncScope::ID SSID,
1317 Instruction *InsertBef)
1318 : UnaryInstruction(Ty, Load, Ptr, InsertBef) {
1319 assert(Ty == cast<PointerType>(Ptr->getType())->getElementType());
1320 setVolatile(isVolatile);
1321 setAlignment(MaybeAlign(Align));
1322 setAtomic(Order, SSID);
1323 AssertOK();
1324 setName(Name);
1327 LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile,
1328 MaybeAlign Align, AtomicOrdering Order, SyncScope::ID SSID,
1329 BasicBlock *InsertAE)
1330 : UnaryInstruction(Ty, Load, Ptr, InsertAE) {
1331 assert(Ty == cast<PointerType>(Ptr->getType())->getElementType());
1332 setVolatile(isVolatile);
1333 setAlignment(Align);
1334 setAtomic(Order, SSID);
1335 AssertOK();
1336 setName(Name);
1339 void LoadInst::setAlignment(MaybeAlign Align) {
1340 assert((!Align || *Align <= MaximumAlignment) &&
1341 "Alignment is greater than MaximumAlignment!");
1342 setInstructionSubclassData((getSubclassDataFromInstruction() & ~(31 << 1)) |
1343 (encode(Align) << 1));
1344 if (Align)
1345 assert(getAlignment() == Align->value() &&
1346 "Alignment representation error!");
1347 else
1348 assert(getAlignment() == 0 && "Alignment representation error!");
1351 //===----------------------------------------------------------------------===//
1352 // StoreInst Implementation
1353 //===----------------------------------------------------------------------===//
1355 void StoreInst::AssertOK() {
1356 assert(getOperand(0) && getOperand(1) && "Both operands must be non-null!");
1357 assert(getOperand(1)->getType()->isPointerTy() &&
1358 "Ptr must have pointer type!");
1359 assert(getOperand(0)->getType() ==
1360 cast<PointerType>(getOperand(1)->getType())->getElementType()
1361 && "Ptr must be a pointer to Val type!");
1362 assert(!(isAtomic() && getAlignment() == 0) &&
1363 "Alignment required for atomic store");
1366 StoreInst::StoreInst(Value *val, Value *addr, Instruction *InsertBefore)
1367 : StoreInst(val, addr, /*isVolatile=*/false, InsertBefore) {}
1369 StoreInst::StoreInst(Value *val, Value *addr, BasicBlock *InsertAtEnd)
1370 : StoreInst(val, addr, /*isVolatile=*/false, InsertAtEnd) {}
1372 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1373 Instruction *InsertBefore)
1374 : StoreInst(val, addr, isVolatile, /*Align=*/0, InsertBefore) {}
1376 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1377 BasicBlock *InsertAtEnd)
1378 : StoreInst(val, addr, isVolatile, /*Align=*/0, InsertAtEnd) {}
1380 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile, unsigned Align,
1381 Instruction *InsertBefore)
1382 : StoreInst(val, addr, isVolatile, Align, AtomicOrdering::NotAtomic,
1383 SyncScope::System, InsertBefore) {}
1385 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile, unsigned Align,
1386 BasicBlock *InsertAtEnd)
1387 : StoreInst(val, addr, isVolatile, Align, AtomicOrdering::NotAtomic,
1388 SyncScope::System, InsertAtEnd) {}
1390 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1391 unsigned Align, AtomicOrdering Order,
1392 SyncScope::ID SSID,
1393 Instruction *InsertBefore)
1394 : Instruction(Type::getVoidTy(val->getContext()), Store,
1395 OperandTraits<StoreInst>::op_begin(this),
1396 OperandTraits<StoreInst>::operands(this),
1397 InsertBefore) {
1398 Op<0>() = val;
1399 Op<1>() = addr;
1400 setVolatile(isVolatile);
1401 setAlignment(MaybeAlign(Align));
1402 setAtomic(Order, SSID);
1403 AssertOK();
1406 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1407 unsigned Align, AtomicOrdering Order,
1408 SyncScope::ID SSID,
1409 BasicBlock *InsertAtEnd)
1410 : Instruction(Type::getVoidTy(val->getContext()), Store,
1411 OperandTraits<StoreInst>::op_begin(this),
1412 OperandTraits<StoreInst>::operands(this),
1413 InsertAtEnd) {
1414 Op<0>() = val;
1415 Op<1>() = addr;
1416 setVolatile(isVolatile);
1417 setAlignment(MaybeAlign(Align));
1418 setAtomic(Order, SSID);
1419 AssertOK();
1422 void StoreInst::setAlignment(MaybeAlign Align) {
1423 assert((!Align || *Align <= MaximumAlignment) &&
1424 "Alignment is greater than MaximumAlignment!");
1425 setInstructionSubclassData((getSubclassDataFromInstruction() & ~(31 << 1)) |
1426 (encode(Align) << 1));
1427 if (Align)
1428 assert(getAlignment() == Align->value() &&
1429 "Alignment representation error!");
1430 else
1431 assert(getAlignment() == 0 && "Alignment representation error!");
1434 //===----------------------------------------------------------------------===//
1435 // AtomicCmpXchgInst Implementation
1436 //===----------------------------------------------------------------------===//
1438 void AtomicCmpXchgInst::Init(Value *Ptr, Value *Cmp, Value *NewVal,
1439 AtomicOrdering SuccessOrdering,
1440 AtomicOrdering FailureOrdering,
1441 SyncScope::ID SSID) {
1442 Op<0>() = Ptr;
1443 Op<1>() = Cmp;
1444 Op<2>() = NewVal;
1445 setSuccessOrdering(SuccessOrdering);
1446 setFailureOrdering(FailureOrdering);
1447 setSyncScopeID(SSID);
1449 assert(getOperand(0) && getOperand(1) && getOperand(2) &&
1450 "All operands must be non-null!");
1451 assert(getOperand(0)->getType()->isPointerTy() &&
1452 "Ptr must have pointer type!");
1453 assert(getOperand(1)->getType() ==
1454 cast<PointerType>(getOperand(0)->getType())->getElementType()
1455 && "Ptr must be a pointer to Cmp type!");
1456 assert(getOperand(2)->getType() ==
1457 cast<PointerType>(getOperand(0)->getType())->getElementType()
1458 && "Ptr must be a pointer to NewVal type!");
1459 assert(SuccessOrdering != AtomicOrdering::NotAtomic &&
1460 "AtomicCmpXchg instructions must be atomic!");
1461 assert(FailureOrdering != AtomicOrdering::NotAtomic &&
1462 "AtomicCmpXchg instructions must be atomic!");
1463 assert(!isStrongerThan(FailureOrdering, SuccessOrdering) &&
1464 "AtomicCmpXchg failure argument shall be no stronger than the success "
1465 "argument");
1466 assert(FailureOrdering != AtomicOrdering::Release &&
1467 FailureOrdering != AtomicOrdering::AcquireRelease &&
1468 "AtomicCmpXchg failure ordering cannot include release semantics");
1471 AtomicCmpXchgInst::AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal,
1472 AtomicOrdering SuccessOrdering,
1473 AtomicOrdering FailureOrdering,
1474 SyncScope::ID SSID,
1475 Instruction *InsertBefore)
1476 : Instruction(
1477 StructType::get(Cmp->getType(), Type::getInt1Ty(Cmp->getContext())),
1478 AtomicCmpXchg, OperandTraits<AtomicCmpXchgInst>::op_begin(this),
1479 OperandTraits<AtomicCmpXchgInst>::operands(this), InsertBefore) {
1480 Init(Ptr, Cmp, NewVal, SuccessOrdering, FailureOrdering, SSID);
1483 AtomicCmpXchgInst::AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal,
1484 AtomicOrdering SuccessOrdering,
1485 AtomicOrdering FailureOrdering,
1486 SyncScope::ID SSID,
1487 BasicBlock *InsertAtEnd)
1488 : Instruction(
1489 StructType::get(Cmp->getType(), Type::getInt1Ty(Cmp->getContext())),
1490 AtomicCmpXchg, OperandTraits<AtomicCmpXchgInst>::op_begin(this),
1491 OperandTraits<AtomicCmpXchgInst>::operands(this), InsertAtEnd) {
1492 Init(Ptr, Cmp, NewVal, SuccessOrdering, FailureOrdering, SSID);
1495 //===----------------------------------------------------------------------===//
1496 // AtomicRMWInst Implementation
1497 //===----------------------------------------------------------------------===//
1499 void AtomicRMWInst::Init(BinOp Operation, Value *Ptr, Value *Val,
1500 AtomicOrdering Ordering,
1501 SyncScope::ID SSID) {
1502 Op<0>() = Ptr;
1503 Op<1>() = Val;
1504 setOperation(Operation);
1505 setOrdering(Ordering);
1506 setSyncScopeID(SSID);
1508 assert(getOperand(0) && getOperand(1) &&
1509 "All operands must be non-null!");
1510 assert(getOperand(0)->getType()->isPointerTy() &&
1511 "Ptr must have pointer type!");
1512 assert(getOperand(1)->getType() ==
1513 cast<PointerType>(getOperand(0)->getType())->getElementType()
1514 && "Ptr must be a pointer to Val type!");
1515 assert(Ordering != AtomicOrdering::NotAtomic &&
1516 "AtomicRMW instructions must be atomic!");
1519 AtomicRMWInst::AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val,
1520 AtomicOrdering Ordering,
1521 SyncScope::ID SSID,
1522 Instruction *InsertBefore)
1523 : Instruction(Val->getType(), AtomicRMW,
1524 OperandTraits<AtomicRMWInst>::op_begin(this),
1525 OperandTraits<AtomicRMWInst>::operands(this),
1526 InsertBefore) {
1527 Init(Operation, Ptr, Val, Ordering, SSID);
1530 AtomicRMWInst::AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val,
1531 AtomicOrdering Ordering,
1532 SyncScope::ID SSID,
1533 BasicBlock *InsertAtEnd)
1534 : Instruction(Val->getType(), AtomicRMW,
1535 OperandTraits<AtomicRMWInst>::op_begin(this),
1536 OperandTraits<AtomicRMWInst>::operands(this),
1537 InsertAtEnd) {
1538 Init(Operation, Ptr, Val, Ordering, SSID);
1541 StringRef AtomicRMWInst::getOperationName(BinOp Op) {
1542 switch (Op) {
1543 case AtomicRMWInst::Xchg:
1544 return "xchg";
1545 case AtomicRMWInst::Add:
1546 return "add";
1547 case AtomicRMWInst::Sub:
1548 return "sub";
1549 case AtomicRMWInst::And:
1550 return "and";
1551 case AtomicRMWInst::Nand:
1552 return "nand";
1553 case AtomicRMWInst::Or:
1554 return "or";
1555 case AtomicRMWInst::Xor:
1556 return "xor";
1557 case AtomicRMWInst::Max:
1558 return "max";
1559 case AtomicRMWInst::Min:
1560 return "min";
1561 case AtomicRMWInst::UMax:
1562 return "umax";
1563 case AtomicRMWInst::UMin:
1564 return "umin";
1565 case AtomicRMWInst::FAdd:
1566 return "fadd";
1567 case AtomicRMWInst::FSub:
1568 return "fsub";
1569 case AtomicRMWInst::BAD_BINOP:
1570 return "<invalid operation>";
1573 llvm_unreachable("invalid atomicrmw operation");
1576 //===----------------------------------------------------------------------===//
1577 // FenceInst Implementation
1578 //===----------------------------------------------------------------------===//
1580 FenceInst::FenceInst(LLVMContext &C, AtomicOrdering Ordering,
1581 SyncScope::ID SSID,
1582 Instruction *InsertBefore)
1583 : Instruction(Type::getVoidTy(C), Fence, nullptr, 0, InsertBefore) {
1584 setOrdering(Ordering);
1585 setSyncScopeID(SSID);
1588 FenceInst::FenceInst(LLVMContext &C, AtomicOrdering Ordering,
1589 SyncScope::ID SSID,
1590 BasicBlock *InsertAtEnd)
1591 : Instruction(Type::getVoidTy(C), Fence, nullptr, 0, InsertAtEnd) {
1592 setOrdering(Ordering);
1593 setSyncScopeID(SSID);
1596 //===----------------------------------------------------------------------===//
1597 // GetElementPtrInst Implementation
1598 //===----------------------------------------------------------------------===//
1600 void GetElementPtrInst::init(Value *Ptr, ArrayRef<Value *> IdxList,
1601 const Twine &Name) {
1602 assert(getNumOperands() == 1 + IdxList.size() &&
1603 "NumOperands not initialized?");
1604 Op<0>() = Ptr;
1605 llvm::copy(IdxList, op_begin() + 1);
1606 setName(Name);
1609 GetElementPtrInst::GetElementPtrInst(const GetElementPtrInst &GEPI)
1610 : Instruction(GEPI.getType(), GetElementPtr,
1611 OperandTraits<GetElementPtrInst>::op_end(this) -
1612 GEPI.getNumOperands(),
1613 GEPI.getNumOperands()),
1614 SourceElementType(GEPI.SourceElementType),
1615 ResultElementType(GEPI.ResultElementType) {
1616 std::copy(GEPI.op_begin(), GEPI.op_end(), op_begin());
1617 SubclassOptionalData = GEPI.SubclassOptionalData;
1620 /// getIndexedType - Returns the type of the element that would be accessed with
1621 /// a gep instruction with the specified parameters.
1623 /// The Idxs pointer should point to a continuous piece of memory containing the
1624 /// indices, either as Value* or uint64_t.
1626 /// A null type is returned if the indices are invalid for the specified
1627 /// pointer type.
1629 template <typename IndexTy>
1630 static Type *getIndexedTypeInternal(Type *Agg, ArrayRef<IndexTy> IdxList) {
1631 // Handle the special case of the empty set index set, which is always valid.
1632 if (IdxList.empty())
1633 return Agg;
1635 // If there is at least one index, the top level type must be sized, otherwise
1636 // it cannot be 'stepped over'.
1637 if (!Agg->isSized())
1638 return nullptr;
1640 unsigned CurIdx = 1;
1641 for (; CurIdx != IdxList.size(); ++CurIdx) {
1642 CompositeType *CT = dyn_cast<CompositeType>(Agg);
1643 if (!CT || CT->isPointerTy()) return nullptr;
1644 IndexTy Index = IdxList[CurIdx];
1645 if (!CT->indexValid(Index)) return nullptr;
1646 Agg = CT->getTypeAtIndex(Index);
1648 return CurIdx == IdxList.size() ? Agg : nullptr;
1651 Type *GetElementPtrInst::getIndexedType(Type *Ty, ArrayRef<Value *> IdxList) {
1652 return getIndexedTypeInternal(Ty, IdxList);
1655 Type *GetElementPtrInst::getIndexedType(Type *Ty,
1656 ArrayRef<Constant *> IdxList) {
1657 return getIndexedTypeInternal(Ty, IdxList);
1660 Type *GetElementPtrInst::getIndexedType(Type *Ty, ArrayRef<uint64_t> IdxList) {
1661 return getIndexedTypeInternal(Ty, IdxList);
1664 /// hasAllZeroIndices - Return true if all of the indices of this GEP are
1665 /// zeros. If so, the result pointer and the first operand have the same
1666 /// value, just potentially different types.
1667 bool GetElementPtrInst::hasAllZeroIndices() const {
1668 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1669 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(i))) {
1670 if (!CI->isZero()) return false;
1671 } else {
1672 return false;
1675 return true;
1678 /// hasAllConstantIndices - Return true if all of the indices of this GEP are
1679 /// constant integers. If so, the result pointer and the first operand have
1680 /// a constant offset between them.
1681 bool GetElementPtrInst::hasAllConstantIndices() const {
1682 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1683 if (!isa<ConstantInt>(getOperand(i)))
1684 return false;
1686 return true;
1689 void GetElementPtrInst::setIsInBounds(bool B) {
1690 cast<GEPOperator>(this)->setIsInBounds(B);
1693 bool GetElementPtrInst::isInBounds() const {
1694 return cast<GEPOperator>(this)->isInBounds();
1697 bool GetElementPtrInst::accumulateConstantOffset(const DataLayout &DL,
1698 APInt &Offset) const {
1699 // Delegate to the generic GEPOperator implementation.
1700 return cast<GEPOperator>(this)->accumulateConstantOffset(DL, Offset);
1703 //===----------------------------------------------------------------------===//
1704 // ExtractElementInst Implementation
1705 //===----------------------------------------------------------------------===//
1707 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1708 const Twine &Name,
1709 Instruction *InsertBef)
1710 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1711 ExtractElement,
1712 OperandTraits<ExtractElementInst>::op_begin(this),
1713 2, InsertBef) {
1714 assert(isValidOperands(Val, Index) &&
1715 "Invalid extractelement instruction operands!");
1716 Op<0>() = Val;
1717 Op<1>() = Index;
1718 setName(Name);
1721 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1722 const Twine &Name,
1723 BasicBlock *InsertAE)
1724 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1725 ExtractElement,
1726 OperandTraits<ExtractElementInst>::op_begin(this),
1727 2, InsertAE) {
1728 assert(isValidOperands(Val, Index) &&
1729 "Invalid extractelement instruction operands!");
1731 Op<0>() = Val;
1732 Op<1>() = Index;
1733 setName(Name);
1736 bool ExtractElementInst::isValidOperands(const Value *Val, const Value *Index) {
1737 if (!Val->getType()->isVectorTy() || !Index->getType()->isIntegerTy())
1738 return false;
1739 return true;
1742 //===----------------------------------------------------------------------===//
1743 // InsertElementInst Implementation
1744 //===----------------------------------------------------------------------===//
1746 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1747 const Twine &Name,
1748 Instruction *InsertBef)
1749 : Instruction(Vec->getType(), InsertElement,
1750 OperandTraits<InsertElementInst>::op_begin(this),
1751 3, InsertBef) {
1752 assert(isValidOperands(Vec, Elt, Index) &&
1753 "Invalid insertelement instruction operands!");
1754 Op<0>() = Vec;
1755 Op<1>() = Elt;
1756 Op<2>() = Index;
1757 setName(Name);
1760 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1761 const Twine &Name,
1762 BasicBlock *InsertAE)
1763 : Instruction(Vec->getType(), InsertElement,
1764 OperandTraits<InsertElementInst>::op_begin(this),
1765 3, InsertAE) {
1766 assert(isValidOperands(Vec, Elt, Index) &&
1767 "Invalid insertelement instruction operands!");
1769 Op<0>() = Vec;
1770 Op<1>() = Elt;
1771 Op<2>() = Index;
1772 setName(Name);
1775 bool InsertElementInst::isValidOperands(const Value *Vec, const Value *Elt,
1776 const Value *Index) {
1777 if (!Vec->getType()->isVectorTy())
1778 return false; // First operand of insertelement must be vector type.
1780 if (Elt->getType() != cast<VectorType>(Vec->getType())->getElementType())
1781 return false;// Second operand of insertelement must be vector element type.
1783 if (!Index->getType()->isIntegerTy())
1784 return false; // Third operand of insertelement must be i32.
1785 return true;
1788 //===----------------------------------------------------------------------===//
1789 // ShuffleVectorInst Implementation
1790 //===----------------------------------------------------------------------===//
1792 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1793 const Twine &Name,
1794 Instruction *InsertBefore)
1795 : Instruction(VectorType::get(cast<VectorType>(V1->getType())->getElementType(),
1796 cast<VectorType>(Mask->getType())->getElementCount()),
1797 ShuffleVector,
1798 OperandTraits<ShuffleVectorInst>::op_begin(this),
1799 OperandTraits<ShuffleVectorInst>::operands(this),
1800 InsertBefore) {
1801 assert(isValidOperands(V1, V2, Mask) &&
1802 "Invalid shuffle vector instruction operands!");
1803 Op<0>() = V1;
1804 Op<1>() = V2;
1805 Op<2>() = Mask;
1806 setName(Name);
1809 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1810 const Twine &Name,
1811 BasicBlock *InsertAtEnd)
1812 : Instruction(VectorType::get(cast<VectorType>(V1->getType())->getElementType(),
1813 cast<VectorType>(Mask->getType())->getElementCount()),
1814 ShuffleVector,
1815 OperandTraits<ShuffleVectorInst>::op_begin(this),
1816 OperandTraits<ShuffleVectorInst>::operands(this),
1817 InsertAtEnd) {
1818 assert(isValidOperands(V1, V2, Mask) &&
1819 "Invalid shuffle vector instruction operands!");
1821 Op<0>() = V1;
1822 Op<1>() = V2;
1823 Op<2>() = Mask;
1824 setName(Name);
1827 void ShuffleVectorInst::commute() {
1828 int NumOpElts = Op<0>()->getType()->getVectorNumElements();
1829 int NumMaskElts = getMask()->getType()->getVectorNumElements();
1830 SmallVector<Constant*, 16> NewMask(NumMaskElts);
1831 Type *Int32Ty = Type::getInt32Ty(getContext());
1832 for (int i = 0; i != NumMaskElts; ++i) {
1833 int MaskElt = getMaskValue(i);
1834 if (MaskElt == -1) {
1835 NewMask[i] = UndefValue::get(Int32Ty);
1836 continue;
1838 assert(MaskElt >= 0 && MaskElt < 2 * NumOpElts && "Out-of-range mask");
1839 MaskElt = (MaskElt < NumOpElts) ? MaskElt + NumOpElts : MaskElt - NumOpElts;
1840 NewMask[i] = ConstantInt::get(Int32Ty, MaskElt);
1842 Op<2>() = ConstantVector::get(NewMask);
1843 Op<0>().swap(Op<1>());
1846 bool ShuffleVectorInst::isValidOperands(const Value *V1, const Value *V2,
1847 const Value *Mask) {
1848 // V1 and V2 must be vectors of the same type.
1849 if (!V1->getType()->isVectorTy() || V1->getType() != V2->getType())
1850 return false;
1852 // Mask must be vector of i32.
1853 auto *MaskTy = dyn_cast<VectorType>(Mask->getType());
1854 if (!MaskTy || !MaskTy->getElementType()->isIntegerTy(32))
1855 return false;
1857 // Check to see if Mask is valid.
1858 if (isa<UndefValue>(Mask) || isa<ConstantAggregateZero>(Mask))
1859 return true;
1861 if (const auto *MV = dyn_cast<ConstantVector>(Mask)) {
1862 unsigned V1Size = cast<VectorType>(V1->getType())->getNumElements();
1863 for (Value *Op : MV->operands()) {
1864 if (auto *CI = dyn_cast<ConstantInt>(Op)) {
1865 if (CI->uge(V1Size*2))
1866 return false;
1867 } else if (!isa<UndefValue>(Op)) {
1868 return false;
1871 return true;
1874 if (const auto *CDS = dyn_cast<ConstantDataSequential>(Mask)) {
1875 unsigned V1Size = cast<VectorType>(V1->getType())->getNumElements();
1876 for (unsigned i = 0, e = MaskTy->getNumElements(); i != e; ++i)
1877 if (CDS->getElementAsInteger(i) >= V1Size*2)
1878 return false;
1879 return true;
1882 // The bitcode reader can create a place holder for a forward reference
1883 // used as the shuffle mask. When this occurs, the shuffle mask will
1884 // fall into this case and fail. To avoid this error, do this bit of
1885 // ugliness to allow such a mask pass.
1886 if (const auto *CE = dyn_cast<ConstantExpr>(Mask))
1887 if (CE->getOpcode() == Instruction::UserOp1)
1888 return true;
1890 return false;
1893 int ShuffleVectorInst::getMaskValue(const Constant *Mask, unsigned i) {
1894 assert(i < Mask->getType()->getVectorNumElements() && "Index out of range");
1895 if (auto *CDS = dyn_cast<ConstantDataSequential>(Mask))
1896 return CDS->getElementAsInteger(i);
1897 Constant *C = Mask->getAggregateElement(i);
1898 if (isa<UndefValue>(C))
1899 return -1;
1900 return cast<ConstantInt>(C)->getZExtValue();
1903 void ShuffleVectorInst::getShuffleMask(const Constant *Mask,
1904 SmallVectorImpl<int> &Result) {
1905 unsigned NumElts = Mask->getType()->getVectorNumElements();
1907 if (auto *CDS = dyn_cast<ConstantDataSequential>(Mask)) {
1908 for (unsigned i = 0; i != NumElts; ++i)
1909 Result.push_back(CDS->getElementAsInteger(i));
1910 return;
1912 for (unsigned i = 0; i != NumElts; ++i) {
1913 Constant *C = Mask->getAggregateElement(i);
1914 Result.push_back(isa<UndefValue>(C) ? -1 :
1915 cast<ConstantInt>(C)->getZExtValue());
1919 static bool isSingleSourceMaskImpl(ArrayRef<int> Mask, int NumOpElts) {
1920 assert(!Mask.empty() && "Shuffle mask must contain elements");
1921 bool UsesLHS = false;
1922 bool UsesRHS = false;
1923 for (int i = 0, NumMaskElts = Mask.size(); i < NumMaskElts; ++i) {
1924 if (Mask[i] == -1)
1925 continue;
1926 assert(Mask[i] >= 0 && Mask[i] < (NumOpElts * 2) &&
1927 "Out-of-bounds shuffle mask element");
1928 UsesLHS |= (Mask[i] < NumOpElts);
1929 UsesRHS |= (Mask[i] >= NumOpElts);
1930 if (UsesLHS && UsesRHS)
1931 return false;
1933 assert((UsesLHS ^ UsesRHS) && "Should have selected from exactly 1 source");
1934 return true;
1937 bool ShuffleVectorInst::isSingleSourceMask(ArrayRef<int> Mask) {
1938 // We don't have vector operand size information, so assume operands are the
1939 // same size as the mask.
1940 return isSingleSourceMaskImpl(Mask, Mask.size());
1943 static bool isIdentityMaskImpl(ArrayRef<int> Mask, int NumOpElts) {
1944 if (!isSingleSourceMaskImpl(Mask, NumOpElts))
1945 return false;
1946 for (int i = 0, NumMaskElts = Mask.size(); i < NumMaskElts; ++i) {
1947 if (Mask[i] == -1)
1948 continue;
1949 if (Mask[i] != i && Mask[i] != (NumOpElts + i))
1950 return false;
1952 return true;
1955 bool ShuffleVectorInst::isIdentityMask(ArrayRef<int> Mask) {
1956 // We don't have vector operand size information, so assume operands are the
1957 // same size as the mask.
1958 return isIdentityMaskImpl(Mask, Mask.size());
1961 bool ShuffleVectorInst::isReverseMask(ArrayRef<int> Mask) {
1962 if (!isSingleSourceMask(Mask))
1963 return false;
1964 for (int i = 0, NumElts = Mask.size(); i < NumElts; ++i) {
1965 if (Mask[i] == -1)
1966 continue;
1967 if (Mask[i] != (NumElts - 1 - i) && Mask[i] != (NumElts + NumElts - 1 - i))
1968 return false;
1970 return true;
1973 bool ShuffleVectorInst::isZeroEltSplatMask(ArrayRef<int> Mask) {
1974 if (!isSingleSourceMask(Mask))
1975 return false;
1976 for (int i = 0, NumElts = Mask.size(); i < NumElts; ++i) {
1977 if (Mask[i] == -1)
1978 continue;
1979 if (Mask[i] != 0 && Mask[i] != NumElts)
1980 return false;
1982 return true;
1985 bool ShuffleVectorInst::isSelectMask(ArrayRef<int> Mask) {
1986 // Select is differentiated from identity. It requires using both sources.
1987 if (isSingleSourceMask(Mask))
1988 return false;
1989 for (int i = 0, NumElts = Mask.size(); i < NumElts; ++i) {
1990 if (Mask[i] == -1)
1991 continue;
1992 if (Mask[i] != i && Mask[i] != (NumElts + i))
1993 return false;
1995 return true;
1998 bool ShuffleVectorInst::isTransposeMask(ArrayRef<int> Mask) {
1999 // Example masks that will return true:
2000 // v1 = <a, b, c, d>
2001 // v2 = <e, f, g, h>
2002 // trn1 = shufflevector v1, v2 <0, 4, 2, 6> = <a, e, c, g>
2003 // trn2 = shufflevector v1, v2 <1, 5, 3, 7> = <b, f, d, h>
2005 // 1. The number of elements in the mask must be a power-of-2 and at least 2.
2006 int NumElts = Mask.size();
2007 if (NumElts < 2 || !isPowerOf2_32(NumElts))
2008 return false;
2010 // 2. The first element of the mask must be either a 0 or a 1.
2011 if (Mask[0] != 0 && Mask[0] != 1)
2012 return false;
2014 // 3. The difference between the first 2 elements must be equal to the
2015 // number of elements in the mask.
2016 if ((Mask[1] - Mask[0]) != NumElts)
2017 return false;
2019 // 4. The difference between consecutive even-numbered and odd-numbered
2020 // elements must be equal to 2.
2021 for (int i = 2; i < NumElts; ++i) {
2022 int MaskEltVal = Mask[i];
2023 if (MaskEltVal == -1)
2024 return false;
2025 int MaskEltPrevVal = Mask[i - 2];
2026 if (MaskEltVal - MaskEltPrevVal != 2)
2027 return false;
2029 return true;
2032 bool ShuffleVectorInst::isExtractSubvectorMask(ArrayRef<int> Mask,
2033 int NumSrcElts, int &Index) {
2034 // Must extract from a single source.
2035 if (!isSingleSourceMaskImpl(Mask, NumSrcElts))
2036 return false;
2038 // Must be smaller (else this is an Identity shuffle).
2039 if (NumSrcElts <= (int)Mask.size())
2040 return false;
2042 // Find start of extraction, accounting that we may start with an UNDEF.
2043 int SubIndex = -1;
2044 for (int i = 0, e = Mask.size(); i != e; ++i) {
2045 int M = Mask[i];
2046 if (M < 0)
2047 continue;
2048 int Offset = (M % NumSrcElts) - i;
2049 if (0 <= SubIndex && SubIndex != Offset)
2050 return false;
2051 SubIndex = Offset;
2054 if (0 <= SubIndex) {
2055 Index = SubIndex;
2056 return true;
2058 return false;
2061 bool ShuffleVectorInst::isIdentityWithPadding() const {
2062 int NumOpElts = Op<0>()->getType()->getVectorNumElements();
2063 int NumMaskElts = getType()->getVectorNumElements();
2064 if (NumMaskElts <= NumOpElts)
2065 return false;
2067 // The first part of the mask must choose elements from exactly 1 source op.
2068 SmallVector<int, 16> Mask = getShuffleMask();
2069 if (!isIdentityMaskImpl(Mask, NumOpElts))
2070 return false;
2072 // All extending must be with undef elements.
2073 for (int i = NumOpElts; i < NumMaskElts; ++i)
2074 if (Mask[i] != -1)
2075 return false;
2077 return true;
2080 bool ShuffleVectorInst::isIdentityWithExtract() const {
2081 int NumOpElts = Op<0>()->getType()->getVectorNumElements();
2082 int NumMaskElts = getType()->getVectorNumElements();
2083 if (NumMaskElts >= NumOpElts)
2084 return false;
2086 return isIdentityMaskImpl(getShuffleMask(), NumOpElts);
2089 bool ShuffleVectorInst::isConcat() const {
2090 // Vector concatenation is differentiated from identity with padding.
2091 if (isa<UndefValue>(Op<0>()) || isa<UndefValue>(Op<1>()))
2092 return false;
2094 int NumOpElts = Op<0>()->getType()->getVectorNumElements();
2095 int NumMaskElts = getType()->getVectorNumElements();
2096 if (NumMaskElts != NumOpElts * 2)
2097 return false;
2099 // Use the mask length rather than the operands' vector lengths here. We
2100 // already know that the shuffle returns a vector twice as long as the inputs,
2101 // and neither of the inputs are undef vectors. If the mask picks consecutive
2102 // elements from both inputs, then this is a concatenation of the inputs.
2103 return isIdentityMaskImpl(getShuffleMask(), NumMaskElts);
2106 //===----------------------------------------------------------------------===//
2107 // InsertValueInst Class
2108 //===----------------------------------------------------------------------===//
2110 void InsertValueInst::init(Value *Agg, Value *Val, ArrayRef<unsigned> Idxs,
2111 const Twine &Name) {
2112 assert(getNumOperands() == 2 && "NumOperands not initialized?");
2114 // There's no fundamental reason why we require at least one index
2115 // (other than weirdness with &*IdxBegin being invalid; see
2116 // getelementptr's init routine for example). But there's no
2117 // present need to support it.
2118 assert(!Idxs.empty() && "InsertValueInst must have at least one index");
2120 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs) ==
2121 Val->getType() && "Inserted value must match indexed type!");
2122 Op<0>() = Agg;
2123 Op<1>() = Val;
2125 Indices.append(Idxs.begin(), Idxs.end());
2126 setName(Name);
2129 InsertValueInst::InsertValueInst(const InsertValueInst &IVI)
2130 : Instruction(IVI.getType(), InsertValue,
2131 OperandTraits<InsertValueInst>::op_begin(this), 2),
2132 Indices(IVI.Indices) {
2133 Op<0>() = IVI.getOperand(0);
2134 Op<1>() = IVI.getOperand(1);
2135 SubclassOptionalData = IVI.SubclassOptionalData;
2138 //===----------------------------------------------------------------------===//
2139 // ExtractValueInst Class
2140 //===----------------------------------------------------------------------===//
2142 void ExtractValueInst::init(ArrayRef<unsigned> Idxs, const Twine &Name) {
2143 assert(getNumOperands() == 1 && "NumOperands not initialized?");
2145 // There's no fundamental reason why we require at least one index.
2146 // But there's no present need to support it.
2147 assert(!Idxs.empty() && "ExtractValueInst must have at least one index");
2149 Indices.append(Idxs.begin(), Idxs.end());
2150 setName(Name);
2153 ExtractValueInst::ExtractValueInst(const ExtractValueInst &EVI)
2154 : UnaryInstruction(EVI.getType(), ExtractValue, EVI.getOperand(0)),
2155 Indices(EVI.Indices) {
2156 SubclassOptionalData = EVI.SubclassOptionalData;
2159 // getIndexedType - Returns the type of the element that would be extracted
2160 // with an extractvalue instruction with the specified parameters.
2162 // A null type is returned if the indices are invalid for the specified
2163 // pointer type.
2165 Type *ExtractValueInst::getIndexedType(Type *Agg,
2166 ArrayRef<unsigned> Idxs) {
2167 for (unsigned Index : Idxs) {
2168 // We can't use CompositeType::indexValid(Index) here.
2169 // indexValid() always returns true for arrays because getelementptr allows
2170 // out-of-bounds indices. Since we don't allow those for extractvalue and
2171 // insertvalue we need to check array indexing manually.
2172 // Since the only other types we can index into are struct types it's just
2173 // as easy to check those manually as well.
2174 if (ArrayType *AT = dyn_cast<ArrayType>(Agg)) {
2175 if (Index >= AT->getNumElements())
2176 return nullptr;
2177 } else if (StructType *ST = dyn_cast<StructType>(Agg)) {
2178 if (Index >= ST->getNumElements())
2179 return nullptr;
2180 } else {
2181 // Not a valid type to index into.
2182 return nullptr;
2185 Agg = cast<CompositeType>(Agg)->getTypeAtIndex(Index);
2187 return const_cast<Type*>(Agg);
2190 //===----------------------------------------------------------------------===//
2191 // UnaryOperator Class
2192 //===----------------------------------------------------------------------===//
2194 UnaryOperator::UnaryOperator(UnaryOps iType, Value *S,
2195 Type *Ty, const Twine &Name,
2196 Instruction *InsertBefore)
2197 : UnaryInstruction(Ty, iType, S, InsertBefore) {
2198 Op<0>() = S;
2199 setName(Name);
2200 AssertOK();
2203 UnaryOperator::UnaryOperator(UnaryOps iType, Value *S,
2204 Type *Ty, const Twine &Name,
2205 BasicBlock *InsertAtEnd)
2206 : UnaryInstruction(Ty, iType, S, InsertAtEnd) {
2207 Op<0>() = S;
2208 setName(Name);
2209 AssertOK();
2212 UnaryOperator *UnaryOperator::Create(UnaryOps Op, Value *S,
2213 const Twine &Name,
2214 Instruction *InsertBefore) {
2215 return new UnaryOperator(Op, S, S->getType(), Name, InsertBefore);
2218 UnaryOperator *UnaryOperator::Create(UnaryOps Op, Value *S,
2219 const Twine &Name,
2220 BasicBlock *InsertAtEnd) {
2221 UnaryOperator *Res = Create(Op, S, Name);
2222 InsertAtEnd->getInstList().push_back(Res);
2223 return Res;
2226 void UnaryOperator::AssertOK() {
2227 Value *LHS = getOperand(0);
2228 (void)LHS; // Silence warnings.
2229 #ifndef NDEBUG
2230 switch (getOpcode()) {
2231 case FNeg:
2232 assert(getType() == LHS->getType() &&
2233 "Unary operation should return same type as operand!");
2234 assert(getType()->isFPOrFPVectorTy() &&
2235 "Tried to create a floating-point operation on a "
2236 "non-floating-point type!");
2237 break;
2238 default: llvm_unreachable("Invalid opcode provided");
2240 #endif
2243 //===----------------------------------------------------------------------===//
2244 // BinaryOperator Class
2245 //===----------------------------------------------------------------------===//
2247 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
2248 Type *Ty, const Twine &Name,
2249 Instruction *InsertBefore)
2250 : Instruction(Ty, iType,
2251 OperandTraits<BinaryOperator>::op_begin(this),
2252 OperandTraits<BinaryOperator>::operands(this),
2253 InsertBefore) {
2254 Op<0>() = S1;
2255 Op<1>() = S2;
2256 setName(Name);
2257 AssertOK();
2260 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
2261 Type *Ty, const Twine &Name,
2262 BasicBlock *InsertAtEnd)
2263 : Instruction(Ty, iType,
2264 OperandTraits<BinaryOperator>::op_begin(this),
2265 OperandTraits<BinaryOperator>::operands(this),
2266 InsertAtEnd) {
2267 Op<0>() = S1;
2268 Op<1>() = S2;
2269 setName(Name);
2270 AssertOK();
2273 void BinaryOperator::AssertOK() {
2274 Value *LHS = getOperand(0), *RHS = getOperand(1);
2275 (void)LHS; (void)RHS; // Silence warnings.
2276 assert(LHS->getType() == RHS->getType() &&
2277 "Binary operator operand types must match!");
2278 #ifndef NDEBUG
2279 switch (getOpcode()) {
2280 case Add: case Sub:
2281 case Mul:
2282 assert(getType() == LHS->getType() &&
2283 "Arithmetic operation should return same type as operands!");
2284 assert(getType()->isIntOrIntVectorTy() &&
2285 "Tried to create an integer operation on a non-integer type!");
2286 break;
2287 case FAdd: case FSub:
2288 case FMul:
2289 assert(getType() == LHS->getType() &&
2290 "Arithmetic operation should return same type as operands!");
2291 assert(getType()->isFPOrFPVectorTy() &&
2292 "Tried to create a floating-point operation on a "
2293 "non-floating-point type!");
2294 break;
2295 case UDiv:
2296 case SDiv:
2297 assert(getType() == LHS->getType() &&
2298 "Arithmetic operation should return same type as operands!");
2299 assert(getType()->isIntOrIntVectorTy() &&
2300 "Incorrect operand type (not integer) for S/UDIV");
2301 break;
2302 case FDiv:
2303 assert(getType() == LHS->getType() &&
2304 "Arithmetic operation should return same type as operands!");
2305 assert(getType()->isFPOrFPVectorTy() &&
2306 "Incorrect operand type (not floating point) for FDIV");
2307 break;
2308 case URem:
2309 case SRem:
2310 assert(getType() == LHS->getType() &&
2311 "Arithmetic operation should return same type as operands!");
2312 assert(getType()->isIntOrIntVectorTy() &&
2313 "Incorrect operand type (not integer) for S/UREM");
2314 break;
2315 case FRem:
2316 assert(getType() == LHS->getType() &&
2317 "Arithmetic operation should return same type as operands!");
2318 assert(getType()->isFPOrFPVectorTy() &&
2319 "Incorrect operand type (not floating point) for FREM");
2320 break;
2321 case Shl:
2322 case LShr:
2323 case AShr:
2324 assert(getType() == LHS->getType() &&
2325 "Shift operation should return same type as operands!");
2326 assert(getType()->isIntOrIntVectorTy() &&
2327 "Tried to create a shift operation on a non-integral type!");
2328 break;
2329 case And: case Or:
2330 case Xor:
2331 assert(getType() == LHS->getType() &&
2332 "Logical operation should return same type as operands!");
2333 assert(getType()->isIntOrIntVectorTy() &&
2334 "Tried to create a logical operation on a non-integral type!");
2335 break;
2336 default: llvm_unreachable("Invalid opcode provided");
2338 #endif
2341 BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2,
2342 const Twine &Name,
2343 Instruction *InsertBefore) {
2344 assert(S1->getType() == S2->getType() &&
2345 "Cannot create binary operator with two operands of differing type!");
2346 return new BinaryOperator(Op, S1, S2, S1->getType(), Name, InsertBefore);
2349 BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2,
2350 const Twine &Name,
2351 BasicBlock *InsertAtEnd) {
2352 BinaryOperator *Res = Create(Op, S1, S2, Name);
2353 InsertAtEnd->getInstList().push_back(Res);
2354 return Res;
2357 BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const Twine &Name,
2358 Instruction *InsertBefore) {
2359 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
2360 return new BinaryOperator(Instruction::Sub,
2361 zero, Op,
2362 Op->getType(), Name, InsertBefore);
2365 BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const Twine &Name,
2366 BasicBlock *InsertAtEnd) {
2367 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
2368 return new BinaryOperator(Instruction::Sub,
2369 zero, Op,
2370 Op->getType(), Name, InsertAtEnd);
2373 BinaryOperator *BinaryOperator::CreateNSWNeg(Value *Op, const Twine &Name,
2374 Instruction *InsertBefore) {
2375 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
2376 return BinaryOperator::CreateNSWSub(zero, Op, Name, InsertBefore);
2379 BinaryOperator *BinaryOperator::CreateNSWNeg(Value *Op, const Twine &Name,
2380 BasicBlock *InsertAtEnd) {
2381 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
2382 return BinaryOperator::CreateNSWSub(zero, Op, Name, InsertAtEnd);
2385 BinaryOperator *BinaryOperator::CreateNUWNeg(Value *Op, const Twine &Name,
2386 Instruction *InsertBefore) {
2387 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
2388 return BinaryOperator::CreateNUWSub(zero, Op, Name, InsertBefore);
2391 BinaryOperator *BinaryOperator::CreateNUWNeg(Value *Op, const Twine &Name,
2392 BasicBlock *InsertAtEnd) {
2393 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
2394 return BinaryOperator::CreateNUWSub(zero, Op, Name, InsertAtEnd);
2397 BinaryOperator *BinaryOperator::CreateFNeg(Value *Op, const Twine &Name,
2398 Instruction *InsertBefore) {
2399 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
2400 return new BinaryOperator(Instruction::FSub, zero, Op,
2401 Op->getType(), Name, InsertBefore);
2404 BinaryOperator *BinaryOperator::CreateFNeg(Value *Op, const Twine &Name,
2405 BasicBlock *InsertAtEnd) {
2406 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
2407 return new BinaryOperator(Instruction::FSub, zero, Op,
2408 Op->getType(), Name, InsertAtEnd);
2411 BinaryOperator *BinaryOperator::CreateNot(Value *Op, const Twine &Name,
2412 Instruction *InsertBefore) {
2413 Constant *C = Constant::getAllOnesValue(Op->getType());
2414 return new BinaryOperator(Instruction::Xor, Op, C,
2415 Op->getType(), Name, InsertBefore);
2418 BinaryOperator *BinaryOperator::CreateNot(Value *Op, const Twine &Name,
2419 BasicBlock *InsertAtEnd) {
2420 Constant *AllOnes = Constant::getAllOnesValue(Op->getType());
2421 return new BinaryOperator(Instruction::Xor, Op, AllOnes,
2422 Op->getType(), Name, InsertAtEnd);
2425 // Exchange the two operands to this instruction. This instruction is safe to
2426 // use on any binary instruction and does not modify the semantics of the
2427 // instruction. If the instruction is order-dependent (SetLT f.e.), the opcode
2428 // is changed.
2429 bool BinaryOperator::swapOperands() {
2430 if (!isCommutative())
2431 return true; // Can't commute operands
2432 Op<0>().swap(Op<1>());
2433 return false;
2436 //===----------------------------------------------------------------------===//
2437 // FPMathOperator Class
2438 //===----------------------------------------------------------------------===//
2440 float FPMathOperator::getFPAccuracy() const {
2441 const MDNode *MD =
2442 cast<Instruction>(this)->getMetadata(LLVMContext::MD_fpmath);
2443 if (!MD)
2444 return 0.0;
2445 ConstantFP *Accuracy = mdconst::extract<ConstantFP>(MD->getOperand(0));
2446 return Accuracy->getValueAPF().convertToFloat();
2449 //===----------------------------------------------------------------------===//
2450 // CastInst Class
2451 //===----------------------------------------------------------------------===//
2453 // Just determine if this cast only deals with integral->integral conversion.
2454 bool CastInst::isIntegerCast() const {
2455 switch (getOpcode()) {
2456 default: return false;
2457 case Instruction::ZExt:
2458 case Instruction::SExt:
2459 case Instruction::Trunc:
2460 return true;
2461 case Instruction::BitCast:
2462 return getOperand(0)->getType()->isIntegerTy() &&
2463 getType()->isIntegerTy();
2467 bool CastInst::isLosslessCast() const {
2468 // Only BitCast can be lossless, exit fast if we're not BitCast
2469 if (getOpcode() != Instruction::BitCast)
2470 return false;
2472 // Identity cast is always lossless
2473 Type *SrcTy = getOperand(0)->getType();
2474 Type *DstTy = getType();
2475 if (SrcTy == DstTy)
2476 return true;
2478 // Pointer to pointer is always lossless.
2479 if (SrcTy->isPointerTy())
2480 return DstTy->isPointerTy();
2481 return false; // Other types have no identity values
2484 /// This function determines if the CastInst does not require any bits to be
2485 /// changed in order to effect the cast. Essentially, it identifies cases where
2486 /// no code gen is necessary for the cast, hence the name no-op cast. For
2487 /// example, the following are all no-op casts:
2488 /// # bitcast i32* %x to i8*
2489 /// # bitcast <2 x i32> %x to <4 x i16>
2490 /// # ptrtoint i32* %x to i32 ; on 32-bit plaforms only
2491 /// Determine if the described cast is a no-op.
2492 bool CastInst::isNoopCast(Instruction::CastOps Opcode,
2493 Type *SrcTy,
2494 Type *DestTy,
2495 const DataLayout &DL) {
2496 switch (Opcode) {
2497 default: llvm_unreachable("Invalid CastOp");
2498 case Instruction::Trunc:
2499 case Instruction::ZExt:
2500 case Instruction::SExt:
2501 case Instruction::FPTrunc:
2502 case Instruction::FPExt:
2503 case Instruction::UIToFP:
2504 case Instruction::SIToFP:
2505 case Instruction::FPToUI:
2506 case Instruction::FPToSI:
2507 case Instruction::AddrSpaceCast:
2508 // TODO: Target informations may give a more accurate answer here.
2509 return false;
2510 case Instruction::BitCast:
2511 return true; // BitCast never modifies bits.
2512 case Instruction::PtrToInt:
2513 return DL.getIntPtrType(SrcTy)->getScalarSizeInBits() ==
2514 DestTy->getScalarSizeInBits();
2515 case Instruction::IntToPtr:
2516 return DL.getIntPtrType(DestTy)->getScalarSizeInBits() ==
2517 SrcTy->getScalarSizeInBits();
2521 bool CastInst::isNoopCast(const DataLayout &DL) const {
2522 return isNoopCast(getOpcode(), getOperand(0)->getType(), getType(), DL);
2525 /// This function determines if a pair of casts can be eliminated and what
2526 /// opcode should be used in the elimination. This assumes that there are two
2527 /// instructions like this:
2528 /// * %F = firstOpcode SrcTy %x to MidTy
2529 /// * %S = secondOpcode MidTy %F to DstTy
2530 /// The function returns a resultOpcode so these two casts can be replaced with:
2531 /// * %Replacement = resultOpcode %SrcTy %x to DstTy
2532 /// If no such cast is permitted, the function returns 0.
2533 unsigned CastInst::isEliminableCastPair(
2534 Instruction::CastOps firstOp, Instruction::CastOps secondOp,
2535 Type *SrcTy, Type *MidTy, Type *DstTy, Type *SrcIntPtrTy, Type *MidIntPtrTy,
2536 Type *DstIntPtrTy) {
2537 // Define the 144 possibilities for these two cast instructions. The values
2538 // in this matrix determine what to do in a given situation and select the
2539 // case in the switch below. The rows correspond to firstOp, the columns
2540 // correspond to secondOp. In looking at the table below, keep in mind
2541 // the following cast properties:
2543 // Size Compare Source Destination
2544 // Operator Src ? Size Type Sign Type Sign
2545 // -------- ------------ ------------------- ---------------------
2546 // TRUNC > Integer Any Integral Any
2547 // ZEXT < Integral Unsigned Integer Any
2548 // SEXT < Integral Signed Integer Any
2549 // FPTOUI n/a FloatPt n/a Integral Unsigned
2550 // FPTOSI n/a FloatPt n/a Integral Signed
2551 // UITOFP n/a Integral Unsigned FloatPt n/a
2552 // SITOFP n/a Integral Signed FloatPt n/a
2553 // FPTRUNC > FloatPt n/a FloatPt n/a
2554 // FPEXT < FloatPt n/a FloatPt n/a
2555 // PTRTOINT n/a Pointer n/a Integral Unsigned
2556 // INTTOPTR n/a Integral Unsigned Pointer n/a
2557 // BITCAST = FirstClass n/a FirstClass n/a
2558 // ADDRSPCST n/a Pointer n/a Pointer n/a
2560 // NOTE: some transforms are safe, but we consider them to be non-profitable.
2561 // For example, we could merge "fptoui double to i32" + "zext i32 to i64",
2562 // into "fptoui double to i64", but this loses information about the range
2563 // of the produced value (we no longer know the top-part is all zeros).
2564 // Further this conversion is often much more expensive for typical hardware,
2565 // and causes issues when building libgcc. We disallow fptosi+sext for the
2566 // same reason.
2567 const unsigned numCastOps =
2568 Instruction::CastOpsEnd - Instruction::CastOpsBegin;
2569 static const uint8_t CastResults[numCastOps][numCastOps] = {
2570 // T F F U S F F P I B A -+
2571 // R Z S P P I I T P 2 N T S |
2572 // U E E 2 2 2 2 R E I T C C +- secondOp
2573 // N X X U S F F N X N 2 V V |
2574 // C T T I I P P C T T P T T -+
2575 { 1, 0, 0,99,99, 0, 0,99,99,99, 0, 3, 0}, // Trunc -+
2576 { 8, 1, 9,99,99, 2,17,99,99,99, 2, 3, 0}, // ZExt |
2577 { 8, 0, 1,99,99, 0, 2,99,99,99, 0, 3, 0}, // SExt |
2578 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3, 0}, // FPToUI |
2579 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3, 0}, // FPToSI |
2580 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4, 0}, // UIToFP +- firstOp
2581 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4, 0}, // SIToFP |
2582 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4, 0}, // FPTrunc |
2583 { 99,99,99, 2, 2,99,99, 8, 2,99,99, 4, 0}, // FPExt |
2584 { 1, 0, 0,99,99, 0, 0,99,99,99, 7, 3, 0}, // PtrToInt |
2585 { 99,99,99,99,99,99,99,99,99,11,99,15, 0}, // IntToPtr |
2586 { 5, 5, 5, 6, 6, 5, 5, 6, 6,16, 5, 1,14}, // BitCast |
2587 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,13,12}, // AddrSpaceCast -+
2590 // TODO: This logic could be encoded into the table above and handled in the
2591 // switch below.
2592 // If either of the casts are a bitcast from scalar to vector, disallow the
2593 // merging. However, any pair of bitcasts are allowed.
2594 bool IsFirstBitcast = (firstOp == Instruction::BitCast);
2595 bool IsSecondBitcast = (secondOp == Instruction::BitCast);
2596 bool AreBothBitcasts = IsFirstBitcast && IsSecondBitcast;
2598 // Check if any of the casts convert scalars <-> vectors.
2599 if ((IsFirstBitcast && isa<VectorType>(SrcTy) != isa<VectorType>(MidTy)) ||
2600 (IsSecondBitcast && isa<VectorType>(MidTy) != isa<VectorType>(DstTy)))
2601 if (!AreBothBitcasts)
2602 return 0;
2604 int ElimCase = CastResults[firstOp-Instruction::CastOpsBegin]
2605 [secondOp-Instruction::CastOpsBegin];
2606 switch (ElimCase) {
2607 case 0:
2608 // Categorically disallowed.
2609 return 0;
2610 case 1:
2611 // Allowed, use first cast's opcode.
2612 return firstOp;
2613 case 2:
2614 // Allowed, use second cast's opcode.
2615 return secondOp;
2616 case 3:
2617 // No-op cast in second op implies firstOp as long as the DestTy
2618 // is integer and we are not converting between a vector and a
2619 // non-vector type.
2620 if (!SrcTy->isVectorTy() && DstTy->isIntegerTy())
2621 return firstOp;
2622 return 0;
2623 case 4:
2624 // No-op cast in second op implies firstOp as long as the DestTy
2625 // is floating point.
2626 if (DstTy->isFloatingPointTy())
2627 return firstOp;
2628 return 0;
2629 case 5:
2630 // No-op cast in first op implies secondOp as long as the SrcTy
2631 // is an integer.
2632 if (SrcTy->isIntegerTy())
2633 return secondOp;
2634 return 0;
2635 case 6:
2636 // No-op cast in first op implies secondOp as long as the SrcTy
2637 // is a floating point.
2638 if (SrcTy->isFloatingPointTy())
2639 return secondOp;
2640 return 0;
2641 case 7: {
2642 // Cannot simplify if address spaces are different!
2643 if (SrcTy->getPointerAddressSpace() != DstTy->getPointerAddressSpace())
2644 return 0;
2646 unsigned MidSize = MidTy->getScalarSizeInBits();
2647 // We can still fold this without knowing the actual sizes as long we
2648 // know that the intermediate pointer is the largest possible
2649 // pointer size.
2650 // FIXME: Is this always true?
2651 if (MidSize == 64)
2652 return Instruction::BitCast;
2654 // ptrtoint, inttoptr -> bitcast (ptr -> ptr) if int size is >= ptr size.
2655 if (!SrcIntPtrTy || DstIntPtrTy != SrcIntPtrTy)
2656 return 0;
2657 unsigned PtrSize = SrcIntPtrTy->getScalarSizeInBits();
2658 if (MidSize >= PtrSize)
2659 return Instruction::BitCast;
2660 return 0;
2662 case 8: {
2663 // ext, trunc -> bitcast, if the SrcTy and DstTy are same size
2664 // ext, trunc -> ext, if sizeof(SrcTy) < sizeof(DstTy)
2665 // ext, trunc -> trunc, if sizeof(SrcTy) > sizeof(DstTy)
2666 unsigned SrcSize = SrcTy->getScalarSizeInBits();
2667 unsigned DstSize = DstTy->getScalarSizeInBits();
2668 if (SrcSize == DstSize)
2669 return Instruction::BitCast;
2670 else if (SrcSize < DstSize)
2671 return firstOp;
2672 return secondOp;
2674 case 9:
2675 // zext, sext -> zext, because sext can't sign extend after zext
2676 return Instruction::ZExt;
2677 case 11: {
2678 // inttoptr, ptrtoint -> bitcast if SrcSize<=PtrSize and SrcSize==DstSize
2679 if (!MidIntPtrTy)
2680 return 0;
2681 unsigned PtrSize = MidIntPtrTy->getScalarSizeInBits();
2682 unsigned SrcSize = SrcTy->getScalarSizeInBits();
2683 unsigned DstSize = DstTy->getScalarSizeInBits();
2684 if (SrcSize <= PtrSize && SrcSize == DstSize)
2685 return Instruction::BitCast;
2686 return 0;
2688 case 12:
2689 // addrspacecast, addrspacecast -> bitcast, if SrcAS == DstAS
2690 // addrspacecast, addrspacecast -> addrspacecast, if SrcAS != DstAS
2691 if (SrcTy->getPointerAddressSpace() != DstTy->getPointerAddressSpace())
2692 return Instruction::AddrSpaceCast;
2693 return Instruction::BitCast;
2694 case 13:
2695 // FIXME: this state can be merged with (1), but the following assert
2696 // is useful to check the correcteness of the sequence due to semantic
2697 // change of bitcast.
2698 assert(
2699 SrcTy->isPtrOrPtrVectorTy() &&
2700 MidTy->isPtrOrPtrVectorTy() &&
2701 DstTy->isPtrOrPtrVectorTy() &&
2702 SrcTy->getPointerAddressSpace() != MidTy->getPointerAddressSpace() &&
2703 MidTy->getPointerAddressSpace() == DstTy->getPointerAddressSpace() &&
2704 "Illegal addrspacecast, bitcast sequence!");
2705 // Allowed, use first cast's opcode
2706 return firstOp;
2707 case 14:
2708 // bitcast, addrspacecast -> addrspacecast if the element type of
2709 // bitcast's source is the same as that of addrspacecast's destination.
2710 if (SrcTy->getScalarType()->getPointerElementType() ==
2711 DstTy->getScalarType()->getPointerElementType())
2712 return Instruction::AddrSpaceCast;
2713 return 0;
2714 case 15:
2715 // FIXME: this state can be merged with (1), but the following assert
2716 // is useful to check the correcteness of the sequence due to semantic
2717 // change of bitcast.
2718 assert(
2719 SrcTy->isIntOrIntVectorTy() &&
2720 MidTy->isPtrOrPtrVectorTy() &&
2721 DstTy->isPtrOrPtrVectorTy() &&
2722 MidTy->getPointerAddressSpace() == DstTy->getPointerAddressSpace() &&
2723 "Illegal inttoptr, bitcast sequence!");
2724 // Allowed, use first cast's opcode
2725 return firstOp;
2726 case 16:
2727 // FIXME: this state can be merged with (2), but the following assert
2728 // is useful to check the correcteness of the sequence due to semantic
2729 // change of bitcast.
2730 assert(
2731 SrcTy->isPtrOrPtrVectorTy() &&
2732 MidTy->isPtrOrPtrVectorTy() &&
2733 DstTy->isIntOrIntVectorTy() &&
2734 SrcTy->getPointerAddressSpace() == MidTy->getPointerAddressSpace() &&
2735 "Illegal bitcast, ptrtoint sequence!");
2736 // Allowed, use second cast's opcode
2737 return secondOp;
2738 case 17:
2739 // (sitofp (zext x)) -> (uitofp x)
2740 return Instruction::UIToFP;
2741 case 99:
2742 // Cast combination can't happen (error in input). This is for all cases
2743 // where the MidTy is not the same for the two cast instructions.
2744 llvm_unreachable("Invalid Cast Combination");
2745 default:
2746 llvm_unreachable("Error in CastResults table!!!");
2750 CastInst *CastInst::Create(Instruction::CastOps op, Value *S, Type *Ty,
2751 const Twine &Name, Instruction *InsertBefore) {
2752 assert(castIsValid(op, S, Ty) && "Invalid cast!");
2753 // Construct and return the appropriate CastInst subclass
2754 switch (op) {
2755 case Trunc: return new TruncInst (S, Ty, Name, InsertBefore);
2756 case ZExt: return new ZExtInst (S, Ty, Name, InsertBefore);
2757 case SExt: return new SExtInst (S, Ty, Name, InsertBefore);
2758 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertBefore);
2759 case FPExt: return new FPExtInst (S, Ty, Name, InsertBefore);
2760 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertBefore);
2761 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertBefore);
2762 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertBefore);
2763 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertBefore);
2764 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertBefore);
2765 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertBefore);
2766 case BitCast: return new BitCastInst (S, Ty, Name, InsertBefore);
2767 case AddrSpaceCast: return new AddrSpaceCastInst (S, Ty, Name, InsertBefore);
2768 default: llvm_unreachable("Invalid opcode provided");
2772 CastInst *CastInst::Create(Instruction::CastOps op, Value *S, Type *Ty,
2773 const Twine &Name, BasicBlock *InsertAtEnd) {
2774 assert(castIsValid(op, S, Ty) && "Invalid cast!");
2775 // Construct and return the appropriate CastInst subclass
2776 switch (op) {
2777 case Trunc: return new TruncInst (S, Ty, Name, InsertAtEnd);
2778 case ZExt: return new ZExtInst (S, Ty, Name, InsertAtEnd);
2779 case SExt: return new SExtInst (S, Ty, Name, InsertAtEnd);
2780 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertAtEnd);
2781 case FPExt: return new FPExtInst (S, Ty, Name, InsertAtEnd);
2782 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertAtEnd);
2783 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertAtEnd);
2784 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertAtEnd);
2785 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertAtEnd);
2786 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertAtEnd);
2787 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertAtEnd);
2788 case BitCast: return new BitCastInst (S, Ty, Name, InsertAtEnd);
2789 case AddrSpaceCast: return new AddrSpaceCastInst (S, Ty, Name, InsertAtEnd);
2790 default: llvm_unreachable("Invalid opcode provided");
2794 CastInst *CastInst::CreateZExtOrBitCast(Value *S, Type *Ty,
2795 const Twine &Name,
2796 Instruction *InsertBefore) {
2797 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2798 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2799 return Create(Instruction::ZExt, S, Ty, Name, InsertBefore);
2802 CastInst *CastInst::CreateZExtOrBitCast(Value *S, Type *Ty,
2803 const Twine &Name,
2804 BasicBlock *InsertAtEnd) {
2805 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2806 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2807 return Create(Instruction::ZExt, S, Ty, Name, InsertAtEnd);
2810 CastInst *CastInst::CreateSExtOrBitCast(Value *S, Type *Ty,
2811 const Twine &Name,
2812 Instruction *InsertBefore) {
2813 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2814 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2815 return Create(Instruction::SExt, S, Ty, Name, InsertBefore);
2818 CastInst *CastInst::CreateSExtOrBitCast(Value *S, Type *Ty,
2819 const Twine &Name,
2820 BasicBlock *InsertAtEnd) {
2821 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2822 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2823 return Create(Instruction::SExt, S, Ty, Name, InsertAtEnd);
2826 CastInst *CastInst::CreateTruncOrBitCast(Value *S, Type *Ty,
2827 const Twine &Name,
2828 Instruction *InsertBefore) {
2829 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2830 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2831 return Create(Instruction::Trunc, S, Ty, Name, InsertBefore);
2834 CastInst *CastInst::CreateTruncOrBitCast(Value *S, Type *Ty,
2835 const Twine &Name,
2836 BasicBlock *InsertAtEnd) {
2837 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2838 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2839 return Create(Instruction::Trunc, S, Ty, Name, InsertAtEnd);
2842 CastInst *CastInst::CreatePointerCast(Value *S, Type *Ty,
2843 const Twine &Name,
2844 BasicBlock *InsertAtEnd) {
2845 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
2846 assert((Ty->isIntOrIntVectorTy() || Ty->isPtrOrPtrVectorTy()) &&
2847 "Invalid cast");
2848 assert(Ty->isVectorTy() == S->getType()->isVectorTy() && "Invalid cast");
2849 assert((!Ty->isVectorTy() ||
2850 Ty->getVectorNumElements() == S->getType()->getVectorNumElements()) &&
2851 "Invalid cast");
2853 if (Ty->isIntOrIntVectorTy())
2854 return Create(Instruction::PtrToInt, S, Ty, Name, InsertAtEnd);
2856 return CreatePointerBitCastOrAddrSpaceCast(S, Ty, Name, InsertAtEnd);
2859 /// Create a BitCast or a PtrToInt cast instruction
2860 CastInst *CastInst::CreatePointerCast(Value *S, Type *Ty,
2861 const Twine &Name,
2862 Instruction *InsertBefore) {
2863 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
2864 assert((Ty->isIntOrIntVectorTy() || Ty->isPtrOrPtrVectorTy()) &&
2865 "Invalid cast");
2866 assert(Ty->isVectorTy() == S->getType()->isVectorTy() && "Invalid cast");
2867 assert((!Ty->isVectorTy() ||
2868 Ty->getVectorNumElements() == S->getType()->getVectorNumElements()) &&
2869 "Invalid cast");
2871 if (Ty->isIntOrIntVectorTy())
2872 return Create(Instruction::PtrToInt, S, Ty, Name, InsertBefore);
2874 return CreatePointerBitCastOrAddrSpaceCast(S, Ty, Name, InsertBefore);
2877 CastInst *CastInst::CreatePointerBitCastOrAddrSpaceCast(
2878 Value *S, Type *Ty,
2879 const Twine &Name,
2880 BasicBlock *InsertAtEnd) {
2881 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
2882 assert(Ty->isPtrOrPtrVectorTy() && "Invalid cast");
2884 if (S->getType()->getPointerAddressSpace() != Ty->getPointerAddressSpace())
2885 return Create(Instruction::AddrSpaceCast, S, Ty, Name, InsertAtEnd);
2887 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2890 CastInst *CastInst::CreatePointerBitCastOrAddrSpaceCast(
2891 Value *S, Type *Ty,
2892 const Twine &Name,
2893 Instruction *InsertBefore) {
2894 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
2895 assert(Ty->isPtrOrPtrVectorTy() && "Invalid cast");
2897 if (S->getType()->getPointerAddressSpace() != Ty->getPointerAddressSpace())
2898 return Create(Instruction::AddrSpaceCast, S, Ty, Name, InsertBefore);
2900 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2903 CastInst *CastInst::CreateBitOrPointerCast(Value *S, Type *Ty,
2904 const Twine &Name,
2905 Instruction *InsertBefore) {
2906 if (S->getType()->isPointerTy() && Ty->isIntegerTy())
2907 return Create(Instruction::PtrToInt, S, Ty, Name, InsertBefore);
2908 if (S->getType()->isIntegerTy() && Ty->isPointerTy())
2909 return Create(Instruction::IntToPtr, S, Ty, Name, InsertBefore);
2911 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2914 CastInst *CastInst::CreateIntegerCast(Value *C, Type *Ty,
2915 bool isSigned, const Twine &Name,
2916 Instruction *InsertBefore) {
2917 assert(C->getType()->isIntOrIntVectorTy() && Ty->isIntOrIntVectorTy() &&
2918 "Invalid integer cast");
2919 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2920 unsigned DstBits = Ty->getScalarSizeInBits();
2921 Instruction::CastOps opcode =
2922 (SrcBits == DstBits ? Instruction::BitCast :
2923 (SrcBits > DstBits ? Instruction::Trunc :
2924 (isSigned ? Instruction::SExt : Instruction::ZExt)));
2925 return Create(opcode, C, Ty, Name, InsertBefore);
2928 CastInst *CastInst::CreateIntegerCast(Value *C, Type *Ty,
2929 bool isSigned, const Twine &Name,
2930 BasicBlock *InsertAtEnd) {
2931 assert(C->getType()->isIntOrIntVectorTy() && Ty->isIntOrIntVectorTy() &&
2932 "Invalid cast");
2933 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2934 unsigned DstBits = Ty->getScalarSizeInBits();
2935 Instruction::CastOps opcode =
2936 (SrcBits == DstBits ? Instruction::BitCast :
2937 (SrcBits > DstBits ? Instruction::Trunc :
2938 (isSigned ? Instruction::SExt : Instruction::ZExt)));
2939 return Create(opcode, C, Ty, Name, InsertAtEnd);
2942 CastInst *CastInst::CreateFPCast(Value *C, Type *Ty,
2943 const Twine &Name,
2944 Instruction *InsertBefore) {
2945 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
2946 "Invalid cast");
2947 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2948 unsigned DstBits = Ty->getScalarSizeInBits();
2949 Instruction::CastOps opcode =
2950 (SrcBits == DstBits ? Instruction::BitCast :
2951 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
2952 return Create(opcode, C, Ty, Name, InsertBefore);
2955 CastInst *CastInst::CreateFPCast(Value *C, Type *Ty,
2956 const Twine &Name,
2957 BasicBlock *InsertAtEnd) {
2958 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
2959 "Invalid cast");
2960 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2961 unsigned DstBits = Ty->getScalarSizeInBits();
2962 Instruction::CastOps opcode =
2963 (SrcBits == DstBits ? Instruction::BitCast :
2964 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
2965 return Create(opcode, C, Ty, Name, InsertAtEnd);
2968 // Check whether it is valid to call getCastOpcode for these types.
2969 // This routine must be kept in sync with getCastOpcode.
2970 bool CastInst::isCastable(Type *SrcTy, Type *DestTy) {
2971 if (!SrcTy->isFirstClassType() || !DestTy->isFirstClassType())
2972 return false;
2974 if (SrcTy == DestTy)
2975 return true;
2977 if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy))
2978 if (VectorType *DestVecTy = dyn_cast<VectorType>(DestTy))
2979 if (SrcVecTy->getNumElements() == DestVecTy->getNumElements()) {
2980 // An element by element cast. Valid if casting the elements is valid.
2981 SrcTy = SrcVecTy->getElementType();
2982 DestTy = DestVecTy->getElementType();
2985 // Get the bit sizes, we'll need these
2986 TypeSize SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr
2987 TypeSize DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr
2989 // Run through the possibilities ...
2990 if (DestTy->isIntegerTy()) { // Casting to integral
2991 if (SrcTy->isIntegerTy()) // Casting from integral
2992 return true;
2993 if (SrcTy->isFloatingPointTy()) // Casting from floating pt
2994 return true;
2995 if (SrcTy->isVectorTy()) // Casting from vector
2996 return DestBits == SrcBits;
2997 // Casting from something else
2998 return SrcTy->isPointerTy();
3000 if (DestTy->isFloatingPointTy()) { // Casting to floating pt
3001 if (SrcTy->isIntegerTy()) // Casting from integral
3002 return true;
3003 if (SrcTy->isFloatingPointTy()) // Casting from floating pt
3004 return true;
3005 if (SrcTy->isVectorTy()) // Casting from vector
3006 return DestBits == SrcBits;
3007 // Casting from something else
3008 return false;
3010 if (DestTy->isVectorTy()) // Casting to vector
3011 return DestBits == SrcBits;
3012 if (DestTy->isPointerTy()) { // Casting to pointer
3013 if (SrcTy->isPointerTy()) // Casting from pointer
3014 return true;
3015 return SrcTy->isIntegerTy(); // Casting from integral
3017 if (DestTy->isX86_MMXTy()) {
3018 if (SrcTy->isVectorTy())
3019 return DestBits == SrcBits; // 64-bit vector to MMX
3020 return false;
3021 } // Casting to something else
3022 return false;
3025 bool CastInst::isBitCastable(Type *SrcTy, Type *DestTy) {
3026 if (!SrcTy->isFirstClassType() || !DestTy->isFirstClassType())
3027 return false;
3029 if (SrcTy == DestTy)
3030 return true;
3032 if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy)) {
3033 if (VectorType *DestVecTy = dyn_cast<VectorType>(DestTy)) {
3034 if (SrcVecTy->getElementCount() == DestVecTy->getElementCount()) {
3035 // An element by element cast. Valid if casting the elements is valid.
3036 SrcTy = SrcVecTy->getElementType();
3037 DestTy = DestVecTy->getElementType();
3042 if (PointerType *DestPtrTy = dyn_cast<PointerType>(DestTy)) {
3043 if (PointerType *SrcPtrTy = dyn_cast<PointerType>(SrcTy)) {
3044 return SrcPtrTy->getAddressSpace() == DestPtrTy->getAddressSpace();
3048 TypeSize SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr
3049 TypeSize DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr
3051 // Could still have vectors of pointers if the number of elements doesn't
3052 // match
3053 if (SrcBits.getKnownMinSize() == 0 || DestBits.getKnownMinSize() == 0)
3054 return false;
3056 if (SrcBits != DestBits)
3057 return false;
3059 if (DestTy->isX86_MMXTy() || SrcTy->isX86_MMXTy())
3060 return false;
3062 return true;
3065 bool CastInst::isBitOrNoopPointerCastable(Type *SrcTy, Type *DestTy,
3066 const DataLayout &DL) {
3067 // ptrtoint and inttoptr are not allowed on non-integral pointers
3068 if (auto *PtrTy = dyn_cast<PointerType>(SrcTy))
3069 if (auto *IntTy = dyn_cast<IntegerType>(DestTy))
3070 return (IntTy->getBitWidth() == DL.getPointerTypeSizeInBits(PtrTy) &&
3071 !DL.isNonIntegralPointerType(PtrTy));
3072 if (auto *PtrTy = dyn_cast<PointerType>(DestTy))
3073 if (auto *IntTy = dyn_cast<IntegerType>(SrcTy))
3074 return (IntTy->getBitWidth() == DL.getPointerTypeSizeInBits(PtrTy) &&
3075 !DL.isNonIntegralPointerType(PtrTy));
3077 return isBitCastable(SrcTy, DestTy);
3080 // Provide a way to get a "cast" where the cast opcode is inferred from the
3081 // types and size of the operand. This, basically, is a parallel of the
3082 // logic in the castIsValid function below. This axiom should hold:
3083 // castIsValid( getCastOpcode(Val, Ty), Val, Ty)
3084 // should not assert in castIsValid. In other words, this produces a "correct"
3085 // casting opcode for the arguments passed to it.
3086 // This routine must be kept in sync with isCastable.
3087 Instruction::CastOps
3088 CastInst::getCastOpcode(
3089 const Value *Src, bool SrcIsSigned, Type *DestTy, bool DestIsSigned) {
3090 Type *SrcTy = Src->getType();
3092 assert(SrcTy->isFirstClassType() && DestTy->isFirstClassType() &&
3093 "Only first class types are castable!");
3095 if (SrcTy == DestTy)
3096 return BitCast;
3098 // FIXME: Check address space sizes here
3099 if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy))
3100 if (VectorType *DestVecTy = dyn_cast<VectorType>(DestTy))
3101 if (SrcVecTy->getNumElements() == DestVecTy->getNumElements()) {
3102 // An element by element cast. Find the appropriate opcode based on the
3103 // element types.
3104 SrcTy = SrcVecTy->getElementType();
3105 DestTy = DestVecTy->getElementType();
3108 // Get the bit sizes, we'll need these
3109 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr
3110 unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr
3112 // Run through the possibilities ...
3113 if (DestTy->isIntegerTy()) { // Casting to integral
3114 if (SrcTy->isIntegerTy()) { // Casting from integral
3115 if (DestBits < SrcBits)
3116 return Trunc; // int -> smaller int
3117 else if (DestBits > SrcBits) { // its an extension
3118 if (SrcIsSigned)
3119 return SExt; // signed -> SEXT
3120 else
3121 return ZExt; // unsigned -> ZEXT
3122 } else {
3123 return BitCast; // Same size, No-op cast
3125 } else if (SrcTy->isFloatingPointTy()) { // Casting from floating pt
3126 if (DestIsSigned)
3127 return FPToSI; // FP -> sint
3128 else
3129 return FPToUI; // FP -> uint
3130 } else if (SrcTy->isVectorTy()) {
3131 assert(DestBits == SrcBits &&
3132 "Casting vector to integer of different width");
3133 return BitCast; // Same size, no-op cast
3134 } else {
3135 assert(SrcTy->isPointerTy() &&
3136 "Casting from a value that is not first-class type");
3137 return PtrToInt; // ptr -> int
3139 } else if (DestTy->isFloatingPointTy()) { // Casting to floating pt
3140 if (SrcTy->isIntegerTy()) { // Casting from integral
3141 if (SrcIsSigned)
3142 return SIToFP; // sint -> FP
3143 else
3144 return UIToFP; // uint -> FP
3145 } else if (SrcTy->isFloatingPointTy()) { // Casting from floating pt
3146 if (DestBits < SrcBits) {
3147 return FPTrunc; // FP -> smaller FP
3148 } else if (DestBits > SrcBits) {
3149 return FPExt; // FP -> larger FP
3150 } else {
3151 return BitCast; // same size, no-op cast
3153 } else if (SrcTy->isVectorTy()) {
3154 assert(DestBits == SrcBits &&
3155 "Casting vector to floating point of different width");
3156 return BitCast; // same size, no-op cast
3158 llvm_unreachable("Casting pointer or non-first class to float");
3159 } else if (DestTy->isVectorTy()) {
3160 assert(DestBits == SrcBits &&
3161 "Illegal cast to vector (wrong type or size)");
3162 return BitCast;
3163 } else if (DestTy->isPointerTy()) {
3164 if (SrcTy->isPointerTy()) {
3165 if (DestTy->getPointerAddressSpace() != SrcTy->getPointerAddressSpace())
3166 return AddrSpaceCast;
3167 return BitCast; // ptr -> ptr
3168 } else if (SrcTy->isIntegerTy()) {
3169 return IntToPtr; // int -> ptr
3171 llvm_unreachable("Casting pointer to other than pointer or int");
3172 } else if (DestTy->isX86_MMXTy()) {
3173 if (SrcTy->isVectorTy()) {
3174 assert(DestBits == SrcBits && "Casting vector of wrong width to X86_MMX");
3175 return BitCast; // 64-bit vector to MMX
3177 llvm_unreachable("Illegal cast to X86_MMX");
3179 llvm_unreachable("Casting to type that is not first-class");
3182 //===----------------------------------------------------------------------===//
3183 // CastInst SubClass Constructors
3184 //===----------------------------------------------------------------------===//
3186 /// Check that the construction parameters for a CastInst are correct. This
3187 /// could be broken out into the separate constructors but it is useful to have
3188 /// it in one place and to eliminate the redundant code for getting the sizes
3189 /// of the types involved.
3190 bool
3191 CastInst::castIsValid(Instruction::CastOps op, Value *S, Type *DstTy) {
3192 // Check for type sanity on the arguments
3193 Type *SrcTy = S->getType();
3195 if (!SrcTy->isFirstClassType() || !DstTy->isFirstClassType() ||
3196 SrcTy->isAggregateType() || DstTy->isAggregateType())
3197 return false;
3199 // Get the size of the types in bits, we'll need this later
3200 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
3201 unsigned DstBitSize = DstTy->getScalarSizeInBits();
3203 // If these are vector types, get the lengths of the vectors (using zero for
3204 // scalar types means that checking that vector lengths match also checks that
3205 // scalars are not being converted to vectors or vectors to scalars).
3206 unsigned SrcLength = SrcTy->isVectorTy() ?
3207 cast<VectorType>(SrcTy)->getNumElements() : 0;
3208 unsigned DstLength = DstTy->isVectorTy() ?
3209 cast<VectorType>(DstTy)->getNumElements() : 0;
3211 // Switch on the opcode provided
3212 switch (op) {
3213 default: return false; // This is an input error
3214 case Instruction::Trunc:
3215 return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() &&
3216 SrcLength == DstLength && SrcBitSize > DstBitSize;
3217 case Instruction::ZExt:
3218 return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() &&
3219 SrcLength == DstLength && SrcBitSize < DstBitSize;
3220 case Instruction::SExt:
3221 return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() &&
3222 SrcLength == DstLength && SrcBitSize < DstBitSize;
3223 case Instruction::FPTrunc:
3224 return SrcTy->isFPOrFPVectorTy() && DstTy->isFPOrFPVectorTy() &&
3225 SrcLength == DstLength && SrcBitSize > DstBitSize;
3226 case Instruction::FPExt:
3227 return SrcTy->isFPOrFPVectorTy() && DstTy->isFPOrFPVectorTy() &&
3228 SrcLength == DstLength && SrcBitSize < DstBitSize;
3229 case Instruction::UIToFP:
3230 case Instruction::SIToFP:
3231 return SrcTy->isIntOrIntVectorTy() && DstTy->isFPOrFPVectorTy() &&
3232 SrcLength == DstLength;
3233 case Instruction::FPToUI:
3234 case Instruction::FPToSI:
3235 return SrcTy->isFPOrFPVectorTy() && DstTy->isIntOrIntVectorTy() &&
3236 SrcLength == DstLength;
3237 case Instruction::PtrToInt:
3238 if (isa<VectorType>(SrcTy) != isa<VectorType>(DstTy))
3239 return false;
3240 if (VectorType *VT = dyn_cast<VectorType>(SrcTy))
3241 if (VT->getNumElements() != cast<VectorType>(DstTy)->getNumElements())
3242 return false;
3243 return SrcTy->isPtrOrPtrVectorTy() && DstTy->isIntOrIntVectorTy();
3244 case Instruction::IntToPtr:
3245 if (isa<VectorType>(SrcTy) != isa<VectorType>(DstTy))
3246 return false;
3247 if (VectorType *VT = dyn_cast<VectorType>(SrcTy))
3248 if (VT->getNumElements() != cast<VectorType>(DstTy)->getNumElements())
3249 return false;
3250 return SrcTy->isIntOrIntVectorTy() && DstTy->isPtrOrPtrVectorTy();
3251 case Instruction::BitCast: {
3252 PointerType *SrcPtrTy = dyn_cast<PointerType>(SrcTy->getScalarType());
3253 PointerType *DstPtrTy = dyn_cast<PointerType>(DstTy->getScalarType());
3255 // BitCast implies a no-op cast of type only. No bits change.
3256 // However, you can't cast pointers to anything but pointers.
3257 if (!SrcPtrTy != !DstPtrTy)
3258 return false;
3260 // For non-pointer cases, the cast is okay if the source and destination bit
3261 // widths are identical.
3262 if (!SrcPtrTy)
3263 return SrcTy->getPrimitiveSizeInBits() == DstTy->getPrimitiveSizeInBits();
3265 // If both are pointers then the address spaces must match.
3266 if (SrcPtrTy->getAddressSpace() != DstPtrTy->getAddressSpace())
3267 return false;
3269 // A vector of pointers must have the same number of elements.
3270 VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy);
3271 VectorType *DstVecTy = dyn_cast<VectorType>(DstTy);
3272 if (SrcVecTy && DstVecTy)
3273 return (SrcVecTy->getNumElements() == DstVecTy->getNumElements());
3274 if (SrcVecTy)
3275 return SrcVecTy->getNumElements() == 1;
3276 if (DstVecTy)
3277 return DstVecTy->getNumElements() == 1;
3279 return true;
3281 case Instruction::AddrSpaceCast: {
3282 PointerType *SrcPtrTy = dyn_cast<PointerType>(SrcTy->getScalarType());
3283 if (!SrcPtrTy)
3284 return false;
3286 PointerType *DstPtrTy = dyn_cast<PointerType>(DstTy->getScalarType());
3287 if (!DstPtrTy)
3288 return false;
3290 if (SrcPtrTy->getAddressSpace() == DstPtrTy->getAddressSpace())
3291 return false;
3293 if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy)) {
3294 if (VectorType *DstVecTy = dyn_cast<VectorType>(DstTy))
3295 return (SrcVecTy->getNumElements() == DstVecTy->getNumElements());
3297 return false;
3300 return true;
3305 TruncInst::TruncInst(
3306 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3307 ) : CastInst(Ty, Trunc, S, Name, InsertBefore) {
3308 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
3311 TruncInst::TruncInst(
3312 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3313 ) : CastInst(Ty, Trunc, S, Name, InsertAtEnd) {
3314 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
3317 ZExtInst::ZExtInst(
3318 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3319 ) : CastInst(Ty, ZExt, S, Name, InsertBefore) {
3320 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
3323 ZExtInst::ZExtInst(
3324 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3325 ) : CastInst(Ty, ZExt, S, Name, InsertAtEnd) {
3326 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
3328 SExtInst::SExtInst(
3329 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3330 ) : CastInst(Ty, SExt, S, Name, InsertBefore) {
3331 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
3334 SExtInst::SExtInst(
3335 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3336 ) : CastInst(Ty, SExt, S, Name, InsertAtEnd) {
3337 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
3340 FPTruncInst::FPTruncInst(
3341 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3342 ) : CastInst(Ty, FPTrunc, S, Name, InsertBefore) {
3343 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
3346 FPTruncInst::FPTruncInst(
3347 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3348 ) : CastInst(Ty, FPTrunc, S, Name, InsertAtEnd) {
3349 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
3352 FPExtInst::FPExtInst(
3353 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3354 ) : CastInst(Ty, FPExt, S, Name, InsertBefore) {
3355 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
3358 FPExtInst::FPExtInst(
3359 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3360 ) : CastInst(Ty, FPExt, S, Name, InsertAtEnd) {
3361 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
3364 UIToFPInst::UIToFPInst(
3365 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3366 ) : CastInst(Ty, UIToFP, S, Name, InsertBefore) {
3367 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
3370 UIToFPInst::UIToFPInst(
3371 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3372 ) : CastInst(Ty, UIToFP, S, Name, InsertAtEnd) {
3373 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
3376 SIToFPInst::SIToFPInst(
3377 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3378 ) : CastInst(Ty, SIToFP, S, Name, InsertBefore) {
3379 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
3382 SIToFPInst::SIToFPInst(
3383 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3384 ) : CastInst(Ty, SIToFP, S, Name, InsertAtEnd) {
3385 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
3388 FPToUIInst::FPToUIInst(
3389 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3390 ) : CastInst(Ty, FPToUI, S, Name, InsertBefore) {
3391 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
3394 FPToUIInst::FPToUIInst(
3395 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3396 ) : CastInst(Ty, FPToUI, S, Name, InsertAtEnd) {
3397 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
3400 FPToSIInst::FPToSIInst(
3401 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3402 ) : CastInst(Ty, FPToSI, S, Name, InsertBefore) {
3403 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
3406 FPToSIInst::FPToSIInst(
3407 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3408 ) : CastInst(Ty, FPToSI, S, Name, InsertAtEnd) {
3409 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
3412 PtrToIntInst::PtrToIntInst(
3413 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3414 ) : CastInst(Ty, PtrToInt, S, Name, InsertBefore) {
3415 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
3418 PtrToIntInst::PtrToIntInst(
3419 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3420 ) : CastInst(Ty, PtrToInt, S, Name, InsertAtEnd) {
3421 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
3424 IntToPtrInst::IntToPtrInst(
3425 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3426 ) : CastInst(Ty, IntToPtr, S, Name, InsertBefore) {
3427 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
3430 IntToPtrInst::IntToPtrInst(
3431 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3432 ) : CastInst(Ty, IntToPtr, S, Name, InsertAtEnd) {
3433 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
3436 BitCastInst::BitCastInst(
3437 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3438 ) : CastInst(Ty, BitCast, S, Name, InsertBefore) {
3439 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
3442 BitCastInst::BitCastInst(
3443 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3444 ) : CastInst(Ty, BitCast, S, Name, InsertAtEnd) {
3445 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
3448 AddrSpaceCastInst::AddrSpaceCastInst(
3449 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3450 ) : CastInst(Ty, AddrSpaceCast, S, Name, InsertBefore) {
3451 assert(castIsValid(getOpcode(), S, Ty) && "Illegal AddrSpaceCast");
3454 AddrSpaceCastInst::AddrSpaceCastInst(
3455 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3456 ) : CastInst(Ty, AddrSpaceCast, S, Name, InsertAtEnd) {
3457 assert(castIsValid(getOpcode(), S, Ty) && "Illegal AddrSpaceCast");
3460 //===----------------------------------------------------------------------===//
3461 // CmpInst Classes
3462 //===----------------------------------------------------------------------===//
3464 CmpInst::CmpInst(Type *ty, OtherOps op, Predicate predicate, Value *LHS,
3465 Value *RHS, const Twine &Name, Instruction *InsertBefore,
3466 Instruction *FlagsSource)
3467 : Instruction(ty, op,
3468 OperandTraits<CmpInst>::op_begin(this),
3469 OperandTraits<CmpInst>::operands(this),
3470 InsertBefore) {
3471 Op<0>() = LHS;
3472 Op<1>() = RHS;
3473 setPredicate((Predicate)predicate);
3474 setName(Name);
3475 if (FlagsSource)
3476 copyIRFlags(FlagsSource);
3479 CmpInst::CmpInst(Type *ty, OtherOps op, Predicate predicate, Value *LHS,
3480 Value *RHS, const Twine &Name, BasicBlock *InsertAtEnd)
3481 : Instruction(ty, op,
3482 OperandTraits<CmpInst>::op_begin(this),
3483 OperandTraits<CmpInst>::operands(this),
3484 InsertAtEnd) {
3485 Op<0>() = LHS;
3486 Op<1>() = RHS;
3487 setPredicate((Predicate)predicate);
3488 setName(Name);
3491 CmpInst *
3492 CmpInst::Create(OtherOps Op, Predicate predicate, Value *S1, Value *S2,
3493 const Twine &Name, Instruction *InsertBefore) {
3494 if (Op == Instruction::ICmp) {
3495 if (InsertBefore)
3496 return new ICmpInst(InsertBefore, CmpInst::Predicate(predicate),
3497 S1, S2, Name);
3498 else
3499 return new ICmpInst(CmpInst::Predicate(predicate),
3500 S1, S2, Name);
3503 if (InsertBefore)
3504 return new FCmpInst(InsertBefore, CmpInst::Predicate(predicate),
3505 S1, S2, Name);
3506 else
3507 return new FCmpInst(CmpInst::Predicate(predicate),
3508 S1, S2, Name);
3511 CmpInst *
3512 CmpInst::Create(OtherOps Op, Predicate predicate, Value *S1, Value *S2,
3513 const Twine &Name, BasicBlock *InsertAtEnd) {
3514 if (Op == Instruction::ICmp) {
3515 return new ICmpInst(*InsertAtEnd, CmpInst::Predicate(predicate),
3516 S1, S2, Name);
3518 return new FCmpInst(*InsertAtEnd, CmpInst::Predicate(predicate),
3519 S1, S2, Name);
3522 void CmpInst::swapOperands() {
3523 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
3524 IC->swapOperands();
3525 else
3526 cast<FCmpInst>(this)->swapOperands();
3529 bool CmpInst::isCommutative() const {
3530 if (const ICmpInst *IC = dyn_cast<ICmpInst>(this))
3531 return IC->isCommutative();
3532 return cast<FCmpInst>(this)->isCommutative();
3535 bool CmpInst::isEquality() const {
3536 if (const ICmpInst *IC = dyn_cast<ICmpInst>(this))
3537 return IC->isEquality();
3538 return cast<FCmpInst>(this)->isEquality();
3541 CmpInst::Predicate CmpInst::getInversePredicate(Predicate pred) {
3542 switch (pred) {
3543 default: llvm_unreachable("Unknown cmp predicate!");
3544 case ICMP_EQ: return ICMP_NE;
3545 case ICMP_NE: return ICMP_EQ;
3546 case ICMP_UGT: return ICMP_ULE;
3547 case ICMP_ULT: return ICMP_UGE;
3548 case ICMP_UGE: return ICMP_ULT;
3549 case ICMP_ULE: return ICMP_UGT;
3550 case ICMP_SGT: return ICMP_SLE;
3551 case ICMP_SLT: return ICMP_SGE;
3552 case ICMP_SGE: return ICMP_SLT;
3553 case ICMP_SLE: return ICMP_SGT;
3555 case FCMP_OEQ: return FCMP_UNE;
3556 case FCMP_ONE: return FCMP_UEQ;
3557 case FCMP_OGT: return FCMP_ULE;
3558 case FCMP_OLT: return FCMP_UGE;
3559 case FCMP_OGE: return FCMP_ULT;
3560 case FCMP_OLE: return FCMP_UGT;
3561 case FCMP_UEQ: return FCMP_ONE;
3562 case FCMP_UNE: return FCMP_OEQ;
3563 case FCMP_UGT: return FCMP_OLE;
3564 case FCMP_ULT: return FCMP_OGE;
3565 case FCMP_UGE: return FCMP_OLT;
3566 case FCMP_ULE: return FCMP_OGT;
3567 case FCMP_ORD: return FCMP_UNO;
3568 case FCMP_UNO: return FCMP_ORD;
3569 case FCMP_TRUE: return FCMP_FALSE;
3570 case FCMP_FALSE: return FCMP_TRUE;
3574 StringRef CmpInst::getPredicateName(Predicate Pred) {
3575 switch (Pred) {
3576 default: return "unknown";
3577 case FCmpInst::FCMP_FALSE: return "false";
3578 case FCmpInst::FCMP_OEQ: return "oeq";
3579 case FCmpInst::FCMP_OGT: return "ogt";
3580 case FCmpInst::FCMP_OGE: return "oge";
3581 case FCmpInst::FCMP_OLT: return "olt";
3582 case FCmpInst::FCMP_OLE: return "ole";
3583 case FCmpInst::FCMP_ONE: return "one";
3584 case FCmpInst::FCMP_ORD: return "ord";
3585 case FCmpInst::FCMP_UNO: return "uno";
3586 case FCmpInst::FCMP_UEQ: return "ueq";
3587 case FCmpInst::FCMP_UGT: return "ugt";
3588 case FCmpInst::FCMP_UGE: return "uge";
3589 case FCmpInst::FCMP_ULT: return "ult";
3590 case FCmpInst::FCMP_ULE: return "ule";
3591 case FCmpInst::FCMP_UNE: return "une";
3592 case FCmpInst::FCMP_TRUE: return "true";
3593 case ICmpInst::ICMP_EQ: return "eq";
3594 case ICmpInst::ICMP_NE: return "ne";
3595 case ICmpInst::ICMP_SGT: return "sgt";
3596 case ICmpInst::ICMP_SGE: return "sge";
3597 case ICmpInst::ICMP_SLT: return "slt";
3598 case ICmpInst::ICMP_SLE: return "sle";
3599 case ICmpInst::ICMP_UGT: return "ugt";
3600 case ICmpInst::ICMP_UGE: return "uge";
3601 case ICmpInst::ICMP_ULT: return "ult";
3602 case ICmpInst::ICMP_ULE: return "ule";
3606 ICmpInst::Predicate ICmpInst::getSignedPredicate(Predicate pred) {
3607 switch (pred) {
3608 default: llvm_unreachable("Unknown icmp predicate!");
3609 case ICMP_EQ: case ICMP_NE:
3610 case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE:
3611 return pred;
3612 case ICMP_UGT: return ICMP_SGT;
3613 case ICMP_ULT: return ICMP_SLT;
3614 case ICMP_UGE: return ICMP_SGE;
3615 case ICMP_ULE: return ICMP_SLE;
3619 ICmpInst::Predicate ICmpInst::getUnsignedPredicate(Predicate pred) {
3620 switch (pred) {
3621 default: llvm_unreachable("Unknown icmp predicate!");
3622 case ICMP_EQ: case ICMP_NE:
3623 case ICMP_UGT: case ICMP_ULT: case ICMP_UGE: case ICMP_ULE:
3624 return pred;
3625 case ICMP_SGT: return ICMP_UGT;
3626 case ICMP_SLT: return ICMP_ULT;
3627 case ICMP_SGE: return ICMP_UGE;
3628 case ICMP_SLE: return ICMP_ULE;
3632 CmpInst::Predicate CmpInst::getFlippedStrictnessPredicate(Predicate pred) {
3633 switch (pred) {
3634 default: llvm_unreachable("Unknown or unsupported cmp predicate!");
3635 case ICMP_SGT: return ICMP_SGE;
3636 case ICMP_SLT: return ICMP_SLE;
3637 case ICMP_SGE: return ICMP_SGT;
3638 case ICMP_SLE: return ICMP_SLT;
3639 case ICMP_UGT: return ICMP_UGE;
3640 case ICMP_ULT: return ICMP_ULE;
3641 case ICMP_UGE: return ICMP_UGT;
3642 case ICMP_ULE: return ICMP_ULT;
3644 case FCMP_OGT: return FCMP_OGE;
3645 case FCMP_OLT: return FCMP_OLE;
3646 case FCMP_OGE: return FCMP_OGT;
3647 case FCMP_OLE: return FCMP_OLT;
3648 case FCMP_UGT: return FCMP_UGE;
3649 case FCMP_ULT: return FCMP_ULE;
3650 case FCMP_UGE: return FCMP_UGT;
3651 case FCMP_ULE: return FCMP_ULT;
3655 CmpInst::Predicate CmpInst::getSwappedPredicate(Predicate pred) {
3656 switch (pred) {
3657 default: llvm_unreachable("Unknown cmp predicate!");
3658 case ICMP_EQ: case ICMP_NE:
3659 return pred;
3660 case ICMP_SGT: return ICMP_SLT;
3661 case ICMP_SLT: return ICMP_SGT;
3662 case ICMP_SGE: return ICMP_SLE;
3663 case ICMP_SLE: return ICMP_SGE;
3664 case ICMP_UGT: return ICMP_ULT;
3665 case ICMP_ULT: return ICMP_UGT;
3666 case ICMP_UGE: return ICMP_ULE;
3667 case ICMP_ULE: return ICMP_UGE;
3669 case FCMP_FALSE: case FCMP_TRUE:
3670 case FCMP_OEQ: case FCMP_ONE:
3671 case FCMP_UEQ: case FCMP_UNE:
3672 case FCMP_ORD: case FCMP_UNO:
3673 return pred;
3674 case FCMP_OGT: return FCMP_OLT;
3675 case FCMP_OLT: return FCMP_OGT;
3676 case FCMP_OGE: return FCMP_OLE;
3677 case FCMP_OLE: return FCMP_OGE;
3678 case FCMP_UGT: return FCMP_ULT;
3679 case FCMP_ULT: return FCMP_UGT;
3680 case FCMP_UGE: return FCMP_ULE;
3681 case FCMP_ULE: return FCMP_UGE;
3685 CmpInst::Predicate CmpInst::getNonStrictPredicate(Predicate pred) {
3686 switch (pred) {
3687 case ICMP_SGT: return ICMP_SGE;
3688 case ICMP_SLT: return ICMP_SLE;
3689 case ICMP_UGT: return ICMP_UGE;
3690 case ICMP_ULT: return ICMP_ULE;
3691 case FCMP_OGT: return FCMP_OGE;
3692 case FCMP_OLT: return FCMP_OLE;
3693 case FCMP_UGT: return FCMP_UGE;
3694 case FCMP_ULT: return FCMP_ULE;
3695 default: return pred;
3699 CmpInst::Predicate CmpInst::getSignedPredicate(Predicate pred) {
3700 assert(CmpInst::isUnsigned(pred) && "Call only with signed predicates!");
3702 switch (pred) {
3703 default:
3704 llvm_unreachable("Unknown predicate!");
3705 case CmpInst::ICMP_ULT:
3706 return CmpInst::ICMP_SLT;
3707 case CmpInst::ICMP_ULE:
3708 return CmpInst::ICMP_SLE;
3709 case CmpInst::ICMP_UGT:
3710 return CmpInst::ICMP_SGT;
3711 case CmpInst::ICMP_UGE:
3712 return CmpInst::ICMP_SGE;
3716 bool CmpInst::isUnsigned(Predicate predicate) {
3717 switch (predicate) {
3718 default: return false;
3719 case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE: case ICmpInst::ICMP_UGT:
3720 case ICmpInst::ICMP_UGE: return true;
3724 bool CmpInst::isSigned(Predicate predicate) {
3725 switch (predicate) {
3726 default: return false;
3727 case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_SLE: case ICmpInst::ICMP_SGT:
3728 case ICmpInst::ICMP_SGE: return true;
3732 bool CmpInst::isOrdered(Predicate predicate) {
3733 switch (predicate) {
3734 default: return false;
3735 case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_OGT:
3736 case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLE:
3737 case FCmpInst::FCMP_ORD: return true;
3741 bool CmpInst::isUnordered(Predicate predicate) {
3742 switch (predicate) {
3743 default: return false;
3744 case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UNE: case FCmpInst::FCMP_UGT:
3745 case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_UGE: case FCmpInst::FCMP_ULE:
3746 case FCmpInst::FCMP_UNO: return true;
3750 bool CmpInst::isTrueWhenEqual(Predicate predicate) {
3751 switch(predicate) {
3752 default: return false;
3753 case ICMP_EQ: case ICMP_UGE: case ICMP_ULE: case ICMP_SGE: case ICMP_SLE:
3754 case FCMP_TRUE: case FCMP_UEQ: case FCMP_UGE: case FCMP_ULE: return true;
3758 bool CmpInst::isFalseWhenEqual(Predicate predicate) {
3759 switch(predicate) {
3760 case ICMP_NE: case ICMP_UGT: case ICMP_ULT: case ICMP_SGT: case ICMP_SLT:
3761 case FCMP_FALSE: case FCMP_ONE: case FCMP_OGT: case FCMP_OLT: return true;
3762 default: return false;
3766 bool CmpInst::isImpliedTrueByMatchingCmp(Predicate Pred1, Predicate Pred2) {
3767 // If the predicates match, then we know the first condition implies the
3768 // second is true.
3769 if (Pred1 == Pred2)
3770 return true;
3772 switch (Pred1) {
3773 default:
3774 break;
3775 case ICMP_EQ:
3776 // A == B implies A >=u B, A <=u B, A >=s B, and A <=s B are true.
3777 return Pred2 == ICMP_UGE || Pred2 == ICMP_ULE || Pred2 == ICMP_SGE ||
3778 Pred2 == ICMP_SLE;
3779 case ICMP_UGT: // A >u B implies A != B and A >=u B are true.
3780 return Pred2 == ICMP_NE || Pred2 == ICMP_UGE;
3781 case ICMP_ULT: // A <u B implies A != B and A <=u B are true.
3782 return Pred2 == ICMP_NE || Pred2 == ICMP_ULE;
3783 case ICMP_SGT: // A >s B implies A != B and A >=s B are true.
3784 return Pred2 == ICMP_NE || Pred2 == ICMP_SGE;
3785 case ICMP_SLT: // A <s B implies A != B and A <=s B are true.
3786 return Pred2 == ICMP_NE || Pred2 == ICMP_SLE;
3788 return false;
3791 bool CmpInst::isImpliedFalseByMatchingCmp(Predicate Pred1, Predicate Pred2) {
3792 return isImpliedTrueByMatchingCmp(Pred1, getInversePredicate(Pred2));
3795 //===----------------------------------------------------------------------===//
3796 // SwitchInst Implementation
3797 //===----------------------------------------------------------------------===//
3799 void SwitchInst::init(Value *Value, BasicBlock *Default, unsigned NumReserved) {
3800 assert(Value && Default && NumReserved);
3801 ReservedSpace = NumReserved;
3802 setNumHungOffUseOperands(2);
3803 allocHungoffUses(ReservedSpace);
3805 Op<0>() = Value;
3806 Op<1>() = Default;
3809 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
3810 /// switch on and a default destination. The number of additional cases can
3811 /// be specified here to make memory allocation more efficient. This
3812 /// constructor can also autoinsert before another instruction.
3813 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
3814 Instruction *InsertBefore)
3815 : Instruction(Type::getVoidTy(Value->getContext()), Instruction::Switch,
3816 nullptr, 0, InsertBefore) {
3817 init(Value, Default, 2+NumCases*2);
3820 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
3821 /// switch on and a default destination. The number of additional cases can
3822 /// be specified here to make memory allocation more efficient. This
3823 /// constructor also autoinserts at the end of the specified BasicBlock.
3824 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
3825 BasicBlock *InsertAtEnd)
3826 : Instruction(Type::getVoidTy(Value->getContext()), Instruction::Switch,
3827 nullptr, 0, InsertAtEnd) {
3828 init(Value, Default, 2+NumCases*2);
3831 SwitchInst::SwitchInst(const SwitchInst &SI)
3832 : Instruction(SI.getType(), Instruction::Switch, nullptr, 0) {
3833 init(SI.getCondition(), SI.getDefaultDest(), SI.getNumOperands());
3834 setNumHungOffUseOperands(SI.getNumOperands());
3835 Use *OL = getOperandList();
3836 const Use *InOL = SI.getOperandList();
3837 for (unsigned i = 2, E = SI.getNumOperands(); i != E; i += 2) {
3838 OL[i] = InOL[i];
3839 OL[i+1] = InOL[i+1];
3841 SubclassOptionalData = SI.SubclassOptionalData;
3844 /// addCase - Add an entry to the switch instruction...
3846 void SwitchInst::addCase(ConstantInt *OnVal, BasicBlock *Dest) {
3847 unsigned NewCaseIdx = getNumCases();
3848 unsigned OpNo = getNumOperands();
3849 if (OpNo+2 > ReservedSpace)
3850 growOperands(); // Get more space!
3851 // Initialize some new operands.
3852 assert(OpNo+1 < ReservedSpace && "Growing didn't work!");
3853 setNumHungOffUseOperands(OpNo+2);
3854 CaseHandle Case(this, NewCaseIdx);
3855 Case.setValue(OnVal);
3856 Case.setSuccessor(Dest);
3859 /// removeCase - This method removes the specified case and its successor
3860 /// from the switch instruction.
3861 SwitchInst::CaseIt SwitchInst::removeCase(CaseIt I) {
3862 unsigned idx = I->getCaseIndex();
3864 assert(2 + idx*2 < getNumOperands() && "Case index out of range!!!");
3866 unsigned NumOps = getNumOperands();
3867 Use *OL = getOperandList();
3869 // Overwrite this case with the end of the list.
3870 if (2 + (idx + 1) * 2 != NumOps) {
3871 OL[2 + idx * 2] = OL[NumOps - 2];
3872 OL[2 + idx * 2 + 1] = OL[NumOps - 1];
3875 // Nuke the last value.
3876 OL[NumOps-2].set(nullptr);
3877 OL[NumOps-2+1].set(nullptr);
3878 setNumHungOffUseOperands(NumOps-2);
3880 return CaseIt(this, idx);
3883 /// growOperands - grow operands - This grows the operand list in response
3884 /// to a push_back style of operation. This grows the number of ops by 3 times.
3886 void SwitchInst::growOperands() {
3887 unsigned e = getNumOperands();
3888 unsigned NumOps = e*3;
3890 ReservedSpace = NumOps;
3891 growHungoffUses(ReservedSpace);
3894 MDNode *
3895 SwitchInstProfUpdateWrapper::getProfBranchWeightsMD(const SwitchInst &SI) {
3896 if (MDNode *ProfileData = SI.getMetadata(LLVMContext::MD_prof))
3897 if (auto *MDName = dyn_cast<MDString>(ProfileData->getOperand(0)))
3898 if (MDName->getString() == "branch_weights")
3899 return ProfileData;
3900 return nullptr;
3903 MDNode *SwitchInstProfUpdateWrapper::buildProfBranchWeightsMD() {
3904 assert(Changed && "called only if metadata has changed");
3906 if (!Weights)
3907 return nullptr;
3909 assert(SI.getNumSuccessors() == Weights->size() &&
3910 "num of prof branch_weights must accord with num of successors");
3912 bool AllZeroes =
3913 all_of(Weights.getValue(), [](uint32_t W) { return W == 0; });
3915 if (AllZeroes || Weights.getValue().size() < 2)
3916 return nullptr;
3918 return MDBuilder(SI.getParent()->getContext()).createBranchWeights(*Weights);
3921 void SwitchInstProfUpdateWrapper::init() {
3922 MDNode *ProfileData = getProfBranchWeightsMD(SI);
3923 if (!ProfileData)
3924 return;
3926 if (ProfileData->getNumOperands() != SI.getNumSuccessors() + 1) {
3927 llvm_unreachable("number of prof branch_weights metadata operands does "
3928 "not correspond to number of succesors");
3931 SmallVector<uint32_t, 8> Weights;
3932 for (unsigned CI = 1, CE = SI.getNumSuccessors(); CI <= CE; ++CI) {
3933 ConstantInt *C = mdconst::extract<ConstantInt>(ProfileData->getOperand(CI));
3934 uint32_t CW = C->getValue().getZExtValue();
3935 Weights.push_back(CW);
3937 this->Weights = std::move(Weights);
3940 SwitchInst::CaseIt
3941 SwitchInstProfUpdateWrapper::removeCase(SwitchInst::CaseIt I) {
3942 if (Weights) {
3943 assert(SI.getNumSuccessors() == Weights->size() &&
3944 "num of prof branch_weights must accord with num of successors");
3945 Changed = true;
3946 // Copy the last case to the place of the removed one and shrink.
3947 // This is tightly coupled with the way SwitchInst::removeCase() removes
3948 // the cases in SwitchInst::removeCase(CaseIt).
3949 Weights.getValue()[I->getCaseIndex() + 1] = Weights.getValue().back();
3950 Weights.getValue().pop_back();
3952 return SI.removeCase(I);
3955 void SwitchInstProfUpdateWrapper::addCase(
3956 ConstantInt *OnVal, BasicBlock *Dest,
3957 SwitchInstProfUpdateWrapper::CaseWeightOpt W) {
3958 SI.addCase(OnVal, Dest);
3960 if (!Weights && W && *W) {
3961 Changed = true;
3962 Weights = SmallVector<uint32_t, 8>(SI.getNumSuccessors(), 0);
3963 Weights.getValue()[SI.getNumSuccessors() - 1] = *W;
3964 } else if (Weights) {
3965 Changed = true;
3966 Weights.getValue().push_back(W ? *W : 0);
3968 if (Weights)
3969 assert(SI.getNumSuccessors() == Weights->size() &&
3970 "num of prof branch_weights must accord with num of successors");
3973 SymbolTableList<Instruction>::iterator
3974 SwitchInstProfUpdateWrapper::eraseFromParent() {
3975 // Instruction is erased. Mark as unchanged to not touch it in the destructor.
3976 Changed = false;
3977 if (Weights)
3978 Weights->resize(0);
3979 return SI.eraseFromParent();
3982 SwitchInstProfUpdateWrapper::CaseWeightOpt
3983 SwitchInstProfUpdateWrapper::getSuccessorWeight(unsigned idx) {
3984 if (!Weights)
3985 return None;
3986 return Weights.getValue()[idx];
3989 void SwitchInstProfUpdateWrapper::setSuccessorWeight(
3990 unsigned idx, SwitchInstProfUpdateWrapper::CaseWeightOpt W) {
3991 if (!W)
3992 return;
3994 if (!Weights && *W)
3995 Weights = SmallVector<uint32_t, 8>(SI.getNumSuccessors(), 0);
3997 if (Weights) {
3998 auto &OldW = Weights.getValue()[idx];
3999 if (*W != OldW) {
4000 Changed = true;
4001 OldW = *W;
4006 SwitchInstProfUpdateWrapper::CaseWeightOpt
4007 SwitchInstProfUpdateWrapper::getSuccessorWeight(const SwitchInst &SI,
4008 unsigned idx) {
4009 if (MDNode *ProfileData = getProfBranchWeightsMD(SI))
4010 if (ProfileData->getNumOperands() == SI.getNumSuccessors() + 1)
4011 return mdconst::extract<ConstantInt>(ProfileData->getOperand(idx + 1))
4012 ->getValue()
4013 .getZExtValue();
4015 return None;
4018 //===----------------------------------------------------------------------===//
4019 // IndirectBrInst Implementation
4020 //===----------------------------------------------------------------------===//
4022 void IndirectBrInst::init(Value *Address, unsigned NumDests) {
4023 assert(Address && Address->getType()->isPointerTy() &&
4024 "Address of indirectbr must be a pointer");
4025 ReservedSpace = 1+NumDests;
4026 setNumHungOffUseOperands(1);
4027 allocHungoffUses(ReservedSpace);
4029 Op<0>() = Address;
4033 /// growOperands - grow operands - This grows the operand list in response
4034 /// to a push_back style of operation. This grows the number of ops by 2 times.
4036 void IndirectBrInst::growOperands() {
4037 unsigned e = getNumOperands();
4038 unsigned NumOps = e*2;
4040 ReservedSpace = NumOps;
4041 growHungoffUses(ReservedSpace);
4044 IndirectBrInst::IndirectBrInst(Value *Address, unsigned NumCases,
4045 Instruction *InsertBefore)
4046 : Instruction(Type::getVoidTy(Address->getContext()),
4047 Instruction::IndirectBr, nullptr, 0, InsertBefore) {
4048 init(Address, NumCases);
4051 IndirectBrInst::IndirectBrInst(Value *Address, unsigned NumCases,
4052 BasicBlock *InsertAtEnd)
4053 : Instruction(Type::getVoidTy(Address->getContext()),
4054 Instruction::IndirectBr, nullptr, 0, InsertAtEnd) {
4055 init(Address, NumCases);
4058 IndirectBrInst::IndirectBrInst(const IndirectBrInst &IBI)
4059 : Instruction(Type::getVoidTy(IBI.getContext()), Instruction::IndirectBr,
4060 nullptr, IBI.getNumOperands()) {
4061 allocHungoffUses(IBI.getNumOperands());
4062 Use *OL = getOperandList();
4063 const Use *InOL = IBI.getOperandList();
4064 for (unsigned i = 0, E = IBI.getNumOperands(); i != E; ++i)
4065 OL[i] = InOL[i];
4066 SubclassOptionalData = IBI.SubclassOptionalData;
4069 /// addDestination - Add a destination.
4071 void IndirectBrInst::addDestination(BasicBlock *DestBB) {
4072 unsigned OpNo = getNumOperands();
4073 if (OpNo+1 > ReservedSpace)
4074 growOperands(); // Get more space!
4075 // Initialize some new operands.
4076 assert(OpNo < ReservedSpace && "Growing didn't work!");
4077 setNumHungOffUseOperands(OpNo+1);
4078 getOperandList()[OpNo] = DestBB;
4081 /// removeDestination - This method removes the specified successor from the
4082 /// indirectbr instruction.
4083 void IndirectBrInst::removeDestination(unsigned idx) {
4084 assert(idx < getNumOperands()-1 && "Successor index out of range!");
4086 unsigned NumOps = getNumOperands();
4087 Use *OL = getOperandList();
4089 // Replace this value with the last one.
4090 OL[idx+1] = OL[NumOps-1];
4092 // Nuke the last value.
4093 OL[NumOps-1].set(nullptr);
4094 setNumHungOffUseOperands(NumOps-1);
4097 //===----------------------------------------------------------------------===//
4098 // cloneImpl() implementations
4099 //===----------------------------------------------------------------------===//
4101 // Define these methods here so vtables don't get emitted into every translation
4102 // unit that uses these classes.
4104 GetElementPtrInst *GetElementPtrInst::cloneImpl() const {
4105 return new (getNumOperands()) GetElementPtrInst(*this);
4108 UnaryOperator *UnaryOperator::cloneImpl() const {
4109 return Create(getOpcode(), Op<0>());
4112 BinaryOperator *BinaryOperator::cloneImpl() const {
4113 return Create(getOpcode(), Op<0>(), Op<1>());
4116 FCmpInst *FCmpInst::cloneImpl() const {
4117 return new FCmpInst(getPredicate(), Op<0>(), Op<1>());
4120 ICmpInst *ICmpInst::cloneImpl() const {
4121 return new ICmpInst(getPredicate(), Op<0>(), Op<1>());
4124 ExtractValueInst *ExtractValueInst::cloneImpl() const {
4125 return new ExtractValueInst(*this);
4128 InsertValueInst *InsertValueInst::cloneImpl() const {
4129 return new InsertValueInst(*this);
4132 AllocaInst *AllocaInst::cloneImpl() const {
4133 AllocaInst *Result = new AllocaInst(getAllocatedType(),
4134 getType()->getAddressSpace(),
4135 (Value *)getOperand(0), getAlignment());
4136 Result->setUsedWithInAlloca(isUsedWithInAlloca());
4137 Result->setSwiftError(isSwiftError());
4138 return Result;
4141 LoadInst *LoadInst::cloneImpl() const {
4142 return new LoadInst(getType(), getOperand(0), Twine(), isVolatile(),
4143 MaybeAlign(getAlignment()), getOrdering(),
4144 getSyncScopeID());
4147 StoreInst *StoreInst::cloneImpl() const {
4148 return new StoreInst(getOperand(0), getOperand(1), isVolatile(),
4149 getAlignment(), getOrdering(), getSyncScopeID());
4153 AtomicCmpXchgInst *AtomicCmpXchgInst::cloneImpl() const {
4154 AtomicCmpXchgInst *Result =
4155 new AtomicCmpXchgInst(getOperand(0), getOperand(1), getOperand(2),
4156 getSuccessOrdering(), getFailureOrdering(),
4157 getSyncScopeID());
4158 Result->setVolatile(isVolatile());
4159 Result->setWeak(isWeak());
4160 return Result;
4163 AtomicRMWInst *AtomicRMWInst::cloneImpl() const {
4164 AtomicRMWInst *Result =
4165 new AtomicRMWInst(getOperation(), getOperand(0), getOperand(1),
4166 getOrdering(), getSyncScopeID());
4167 Result->setVolatile(isVolatile());
4168 return Result;
4171 FenceInst *FenceInst::cloneImpl() const {
4172 return new FenceInst(getContext(), getOrdering(), getSyncScopeID());
4175 TruncInst *TruncInst::cloneImpl() const {
4176 return new TruncInst(getOperand(0), getType());
4179 ZExtInst *ZExtInst::cloneImpl() const {
4180 return new ZExtInst(getOperand(0), getType());
4183 SExtInst *SExtInst::cloneImpl() const {
4184 return new SExtInst(getOperand(0), getType());
4187 FPTruncInst *FPTruncInst::cloneImpl() const {
4188 return new FPTruncInst(getOperand(0), getType());
4191 FPExtInst *FPExtInst::cloneImpl() const {
4192 return new FPExtInst(getOperand(0), getType());
4195 UIToFPInst *UIToFPInst::cloneImpl() const {
4196 return new UIToFPInst(getOperand(0), getType());
4199 SIToFPInst *SIToFPInst::cloneImpl() const {
4200 return new SIToFPInst(getOperand(0), getType());
4203 FPToUIInst *FPToUIInst::cloneImpl() const {
4204 return new FPToUIInst(getOperand(0), getType());
4207 FPToSIInst *FPToSIInst::cloneImpl() const {
4208 return new FPToSIInst(getOperand(0), getType());
4211 PtrToIntInst *PtrToIntInst::cloneImpl() const {
4212 return new PtrToIntInst(getOperand(0), getType());
4215 IntToPtrInst *IntToPtrInst::cloneImpl() const {
4216 return new IntToPtrInst(getOperand(0), getType());
4219 BitCastInst *BitCastInst::cloneImpl() const {
4220 return new BitCastInst(getOperand(0), getType());
4223 AddrSpaceCastInst *AddrSpaceCastInst::cloneImpl() const {
4224 return new AddrSpaceCastInst(getOperand(0), getType());
4227 CallInst *CallInst::cloneImpl() const {
4228 if (hasOperandBundles()) {
4229 unsigned DescriptorBytes = getNumOperandBundles() * sizeof(BundleOpInfo);
4230 return new(getNumOperands(), DescriptorBytes) CallInst(*this);
4232 return new(getNumOperands()) CallInst(*this);
4235 SelectInst *SelectInst::cloneImpl() const {
4236 return SelectInst::Create(getOperand(0), getOperand(1), getOperand(2));
4239 VAArgInst *VAArgInst::cloneImpl() const {
4240 return new VAArgInst(getOperand(0), getType());
4243 ExtractElementInst *ExtractElementInst::cloneImpl() const {
4244 return ExtractElementInst::Create(getOperand(0), getOperand(1));
4247 InsertElementInst *InsertElementInst::cloneImpl() const {
4248 return InsertElementInst::Create(getOperand(0), getOperand(1), getOperand(2));
4251 ShuffleVectorInst *ShuffleVectorInst::cloneImpl() const {
4252 return new ShuffleVectorInst(getOperand(0), getOperand(1), getOperand(2));
4255 PHINode *PHINode::cloneImpl() const { return new PHINode(*this); }
4257 LandingPadInst *LandingPadInst::cloneImpl() const {
4258 return new LandingPadInst(*this);
4261 ReturnInst *ReturnInst::cloneImpl() const {
4262 return new(getNumOperands()) ReturnInst(*this);
4265 BranchInst *BranchInst::cloneImpl() const {
4266 return new(getNumOperands()) BranchInst(*this);
4269 SwitchInst *SwitchInst::cloneImpl() const { return new SwitchInst(*this); }
4271 IndirectBrInst *IndirectBrInst::cloneImpl() const {
4272 return new IndirectBrInst(*this);
4275 InvokeInst *InvokeInst::cloneImpl() const {
4276 if (hasOperandBundles()) {
4277 unsigned DescriptorBytes = getNumOperandBundles() * sizeof(BundleOpInfo);
4278 return new(getNumOperands(), DescriptorBytes) InvokeInst(*this);
4280 return new(getNumOperands()) InvokeInst(*this);
4283 CallBrInst *CallBrInst::cloneImpl() const {
4284 if (hasOperandBundles()) {
4285 unsigned DescriptorBytes = getNumOperandBundles() * sizeof(BundleOpInfo);
4286 return new (getNumOperands(), DescriptorBytes) CallBrInst(*this);
4288 return new (getNumOperands()) CallBrInst(*this);
4291 ResumeInst *ResumeInst::cloneImpl() const { return new (1) ResumeInst(*this); }
4293 CleanupReturnInst *CleanupReturnInst::cloneImpl() const {
4294 return new (getNumOperands()) CleanupReturnInst(*this);
4297 CatchReturnInst *CatchReturnInst::cloneImpl() const {
4298 return new (getNumOperands()) CatchReturnInst(*this);
4301 CatchSwitchInst *CatchSwitchInst::cloneImpl() const {
4302 return new CatchSwitchInst(*this);
4305 FuncletPadInst *FuncletPadInst::cloneImpl() const {
4306 return new (getNumOperands()) FuncletPadInst(*this);
4309 UnreachableInst *UnreachableInst::cloneImpl() const {
4310 LLVMContext &Context = getContext();
4311 return new UnreachableInst(Context);