106f32e7eSjoerg //===- Instructions.cpp - Implement the LLVM instructions -----------------===//
206f32e7eSjoerg //
306f32e7eSjoerg // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
406f32e7eSjoerg // See https://llvm.org/LICENSE.txt for license information.
506f32e7eSjoerg // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
606f32e7eSjoerg //
706f32e7eSjoerg //===----------------------------------------------------------------------===//
806f32e7eSjoerg //
906f32e7eSjoerg // This file implements all of the non-inline methods for the LLVM instruction
1006f32e7eSjoerg // classes.
1106f32e7eSjoerg //
1206f32e7eSjoerg //===----------------------------------------------------------------------===//
1306f32e7eSjoerg 
1406f32e7eSjoerg #include "llvm/IR/Instructions.h"
1506f32e7eSjoerg #include "LLVMContextImpl.h"
1606f32e7eSjoerg #include "llvm/ADT/None.h"
1706f32e7eSjoerg #include "llvm/ADT/SmallVector.h"
1806f32e7eSjoerg #include "llvm/ADT/Twine.h"
1906f32e7eSjoerg #include "llvm/IR/Attributes.h"
2006f32e7eSjoerg #include "llvm/IR/BasicBlock.h"
2106f32e7eSjoerg #include "llvm/IR/Constant.h"
2206f32e7eSjoerg #include "llvm/IR/Constants.h"
2306f32e7eSjoerg #include "llvm/IR/DataLayout.h"
2406f32e7eSjoerg #include "llvm/IR/DerivedTypes.h"
2506f32e7eSjoerg #include "llvm/IR/Function.h"
2606f32e7eSjoerg #include "llvm/IR/InstrTypes.h"
2706f32e7eSjoerg #include "llvm/IR/Instruction.h"
2806f32e7eSjoerg #include "llvm/IR/Intrinsics.h"
2906f32e7eSjoerg #include "llvm/IR/LLVMContext.h"
3006f32e7eSjoerg #include "llvm/IR/MDBuilder.h"
3106f32e7eSjoerg #include "llvm/IR/Metadata.h"
3206f32e7eSjoerg #include "llvm/IR/Module.h"
3306f32e7eSjoerg #include "llvm/IR/Operator.h"
3406f32e7eSjoerg #include "llvm/IR/Type.h"
3506f32e7eSjoerg #include "llvm/IR/Value.h"
3606f32e7eSjoerg #include "llvm/Support/AtomicOrdering.h"
3706f32e7eSjoerg #include "llvm/Support/Casting.h"
3806f32e7eSjoerg #include "llvm/Support/ErrorHandling.h"
3906f32e7eSjoerg #include "llvm/Support/MathExtras.h"
4006f32e7eSjoerg #include "llvm/Support/TypeSize.h"
4106f32e7eSjoerg #include <algorithm>
4206f32e7eSjoerg #include <cassert>
4306f32e7eSjoerg #include <cstdint>
4406f32e7eSjoerg #include <vector>
4506f32e7eSjoerg 
4606f32e7eSjoerg using namespace llvm;
4706f32e7eSjoerg 
4806f32e7eSjoerg //===----------------------------------------------------------------------===//
4906f32e7eSjoerg //                            AllocaInst Class
5006f32e7eSjoerg //===----------------------------------------------------------------------===//
5106f32e7eSjoerg 
52*da58b97aSjoerg Optional<TypeSize>
getAllocationSizeInBits(const DataLayout & DL) const5306f32e7eSjoerg AllocaInst::getAllocationSizeInBits(const DataLayout &DL) const {
54*da58b97aSjoerg   TypeSize Size = DL.getTypeAllocSizeInBits(getAllocatedType());
5506f32e7eSjoerg   if (isArrayAllocation()) {
56*da58b97aSjoerg     auto *C = dyn_cast<ConstantInt>(getArraySize());
5706f32e7eSjoerg     if (!C)
5806f32e7eSjoerg       return None;
59*da58b97aSjoerg     assert(!Size.isScalable() && "Array elements cannot have a scalable size");
6006f32e7eSjoerg     Size *= C->getZExtValue();
6106f32e7eSjoerg   }
6206f32e7eSjoerg   return Size;
6306f32e7eSjoerg }
6406f32e7eSjoerg 
6506f32e7eSjoerg //===----------------------------------------------------------------------===//
6606f32e7eSjoerg //                              SelectInst Class
6706f32e7eSjoerg //===----------------------------------------------------------------------===//
6806f32e7eSjoerg 
6906f32e7eSjoerg /// areInvalidOperands - Return a string if the specified operands are invalid
7006f32e7eSjoerg /// for a select operation, otherwise return null.
areInvalidOperands(Value * Op0,Value * Op1,Value * Op2)7106f32e7eSjoerg const char *SelectInst::areInvalidOperands(Value *Op0, Value *Op1, Value *Op2) {
7206f32e7eSjoerg   if (Op1->getType() != Op2->getType())
7306f32e7eSjoerg     return "both values to select must have same type";
7406f32e7eSjoerg 
7506f32e7eSjoerg   if (Op1->getType()->isTokenTy())
7606f32e7eSjoerg     return "select values cannot have token type";
7706f32e7eSjoerg 
7806f32e7eSjoerg   if (VectorType *VT = dyn_cast<VectorType>(Op0->getType())) {
7906f32e7eSjoerg     // Vector select.
8006f32e7eSjoerg     if (VT->getElementType() != Type::getInt1Ty(Op0->getContext()))
8106f32e7eSjoerg       return "vector select condition element type must be i1";
8206f32e7eSjoerg     VectorType *ET = dyn_cast<VectorType>(Op1->getType());
8306f32e7eSjoerg     if (!ET)
8406f32e7eSjoerg       return "selected values for vector select must be vectors";
85*da58b97aSjoerg     if (ET->getElementCount() != VT->getElementCount())
8606f32e7eSjoerg       return "vector select requires selected vectors to have "
8706f32e7eSjoerg                    "the same vector length as select condition";
8806f32e7eSjoerg   } else if (Op0->getType() != Type::getInt1Ty(Op0->getContext())) {
8906f32e7eSjoerg     return "select condition must be i1 or <n x i1>";
9006f32e7eSjoerg   }
9106f32e7eSjoerg   return nullptr;
9206f32e7eSjoerg }
9306f32e7eSjoerg 
9406f32e7eSjoerg //===----------------------------------------------------------------------===//
9506f32e7eSjoerg //                               PHINode Class
9606f32e7eSjoerg //===----------------------------------------------------------------------===//
9706f32e7eSjoerg 
PHINode(const PHINode & PN)9806f32e7eSjoerg PHINode::PHINode(const PHINode &PN)
9906f32e7eSjoerg     : Instruction(PN.getType(), Instruction::PHI, nullptr, PN.getNumOperands()),
10006f32e7eSjoerg       ReservedSpace(PN.getNumOperands()) {
10106f32e7eSjoerg   allocHungoffUses(PN.getNumOperands());
10206f32e7eSjoerg   std::copy(PN.op_begin(), PN.op_end(), op_begin());
10306f32e7eSjoerg   std::copy(PN.block_begin(), PN.block_end(), block_begin());
10406f32e7eSjoerg   SubclassOptionalData = PN.SubclassOptionalData;
10506f32e7eSjoerg }
10606f32e7eSjoerg 
10706f32e7eSjoerg // removeIncomingValue - Remove an incoming value.  This is useful if a
10806f32e7eSjoerg // predecessor basic block is deleted.
removeIncomingValue(unsigned Idx,bool DeletePHIIfEmpty)10906f32e7eSjoerg Value *PHINode::removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty) {
11006f32e7eSjoerg   Value *Removed = getIncomingValue(Idx);
11106f32e7eSjoerg 
11206f32e7eSjoerg   // Move everything after this operand down.
11306f32e7eSjoerg   //
11406f32e7eSjoerg   // FIXME: we could just swap with the end of the list, then erase.  However,
11506f32e7eSjoerg   // clients might not expect this to happen.  The code as it is thrashes the
11606f32e7eSjoerg   // use/def lists, which is kinda lame.
11706f32e7eSjoerg   std::copy(op_begin() + Idx + 1, op_end(), op_begin() + Idx);
11806f32e7eSjoerg   std::copy(block_begin() + Idx + 1, block_end(), block_begin() + Idx);
11906f32e7eSjoerg 
12006f32e7eSjoerg   // Nuke the last value.
12106f32e7eSjoerg   Op<-1>().set(nullptr);
12206f32e7eSjoerg   setNumHungOffUseOperands(getNumOperands() - 1);
12306f32e7eSjoerg 
12406f32e7eSjoerg   // If the PHI node is dead, because it has zero entries, nuke it now.
12506f32e7eSjoerg   if (getNumOperands() == 0 && DeletePHIIfEmpty) {
12606f32e7eSjoerg     // If anyone is using this PHI, make them use a dummy value instead...
12706f32e7eSjoerg     replaceAllUsesWith(UndefValue::get(getType()));
12806f32e7eSjoerg     eraseFromParent();
12906f32e7eSjoerg   }
13006f32e7eSjoerg   return Removed;
13106f32e7eSjoerg }
13206f32e7eSjoerg 
13306f32e7eSjoerg /// growOperands - grow operands - This grows the operand list in response
13406f32e7eSjoerg /// to a push_back style of operation.  This grows the number of ops by 1.5
13506f32e7eSjoerg /// times.
13606f32e7eSjoerg ///
growOperands()13706f32e7eSjoerg void PHINode::growOperands() {
13806f32e7eSjoerg   unsigned e = getNumOperands();
13906f32e7eSjoerg   unsigned NumOps = e + e / 2;
14006f32e7eSjoerg   if (NumOps < 2) NumOps = 2;      // 2 op PHI nodes are VERY common.
14106f32e7eSjoerg 
14206f32e7eSjoerg   ReservedSpace = NumOps;
14306f32e7eSjoerg   growHungoffUses(ReservedSpace, /* IsPhi */ true);
14406f32e7eSjoerg }
14506f32e7eSjoerg 
14606f32e7eSjoerg /// hasConstantValue - If the specified PHI node always merges together the same
14706f32e7eSjoerg /// value, return the value, otherwise return null.
hasConstantValue() const14806f32e7eSjoerg Value *PHINode::hasConstantValue() const {
14906f32e7eSjoerg   // Exploit the fact that phi nodes always have at least one entry.
15006f32e7eSjoerg   Value *ConstantValue = getIncomingValue(0);
15106f32e7eSjoerg   for (unsigned i = 1, e = getNumIncomingValues(); i != e; ++i)
15206f32e7eSjoerg     if (getIncomingValue(i) != ConstantValue && getIncomingValue(i) != this) {
15306f32e7eSjoerg       if (ConstantValue != this)
15406f32e7eSjoerg         return nullptr; // Incoming values not all the same.
15506f32e7eSjoerg        // The case where the first value is this PHI.
15606f32e7eSjoerg       ConstantValue = getIncomingValue(i);
15706f32e7eSjoerg     }
15806f32e7eSjoerg   if (ConstantValue == this)
15906f32e7eSjoerg     return UndefValue::get(getType());
16006f32e7eSjoerg   return ConstantValue;
16106f32e7eSjoerg }
16206f32e7eSjoerg 
16306f32e7eSjoerg /// hasConstantOrUndefValue - Whether the specified PHI node always merges
16406f32e7eSjoerg /// together the same value, assuming that undefs result in the same value as
16506f32e7eSjoerg /// non-undefs.
16606f32e7eSjoerg /// Unlike \ref hasConstantValue, this does not return a value because the
16706f32e7eSjoerg /// unique non-undef incoming value need not dominate the PHI node.
hasConstantOrUndefValue() const16806f32e7eSjoerg bool PHINode::hasConstantOrUndefValue() const {
16906f32e7eSjoerg   Value *ConstantValue = nullptr;
17006f32e7eSjoerg   for (unsigned i = 0, e = getNumIncomingValues(); i != e; ++i) {
17106f32e7eSjoerg     Value *Incoming = getIncomingValue(i);
17206f32e7eSjoerg     if (Incoming != this && !isa<UndefValue>(Incoming)) {
17306f32e7eSjoerg       if (ConstantValue && ConstantValue != Incoming)
17406f32e7eSjoerg         return false;
17506f32e7eSjoerg       ConstantValue = Incoming;
17606f32e7eSjoerg     }
17706f32e7eSjoerg   }
17806f32e7eSjoerg   return true;
17906f32e7eSjoerg }
18006f32e7eSjoerg 
18106f32e7eSjoerg //===----------------------------------------------------------------------===//
18206f32e7eSjoerg //                       LandingPadInst Implementation
18306f32e7eSjoerg //===----------------------------------------------------------------------===//
18406f32e7eSjoerg 
LandingPadInst(Type * RetTy,unsigned NumReservedValues,const Twine & NameStr,Instruction * InsertBefore)18506f32e7eSjoerg LandingPadInst::LandingPadInst(Type *RetTy, unsigned NumReservedValues,
18606f32e7eSjoerg                                const Twine &NameStr, Instruction *InsertBefore)
18706f32e7eSjoerg     : Instruction(RetTy, Instruction::LandingPad, nullptr, 0, InsertBefore) {
18806f32e7eSjoerg   init(NumReservedValues, NameStr);
18906f32e7eSjoerg }
19006f32e7eSjoerg 
LandingPadInst(Type * RetTy,unsigned NumReservedValues,const Twine & NameStr,BasicBlock * InsertAtEnd)19106f32e7eSjoerg LandingPadInst::LandingPadInst(Type *RetTy, unsigned NumReservedValues,
19206f32e7eSjoerg                                const Twine &NameStr, BasicBlock *InsertAtEnd)
19306f32e7eSjoerg     : Instruction(RetTy, Instruction::LandingPad, nullptr, 0, InsertAtEnd) {
19406f32e7eSjoerg   init(NumReservedValues, NameStr);
19506f32e7eSjoerg }
19606f32e7eSjoerg 
LandingPadInst(const LandingPadInst & LP)19706f32e7eSjoerg LandingPadInst::LandingPadInst(const LandingPadInst &LP)
19806f32e7eSjoerg     : Instruction(LP.getType(), Instruction::LandingPad, nullptr,
19906f32e7eSjoerg                   LP.getNumOperands()),
20006f32e7eSjoerg       ReservedSpace(LP.getNumOperands()) {
20106f32e7eSjoerg   allocHungoffUses(LP.getNumOperands());
20206f32e7eSjoerg   Use *OL = getOperandList();
20306f32e7eSjoerg   const Use *InOL = LP.getOperandList();
20406f32e7eSjoerg   for (unsigned I = 0, E = ReservedSpace; I != E; ++I)
20506f32e7eSjoerg     OL[I] = InOL[I];
20606f32e7eSjoerg 
20706f32e7eSjoerg   setCleanup(LP.isCleanup());
20806f32e7eSjoerg }
20906f32e7eSjoerg 
Create(Type * RetTy,unsigned NumReservedClauses,const Twine & NameStr,Instruction * InsertBefore)21006f32e7eSjoerg LandingPadInst *LandingPadInst::Create(Type *RetTy, unsigned NumReservedClauses,
21106f32e7eSjoerg                                        const Twine &NameStr,
21206f32e7eSjoerg                                        Instruction *InsertBefore) {
21306f32e7eSjoerg   return new LandingPadInst(RetTy, NumReservedClauses, NameStr, InsertBefore);
21406f32e7eSjoerg }
21506f32e7eSjoerg 
Create(Type * RetTy,unsigned NumReservedClauses,const Twine & NameStr,BasicBlock * InsertAtEnd)21606f32e7eSjoerg LandingPadInst *LandingPadInst::Create(Type *RetTy, unsigned NumReservedClauses,
21706f32e7eSjoerg                                        const Twine &NameStr,
21806f32e7eSjoerg                                        BasicBlock *InsertAtEnd) {
21906f32e7eSjoerg   return new LandingPadInst(RetTy, NumReservedClauses, NameStr, InsertAtEnd);
22006f32e7eSjoerg }
22106f32e7eSjoerg 
init(unsigned NumReservedValues,const Twine & NameStr)22206f32e7eSjoerg void LandingPadInst::init(unsigned NumReservedValues, const Twine &NameStr) {
22306f32e7eSjoerg   ReservedSpace = NumReservedValues;
22406f32e7eSjoerg   setNumHungOffUseOperands(0);
22506f32e7eSjoerg   allocHungoffUses(ReservedSpace);
22606f32e7eSjoerg   setName(NameStr);
22706f32e7eSjoerg   setCleanup(false);
22806f32e7eSjoerg }
22906f32e7eSjoerg 
23006f32e7eSjoerg /// growOperands - grow operands - This grows the operand list in response to a
23106f32e7eSjoerg /// push_back style of operation. This grows the number of ops by 2 times.
growOperands(unsigned Size)23206f32e7eSjoerg void LandingPadInst::growOperands(unsigned Size) {
23306f32e7eSjoerg   unsigned e = getNumOperands();
23406f32e7eSjoerg   if (ReservedSpace >= e + Size) return;
23506f32e7eSjoerg   ReservedSpace = (std::max(e, 1U) + Size / 2) * 2;
23606f32e7eSjoerg   growHungoffUses(ReservedSpace);
23706f32e7eSjoerg }
23806f32e7eSjoerg 
addClause(Constant * Val)23906f32e7eSjoerg void LandingPadInst::addClause(Constant *Val) {
24006f32e7eSjoerg   unsigned OpNo = getNumOperands();
24106f32e7eSjoerg   growOperands(1);
24206f32e7eSjoerg   assert(OpNo < ReservedSpace && "Growing didn't work!");
24306f32e7eSjoerg   setNumHungOffUseOperands(getNumOperands() + 1);
24406f32e7eSjoerg   getOperandList()[OpNo] = Val;
24506f32e7eSjoerg }
24606f32e7eSjoerg 
24706f32e7eSjoerg //===----------------------------------------------------------------------===//
24806f32e7eSjoerg //                        CallBase Implementation
24906f32e7eSjoerg //===----------------------------------------------------------------------===//
25006f32e7eSjoerg 
Create(CallBase * CB,ArrayRef<OperandBundleDef> Bundles,Instruction * InsertPt)251*da58b97aSjoerg CallBase *CallBase::Create(CallBase *CB, ArrayRef<OperandBundleDef> Bundles,
252*da58b97aSjoerg                            Instruction *InsertPt) {
253*da58b97aSjoerg   switch (CB->getOpcode()) {
254*da58b97aSjoerg   case Instruction::Call:
255*da58b97aSjoerg     return CallInst::Create(cast<CallInst>(CB), Bundles, InsertPt);
256*da58b97aSjoerg   case Instruction::Invoke:
257*da58b97aSjoerg     return InvokeInst::Create(cast<InvokeInst>(CB), Bundles, InsertPt);
258*da58b97aSjoerg   case Instruction::CallBr:
259*da58b97aSjoerg     return CallBrInst::Create(cast<CallBrInst>(CB), Bundles, InsertPt);
260*da58b97aSjoerg   default:
261*da58b97aSjoerg     llvm_unreachable("Unknown CallBase sub-class!");
262*da58b97aSjoerg   }
263*da58b97aSjoerg }
264*da58b97aSjoerg 
Create(CallBase * CI,OperandBundleDef OpB,Instruction * InsertPt)265*da58b97aSjoerg CallBase *CallBase::Create(CallBase *CI, OperandBundleDef OpB,
266*da58b97aSjoerg                            Instruction *InsertPt) {
267*da58b97aSjoerg   SmallVector<OperandBundleDef, 2> OpDefs;
268*da58b97aSjoerg   for (unsigned i = 0, e = CI->getNumOperandBundles(); i < e; ++i) {
269*da58b97aSjoerg     auto ChildOB = CI->getOperandBundleAt(i);
270*da58b97aSjoerg     if (ChildOB.getTagName() != OpB.getTag())
271*da58b97aSjoerg       OpDefs.emplace_back(ChildOB);
272*da58b97aSjoerg   }
273*da58b97aSjoerg   OpDefs.emplace_back(OpB);
274*da58b97aSjoerg   return CallBase::Create(CI, OpDefs, InsertPt);
275*da58b97aSjoerg }
276*da58b97aSjoerg 
277*da58b97aSjoerg 
getCaller()27806f32e7eSjoerg Function *CallBase::getCaller() { return getParent()->getParent(); }
27906f32e7eSjoerg 
getNumSubclassExtraOperandsDynamic() const28006f32e7eSjoerg unsigned CallBase::getNumSubclassExtraOperandsDynamic() const {
28106f32e7eSjoerg   assert(getOpcode() == Instruction::CallBr && "Unexpected opcode!");
28206f32e7eSjoerg   return cast<CallBrInst>(this)->getNumIndirectDests() + 1;
28306f32e7eSjoerg }
28406f32e7eSjoerg 
isIndirectCall() const28506f32e7eSjoerg bool CallBase::isIndirectCall() const {
286*da58b97aSjoerg   const Value *V = getCalledOperand();
28706f32e7eSjoerg   if (isa<Function>(V) || isa<Constant>(V))
28806f32e7eSjoerg     return false;
289*da58b97aSjoerg   return !isInlineAsm();
29006f32e7eSjoerg }
29106f32e7eSjoerg 
29206f32e7eSjoerg /// Tests if this call site must be tail call optimized. Only a CallInst can
29306f32e7eSjoerg /// be tail call optimized.
isMustTailCall() const29406f32e7eSjoerg bool CallBase::isMustTailCall() const {
29506f32e7eSjoerg   if (auto *CI = dyn_cast<CallInst>(this))
29606f32e7eSjoerg     return CI->isMustTailCall();
29706f32e7eSjoerg   return false;
29806f32e7eSjoerg }
29906f32e7eSjoerg 
30006f32e7eSjoerg /// Tests if this call site is marked as a tail call.
isTailCall() const30106f32e7eSjoerg bool CallBase::isTailCall() const {
30206f32e7eSjoerg   if (auto *CI = dyn_cast<CallInst>(this))
30306f32e7eSjoerg     return CI->isTailCall();
30406f32e7eSjoerg   return false;
30506f32e7eSjoerg }
30606f32e7eSjoerg 
getIntrinsicID() const30706f32e7eSjoerg Intrinsic::ID CallBase::getIntrinsicID() const {
30806f32e7eSjoerg   if (auto *F = getCalledFunction())
30906f32e7eSjoerg     return F->getIntrinsicID();
31006f32e7eSjoerg   return Intrinsic::not_intrinsic;
31106f32e7eSjoerg }
31206f32e7eSjoerg 
isReturnNonNull() const31306f32e7eSjoerg bool CallBase::isReturnNonNull() const {
31406f32e7eSjoerg   if (hasRetAttr(Attribute::NonNull))
31506f32e7eSjoerg     return true;
31606f32e7eSjoerg 
31706f32e7eSjoerg   if (getDereferenceableBytes(AttributeList::ReturnIndex) > 0 &&
31806f32e7eSjoerg            !NullPointerIsDefined(getCaller(),
31906f32e7eSjoerg                                  getType()->getPointerAddressSpace()))
32006f32e7eSjoerg     return true;
32106f32e7eSjoerg 
32206f32e7eSjoerg   return false;
32306f32e7eSjoerg }
32406f32e7eSjoerg 
getReturnedArgOperand() const32506f32e7eSjoerg Value *CallBase::getReturnedArgOperand() const {
32606f32e7eSjoerg   unsigned Index;
32706f32e7eSjoerg 
32806f32e7eSjoerg   if (Attrs.hasAttrSomewhere(Attribute::Returned, &Index) && Index)
32906f32e7eSjoerg     return getArgOperand(Index - AttributeList::FirstArgIndex);
33006f32e7eSjoerg   if (const Function *F = getCalledFunction())
33106f32e7eSjoerg     if (F->getAttributes().hasAttrSomewhere(Attribute::Returned, &Index) &&
33206f32e7eSjoerg         Index)
33306f32e7eSjoerg       return getArgOperand(Index - AttributeList::FirstArgIndex);
33406f32e7eSjoerg 
33506f32e7eSjoerg   return nullptr;
33606f32e7eSjoerg }
33706f32e7eSjoerg 
33806f32e7eSjoerg /// Determine whether the argument or parameter has the given attribute.
paramHasAttr(unsigned ArgNo,Attribute::AttrKind Kind) const33906f32e7eSjoerg bool CallBase::paramHasAttr(unsigned ArgNo, Attribute::AttrKind Kind) const {
34006f32e7eSjoerg   assert(ArgNo < getNumArgOperands() && "Param index out of bounds!");
34106f32e7eSjoerg 
34206f32e7eSjoerg   if (Attrs.hasParamAttribute(ArgNo, Kind))
34306f32e7eSjoerg     return true;
34406f32e7eSjoerg   if (const Function *F = getCalledFunction())
34506f32e7eSjoerg     return F->getAttributes().hasParamAttribute(ArgNo, Kind);
34606f32e7eSjoerg   return false;
34706f32e7eSjoerg }
34806f32e7eSjoerg 
hasFnAttrOnCalledFunction(Attribute::AttrKind Kind) const34906f32e7eSjoerg bool CallBase::hasFnAttrOnCalledFunction(Attribute::AttrKind Kind) const {
35006f32e7eSjoerg   if (const Function *F = getCalledFunction())
351*da58b97aSjoerg     return F->getAttributes().hasFnAttribute(Kind);
35206f32e7eSjoerg   return false;
35306f32e7eSjoerg }
35406f32e7eSjoerg 
hasFnAttrOnCalledFunction(StringRef Kind) const35506f32e7eSjoerg bool CallBase::hasFnAttrOnCalledFunction(StringRef Kind) const {
35606f32e7eSjoerg   if (const Function *F = getCalledFunction())
357*da58b97aSjoerg     return F->getAttributes().hasFnAttribute(Kind);
35806f32e7eSjoerg   return false;
35906f32e7eSjoerg }
36006f32e7eSjoerg 
getOperandBundlesAsDefs(SmallVectorImpl<OperandBundleDef> & Defs) const361*da58b97aSjoerg void CallBase::getOperandBundlesAsDefs(
362*da58b97aSjoerg     SmallVectorImpl<OperandBundleDef> &Defs) const {
363*da58b97aSjoerg   for (unsigned i = 0, e = getNumOperandBundles(); i != e; ++i)
364*da58b97aSjoerg     Defs.emplace_back(getOperandBundleAt(i));
365*da58b97aSjoerg }
366*da58b97aSjoerg 
36706f32e7eSjoerg CallBase::op_iterator
populateBundleOperandInfos(ArrayRef<OperandBundleDef> Bundles,const unsigned BeginIndex)36806f32e7eSjoerg CallBase::populateBundleOperandInfos(ArrayRef<OperandBundleDef> Bundles,
36906f32e7eSjoerg                                      const unsigned BeginIndex) {
37006f32e7eSjoerg   auto It = op_begin() + BeginIndex;
37106f32e7eSjoerg   for (auto &B : Bundles)
37206f32e7eSjoerg     It = std::copy(B.input_begin(), B.input_end(), It);
37306f32e7eSjoerg 
37406f32e7eSjoerg   auto *ContextImpl = getContext().pImpl;
37506f32e7eSjoerg   auto BI = Bundles.begin();
37606f32e7eSjoerg   unsigned CurrentIndex = BeginIndex;
37706f32e7eSjoerg 
37806f32e7eSjoerg   for (auto &BOI : bundle_op_infos()) {
37906f32e7eSjoerg     assert(BI != Bundles.end() && "Incorrect allocation?");
38006f32e7eSjoerg 
38106f32e7eSjoerg     BOI.Tag = ContextImpl->getOrInsertBundleTag(BI->getTag());
38206f32e7eSjoerg     BOI.Begin = CurrentIndex;
38306f32e7eSjoerg     BOI.End = CurrentIndex + BI->input_size();
38406f32e7eSjoerg     CurrentIndex = BOI.End;
38506f32e7eSjoerg     BI++;
38606f32e7eSjoerg   }
38706f32e7eSjoerg 
38806f32e7eSjoerg   assert(BI == Bundles.end() && "Incorrect allocation?");
38906f32e7eSjoerg 
39006f32e7eSjoerg   return It;
39106f32e7eSjoerg }
39206f32e7eSjoerg 
getBundleOpInfoForOperand(unsigned OpIdx)393*da58b97aSjoerg CallBase::BundleOpInfo &CallBase::getBundleOpInfoForOperand(unsigned OpIdx) {
394*da58b97aSjoerg   /// When there isn't many bundles, we do a simple linear search.
395*da58b97aSjoerg   /// Else fallback to a binary-search that use the fact that bundles usually
396*da58b97aSjoerg   /// have similar number of argument to get faster convergence.
397*da58b97aSjoerg   if (bundle_op_info_end() - bundle_op_info_begin() < 8) {
398*da58b97aSjoerg     for (auto &BOI : bundle_op_infos())
399*da58b97aSjoerg       if (BOI.Begin <= OpIdx && OpIdx < BOI.End)
400*da58b97aSjoerg         return BOI;
401*da58b97aSjoerg 
402*da58b97aSjoerg     llvm_unreachable("Did not find operand bundle for operand!");
403*da58b97aSjoerg   }
404*da58b97aSjoerg 
405*da58b97aSjoerg   assert(OpIdx >= arg_size() && "the Idx is not in the operand bundles");
406*da58b97aSjoerg   assert(bundle_op_info_end() - bundle_op_info_begin() > 0 &&
407*da58b97aSjoerg          OpIdx < std::prev(bundle_op_info_end())->End &&
408*da58b97aSjoerg          "The Idx isn't in the operand bundle");
409*da58b97aSjoerg 
410*da58b97aSjoerg   /// We need a decimal number below and to prevent using floating point numbers
411*da58b97aSjoerg   /// we use an intergal value multiplied by this constant.
412*da58b97aSjoerg   constexpr unsigned NumberScaling = 1024;
413*da58b97aSjoerg 
414*da58b97aSjoerg   bundle_op_iterator Begin = bundle_op_info_begin();
415*da58b97aSjoerg   bundle_op_iterator End = bundle_op_info_end();
416*da58b97aSjoerg   bundle_op_iterator Current = Begin;
417*da58b97aSjoerg 
418*da58b97aSjoerg   while (Begin != End) {
419*da58b97aSjoerg     unsigned ScaledOperandPerBundle =
420*da58b97aSjoerg         NumberScaling * (std::prev(End)->End - Begin->Begin) / (End - Begin);
421*da58b97aSjoerg     Current = Begin + (((OpIdx - Begin->Begin) * NumberScaling) /
422*da58b97aSjoerg                        ScaledOperandPerBundle);
423*da58b97aSjoerg     if (Current >= End)
424*da58b97aSjoerg       Current = std::prev(End);
425*da58b97aSjoerg     assert(Current < End && Current >= Begin &&
426*da58b97aSjoerg            "the operand bundle doesn't cover every value in the range");
427*da58b97aSjoerg     if (OpIdx >= Current->Begin && OpIdx < Current->End)
428*da58b97aSjoerg       break;
429*da58b97aSjoerg     if (OpIdx >= Current->End)
430*da58b97aSjoerg       Begin = Current + 1;
431*da58b97aSjoerg     else
432*da58b97aSjoerg       End = Current;
433*da58b97aSjoerg   }
434*da58b97aSjoerg 
435*da58b97aSjoerg   assert(OpIdx >= Current->Begin && OpIdx < Current->End &&
436*da58b97aSjoerg          "the operand bundle doesn't cover every value in the range");
437*da58b97aSjoerg   return *Current;
438*da58b97aSjoerg }
439*da58b97aSjoerg 
addOperandBundle(CallBase * CB,uint32_t ID,OperandBundleDef OB,Instruction * InsertPt)440*da58b97aSjoerg CallBase *CallBase::addOperandBundle(CallBase *CB, uint32_t ID,
441*da58b97aSjoerg                                      OperandBundleDef OB,
442*da58b97aSjoerg                                      Instruction *InsertPt) {
443*da58b97aSjoerg   if (CB->getOperandBundle(ID))
444*da58b97aSjoerg     return CB;
445*da58b97aSjoerg 
446*da58b97aSjoerg   SmallVector<OperandBundleDef, 1> Bundles;
447*da58b97aSjoerg   CB->getOperandBundlesAsDefs(Bundles);
448*da58b97aSjoerg   Bundles.push_back(OB);
449*da58b97aSjoerg   return Create(CB, Bundles, InsertPt);
450*da58b97aSjoerg }
451*da58b97aSjoerg 
removeOperandBundle(CallBase * CB,uint32_t ID,Instruction * InsertPt)452*da58b97aSjoerg CallBase *CallBase::removeOperandBundle(CallBase *CB, uint32_t ID,
453*da58b97aSjoerg                                         Instruction *InsertPt) {
454*da58b97aSjoerg   SmallVector<OperandBundleDef, 1> Bundles;
455*da58b97aSjoerg   bool CreateNew = false;
456*da58b97aSjoerg 
457*da58b97aSjoerg   for (unsigned I = 0, E = CB->getNumOperandBundles(); I != E; ++I) {
458*da58b97aSjoerg     auto Bundle = CB->getOperandBundleAt(I);
459*da58b97aSjoerg     if (Bundle.getTagID() == ID) {
460*da58b97aSjoerg       CreateNew = true;
461*da58b97aSjoerg       continue;
462*da58b97aSjoerg     }
463*da58b97aSjoerg     Bundles.emplace_back(Bundle);
464*da58b97aSjoerg   }
465*da58b97aSjoerg 
466*da58b97aSjoerg   return CreateNew ? Create(CB, Bundles, InsertPt) : CB;
467*da58b97aSjoerg }
468*da58b97aSjoerg 
hasReadingOperandBundles() const469*da58b97aSjoerg bool CallBase::hasReadingOperandBundles() const {
470*da58b97aSjoerg   // Implementation note: this is a conservative implementation of operand
471*da58b97aSjoerg   // bundle semantics, where *any* non-assume operand bundle forces a callsite
472*da58b97aSjoerg   // to be at least readonly.
473*da58b97aSjoerg   return hasOperandBundles() && getIntrinsicID() != Intrinsic::assume;
474*da58b97aSjoerg }
475*da58b97aSjoerg 
47606f32e7eSjoerg //===----------------------------------------------------------------------===//
47706f32e7eSjoerg //                        CallInst Implementation
47806f32e7eSjoerg //===----------------------------------------------------------------------===//
47906f32e7eSjoerg 
init(FunctionType * FTy,Value * Func,ArrayRef<Value * > Args,ArrayRef<OperandBundleDef> Bundles,const Twine & NameStr)48006f32e7eSjoerg void CallInst::init(FunctionType *FTy, Value *Func, ArrayRef<Value *> Args,
48106f32e7eSjoerg                     ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr) {
48206f32e7eSjoerg   this->FTy = FTy;
48306f32e7eSjoerg   assert(getNumOperands() == Args.size() + CountBundleInputs(Bundles) + 1 &&
48406f32e7eSjoerg          "NumOperands not set up?");
48506f32e7eSjoerg   setCalledOperand(Func);
48606f32e7eSjoerg 
48706f32e7eSjoerg #ifndef NDEBUG
48806f32e7eSjoerg   assert((Args.size() == FTy->getNumParams() ||
48906f32e7eSjoerg           (FTy->isVarArg() && Args.size() > FTy->getNumParams())) &&
49006f32e7eSjoerg          "Calling a function with bad signature!");
49106f32e7eSjoerg 
49206f32e7eSjoerg   for (unsigned i = 0; i != Args.size(); ++i)
49306f32e7eSjoerg     assert((i >= FTy->getNumParams() ||
49406f32e7eSjoerg             FTy->getParamType(i) == Args[i]->getType()) &&
49506f32e7eSjoerg            "Calling a function with a bad signature!");
49606f32e7eSjoerg #endif
49706f32e7eSjoerg 
49806f32e7eSjoerg   llvm::copy(Args, op_begin());
49906f32e7eSjoerg 
50006f32e7eSjoerg   auto It = populateBundleOperandInfos(Bundles, Args.size());
50106f32e7eSjoerg   (void)It;
50206f32e7eSjoerg   assert(It + 1 == op_end() && "Should add up!");
50306f32e7eSjoerg 
50406f32e7eSjoerg   setName(NameStr);
50506f32e7eSjoerg }
50606f32e7eSjoerg 
init(FunctionType * FTy,Value * Func,const Twine & NameStr)50706f32e7eSjoerg void CallInst::init(FunctionType *FTy, Value *Func, const Twine &NameStr) {
50806f32e7eSjoerg   this->FTy = FTy;
50906f32e7eSjoerg   assert(getNumOperands() == 1 && "NumOperands not set up?");
51006f32e7eSjoerg   setCalledOperand(Func);
51106f32e7eSjoerg 
51206f32e7eSjoerg   assert(FTy->getNumParams() == 0 && "Calling a function with bad signature");
51306f32e7eSjoerg 
51406f32e7eSjoerg   setName(NameStr);
51506f32e7eSjoerg }
51606f32e7eSjoerg 
CallInst(FunctionType * Ty,Value * Func,const Twine & Name,Instruction * InsertBefore)51706f32e7eSjoerg CallInst::CallInst(FunctionType *Ty, Value *Func, const Twine &Name,
51806f32e7eSjoerg                    Instruction *InsertBefore)
51906f32e7eSjoerg     : CallBase(Ty->getReturnType(), Instruction::Call,
52006f32e7eSjoerg                OperandTraits<CallBase>::op_end(this) - 1, 1, InsertBefore) {
52106f32e7eSjoerg   init(Ty, Func, Name);
52206f32e7eSjoerg }
52306f32e7eSjoerg 
CallInst(FunctionType * Ty,Value * Func,const Twine & Name,BasicBlock * InsertAtEnd)52406f32e7eSjoerg CallInst::CallInst(FunctionType *Ty, Value *Func, const Twine &Name,
52506f32e7eSjoerg                    BasicBlock *InsertAtEnd)
52606f32e7eSjoerg     : CallBase(Ty->getReturnType(), Instruction::Call,
52706f32e7eSjoerg                OperandTraits<CallBase>::op_end(this) - 1, 1, InsertAtEnd) {
52806f32e7eSjoerg   init(Ty, Func, Name);
52906f32e7eSjoerg }
53006f32e7eSjoerg 
CallInst(const CallInst & CI)53106f32e7eSjoerg CallInst::CallInst(const CallInst &CI)
53206f32e7eSjoerg     : CallBase(CI.Attrs, CI.FTy, CI.getType(), Instruction::Call,
53306f32e7eSjoerg                OperandTraits<CallBase>::op_end(this) - CI.getNumOperands(),
53406f32e7eSjoerg                CI.getNumOperands()) {
53506f32e7eSjoerg   setTailCallKind(CI.getTailCallKind());
53606f32e7eSjoerg   setCallingConv(CI.getCallingConv());
53706f32e7eSjoerg 
53806f32e7eSjoerg   std::copy(CI.op_begin(), CI.op_end(), op_begin());
53906f32e7eSjoerg   std::copy(CI.bundle_op_info_begin(), CI.bundle_op_info_end(),
54006f32e7eSjoerg             bundle_op_info_begin());
54106f32e7eSjoerg   SubclassOptionalData = CI.SubclassOptionalData;
54206f32e7eSjoerg }
54306f32e7eSjoerg 
Create(CallInst * CI,ArrayRef<OperandBundleDef> OpB,Instruction * InsertPt)54406f32e7eSjoerg CallInst *CallInst::Create(CallInst *CI, ArrayRef<OperandBundleDef> OpB,
54506f32e7eSjoerg                            Instruction *InsertPt) {
54606f32e7eSjoerg   std::vector<Value *> Args(CI->arg_begin(), CI->arg_end());
54706f32e7eSjoerg 
548*da58b97aSjoerg   auto *NewCI = CallInst::Create(CI->getFunctionType(), CI->getCalledOperand(),
54906f32e7eSjoerg                                  Args, OpB, CI->getName(), InsertPt);
55006f32e7eSjoerg   NewCI->setTailCallKind(CI->getTailCallKind());
55106f32e7eSjoerg   NewCI->setCallingConv(CI->getCallingConv());
55206f32e7eSjoerg   NewCI->SubclassOptionalData = CI->SubclassOptionalData;
55306f32e7eSjoerg   NewCI->setAttributes(CI->getAttributes());
55406f32e7eSjoerg   NewCI->setDebugLoc(CI->getDebugLoc());
55506f32e7eSjoerg   return NewCI;
55606f32e7eSjoerg }
55706f32e7eSjoerg 
55806f32e7eSjoerg // Update profile weight for call instruction by scaling it using the ratio
55906f32e7eSjoerg // of S/T. The meaning of "branch_weights" meta data for call instruction is
56006f32e7eSjoerg // transfered to represent call count.
updateProfWeight(uint64_t S,uint64_t T)56106f32e7eSjoerg void CallInst::updateProfWeight(uint64_t S, uint64_t T) {
56206f32e7eSjoerg   auto *ProfileData = getMetadata(LLVMContext::MD_prof);
56306f32e7eSjoerg   if (ProfileData == nullptr)
56406f32e7eSjoerg     return;
56506f32e7eSjoerg 
56606f32e7eSjoerg   auto *ProfDataName = dyn_cast<MDString>(ProfileData->getOperand(0));
56706f32e7eSjoerg   if (!ProfDataName || (!ProfDataName->getString().equals("branch_weights") &&
56806f32e7eSjoerg                         !ProfDataName->getString().equals("VP")))
56906f32e7eSjoerg     return;
57006f32e7eSjoerg 
57106f32e7eSjoerg   if (T == 0) {
57206f32e7eSjoerg     LLVM_DEBUG(dbgs() << "Attempting to update profile weights will result in "
57306f32e7eSjoerg                          "div by 0. Ignoring. Likely the function "
57406f32e7eSjoerg                       << getParent()->getParent()->getName()
57506f32e7eSjoerg                       << " has 0 entry count, and contains call instructions "
57606f32e7eSjoerg                          "with non-zero prof info.");
57706f32e7eSjoerg     return;
57806f32e7eSjoerg   }
57906f32e7eSjoerg 
58006f32e7eSjoerg   MDBuilder MDB(getContext());
58106f32e7eSjoerg   SmallVector<Metadata *, 3> Vals;
58206f32e7eSjoerg   Vals.push_back(ProfileData->getOperand(0));
58306f32e7eSjoerg   APInt APS(128, S), APT(128, T);
58406f32e7eSjoerg   if (ProfDataName->getString().equals("branch_weights") &&
58506f32e7eSjoerg       ProfileData->getNumOperands() > 0) {
58606f32e7eSjoerg     // Using APInt::div may be expensive, but most cases should fit 64 bits.
58706f32e7eSjoerg     APInt Val(128, mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(1))
58806f32e7eSjoerg                        ->getValue()
58906f32e7eSjoerg                        .getZExtValue());
59006f32e7eSjoerg     Val *= APS;
591*da58b97aSjoerg     Vals.push_back(MDB.createConstant(
592*da58b97aSjoerg         ConstantInt::get(Type::getInt32Ty(getContext()),
593*da58b97aSjoerg                          Val.udiv(APT).getLimitedValue(UINT32_MAX))));
59406f32e7eSjoerg   } else if (ProfDataName->getString().equals("VP"))
59506f32e7eSjoerg     for (unsigned i = 1; i < ProfileData->getNumOperands(); i += 2) {
59606f32e7eSjoerg       // The first value is the key of the value profile, which will not change.
59706f32e7eSjoerg       Vals.push_back(ProfileData->getOperand(i));
598*da58b97aSjoerg       uint64_t Count =
59906f32e7eSjoerg           mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(i + 1))
60006f32e7eSjoerg               ->getValue()
601*da58b97aSjoerg               .getZExtValue();
602*da58b97aSjoerg       // Don't scale the magic number.
603*da58b97aSjoerg       if (Count == NOMORE_ICP_MAGICNUM) {
604*da58b97aSjoerg         Vals.push_back(ProfileData->getOperand(i + 1));
605*da58b97aSjoerg         continue;
606*da58b97aSjoerg       }
607*da58b97aSjoerg       // Using APInt::div may be expensive, but most cases should fit 64 bits.
608*da58b97aSjoerg       APInt Val(128, Count);
60906f32e7eSjoerg       Val *= APS;
61006f32e7eSjoerg       Vals.push_back(MDB.createConstant(
61106f32e7eSjoerg           ConstantInt::get(Type::getInt64Ty(getContext()),
61206f32e7eSjoerg                            Val.udiv(APT).getLimitedValue())));
61306f32e7eSjoerg     }
61406f32e7eSjoerg   setMetadata(LLVMContext::MD_prof, MDNode::get(getContext(), Vals));
61506f32e7eSjoerg }
61606f32e7eSjoerg 
61706f32e7eSjoerg /// IsConstantOne - Return true only if val is constant int 1
IsConstantOne(Value * val)61806f32e7eSjoerg static bool IsConstantOne(Value *val) {
61906f32e7eSjoerg   assert(val && "IsConstantOne does not work with nullptr val");
62006f32e7eSjoerg   const ConstantInt *CVal = dyn_cast<ConstantInt>(val);
62106f32e7eSjoerg   return CVal && CVal->isOne();
62206f32e7eSjoerg }
62306f32e7eSjoerg 
createMalloc(Instruction * InsertBefore,BasicBlock * InsertAtEnd,Type * IntPtrTy,Type * AllocTy,Value * AllocSize,Value * ArraySize,ArrayRef<OperandBundleDef> OpB,Function * MallocF,const Twine & Name)62406f32e7eSjoerg static Instruction *createMalloc(Instruction *InsertBefore,
62506f32e7eSjoerg                                  BasicBlock *InsertAtEnd, Type *IntPtrTy,
62606f32e7eSjoerg                                  Type *AllocTy, Value *AllocSize,
62706f32e7eSjoerg                                  Value *ArraySize,
62806f32e7eSjoerg                                  ArrayRef<OperandBundleDef> OpB,
62906f32e7eSjoerg                                  Function *MallocF, const Twine &Name) {
63006f32e7eSjoerg   assert(((!InsertBefore && InsertAtEnd) || (InsertBefore && !InsertAtEnd)) &&
63106f32e7eSjoerg          "createMalloc needs either InsertBefore or InsertAtEnd");
63206f32e7eSjoerg 
63306f32e7eSjoerg   // malloc(type) becomes:
63406f32e7eSjoerg   //       bitcast (i8* malloc(typeSize)) to type*
63506f32e7eSjoerg   // malloc(type, arraySize) becomes:
63606f32e7eSjoerg   //       bitcast (i8* malloc(typeSize*arraySize)) to type*
63706f32e7eSjoerg   if (!ArraySize)
63806f32e7eSjoerg     ArraySize = ConstantInt::get(IntPtrTy, 1);
63906f32e7eSjoerg   else if (ArraySize->getType() != IntPtrTy) {
64006f32e7eSjoerg     if (InsertBefore)
64106f32e7eSjoerg       ArraySize = CastInst::CreateIntegerCast(ArraySize, IntPtrTy, false,
64206f32e7eSjoerg                                               "", InsertBefore);
64306f32e7eSjoerg     else
64406f32e7eSjoerg       ArraySize = CastInst::CreateIntegerCast(ArraySize, IntPtrTy, false,
64506f32e7eSjoerg                                               "", InsertAtEnd);
64606f32e7eSjoerg   }
64706f32e7eSjoerg 
64806f32e7eSjoerg   if (!IsConstantOne(ArraySize)) {
64906f32e7eSjoerg     if (IsConstantOne(AllocSize)) {
65006f32e7eSjoerg       AllocSize = ArraySize;         // Operand * 1 = Operand
65106f32e7eSjoerg     } else if (Constant *CO = dyn_cast<Constant>(ArraySize)) {
65206f32e7eSjoerg       Constant *Scale = ConstantExpr::getIntegerCast(CO, IntPtrTy,
65306f32e7eSjoerg                                                      false /*ZExt*/);
65406f32e7eSjoerg       // Malloc arg is constant product of type size and array size
65506f32e7eSjoerg       AllocSize = ConstantExpr::getMul(Scale, cast<Constant>(AllocSize));
65606f32e7eSjoerg     } else {
65706f32e7eSjoerg       // Multiply type size by the array size...
65806f32e7eSjoerg       if (InsertBefore)
65906f32e7eSjoerg         AllocSize = BinaryOperator::CreateMul(ArraySize, AllocSize,
66006f32e7eSjoerg                                               "mallocsize", InsertBefore);
66106f32e7eSjoerg       else
66206f32e7eSjoerg         AllocSize = BinaryOperator::CreateMul(ArraySize, AllocSize,
66306f32e7eSjoerg                                               "mallocsize", InsertAtEnd);
66406f32e7eSjoerg     }
66506f32e7eSjoerg   }
66606f32e7eSjoerg 
66706f32e7eSjoerg   assert(AllocSize->getType() == IntPtrTy && "malloc arg is wrong size");
66806f32e7eSjoerg   // Create the call to Malloc.
66906f32e7eSjoerg   BasicBlock *BB = InsertBefore ? InsertBefore->getParent() : InsertAtEnd;
67006f32e7eSjoerg   Module *M = BB->getParent()->getParent();
67106f32e7eSjoerg   Type *BPTy = Type::getInt8PtrTy(BB->getContext());
67206f32e7eSjoerg   FunctionCallee MallocFunc = MallocF;
67306f32e7eSjoerg   if (!MallocFunc)
67406f32e7eSjoerg     // prototype malloc as "void *malloc(size_t)"
67506f32e7eSjoerg     MallocFunc = M->getOrInsertFunction("malloc", BPTy, IntPtrTy);
67606f32e7eSjoerg   PointerType *AllocPtrType = PointerType::getUnqual(AllocTy);
67706f32e7eSjoerg   CallInst *MCall = nullptr;
67806f32e7eSjoerg   Instruction *Result = nullptr;
67906f32e7eSjoerg   if (InsertBefore) {
68006f32e7eSjoerg     MCall = CallInst::Create(MallocFunc, AllocSize, OpB, "malloccall",
68106f32e7eSjoerg                              InsertBefore);
68206f32e7eSjoerg     Result = MCall;
68306f32e7eSjoerg     if (Result->getType() != AllocPtrType)
68406f32e7eSjoerg       // Create a cast instruction to convert to the right type...
68506f32e7eSjoerg       Result = new BitCastInst(MCall, AllocPtrType, Name, InsertBefore);
68606f32e7eSjoerg   } else {
68706f32e7eSjoerg     MCall = CallInst::Create(MallocFunc, AllocSize, OpB, "malloccall");
68806f32e7eSjoerg     Result = MCall;
68906f32e7eSjoerg     if (Result->getType() != AllocPtrType) {
69006f32e7eSjoerg       InsertAtEnd->getInstList().push_back(MCall);
69106f32e7eSjoerg       // Create a cast instruction to convert to the right type...
69206f32e7eSjoerg       Result = new BitCastInst(MCall, AllocPtrType, Name);
69306f32e7eSjoerg     }
69406f32e7eSjoerg   }
69506f32e7eSjoerg   MCall->setTailCall();
69606f32e7eSjoerg   if (Function *F = dyn_cast<Function>(MallocFunc.getCallee())) {
69706f32e7eSjoerg     MCall->setCallingConv(F->getCallingConv());
69806f32e7eSjoerg     if (!F->returnDoesNotAlias())
69906f32e7eSjoerg       F->setReturnDoesNotAlias();
70006f32e7eSjoerg   }
70106f32e7eSjoerg   assert(!MCall->getType()->isVoidTy() && "Malloc has void return type");
70206f32e7eSjoerg 
70306f32e7eSjoerg   return Result;
70406f32e7eSjoerg }
70506f32e7eSjoerg 
70606f32e7eSjoerg /// CreateMalloc - Generate the IR for a call to malloc:
70706f32e7eSjoerg /// 1. Compute the malloc call's argument as the specified type's size,
70806f32e7eSjoerg ///    possibly multiplied by the array size if the array size is not
70906f32e7eSjoerg ///    constant 1.
71006f32e7eSjoerg /// 2. Call malloc with that argument.
71106f32e7eSjoerg /// 3. Bitcast the result of the malloc call to the specified type.
CreateMalloc(Instruction * InsertBefore,Type * IntPtrTy,Type * AllocTy,Value * AllocSize,Value * ArraySize,Function * MallocF,const Twine & Name)71206f32e7eSjoerg Instruction *CallInst::CreateMalloc(Instruction *InsertBefore,
71306f32e7eSjoerg                                     Type *IntPtrTy, Type *AllocTy,
71406f32e7eSjoerg                                     Value *AllocSize, Value *ArraySize,
71506f32e7eSjoerg                                     Function *MallocF,
71606f32e7eSjoerg                                     const Twine &Name) {
71706f32e7eSjoerg   return createMalloc(InsertBefore, nullptr, IntPtrTy, AllocTy, AllocSize,
71806f32e7eSjoerg                       ArraySize, None, MallocF, Name);
71906f32e7eSjoerg }
CreateMalloc(Instruction * InsertBefore,Type * IntPtrTy,Type * AllocTy,Value * AllocSize,Value * ArraySize,ArrayRef<OperandBundleDef> OpB,Function * MallocF,const Twine & Name)72006f32e7eSjoerg Instruction *CallInst::CreateMalloc(Instruction *InsertBefore,
72106f32e7eSjoerg                                     Type *IntPtrTy, Type *AllocTy,
72206f32e7eSjoerg                                     Value *AllocSize, Value *ArraySize,
72306f32e7eSjoerg                                     ArrayRef<OperandBundleDef> OpB,
72406f32e7eSjoerg                                     Function *MallocF,
72506f32e7eSjoerg                                     const Twine &Name) {
72606f32e7eSjoerg   return createMalloc(InsertBefore, nullptr, IntPtrTy, AllocTy, AllocSize,
72706f32e7eSjoerg                       ArraySize, OpB, MallocF, Name);
72806f32e7eSjoerg }
72906f32e7eSjoerg 
73006f32e7eSjoerg /// CreateMalloc - Generate the IR for a call to malloc:
73106f32e7eSjoerg /// 1. Compute the malloc call's argument as the specified type's size,
73206f32e7eSjoerg ///    possibly multiplied by the array size if the array size is not
73306f32e7eSjoerg ///    constant 1.
73406f32e7eSjoerg /// 2. Call malloc with that argument.
73506f32e7eSjoerg /// 3. Bitcast the result of the malloc call to the specified type.
73606f32e7eSjoerg /// Note: This function does not add the bitcast to the basic block, that is the
73706f32e7eSjoerg /// responsibility of the caller.
CreateMalloc(BasicBlock * InsertAtEnd,Type * IntPtrTy,Type * AllocTy,Value * AllocSize,Value * ArraySize,Function * MallocF,const Twine & Name)73806f32e7eSjoerg Instruction *CallInst::CreateMalloc(BasicBlock *InsertAtEnd,
73906f32e7eSjoerg                                     Type *IntPtrTy, Type *AllocTy,
74006f32e7eSjoerg                                     Value *AllocSize, Value *ArraySize,
74106f32e7eSjoerg                                     Function *MallocF, const Twine &Name) {
74206f32e7eSjoerg   return createMalloc(nullptr, InsertAtEnd, IntPtrTy, AllocTy, AllocSize,
74306f32e7eSjoerg                       ArraySize, None, MallocF, Name);
74406f32e7eSjoerg }
CreateMalloc(BasicBlock * InsertAtEnd,Type * IntPtrTy,Type * AllocTy,Value * AllocSize,Value * ArraySize,ArrayRef<OperandBundleDef> OpB,Function * MallocF,const Twine & Name)74506f32e7eSjoerg Instruction *CallInst::CreateMalloc(BasicBlock *InsertAtEnd,
74606f32e7eSjoerg                                     Type *IntPtrTy, Type *AllocTy,
74706f32e7eSjoerg                                     Value *AllocSize, Value *ArraySize,
74806f32e7eSjoerg                                     ArrayRef<OperandBundleDef> OpB,
74906f32e7eSjoerg                                     Function *MallocF, const Twine &Name) {
75006f32e7eSjoerg   return createMalloc(nullptr, InsertAtEnd, IntPtrTy, AllocTy, AllocSize,
75106f32e7eSjoerg                       ArraySize, OpB, MallocF, Name);
75206f32e7eSjoerg }
75306f32e7eSjoerg 
createFree(Value * Source,ArrayRef<OperandBundleDef> Bundles,Instruction * InsertBefore,BasicBlock * InsertAtEnd)75406f32e7eSjoerg static Instruction *createFree(Value *Source,
75506f32e7eSjoerg                                ArrayRef<OperandBundleDef> Bundles,
75606f32e7eSjoerg                                Instruction *InsertBefore,
75706f32e7eSjoerg                                BasicBlock *InsertAtEnd) {
75806f32e7eSjoerg   assert(((!InsertBefore && InsertAtEnd) || (InsertBefore && !InsertAtEnd)) &&
75906f32e7eSjoerg          "createFree needs either InsertBefore or InsertAtEnd");
76006f32e7eSjoerg   assert(Source->getType()->isPointerTy() &&
76106f32e7eSjoerg          "Can not free something of nonpointer type!");
76206f32e7eSjoerg 
76306f32e7eSjoerg   BasicBlock *BB = InsertBefore ? InsertBefore->getParent() : InsertAtEnd;
76406f32e7eSjoerg   Module *M = BB->getParent()->getParent();
76506f32e7eSjoerg 
76606f32e7eSjoerg   Type *VoidTy = Type::getVoidTy(M->getContext());
76706f32e7eSjoerg   Type *IntPtrTy = Type::getInt8PtrTy(M->getContext());
76806f32e7eSjoerg   // prototype free as "void free(void*)"
76906f32e7eSjoerg   FunctionCallee FreeFunc = M->getOrInsertFunction("free", VoidTy, IntPtrTy);
77006f32e7eSjoerg   CallInst *Result = nullptr;
77106f32e7eSjoerg   Value *PtrCast = Source;
77206f32e7eSjoerg   if (InsertBefore) {
77306f32e7eSjoerg     if (Source->getType() != IntPtrTy)
77406f32e7eSjoerg       PtrCast = new BitCastInst(Source, IntPtrTy, "", InsertBefore);
77506f32e7eSjoerg     Result = CallInst::Create(FreeFunc, PtrCast, Bundles, "", InsertBefore);
77606f32e7eSjoerg   } else {
77706f32e7eSjoerg     if (Source->getType() != IntPtrTy)
77806f32e7eSjoerg       PtrCast = new BitCastInst(Source, IntPtrTy, "", InsertAtEnd);
77906f32e7eSjoerg     Result = CallInst::Create(FreeFunc, PtrCast, Bundles, "");
78006f32e7eSjoerg   }
78106f32e7eSjoerg   Result->setTailCall();
78206f32e7eSjoerg   if (Function *F = dyn_cast<Function>(FreeFunc.getCallee()))
78306f32e7eSjoerg     Result->setCallingConv(F->getCallingConv());
78406f32e7eSjoerg 
78506f32e7eSjoerg   return Result;
78606f32e7eSjoerg }
78706f32e7eSjoerg 
78806f32e7eSjoerg /// CreateFree - Generate the IR for a call to the builtin free function.
CreateFree(Value * Source,Instruction * InsertBefore)78906f32e7eSjoerg Instruction *CallInst::CreateFree(Value *Source, Instruction *InsertBefore) {
79006f32e7eSjoerg   return createFree(Source, None, InsertBefore, nullptr);
79106f32e7eSjoerg }
CreateFree(Value * Source,ArrayRef<OperandBundleDef> Bundles,Instruction * InsertBefore)79206f32e7eSjoerg Instruction *CallInst::CreateFree(Value *Source,
79306f32e7eSjoerg                                   ArrayRef<OperandBundleDef> Bundles,
79406f32e7eSjoerg                                   Instruction *InsertBefore) {
79506f32e7eSjoerg   return createFree(Source, Bundles, InsertBefore, nullptr);
79606f32e7eSjoerg }
79706f32e7eSjoerg 
79806f32e7eSjoerg /// CreateFree - Generate the IR for a call to the builtin free function.
79906f32e7eSjoerg /// Note: This function does not add the call to the basic block, that is the
80006f32e7eSjoerg /// responsibility of the caller.
CreateFree(Value * Source,BasicBlock * InsertAtEnd)80106f32e7eSjoerg Instruction *CallInst::CreateFree(Value *Source, BasicBlock *InsertAtEnd) {
80206f32e7eSjoerg   Instruction *FreeCall = createFree(Source, None, nullptr, InsertAtEnd);
80306f32e7eSjoerg   assert(FreeCall && "CreateFree did not create a CallInst");
80406f32e7eSjoerg   return FreeCall;
80506f32e7eSjoerg }
CreateFree(Value * Source,ArrayRef<OperandBundleDef> Bundles,BasicBlock * InsertAtEnd)80606f32e7eSjoerg Instruction *CallInst::CreateFree(Value *Source,
80706f32e7eSjoerg                                   ArrayRef<OperandBundleDef> Bundles,
80806f32e7eSjoerg                                   BasicBlock *InsertAtEnd) {
80906f32e7eSjoerg   Instruction *FreeCall = createFree(Source, Bundles, nullptr, InsertAtEnd);
81006f32e7eSjoerg   assert(FreeCall && "CreateFree did not create a CallInst");
81106f32e7eSjoerg   return FreeCall;
81206f32e7eSjoerg }
81306f32e7eSjoerg 
81406f32e7eSjoerg //===----------------------------------------------------------------------===//
81506f32e7eSjoerg //                        InvokeInst Implementation
81606f32e7eSjoerg //===----------------------------------------------------------------------===//
81706f32e7eSjoerg 
init(FunctionType * FTy,Value * Fn,BasicBlock * IfNormal,BasicBlock * IfException,ArrayRef<Value * > Args,ArrayRef<OperandBundleDef> Bundles,const Twine & NameStr)81806f32e7eSjoerg void InvokeInst::init(FunctionType *FTy, Value *Fn, BasicBlock *IfNormal,
81906f32e7eSjoerg                       BasicBlock *IfException, ArrayRef<Value *> Args,
82006f32e7eSjoerg                       ArrayRef<OperandBundleDef> Bundles,
82106f32e7eSjoerg                       const Twine &NameStr) {
82206f32e7eSjoerg   this->FTy = FTy;
82306f32e7eSjoerg 
82406f32e7eSjoerg   assert((int)getNumOperands() ==
82506f32e7eSjoerg              ComputeNumOperands(Args.size(), CountBundleInputs(Bundles)) &&
82606f32e7eSjoerg          "NumOperands not set up?");
82706f32e7eSjoerg   setNormalDest(IfNormal);
82806f32e7eSjoerg   setUnwindDest(IfException);
82906f32e7eSjoerg   setCalledOperand(Fn);
83006f32e7eSjoerg 
83106f32e7eSjoerg #ifndef NDEBUG
83206f32e7eSjoerg   assert(((Args.size() == FTy->getNumParams()) ||
83306f32e7eSjoerg           (FTy->isVarArg() && Args.size() > FTy->getNumParams())) &&
83406f32e7eSjoerg          "Invoking a function with bad signature");
83506f32e7eSjoerg 
83606f32e7eSjoerg   for (unsigned i = 0, e = Args.size(); i != e; i++)
83706f32e7eSjoerg     assert((i >= FTy->getNumParams() ||
83806f32e7eSjoerg             FTy->getParamType(i) == Args[i]->getType()) &&
83906f32e7eSjoerg            "Invoking a function with a bad signature!");
84006f32e7eSjoerg #endif
84106f32e7eSjoerg 
84206f32e7eSjoerg   llvm::copy(Args, op_begin());
84306f32e7eSjoerg 
84406f32e7eSjoerg   auto It = populateBundleOperandInfos(Bundles, Args.size());
84506f32e7eSjoerg   (void)It;
84606f32e7eSjoerg   assert(It + 3 == op_end() && "Should add up!");
84706f32e7eSjoerg 
84806f32e7eSjoerg   setName(NameStr);
84906f32e7eSjoerg }
85006f32e7eSjoerg 
InvokeInst(const InvokeInst & II)85106f32e7eSjoerg InvokeInst::InvokeInst(const InvokeInst &II)
85206f32e7eSjoerg     : CallBase(II.Attrs, II.FTy, II.getType(), Instruction::Invoke,
85306f32e7eSjoerg                OperandTraits<CallBase>::op_end(this) - II.getNumOperands(),
85406f32e7eSjoerg                II.getNumOperands()) {
85506f32e7eSjoerg   setCallingConv(II.getCallingConv());
85606f32e7eSjoerg   std::copy(II.op_begin(), II.op_end(), op_begin());
85706f32e7eSjoerg   std::copy(II.bundle_op_info_begin(), II.bundle_op_info_end(),
85806f32e7eSjoerg             bundle_op_info_begin());
85906f32e7eSjoerg   SubclassOptionalData = II.SubclassOptionalData;
86006f32e7eSjoerg }
86106f32e7eSjoerg 
Create(InvokeInst * II,ArrayRef<OperandBundleDef> OpB,Instruction * InsertPt)86206f32e7eSjoerg InvokeInst *InvokeInst::Create(InvokeInst *II, ArrayRef<OperandBundleDef> OpB,
86306f32e7eSjoerg                                Instruction *InsertPt) {
86406f32e7eSjoerg   std::vector<Value *> Args(II->arg_begin(), II->arg_end());
86506f32e7eSjoerg 
866*da58b97aSjoerg   auto *NewII = InvokeInst::Create(
867*da58b97aSjoerg       II->getFunctionType(), II->getCalledOperand(), II->getNormalDest(),
868*da58b97aSjoerg       II->getUnwindDest(), Args, OpB, II->getName(), InsertPt);
86906f32e7eSjoerg   NewII->setCallingConv(II->getCallingConv());
87006f32e7eSjoerg   NewII->SubclassOptionalData = II->SubclassOptionalData;
87106f32e7eSjoerg   NewII->setAttributes(II->getAttributes());
87206f32e7eSjoerg   NewII->setDebugLoc(II->getDebugLoc());
87306f32e7eSjoerg   return NewII;
87406f32e7eSjoerg }
87506f32e7eSjoerg 
getLandingPadInst() const87606f32e7eSjoerg LandingPadInst *InvokeInst::getLandingPadInst() const {
87706f32e7eSjoerg   return cast<LandingPadInst>(getUnwindDest()->getFirstNonPHI());
87806f32e7eSjoerg }
87906f32e7eSjoerg 
88006f32e7eSjoerg //===----------------------------------------------------------------------===//
88106f32e7eSjoerg //                        CallBrInst Implementation
88206f32e7eSjoerg //===----------------------------------------------------------------------===//
88306f32e7eSjoerg 
init(FunctionType * FTy,Value * Fn,BasicBlock * Fallthrough,ArrayRef<BasicBlock * > IndirectDests,ArrayRef<Value * > Args,ArrayRef<OperandBundleDef> Bundles,const Twine & NameStr)88406f32e7eSjoerg void CallBrInst::init(FunctionType *FTy, Value *Fn, BasicBlock *Fallthrough,
88506f32e7eSjoerg                       ArrayRef<BasicBlock *> IndirectDests,
88606f32e7eSjoerg                       ArrayRef<Value *> Args,
88706f32e7eSjoerg                       ArrayRef<OperandBundleDef> Bundles,
88806f32e7eSjoerg                       const Twine &NameStr) {
88906f32e7eSjoerg   this->FTy = FTy;
89006f32e7eSjoerg 
89106f32e7eSjoerg   assert((int)getNumOperands() ==
89206f32e7eSjoerg              ComputeNumOperands(Args.size(), IndirectDests.size(),
89306f32e7eSjoerg                                 CountBundleInputs(Bundles)) &&
89406f32e7eSjoerg          "NumOperands not set up?");
89506f32e7eSjoerg   NumIndirectDests = IndirectDests.size();
89606f32e7eSjoerg   setDefaultDest(Fallthrough);
89706f32e7eSjoerg   for (unsigned i = 0; i != NumIndirectDests; ++i)
89806f32e7eSjoerg     setIndirectDest(i, IndirectDests[i]);
89906f32e7eSjoerg   setCalledOperand(Fn);
90006f32e7eSjoerg 
90106f32e7eSjoerg #ifndef NDEBUG
90206f32e7eSjoerg   assert(((Args.size() == FTy->getNumParams()) ||
90306f32e7eSjoerg           (FTy->isVarArg() && Args.size() > FTy->getNumParams())) &&
90406f32e7eSjoerg          "Calling a function with bad signature");
90506f32e7eSjoerg 
90606f32e7eSjoerg   for (unsigned i = 0, e = Args.size(); i != e; i++)
90706f32e7eSjoerg     assert((i >= FTy->getNumParams() ||
90806f32e7eSjoerg             FTy->getParamType(i) == Args[i]->getType()) &&
90906f32e7eSjoerg            "Calling a function with a bad signature!");
91006f32e7eSjoerg #endif
91106f32e7eSjoerg 
91206f32e7eSjoerg   std::copy(Args.begin(), Args.end(), op_begin());
91306f32e7eSjoerg 
91406f32e7eSjoerg   auto It = populateBundleOperandInfos(Bundles, Args.size());
91506f32e7eSjoerg   (void)It;
91606f32e7eSjoerg   assert(It + 2 + IndirectDests.size() == op_end() && "Should add up!");
91706f32e7eSjoerg 
91806f32e7eSjoerg   setName(NameStr);
91906f32e7eSjoerg }
92006f32e7eSjoerg 
updateArgBlockAddresses(unsigned i,BasicBlock * B)92106f32e7eSjoerg void CallBrInst::updateArgBlockAddresses(unsigned i, BasicBlock *B) {
92206f32e7eSjoerg   assert(getNumIndirectDests() > i && "IndirectDest # out of range for callbr");
92306f32e7eSjoerg   if (BasicBlock *OldBB = getIndirectDest(i)) {
92406f32e7eSjoerg     BlockAddress *Old = BlockAddress::get(OldBB);
92506f32e7eSjoerg     BlockAddress *New = BlockAddress::get(B);
92606f32e7eSjoerg     for (unsigned ArgNo = 0, e = getNumArgOperands(); ArgNo != e; ++ArgNo)
92706f32e7eSjoerg       if (dyn_cast<BlockAddress>(getArgOperand(ArgNo)) == Old)
92806f32e7eSjoerg         setArgOperand(ArgNo, New);
92906f32e7eSjoerg   }
93006f32e7eSjoerg }
93106f32e7eSjoerg 
CallBrInst(const CallBrInst & CBI)93206f32e7eSjoerg CallBrInst::CallBrInst(const CallBrInst &CBI)
93306f32e7eSjoerg     : CallBase(CBI.Attrs, CBI.FTy, CBI.getType(), Instruction::CallBr,
93406f32e7eSjoerg                OperandTraits<CallBase>::op_end(this) - CBI.getNumOperands(),
93506f32e7eSjoerg                CBI.getNumOperands()) {
93606f32e7eSjoerg   setCallingConv(CBI.getCallingConv());
93706f32e7eSjoerg   std::copy(CBI.op_begin(), CBI.op_end(), op_begin());
93806f32e7eSjoerg   std::copy(CBI.bundle_op_info_begin(), CBI.bundle_op_info_end(),
93906f32e7eSjoerg             bundle_op_info_begin());
94006f32e7eSjoerg   SubclassOptionalData = CBI.SubclassOptionalData;
94106f32e7eSjoerg   NumIndirectDests = CBI.NumIndirectDests;
94206f32e7eSjoerg }
94306f32e7eSjoerg 
Create(CallBrInst * CBI,ArrayRef<OperandBundleDef> OpB,Instruction * InsertPt)94406f32e7eSjoerg CallBrInst *CallBrInst::Create(CallBrInst *CBI, ArrayRef<OperandBundleDef> OpB,
94506f32e7eSjoerg                                Instruction *InsertPt) {
94606f32e7eSjoerg   std::vector<Value *> Args(CBI->arg_begin(), CBI->arg_end());
94706f32e7eSjoerg 
948*da58b97aSjoerg   auto *NewCBI = CallBrInst::Create(
949*da58b97aSjoerg       CBI->getFunctionType(), CBI->getCalledOperand(), CBI->getDefaultDest(),
950*da58b97aSjoerg       CBI->getIndirectDests(), Args, OpB, CBI->getName(), InsertPt);
95106f32e7eSjoerg   NewCBI->setCallingConv(CBI->getCallingConv());
95206f32e7eSjoerg   NewCBI->SubclassOptionalData = CBI->SubclassOptionalData;
95306f32e7eSjoerg   NewCBI->setAttributes(CBI->getAttributes());
95406f32e7eSjoerg   NewCBI->setDebugLoc(CBI->getDebugLoc());
95506f32e7eSjoerg   NewCBI->NumIndirectDests = CBI->NumIndirectDests;
95606f32e7eSjoerg   return NewCBI;
95706f32e7eSjoerg }
95806f32e7eSjoerg 
95906f32e7eSjoerg //===----------------------------------------------------------------------===//
96006f32e7eSjoerg //                        ReturnInst Implementation
96106f32e7eSjoerg //===----------------------------------------------------------------------===//
96206f32e7eSjoerg 
ReturnInst(const ReturnInst & RI)96306f32e7eSjoerg ReturnInst::ReturnInst(const ReturnInst &RI)
96406f32e7eSjoerg     : Instruction(Type::getVoidTy(RI.getContext()), Instruction::Ret,
96506f32e7eSjoerg                   OperandTraits<ReturnInst>::op_end(this) - RI.getNumOperands(),
96606f32e7eSjoerg                   RI.getNumOperands()) {
96706f32e7eSjoerg   if (RI.getNumOperands())
96806f32e7eSjoerg     Op<0>() = RI.Op<0>();
96906f32e7eSjoerg   SubclassOptionalData = RI.SubclassOptionalData;
97006f32e7eSjoerg }
97106f32e7eSjoerg 
ReturnInst(LLVMContext & C,Value * retVal,Instruction * InsertBefore)97206f32e7eSjoerg ReturnInst::ReturnInst(LLVMContext &C, Value *retVal, Instruction *InsertBefore)
97306f32e7eSjoerg     : Instruction(Type::getVoidTy(C), Instruction::Ret,
97406f32e7eSjoerg                   OperandTraits<ReturnInst>::op_end(this) - !!retVal, !!retVal,
97506f32e7eSjoerg                   InsertBefore) {
97606f32e7eSjoerg   if (retVal)
97706f32e7eSjoerg     Op<0>() = retVal;
97806f32e7eSjoerg }
97906f32e7eSjoerg 
ReturnInst(LLVMContext & C,Value * retVal,BasicBlock * InsertAtEnd)98006f32e7eSjoerg ReturnInst::ReturnInst(LLVMContext &C, Value *retVal, BasicBlock *InsertAtEnd)
98106f32e7eSjoerg     : Instruction(Type::getVoidTy(C), Instruction::Ret,
98206f32e7eSjoerg                   OperandTraits<ReturnInst>::op_end(this) - !!retVal, !!retVal,
98306f32e7eSjoerg                   InsertAtEnd) {
98406f32e7eSjoerg   if (retVal)
98506f32e7eSjoerg     Op<0>() = retVal;
98606f32e7eSjoerg }
98706f32e7eSjoerg 
ReturnInst(LLVMContext & Context,BasicBlock * InsertAtEnd)98806f32e7eSjoerg ReturnInst::ReturnInst(LLVMContext &Context, BasicBlock *InsertAtEnd)
98906f32e7eSjoerg     : Instruction(Type::getVoidTy(Context), Instruction::Ret,
99006f32e7eSjoerg                   OperandTraits<ReturnInst>::op_end(this), 0, InsertAtEnd) {}
99106f32e7eSjoerg 
99206f32e7eSjoerg //===----------------------------------------------------------------------===//
99306f32e7eSjoerg //                        ResumeInst Implementation
99406f32e7eSjoerg //===----------------------------------------------------------------------===//
99506f32e7eSjoerg 
ResumeInst(const ResumeInst & RI)99606f32e7eSjoerg ResumeInst::ResumeInst(const ResumeInst &RI)
99706f32e7eSjoerg     : Instruction(Type::getVoidTy(RI.getContext()), Instruction::Resume,
99806f32e7eSjoerg                   OperandTraits<ResumeInst>::op_begin(this), 1) {
99906f32e7eSjoerg   Op<0>() = RI.Op<0>();
100006f32e7eSjoerg }
100106f32e7eSjoerg 
ResumeInst(Value * Exn,Instruction * InsertBefore)100206f32e7eSjoerg ResumeInst::ResumeInst(Value *Exn, Instruction *InsertBefore)
100306f32e7eSjoerg     : Instruction(Type::getVoidTy(Exn->getContext()), Instruction::Resume,
100406f32e7eSjoerg                   OperandTraits<ResumeInst>::op_begin(this), 1, InsertBefore) {
100506f32e7eSjoerg   Op<0>() = Exn;
100606f32e7eSjoerg }
100706f32e7eSjoerg 
ResumeInst(Value * Exn,BasicBlock * InsertAtEnd)100806f32e7eSjoerg ResumeInst::ResumeInst(Value *Exn, BasicBlock *InsertAtEnd)
100906f32e7eSjoerg     : Instruction(Type::getVoidTy(Exn->getContext()), Instruction::Resume,
101006f32e7eSjoerg                   OperandTraits<ResumeInst>::op_begin(this), 1, InsertAtEnd) {
101106f32e7eSjoerg   Op<0>() = Exn;
101206f32e7eSjoerg }
101306f32e7eSjoerg 
101406f32e7eSjoerg //===----------------------------------------------------------------------===//
101506f32e7eSjoerg //                        CleanupReturnInst Implementation
101606f32e7eSjoerg //===----------------------------------------------------------------------===//
101706f32e7eSjoerg 
CleanupReturnInst(const CleanupReturnInst & CRI)101806f32e7eSjoerg CleanupReturnInst::CleanupReturnInst(const CleanupReturnInst &CRI)
101906f32e7eSjoerg     : Instruction(CRI.getType(), Instruction::CleanupRet,
102006f32e7eSjoerg                   OperandTraits<CleanupReturnInst>::op_end(this) -
102106f32e7eSjoerg                       CRI.getNumOperands(),
102206f32e7eSjoerg                   CRI.getNumOperands()) {
1023*da58b97aSjoerg   setSubclassData<Instruction::OpaqueField>(
1024*da58b97aSjoerg       CRI.getSubclassData<Instruction::OpaqueField>());
102506f32e7eSjoerg   Op<0>() = CRI.Op<0>();
102606f32e7eSjoerg   if (CRI.hasUnwindDest())
102706f32e7eSjoerg     Op<1>() = CRI.Op<1>();
102806f32e7eSjoerg }
102906f32e7eSjoerg 
init(Value * CleanupPad,BasicBlock * UnwindBB)103006f32e7eSjoerg void CleanupReturnInst::init(Value *CleanupPad, BasicBlock *UnwindBB) {
103106f32e7eSjoerg   if (UnwindBB)
1032*da58b97aSjoerg     setSubclassData<UnwindDestField>(true);
103306f32e7eSjoerg 
103406f32e7eSjoerg   Op<0>() = CleanupPad;
103506f32e7eSjoerg   if (UnwindBB)
103606f32e7eSjoerg     Op<1>() = UnwindBB;
103706f32e7eSjoerg }
103806f32e7eSjoerg 
CleanupReturnInst(Value * CleanupPad,BasicBlock * UnwindBB,unsigned Values,Instruction * InsertBefore)103906f32e7eSjoerg CleanupReturnInst::CleanupReturnInst(Value *CleanupPad, BasicBlock *UnwindBB,
104006f32e7eSjoerg                                      unsigned Values, Instruction *InsertBefore)
104106f32e7eSjoerg     : Instruction(Type::getVoidTy(CleanupPad->getContext()),
104206f32e7eSjoerg                   Instruction::CleanupRet,
104306f32e7eSjoerg                   OperandTraits<CleanupReturnInst>::op_end(this) - Values,
104406f32e7eSjoerg                   Values, InsertBefore) {
104506f32e7eSjoerg   init(CleanupPad, UnwindBB);
104606f32e7eSjoerg }
104706f32e7eSjoerg 
CleanupReturnInst(Value * CleanupPad,BasicBlock * UnwindBB,unsigned Values,BasicBlock * InsertAtEnd)104806f32e7eSjoerg CleanupReturnInst::CleanupReturnInst(Value *CleanupPad, BasicBlock *UnwindBB,
104906f32e7eSjoerg                                      unsigned Values, BasicBlock *InsertAtEnd)
105006f32e7eSjoerg     : Instruction(Type::getVoidTy(CleanupPad->getContext()),
105106f32e7eSjoerg                   Instruction::CleanupRet,
105206f32e7eSjoerg                   OperandTraits<CleanupReturnInst>::op_end(this) - Values,
105306f32e7eSjoerg                   Values, InsertAtEnd) {
105406f32e7eSjoerg   init(CleanupPad, UnwindBB);
105506f32e7eSjoerg }
105606f32e7eSjoerg 
105706f32e7eSjoerg //===----------------------------------------------------------------------===//
105806f32e7eSjoerg //                        CatchReturnInst Implementation
105906f32e7eSjoerg //===----------------------------------------------------------------------===//
init(Value * CatchPad,BasicBlock * BB)106006f32e7eSjoerg void CatchReturnInst::init(Value *CatchPad, BasicBlock *BB) {
106106f32e7eSjoerg   Op<0>() = CatchPad;
106206f32e7eSjoerg   Op<1>() = BB;
106306f32e7eSjoerg }
106406f32e7eSjoerg 
CatchReturnInst(const CatchReturnInst & CRI)106506f32e7eSjoerg CatchReturnInst::CatchReturnInst(const CatchReturnInst &CRI)
106606f32e7eSjoerg     : Instruction(Type::getVoidTy(CRI.getContext()), Instruction::CatchRet,
106706f32e7eSjoerg                   OperandTraits<CatchReturnInst>::op_begin(this), 2) {
106806f32e7eSjoerg   Op<0>() = CRI.Op<0>();
106906f32e7eSjoerg   Op<1>() = CRI.Op<1>();
107006f32e7eSjoerg }
107106f32e7eSjoerg 
CatchReturnInst(Value * CatchPad,BasicBlock * BB,Instruction * InsertBefore)107206f32e7eSjoerg CatchReturnInst::CatchReturnInst(Value *CatchPad, BasicBlock *BB,
107306f32e7eSjoerg                                  Instruction *InsertBefore)
107406f32e7eSjoerg     : Instruction(Type::getVoidTy(BB->getContext()), Instruction::CatchRet,
107506f32e7eSjoerg                   OperandTraits<CatchReturnInst>::op_begin(this), 2,
107606f32e7eSjoerg                   InsertBefore) {
107706f32e7eSjoerg   init(CatchPad, BB);
107806f32e7eSjoerg }
107906f32e7eSjoerg 
CatchReturnInst(Value * CatchPad,BasicBlock * BB,BasicBlock * InsertAtEnd)108006f32e7eSjoerg CatchReturnInst::CatchReturnInst(Value *CatchPad, BasicBlock *BB,
108106f32e7eSjoerg                                  BasicBlock *InsertAtEnd)
108206f32e7eSjoerg     : Instruction(Type::getVoidTy(BB->getContext()), Instruction::CatchRet,
108306f32e7eSjoerg                   OperandTraits<CatchReturnInst>::op_begin(this), 2,
108406f32e7eSjoerg                   InsertAtEnd) {
108506f32e7eSjoerg   init(CatchPad, BB);
108606f32e7eSjoerg }
108706f32e7eSjoerg 
108806f32e7eSjoerg //===----------------------------------------------------------------------===//
108906f32e7eSjoerg //                       CatchSwitchInst Implementation
109006f32e7eSjoerg //===----------------------------------------------------------------------===//
109106f32e7eSjoerg 
CatchSwitchInst(Value * ParentPad,BasicBlock * UnwindDest,unsigned NumReservedValues,const Twine & NameStr,Instruction * InsertBefore)109206f32e7eSjoerg CatchSwitchInst::CatchSwitchInst(Value *ParentPad, BasicBlock *UnwindDest,
109306f32e7eSjoerg                                  unsigned NumReservedValues,
109406f32e7eSjoerg                                  const Twine &NameStr,
109506f32e7eSjoerg                                  Instruction *InsertBefore)
109606f32e7eSjoerg     : Instruction(ParentPad->getType(), Instruction::CatchSwitch, nullptr, 0,
109706f32e7eSjoerg                   InsertBefore) {
109806f32e7eSjoerg   if (UnwindDest)
109906f32e7eSjoerg     ++NumReservedValues;
110006f32e7eSjoerg   init(ParentPad, UnwindDest, NumReservedValues + 1);
110106f32e7eSjoerg   setName(NameStr);
110206f32e7eSjoerg }
110306f32e7eSjoerg 
CatchSwitchInst(Value * ParentPad,BasicBlock * UnwindDest,unsigned NumReservedValues,const Twine & NameStr,BasicBlock * InsertAtEnd)110406f32e7eSjoerg CatchSwitchInst::CatchSwitchInst(Value *ParentPad, BasicBlock *UnwindDest,
110506f32e7eSjoerg                                  unsigned NumReservedValues,
110606f32e7eSjoerg                                  const Twine &NameStr, BasicBlock *InsertAtEnd)
110706f32e7eSjoerg     : Instruction(ParentPad->getType(), Instruction::CatchSwitch, nullptr, 0,
110806f32e7eSjoerg                   InsertAtEnd) {
110906f32e7eSjoerg   if (UnwindDest)
111006f32e7eSjoerg     ++NumReservedValues;
111106f32e7eSjoerg   init(ParentPad, UnwindDest, NumReservedValues + 1);
111206f32e7eSjoerg   setName(NameStr);
111306f32e7eSjoerg }
111406f32e7eSjoerg 
CatchSwitchInst(const CatchSwitchInst & CSI)111506f32e7eSjoerg CatchSwitchInst::CatchSwitchInst(const CatchSwitchInst &CSI)
111606f32e7eSjoerg     : Instruction(CSI.getType(), Instruction::CatchSwitch, nullptr,
111706f32e7eSjoerg                   CSI.getNumOperands()) {
111806f32e7eSjoerg   init(CSI.getParentPad(), CSI.getUnwindDest(), CSI.getNumOperands());
111906f32e7eSjoerg   setNumHungOffUseOperands(ReservedSpace);
112006f32e7eSjoerg   Use *OL = getOperandList();
112106f32e7eSjoerg   const Use *InOL = CSI.getOperandList();
112206f32e7eSjoerg   for (unsigned I = 1, E = ReservedSpace; I != E; ++I)
112306f32e7eSjoerg     OL[I] = InOL[I];
112406f32e7eSjoerg }
112506f32e7eSjoerg 
init(Value * ParentPad,BasicBlock * UnwindDest,unsigned NumReservedValues)112606f32e7eSjoerg void CatchSwitchInst::init(Value *ParentPad, BasicBlock *UnwindDest,
112706f32e7eSjoerg                            unsigned NumReservedValues) {
112806f32e7eSjoerg   assert(ParentPad && NumReservedValues);
112906f32e7eSjoerg 
113006f32e7eSjoerg   ReservedSpace = NumReservedValues;
113106f32e7eSjoerg   setNumHungOffUseOperands(UnwindDest ? 2 : 1);
113206f32e7eSjoerg   allocHungoffUses(ReservedSpace);
113306f32e7eSjoerg 
113406f32e7eSjoerg   Op<0>() = ParentPad;
113506f32e7eSjoerg   if (UnwindDest) {
1136*da58b97aSjoerg     setSubclassData<UnwindDestField>(true);
113706f32e7eSjoerg     setUnwindDest(UnwindDest);
113806f32e7eSjoerg   }
113906f32e7eSjoerg }
114006f32e7eSjoerg 
114106f32e7eSjoerg /// growOperands - grow operands - This grows the operand list in response to a
114206f32e7eSjoerg /// push_back style of operation. This grows the number of ops by 2 times.
growOperands(unsigned Size)114306f32e7eSjoerg void CatchSwitchInst::growOperands(unsigned Size) {
114406f32e7eSjoerg   unsigned NumOperands = getNumOperands();
114506f32e7eSjoerg   assert(NumOperands >= 1);
114606f32e7eSjoerg   if (ReservedSpace >= NumOperands + Size)
114706f32e7eSjoerg     return;
114806f32e7eSjoerg   ReservedSpace = (NumOperands + Size / 2) * 2;
114906f32e7eSjoerg   growHungoffUses(ReservedSpace);
115006f32e7eSjoerg }
115106f32e7eSjoerg 
addHandler(BasicBlock * Handler)115206f32e7eSjoerg void CatchSwitchInst::addHandler(BasicBlock *Handler) {
115306f32e7eSjoerg   unsigned OpNo = getNumOperands();
115406f32e7eSjoerg   growOperands(1);
115506f32e7eSjoerg   assert(OpNo < ReservedSpace && "Growing didn't work!");
115606f32e7eSjoerg   setNumHungOffUseOperands(getNumOperands() + 1);
115706f32e7eSjoerg   getOperandList()[OpNo] = Handler;
115806f32e7eSjoerg }
115906f32e7eSjoerg 
removeHandler(handler_iterator HI)116006f32e7eSjoerg void CatchSwitchInst::removeHandler(handler_iterator HI) {
116106f32e7eSjoerg   // Move all subsequent handlers up one.
116206f32e7eSjoerg   Use *EndDst = op_end() - 1;
116306f32e7eSjoerg   for (Use *CurDst = HI.getCurrent(); CurDst != EndDst; ++CurDst)
116406f32e7eSjoerg     *CurDst = *(CurDst + 1);
116506f32e7eSjoerg   // Null out the last handler use.
116606f32e7eSjoerg   *EndDst = nullptr;
116706f32e7eSjoerg 
116806f32e7eSjoerg   setNumHungOffUseOperands(getNumOperands() - 1);
116906f32e7eSjoerg }
117006f32e7eSjoerg 
117106f32e7eSjoerg //===----------------------------------------------------------------------===//
117206f32e7eSjoerg //                        FuncletPadInst Implementation
117306f32e7eSjoerg //===----------------------------------------------------------------------===//
init(Value * ParentPad,ArrayRef<Value * > Args,const Twine & NameStr)117406f32e7eSjoerg void FuncletPadInst::init(Value *ParentPad, ArrayRef<Value *> Args,
117506f32e7eSjoerg                           const Twine &NameStr) {
117606f32e7eSjoerg   assert(getNumOperands() == 1 + Args.size() && "NumOperands not set up?");
117706f32e7eSjoerg   llvm::copy(Args, op_begin());
117806f32e7eSjoerg   setParentPad(ParentPad);
117906f32e7eSjoerg   setName(NameStr);
118006f32e7eSjoerg }
118106f32e7eSjoerg 
FuncletPadInst(const FuncletPadInst & FPI)118206f32e7eSjoerg FuncletPadInst::FuncletPadInst(const FuncletPadInst &FPI)
118306f32e7eSjoerg     : Instruction(FPI.getType(), FPI.getOpcode(),
118406f32e7eSjoerg                   OperandTraits<FuncletPadInst>::op_end(this) -
118506f32e7eSjoerg                       FPI.getNumOperands(),
118606f32e7eSjoerg                   FPI.getNumOperands()) {
118706f32e7eSjoerg   std::copy(FPI.op_begin(), FPI.op_end(), op_begin());
118806f32e7eSjoerg   setParentPad(FPI.getParentPad());
118906f32e7eSjoerg }
119006f32e7eSjoerg 
FuncletPadInst(Instruction::FuncletPadOps Op,Value * ParentPad,ArrayRef<Value * > Args,unsigned Values,const Twine & NameStr,Instruction * InsertBefore)119106f32e7eSjoerg FuncletPadInst::FuncletPadInst(Instruction::FuncletPadOps Op, Value *ParentPad,
119206f32e7eSjoerg                                ArrayRef<Value *> Args, unsigned Values,
119306f32e7eSjoerg                                const Twine &NameStr, Instruction *InsertBefore)
119406f32e7eSjoerg     : Instruction(ParentPad->getType(), Op,
119506f32e7eSjoerg                   OperandTraits<FuncletPadInst>::op_end(this) - Values, Values,
119606f32e7eSjoerg                   InsertBefore) {
119706f32e7eSjoerg   init(ParentPad, Args, NameStr);
119806f32e7eSjoerg }
119906f32e7eSjoerg 
FuncletPadInst(Instruction::FuncletPadOps Op,Value * ParentPad,ArrayRef<Value * > Args,unsigned Values,const Twine & NameStr,BasicBlock * InsertAtEnd)120006f32e7eSjoerg FuncletPadInst::FuncletPadInst(Instruction::FuncletPadOps Op, Value *ParentPad,
120106f32e7eSjoerg                                ArrayRef<Value *> Args, unsigned Values,
120206f32e7eSjoerg                                const Twine &NameStr, BasicBlock *InsertAtEnd)
120306f32e7eSjoerg     : Instruction(ParentPad->getType(), Op,
120406f32e7eSjoerg                   OperandTraits<FuncletPadInst>::op_end(this) - Values, Values,
120506f32e7eSjoerg                   InsertAtEnd) {
120606f32e7eSjoerg   init(ParentPad, Args, NameStr);
120706f32e7eSjoerg }
120806f32e7eSjoerg 
120906f32e7eSjoerg //===----------------------------------------------------------------------===//
121006f32e7eSjoerg //                      UnreachableInst Implementation
121106f32e7eSjoerg //===----------------------------------------------------------------------===//
121206f32e7eSjoerg 
UnreachableInst(LLVMContext & Context,Instruction * InsertBefore)121306f32e7eSjoerg UnreachableInst::UnreachableInst(LLVMContext &Context,
121406f32e7eSjoerg                                  Instruction *InsertBefore)
121506f32e7eSjoerg     : Instruction(Type::getVoidTy(Context), Instruction::Unreachable, nullptr,
121606f32e7eSjoerg                   0, InsertBefore) {}
UnreachableInst(LLVMContext & Context,BasicBlock * InsertAtEnd)121706f32e7eSjoerg UnreachableInst::UnreachableInst(LLVMContext &Context, BasicBlock *InsertAtEnd)
121806f32e7eSjoerg     : Instruction(Type::getVoidTy(Context), Instruction::Unreachable, nullptr,
121906f32e7eSjoerg                   0, InsertAtEnd) {}
122006f32e7eSjoerg 
122106f32e7eSjoerg //===----------------------------------------------------------------------===//
122206f32e7eSjoerg //                        BranchInst Implementation
122306f32e7eSjoerg //===----------------------------------------------------------------------===//
122406f32e7eSjoerg 
AssertOK()122506f32e7eSjoerg void BranchInst::AssertOK() {
122606f32e7eSjoerg   if (isConditional())
122706f32e7eSjoerg     assert(getCondition()->getType()->isIntegerTy(1) &&
122806f32e7eSjoerg            "May only branch on boolean predicates!");
122906f32e7eSjoerg }
123006f32e7eSjoerg 
BranchInst(BasicBlock * IfTrue,Instruction * InsertBefore)123106f32e7eSjoerg BranchInst::BranchInst(BasicBlock *IfTrue, Instruction *InsertBefore)
123206f32e7eSjoerg     : Instruction(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
123306f32e7eSjoerg                   OperandTraits<BranchInst>::op_end(this) - 1, 1,
123406f32e7eSjoerg                   InsertBefore) {
123506f32e7eSjoerg   assert(IfTrue && "Branch destination may not be null!");
123606f32e7eSjoerg   Op<-1>() = IfTrue;
123706f32e7eSjoerg }
123806f32e7eSjoerg 
BranchInst(BasicBlock * IfTrue,BasicBlock * IfFalse,Value * Cond,Instruction * InsertBefore)123906f32e7eSjoerg BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
124006f32e7eSjoerg                        Instruction *InsertBefore)
124106f32e7eSjoerg     : Instruction(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
124206f32e7eSjoerg                   OperandTraits<BranchInst>::op_end(this) - 3, 3,
124306f32e7eSjoerg                   InsertBefore) {
124406f32e7eSjoerg   Op<-1>() = IfTrue;
124506f32e7eSjoerg   Op<-2>() = IfFalse;
124606f32e7eSjoerg   Op<-3>() = Cond;
124706f32e7eSjoerg #ifndef NDEBUG
124806f32e7eSjoerg   AssertOK();
124906f32e7eSjoerg #endif
125006f32e7eSjoerg }
125106f32e7eSjoerg 
BranchInst(BasicBlock * IfTrue,BasicBlock * InsertAtEnd)125206f32e7eSjoerg BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *InsertAtEnd)
125306f32e7eSjoerg     : Instruction(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
125406f32e7eSjoerg                   OperandTraits<BranchInst>::op_end(this) - 1, 1, InsertAtEnd) {
125506f32e7eSjoerg   assert(IfTrue && "Branch destination may not be null!");
125606f32e7eSjoerg   Op<-1>() = IfTrue;
125706f32e7eSjoerg }
125806f32e7eSjoerg 
BranchInst(BasicBlock * IfTrue,BasicBlock * IfFalse,Value * Cond,BasicBlock * InsertAtEnd)125906f32e7eSjoerg BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
126006f32e7eSjoerg                        BasicBlock *InsertAtEnd)
126106f32e7eSjoerg     : Instruction(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
126206f32e7eSjoerg                   OperandTraits<BranchInst>::op_end(this) - 3, 3, InsertAtEnd) {
126306f32e7eSjoerg   Op<-1>() = IfTrue;
126406f32e7eSjoerg   Op<-2>() = IfFalse;
126506f32e7eSjoerg   Op<-3>() = Cond;
126606f32e7eSjoerg #ifndef NDEBUG
126706f32e7eSjoerg   AssertOK();
126806f32e7eSjoerg #endif
126906f32e7eSjoerg }
127006f32e7eSjoerg 
BranchInst(const BranchInst & BI)127106f32e7eSjoerg BranchInst::BranchInst(const BranchInst &BI)
127206f32e7eSjoerg     : Instruction(Type::getVoidTy(BI.getContext()), Instruction::Br,
127306f32e7eSjoerg                   OperandTraits<BranchInst>::op_end(this) - BI.getNumOperands(),
127406f32e7eSjoerg                   BI.getNumOperands()) {
127506f32e7eSjoerg   Op<-1>() = BI.Op<-1>();
127606f32e7eSjoerg   if (BI.getNumOperands() != 1) {
127706f32e7eSjoerg     assert(BI.getNumOperands() == 3 && "BR can have 1 or 3 operands!");
127806f32e7eSjoerg     Op<-3>() = BI.Op<-3>();
127906f32e7eSjoerg     Op<-2>() = BI.Op<-2>();
128006f32e7eSjoerg   }
128106f32e7eSjoerg   SubclassOptionalData = BI.SubclassOptionalData;
128206f32e7eSjoerg }
128306f32e7eSjoerg 
swapSuccessors()128406f32e7eSjoerg void BranchInst::swapSuccessors() {
128506f32e7eSjoerg   assert(isConditional() &&
128606f32e7eSjoerg          "Cannot swap successors of an unconditional branch");
128706f32e7eSjoerg   Op<-1>().swap(Op<-2>());
128806f32e7eSjoerg 
128906f32e7eSjoerg   // Update profile metadata if present and it matches our structural
129006f32e7eSjoerg   // expectations.
129106f32e7eSjoerg   swapProfMetadata();
129206f32e7eSjoerg }
129306f32e7eSjoerg 
129406f32e7eSjoerg //===----------------------------------------------------------------------===//
129506f32e7eSjoerg //                        AllocaInst Implementation
129606f32e7eSjoerg //===----------------------------------------------------------------------===//
129706f32e7eSjoerg 
getAISize(LLVMContext & Context,Value * Amt)129806f32e7eSjoerg static Value *getAISize(LLVMContext &Context, Value *Amt) {
129906f32e7eSjoerg   if (!Amt)
130006f32e7eSjoerg     Amt = ConstantInt::get(Type::getInt32Ty(Context), 1);
130106f32e7eSjoerg   else {
130206f32e7eSjoerg     assert(!isa<BasicBlock>(Amt) &&
130306f32e7eSjoerg            "Passed basic block into allocation size parameter! Use other ctor");
130406f32e7eSjoerg     assert(Amt->getType()->isIntegerTy() &&
130506f32e7eSjoerg            "Allocation array size is not an integer!");
130606f32e7eSjoerg   }
130706f32e7eSjoerg   return Amt;
130806f32e7eSjoerg }
130906f32e7eSjoerg 
computeAllocaDefaultAlign(Type * Ty,BasicBlock * BB)1310*da58b97aSjoerg static Align computeAllocaDefaultAlign(Type *Ty, BasicBlock *BB) {
1311*da58b97aSjoerg   assert(BB && "Insertion BB cannot be null when alignment not provided!");
1312*da58b97aSjoerg   assert(BB->getParent() &&
1313*da58b97aSjoerg          "BB must be in a Function when alignment not provided!");
1314*da58b97aSjoerg   const DataLayout &DL = BB->getModule()->getDataLayout();
1315*da58b97aSjoerg   return DL.getPrefTypeAlign(Ty);
1316*da58b97aSjoerg }
1317*da58b97aSjoerg 
computeAllocaDefaultAlign(Type * Ty,Instruction * I)1318*da58b97aSjoerg static Align computeAllocaDefaultAlign(Type *Ty, Instruction *I) {
1319*da58b97aSjoerg   assert(I && "Insertion position cannot be null when alignment not provided!");
1320*da58b97aSjoerg   return computeAllocaDefaultAlign(Ty, I->getParent());
1321*da58b97aSjoerg }
1322*da58b97aSjoerg 
AllocaInst(Type * Ty,unsigned AddrSpace,const Twine & Name,Instruction * InsertBefore)132306f32e7eSjoerg AllocaInst::AllocaInst(Type *Ty, unsigned AddrSpace, const Twine &Name,
132406f32e7eSjoerg                        Instruction *InsertBefore)
132506f32e7eSjoerg   : AllocaInst(Ty, AddrSpace, /*ArraySize=*/nullptr, Name, InsertBefore) {}
132606f32e7eSjoerg 
AllocaInst(Type * Ty,unsigned AddrSpace,const Twine & Name,BasicBlock * InsertAtEnd)132706f32e7eSjoerg AllocaInst::AllocaInst(Type *Ty, unsigned AddrSpace, const Twine &Name,
132806f32e7eSjoerg                        BasicBlock *InsertAtEnd)
132906f32e7eSjoerg   : AllocaInst(Ty, AddrSpace, /*ArraySize=*/nullptr, Name, InsertAtEnd) {}
133006f32e7eSjoerg 
AllocaInst(Type * Ty,unsigned AddrSpace,Value * ArraySize,const Twine & Name,Instruction * InsertBefore)133106f32e7eSjoerg AllocaInst::AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize,
133206f32e7eSjoerg                        const Twine &Name, Instruction *InsertBefore)
1333*da58b97aSjoerg     : AllocaInst(Ty, AddrSpace, ArraySize,
1334*da58b97aSjoerg                  computeAllocaDefaultAlign(Ty, InsertBefore), Name,
1335*da58b97aSjoerg                  InsertBefore) {}
133606f32e7eSjoerg 
AllocaInst(Type * Ty,unsigned AddrSpace,Value * ArraySize,const Twine & Name,BasicBlock * InsertAtEnd)133706f32e7eSjoerg AllocaInst::AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize,
133806f32e7eSjoerg                        const Twine &Name, BasicBlock *InsertAtEnd)
1339*da58b97aSjoerg     : AllocaInst(Ty, AddrSpace, ArraySize,
1340*da58b97aSjoerg                  computeAllocaDefaultAlign(Ty, InsertAtEnd), Name,
1341*da58b97aSjoerg                  InsertAtEnd) {}
134206f32e7eSjoerg 
AllocaInst(Type * Ty,unsigned AddrSpace,Value * ArraySize,Align Align,const Twine & Name,Instruction * InsertBefore)134306f32e7eSjoerg AllocaInst::AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize,
1344*da58b97aSjoerg                        Align Align, const Twine &Name,
134506f32e7eSjoerg                        Instruction *InsertBefore)
134606f32e7eSjoerg     : UnaryInstruction(PointerType::get(Ty, AddrSpace), Alloca,
134706f32e7eSjoerg                        getAISize(Ty->getContext(), ArraySize), InsertBefore),
134806f32e7eSjoerg       AllocatedType(Ty) {
1349*da58b97aSjoerg   setAlignment(Align);
135006f32e7eSjoerg   assert(!Ty->isVoidTy() && "Cannot allocate void!");
135106f32e7eSjoerg   setName(Name);
135206f32e7eSjoerg }
135306f32e7eSjoerg 
AllocaInst(Type * Ty,unsigned AddrSpace,Value * ArraySize,Align Align,const Twine & Name,BasicBlock * InsertAtEnd)135406f32e7eSjoerg AllocaInst::AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize,
1355*da58b97aSjoerg                        Align Align, const Twine &Name, BasicBlock *InsertAtEnd)
135606f32e7eSjoerg     : UnaryInstruction(PointerType::get(Ty, AddrSpace), Alloca,
135706f32e7eSjoerg                        getAISize(Ty->getContext(), ArraySize), InsertAtEnd),
135806f32e7eSjoerg       AllocatedType(Ty) {
135906f32e7eSjoerg   setAlignment(Align);
136006f32e7eSjoerg   assert(!Ty->isVoidTy() && "Cannot allocate void!");
136106f32e7eSjoerg   setName(Name);
136206f32e7eSjoerg }
136306f32e7eSjoerg 
136406f32e7eSjoerg 
isArrayAllocation() const136506f32e7eSjoerg bool AllocaInst::isArrayAllocation() const {
136606f32e7eSjoerg   if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(0)))
136706f32e7eSjoerg     return !CI->isOne();
136806f32e7eSjoerg   return true;
136906f32e7eSjoerg }
137006f32e7eSjoerg 
137106f32e7eSjoerg /// isStaticAlloca - Return true if this alloca is in the entry block of the
137206f32e7eSjoerg /// function and is a constant size.  If so, the code generator will fold it
137306f32e7eSjoerg /// into the prolog/epilog code, so it is basically free.
isStaticAlloca() const137406f32e7eSjoerg bool AllocaInst::isStaticAlloca() const {
137506f32e7eSjoerg   // Must be constant size.
137606f32e7eSjoerg   if (!isa<ConstantInt>(getArraySize())) return false;
137706f32e7eSjoerg 
137806f32e7eSjoerg   // Must be in the entry block.
137906f32e7eSjoerg   const BasicBlock *Parent = getParent();
138006f32e7eSjoerg   return Parent == &Parent->getParent()->front() && !isUsedWithInAlloca();
138106f32e7eSjoerg }
138206f32e7eSjoerg 
138306f32e7eSjoerg //===----------------------------------------------------------------------===//
138406f32e7eSjoerg //                           LoadInst Implementation
138506f32e7eSjoerg //===----------------------------------------------------------------------===//
138606f32e7eSjoerg 
AssertOK()138706f32e7eSjoerg void LoadInst::AssertOK() {
138806f32e7eSjoerg   assert(getOperand(0)->getType()->isPointerTy() &&
138906f32e7eSjoerg          "Ptr must have pointer type.");
139006f32e7eSjoerg   assert(!(isAtomic() && getAlignment() == 0) &&
139106f32e7eSjoerg          "Alignment required for atomic load");
139206f32e7eSjoerg }
139306f32e7eSjoerg 
computeLoadStoreDefaultAlign(Type * Ty,BasicBlock * BB)1394*da58b97aSjoerg static Align computeLoadStoreDefaultAlign(Type *Ty, BasicBlock *BB) {
1395*da58b97aSjoerg   assert(BB && "Insertion BB cannot be null when alignment not provided!");
1396*da58b97aSjoerg   assert(BB->getParent() &&
1397*da58b97aSjoerg          "BB must be in a Function when alignment not provided!");
1398*da58b97aSjoerg   const DataLayout &DL = BB->getModule()->getDataLayout();
1399*da58b97aSjoerg   return DL.getABITypeAlign(Ty);
1400*da58b97aSjoerg }
1401*da58b97aSjoerg 
computeLoadStoreDefaultAlign(Type * Ty,Instruction * I)1402*da58b97aSjoerg static Align computeLoadStoreDefaultAlign(Type *Ty, Instruction *I) {
1403*da58b97aSjoerg   assert(I && "Insertion position cannot be null when alignment not provided!");
1404*da58b97aSjoerg   return computeLoadStoreDefaultAlign(Ty, I->getParent());
1405*da58b97aSjoerg }
1406*da58b97aSjoerg 
LoadInst(Type * Ty,Value * Ptr,const Twine & Name,Instruction * InsertBef)140706f32e7eSjoerg LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name,
140806f32e7eSjoerg                    Instruction *InsertBef)
140906f32e7eSjoerg     : LoadInst(Ty, Ptr, Name, /*isVolatile=*/false, InsertBef) {}
141006f32e7eSjoerg 
LoadInst(Type * Ty,Value * Ptr,const Twine & Name,BasicBlock * InsertAE)141106f32e7eSjoerg LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name,
141206f32e7eSjoerg                    BasicBlock *InsertAE)
141306f32e7eSjoerg     : LoadInst(Ty, Ptr, Name, /*isVolatile=*/false, InsertAE) {}
141406f32e7eSjoerg 
LoadInst(Type * Ty,Value * Ptr,const Twine & Name,bool isVolatile,Instruction * InsertBef)141506f32e7eSjoerg LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile,
141606f32e7eSjoerg                    Instruction *InsertBef)
1417*da58b97aSjoerg     : LoadInst(Ty, Ptr, Name, isVolatile,
1418*da58b97aSjoerg                computeLoadStoreDefaultAlign(Ty, InsertBef), InsertBef) {}
141906f32e7eSjoerg 
LoadInst(Type * Ty,Value * Ptr,const Twine & Name,bool isVolatile,BasicBlock * InsertAE)142006f32e7eSjoerg LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile,
142106f32e7eSjoerg                    BasicBlock *InsertAE)
1422*da58b97aSjoerg     : LoadInst(Ty, Ptr, Name, isVolatile,
1423*da58b97aSjoerg                computeLoadStoreDefaultAlign(Ty, InsertAE), InsertAE) {}
142406f32e7eSjoerg 
LoadInst(Type * Ty,Value * Ptr,const Twine & Name,bool isVolatile,Align Align,Instruction * InsertBef)142506f32e7eSjoerg LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile,
1426*da58b97aSjoerg                    Align Align, Instruction *InsertBef)
142706f32e7eSjoerg     : LoadInst(Ty, Ptr, Name, isVolatile, Align, AtomicOrdering::NotAtomic,
142806f32e7eSjoerg                SyncScope::System, InsertBef) {}
142906f32e7eSjoerg 
LoadInst(Type * Ty,Value * Ptr,const Twine & Name,bool isVolatile,Align Align,BasicBlock * InsertAE)143006f32e7eSjoerg LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile,
1431*da58b97aSjoerg                    Align Align, BasicBlock *InsertAE)
143206f32e7eSjoerg     : LoadInst(Ty, Ptr, Name, isVolatile, Align, AtomicOrdering::NotAtomic,
143306f32e7eSjoerg                SyncScope::System, InsertAE) {}
143406f32e7eSjoerg 
LoadInst(Type * Ty,Value * Ptr,const Twine & Name,bool isVolatile,Align Align,AtomicOrdering Order,SyncScope::ID SSID,Instruction * InsertBef)143506f32e7eSjoerg LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile,
1436*da58b97aSjoerg                    Align Align, AtomicOrdering Order, SyncScope::ID SSID,
143706f32e7eSjoerg                    Instruction *InsertBef)
143806f32e7eSjoerg     : UnaryInstruction(Ty, Load, Ptr, InsertBef) {
1439*da58b97aSjoerg   assert(cast<PointerType>(Ptr->getType())->isOpaqueOrPointeeTypeMatches(Ty));
144006f32e7eSjoerg   setVolatile(isVolatile);
144106f32e7eSjoerg   setAlignment(Align);
144206f32e7eSjoerg   setAtomic(Order, SSID);
144306f32e7eSjoerg   AssertOK();
144406f32e7eSjoerg   setName(Name);
144506f32e7eSjoerg }
144606f32e7eSjoerg 
LoadInst(Type * Ty,Value * Ptr,const Twine & Name,bool isVolatile,Align Align,AtomicOrdering Order,SyncScope::ID SSID,BasicBlock * InsertAE)1447*da58b97aSjoerg LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile,
1448*da58b97aSjoerg                    Align Align, AtomicOrdering Order, SyncScope::ID SSID,
1449*da58b97aSjoerg                    BasicBlock *InsertAE)
1450*da58b97aSjoerg     : UnaryInstruction(Ty, Load, Ptr, InsertAE) {
1451*da58b97aSjoerg   assert(cast<PointerType>(Ptr->getType())->isOpaqueOrPointeeTypeMatches(Ty));
1452*da58b97aSjoerg   setVolatile(isVolatile);
1453*da58b97aSjoerg   setAlignment(Align);
1454*da58b97aSjoerg   setAtomic(Order, SSID);
1455*da58b97aSjoerg   AssertOK();
1456*da58b97aSjoerg   setName(Name);
145706f32e7eSjoerg }
145806f32e7eSjoerg 
145906f32e7eSjoerg //===----------------------------------------------------------------------===//
146006f32e7eSjoerg //                           StoreInst Implementation
146106f32e7eSjoerg //===----------------------------------------------------------------------===//
146206f32e7eSjoerg 
AssertOK()146306f32e7eSjoerg void StoreInst::AssertOK() {
146406f32e7eSjoerg   assert(getOperand(0) && getOperand(1) && "Both operands must be non-null!");
146506f32e7eSjoerg   assert(getOperand(1)->getType()->isPointerTy() &&
146606f32e7eSjoerg          "Ptr must have pointer type!");
1467*da58b97aSjoerg   assert(cast<PointerType>(getOperand(1)->getType())
1468*da58b97aSjoerg              ->isOpaqueOrPointeeTypeMatches(getOperand(0)->getType()) &&
1469*da58b97aSjoerg          "Ptr must be a pointer to Val type!");
147006f32e7eSjoerg   assert(!(isAtomic() && getAlignment() == 0) &&
147106f32e7eSjoerg          "Alignment required for atomic store");
147206f32e7eSjoerg }
147306f32e7eSjoerg 
StoreInst(Value * val,Value * addr,Instruction * InsertBefore)147406f32e7eSjoerg StoreInst::StoreInst(Value *val, Value *addr, Instruction *InsertBefore)
147506f32e7eSjoerg     : StoreInst(val, addr, /*isVolatile=*/false, InsertBefore) {}
147606f32e7eSjoerg 
StoreInst(Value * val,Value * addr,BasicBlock * InsertAtEnd)147706f32e7eSjoerg StoreInst::StoreInst(Value *val, Value *addr, BasicBlock *InsertAtEnd)
147806f32e7eSjoerg     : StoreInst(val, addr, /*isVolatile=*/false, InsertAtEnd) {}
147906f32e7eSjoerg 
StoreInst(Value * val,Value * addr,bool isVolatile,Instruction * InsertBefore)148006f32e7eSjoerg StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
148106f32e7eSjoerg                      Instruction *InsertBefore)
1482*da58b97aSjoerg     : StoreInst(val, addr, isVolatile,
1483*da58b97aSjoerg                 computeLoadStoreDefaultAlign(val->getType(), InsertBefore),
1484*da58b97aSjoerg                 InsertBefore) {}
148506f32e7eSjoerg 
StoreInst(Value * val,Value * addr,bool isVolatile,BasicBlock * InsertAtEnd)148606f32e7eSjoerg StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
148706f32e7eSjoerg                      BasicBlock *InsertAtEnd)
1488*da58b97aSjoerg     : StoreInst(val, addr, isVolatile,
1489*da58b97aSjoerg                 computeLoadStoreDefaultAlign(val->getType(), InsertAtEnd),
1490*da58b97aSjoerg                 InsertAtEnd) {}
149106f32e7eSjoerg 
StoreInst(Value * val,Value * addr,bool isVolatile,Align Align,Instruction * InsertBefore)1492*da58b97aSjoerg StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile, Align Align,
149306f32e7eSjoerg                      Instruction *InsertBefore)
149406f32e7eSjoerg     : StoreInst(val, addr, isVolatile, Align, AtomicOrdering::NotAtomic,
149506f32e7eSjoerg                 SyncScope::System, InsertBefore) {}
149606f32e7eSjoerg 
StoreInst(Value * val,Value * addr,bool isVolatile,Align Align,BasicBlock * InsertAtEnd)1497*da58b97aSjoerg StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile, Align Align,
149806f32e7eSjoerg                      BasicBlock *InsertAtEnd)
149906f32e7eSjoerg     : StoreInst(val, addr, isVolatile, Align, AtomicOrdering::NotAtomic,
150006f32e7eSjoerg                 SyncScope::System, InsertAtEnd) {}
150106f32e7eSjoerg 
StoreInst(Value * val,Value * addr,bool isVolatile,Align Align,AtomicOrdering Order,SyncScope::ID SSID,Instruction * InsertBefore)1502*da58b97aSjoerg StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile, Align Align,
150306f32e7eSjoerg                      AtomicOrdering Order, SyncScope::ID SSID,
150406f32e7eSjoerg                      Instruction *InsertBefore)
150506f32e7eSjoerg     : Instruction(Type::getVoidTy(val->getContext()), Store,
150606f32e7eSjoerg                   OperandTraits<StoreInst>::op_begin(this),
150706f32e7eSjoerg                   OperandTraits<StoreInst>::operands(this), InsertBefore) {
150806f32e7eSjoerg   Op<0>() = val;
150906f32e7eSjoerg   Op<1>() = addr;
151006f32e7eSjoerg   setVolatile(isVolatile);
151106f32e7eSjoerg   setAlignment(Align);
151206f32e7eSjoerg   setAtomic(Order, SSID);
151306f32e7eSjoerg   AssertOK();
151406f32e7eSjoerg }
151506f32e7eSjoerg 
StoreInst(Value * val,Value * addr,bool isVolatile,Align Align,AtomicOrdering Order,SyncScope::ID SSID,BasicBlock * InsertAtEnd)1516*da58b97aSjoerg StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile, Align Align,
151706f32e7eSjoerg                      AtomicOrdering Order, SyncScope::ID SSID,
151806f32e7eSjoerg                      BasicBlock *InsertAtEnd)
151906f32e7eSjoerg     : Instruction(Type::getVoidTy(val->getContext()), Store,
152006f32e7eSjoerg                   OperandTraits<StoreInst>::op_begin(this),
152106f32e7eSjoerg                   OperandTraits<StoreInst>::operands(this), InsertAtEnd) {
152206f32e7eSjoerg   Op<0>() = val;
152306f32e7eSjoerg   Op<1>() = addr;
152406f32e7eSjoerg   setVolatile(isVolatile);
152506f32e7eSjoerg   setAlignment(Align);
152606f32e7eSjoerg   setAtomic(Order, SSID);
152706f32e7eSjoerg   AssertOK();
152806f32e7eSjoerg }
152906f32e7eSjoerg 
153006f32e7eSjoerg 
153106f32e7eSjoerg //===----------------------------------------------------------------------===//
153206f32e7eSjoerg //                       AtomicCmpXchgInst Implementation
153306f32e7eSjoerg //===----------------------------------------------------------------------===//
153406f32e7eSjoerg 
Init(Value * Ptr,Value * Cmp,Value * NewVal,Align Alignment,AtomicOrdering SuccessOrdering,AtomicOrdering FailureOrdering,SyncScope::ID SSID)153506f32e7eSjoerg void AtomicCmpXchgInst::Init(Value *Ptr, Value *Cmp, Value *NewVal,
1536*da58b97aSjoerg                              Align Alignment, AtomicOrdering SuccessOrdering,
153706f32e7eSjoerg                              AtomicOrdering FailureOrdering,
153806f32e7eSjoerg                              SyncScope::ID SSID) {
153906f32e7eSjoerg   Op<0>() = Ptr;
154006f32e7eSjoerg   Op<1>() = Cmp;
154106f32e7eSjoerg   Op<2>() = NewVal;
154206f32e7eSjoerg   setSuccessOrdering(SuccessOrdering);
154306f32e7eSjoerg   setFailureOrdering(FailureOrdering);
154406f32e7eSjoerg   setSyncScopeID(SSID);
1545*da58b97aSjoerg   setAlignment(Alignment);
154606f32e7eSjoerg 
154706f32e7eSjoerg   assert(getOperand(0) && getOperand(1) && getOperand(2) &&
154806f32e7eSjoerg          "All operands must be non-null!");
154906f32e7eSjoerg   assert(getOperand(0)->getType()->isPointerTy() &&
155006f32e7eSjoerg          "Ptr must have pointer type!");
1551*da58b97aSjoerg   assert(cast<PointerType>(getOperand(0)->getType())
1552*da58b97aSjoerg              ->isOpaqueOrPointeeTypeMatches(getOperand(1)->getType()) &&
1553*da58b97aSjoerg          "Ptr must be a pointer to Cmp type!");
1554*da58b97aSjoerg   assert(cast<PointerType>(getOperand(0)->getType())
1555*da58b97aSjoerg              ->isOpaqueOrPointeeTypeMatches(getOperand(2)->getType()) &&
1556*da58b97aSjoerg          "Ptr must be a pointer to NewVal type!");
1557*da58b97aSjoerg   assert(getOperand(1)->getType() == getOperand(2)->getType() &&
1558*da58b97aSjoerg          "Cmp type and NewVal type must be same!");
155906f32e7eSjoerg }
156006f32e7eSjoerg 
AtomicCmpXchgInst(Value * Ptr,Value * Cmp,Value * NewVal,Align Alignment,AtomicOrdering SuccessOrdering,AtomicOrdering FailureOrdering,SyncScope::ID SSID,Instruction * InsertBefore)156106f32e7eSjoerg AtomicCmpXchgInst::AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal,
1562*da58b97aSjoerg                                      Align Alignment,
156306f32e7eSjoerg                                      AtomicOrdering SuccessOrdering,
156406f32e7eSjoerg                                      AtomicOrdering FailureOrdering,
156506f32e7eSjoerg                                      SyncScope::ID SSID,
156606f32e7eSjoerg                                      Instruction *InsertBefore)
156706f32e7eSjoerg     : Instruction(
156806f32e7eSjoerg           StructType::get(Cmp->getType(), Type::getInt1Ty(Cmp->getContext())),
156906f32e7eSjoerg           AtomicCmpXchg, OperandTraits<AtomicCmpXchgInst>::op_begin(this),
157006f32e7eSjoerg           OperandTraits<AtomicCmpXchgInst>::operands(this), InsertBefore) {
1571*da58b97aSjoerg   Init(Ptr, Cmp, NewVal, Alignment, SuccessOrdering, FailureOrdering, SSID);
157206f32e7eSjoerg }
157306f32e7eSjoerg 
AtomicCmpXchgInst(Value * Ptr,Value * Cmp,Value * NewVal,Align Alignment,AtomicOrdering SuccessOrdering,AtomicOrdering FailureOrdering,SyncScope::ID SSID,BasicBlock * InsertAtEnd)157406f32e7eSjoerg AtomicCmpXchgInst::AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal,
1575*da58b97aSjoerg                                      Align Alignment,
157606f32e7eSjoerg                                      AtomicOrdering SuccessOrdering,
157706f32e7eSjoerg                                      AtomicOrdering FailureOrdering,
157806f32e7eSjoerg                                      SyncScope::ID SSID,
157906f32e7eSjoerg                                      BasicBlock *InsertAtEnd)
158006f32e7eSjoerg     : Instruction(
158106f32e7eSjoerg           StructType::get(Cmp->getType(), Type::getInt1Ty(Cmp->getContext())),
158206f32e7eSjoerg           AtomicCmpXchg, OperandTraits<AtomicCmpXchgInst>::op_begin(this),
158306f32e7eSjoerg           OperandTraits<AtomicCmpXchgInst>::operands(this), InsertAtEnd) {
1584*da58b97aSjoerg   Init(Ptr, Cmp, NewVal, Alignment, SuccessOrdering, FailureOrdering, SSID);
158506f32e7eSjoerg }
158606f32e7eSjoerg 
158706f32e7eSjoerg //===----------------------------------------------------------------------===//
158806f32e7eSjoerg //                       AtomicRMWInst Implementation
158906f32e7eSjoerg //===----------------------------------------------------------------------===//
159006f32e7eSjoerg 
Init(BinOp Operation,Value * Ptr,Value * Val,Align Alignment,AtomicOrdering Ordering,SyncScope::ID SSID)159106f32e7eSjoerg void AtomicRMWInst::Init(BinOp Operation, Value *Ptr, Value *Val,
1592*da58b97aSjoerg                          Align Alignment, AtomicOrdering Ordering,
159306f32e7eSjoerg                          SyncScope::ID SSID) {
159406f32e7eSjoerg   Op<0>() = Ptr;
159506f32e7eSjoerg   Op<1>() = Val;
159606f32e7eSjoerg   setOperation(Operation);
159706f32e7eSjoerg   setOrdering(Ordering);
159806f32e7eSjoerg   setSyncScopeID(SSID);
1599*da58b97aSjoerg   setAlignment(Alignment);
160006f32e7eSjoerg 
160106f32e7eSjoerg   assert(getOperand(0) && getOperand(1) &&
160206f32e7eSjoerg          "All operands must be non-null!");
160306f32e7eSjoerg   assert(getOperand(0)->getType()->isPointerTy() &&
160406f32e7eSjoerg          "Ptr must have pointer type!");
1605*da58b97aSjoerg   assert(cast<PointerType>(getOperand(0)->getType())
1606*da58b97aSjoerg              ->isOpaqueOrPointeeTypeMatches(getOperand(1)->getType()) &&
1607*da58b97aSjoerg          "Ptr must be a pointer to Val type!");
160806f32e7eSjoerg   assert(Ordering != AtomicOrdering::NotAtomic &&
160906f32e7eSjoerg          "AtomicRMW instructions must be atomic!");
161006f32e7eSjoerg }
161106f32e7eSjoerg 
AtomicRMWInst(BinOp Operation,Value * Ptr,Value * Val,Align Alignment,AtomicOrdering Ordering,SyncScope::ID SSID,Instruction * InsertBefore)161206f32e7eSjoerg AtomicRMWInst::AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val,
1613*da58b97aSjoerg                              Align Alignment, AtomicOrdering Ordering,
1614*da58b97aSjoerg                              SyncScope::ID SSID, Instruction *InsertBefore)
161506f32e7eSjoerg     : Instruction(Val->getType(), AtomicRMW,
161606f32e7eSjoerg                   OperandTraits<AtomicRMWInst>::op_begin(this),
1617*da58b97aSjoerg                   OperandTraits<AtomicRMWInst>::operands(this), InsertBefore) {
1618*da58b97aSjoerg   Init(Operation, Ptr, Val, Alignment, Ordering, SSID);
161906f32e7eSjoerg }
162006f32e7eSjoerg 
AtomicRMWInst(BinOp Operation,Value * Ptr,Value * Val,Align Alignment,AtomicOrdering Ordering,SyncScope::ID SSID,BasicBlock * InsertAtEnd)162106f32e7eSjoerg AtomicRMWInst::AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val,
1622*da58b97aSjoerg                              Align Alignment, AtomicOrdering Ordering,
1623*da58b97aSjoerg                              SyncScope::ID SSID, BasicBlock *InsertAtEnd)
162406f32e7eSjoerg     : Instruction(Val->getType(), AtomicRMW,
162506f32e7eSjoerg                   OperandTraits<AtomicRMWInst>::op_begin(this),
1626*da58b97aSjoerg                   OperandTraits<AtomicRMWInst>::operands(this), InsertAtEnd) {
1627*da58b97aSjoerg   Init(Operation, Ptr, Val, Alignment, Ordering, SSID);
162806f32e7eSjoerg }
162906f32e7eSjoerg 
getOperationName(BinOp Op)163006f32e7eSjoerg StringRef AtomicRMWInst::getOperationName(BinOp Op) {
163106f32e7eSjoerg   switch (Op) {
163206f32e7eSjoerg   case AtomicRMWInst::Xchg:
163306f32e7eSjoerg     return "xchg";
163406f32e7eSjoerg   case AtomicRMWInst::Add:
163506f32e7eSjoerg     return "add";
163606f32e7eSjoerg   case AtomicRMWInst::Sub:
163706f32e7eSjoerg     return "sub";
163806f32e7eSjoerg   case AtomicRMWInst::And:
163906f32e7eSjoerg     return "and";
164006f32e7eSjoerg   case AtomicRMWInst::Nand:
164106f32e7eSjoerg     return "nand";
164206f32e7eSjoerg   case AtomicRMWInst::Or:
164306f32e7eSjoerg     return "or";
164406f32e7eSjoerg   case AtomicRMWInst::Xor:
164506f32e7eSjoerg     return "xor";
164606f32e7eSjoerg   case AtomicRMWInst::Max:
164706f32e7eSjoerg     return "max";
164806f32e7eSjoerg   case AtomicRMWInst::Min:
164906f32e7eSjoerg     return "min";
165006f32e7eSjoerg   case AtomicRMWInst::UMax:
165106f32e7eSjoerg     return "umax";
165206f32e7eSjoerg   case AtomicRMWInst::UMin:
165306f32e7eSjoerg     return "umin";
165406f32e7eSjoerg   case AtomicRMWInst::FAdd:
165506f32e7eSjoerg     return "fadd";
165606f32e7eSjoerg   case AtomicRMWInst::FSub:
165706f32e7eSjoerg     return "fsub";
165806f32e7eSjoerg   case AtomicRMWInst::BAD_BINOP:
165906f32e7eSjoerg     return "<invalid operation>";
166006f32e7eSjoerg   }
166106f32e7eSjoerg 
166206f32e7eSjoerg   llvm_unreachable("invalid atomicrmw operation");
166306f32e7eSjoerg }
166406f32e7eSjoerg 
166506f32e7eSjoerg //===----------------------------------------------------------------------===//
166606f32e7eSjoerg //                       FenceInst Implementation
166706f32e7eSjoerg //===----------------------------------------------------------------------===//
166806f32e7eSjoerg 
FenceInst(LLVMContext & C,AtomicOrdering Ordering,SyncScope::ID SSID,Instruction * InsertBefore)166906f32e7eSjoerg FenceInst::FenceInst(LLVMContext &C, AtomicOrdering Ordering,
167006f32e7eSjoerg                      SyncScope::ID SSID,
167106f32e7eSjoerg                      Instruction *InsertBefore)
167206f32e7eSjoerg   : Instruction(Type::getVoidTy(C), Fence, nullptr, 0, InsertBefore) {
167306f32e7eSjoerg   setOrdering(Ordering);
167406f32e7eSjoerg   setSyncScopeID(SSID);
167506f32e7eSjoerg }
167606f32e7eSjoerg 
FenceInst(LLVMContext & C,AtomicOrdering Ordering,SyncScope::ID SSID,BasicBlock * InsertAtEnd)167706f32e7eSjoerg FenceInst::FenceInst(LLVMContext &C, AtomicOrdering Ordering,
167806f32e7eSjoerg                      SyncScope::ID SSID,
167906f32e7eSjoerg                      BasicBlock *InsertAtEnd)
168006f32e7eSjoerg   : Instruction(Type::getVoidTy(C), Fence, nullptr, 0, InsertAtEnd) {
168106f32e7eSjoerg   setOrdering(Ordering);
168206f32e7eSjoerg   setSyncScopeID(SSID);
168306f32e7eSjoerg }
168406f32e7eSjoerg 
168506f32e7eSjoerg //===----------------------------------------------------------------------===//
168606f32e7eSjoerg //                       GetElementPtrInst Implementation
168706f32e7eSjoerg //===----------------------------------------------------------------------===//
168806f32e7eSjoerg 
init(Value * Ptr,ArrayRef<Value * > IdxList,const Twine & Name)168906f32e7eSjoerg void GetElementPtrInst::init(Value *Ptr, ArrayRef<Value *> IdxList,
169006f32e7eSjoerg                              const Twine &Name) {
169106f32e7eSjoerg   assert(getNumOperands() == 1 + IdxList.size() &&
169206f32e7eSjoerg          "NumOperands not initialized?");
169306f32e7eSjoerg   Op<0>() = Ptr;
169406f32e7eSjoerg   llvm::copy(IdxList, op_begin() + 1);
169506f32e7eSjoerg   setName(Name);
169606f32e7eSjoerg }
169706f32e7eSjoerg 
GetElementPtrInst(const GetElementPtrInst & GEPI)169806f32e7eSjoerg GetElementPtrInst::GetElementPtrInst(const GetElementPtrInst &GEPI)
169906f32e7eSjoerg     : Instruction(GEPI.getType(), GetElementPtr,
170006f32e7eSjoerg                   OperandTraits<GetElementPtrInst>::op_end(this) -
170106f32e7eSjoerg                       GEPI.getNumOperands(),
170206f32e7eSjoerg                   GEPI.getNumOperands()),
170306f32e7eSjoerg       SourceElementType(GEPI.SourceElementType),
170406f32e7eSjoerg       ResultElementType(GEPI.ResultElementType) {
170506f32e7eSjoerg   std::copy(GEPI.op_begin(), GEPI.op_end(), op_begin());
170606f32e7eSjoerg   SubclassOptionalData = GEPI.SubclassOptionalData;
170706f32e7eSjoerg }
170806f32e7eSjoerg 
getTypeAtIndex(Type * Ty,Value * Idx)1709*da58b97aSjoerg Type *GetElementPtrInst::getTypeAtIndex(Type *Ty, Value *Idx) {
1710*da58b97aSjoerg   if (auto *Struct = dyn_cast<StructType>(Ty)) {
1711*da58b97aSjoerg     if (!Struct->indexValid(Idx))
171206f32e7eSjoerg       return nullptr;
1713*da58b97aSjoerg     return Struct->getTypeAtIndex(Idx);
171406f32e7eSjoerg   }
1715*da58b97aSjoerg   if (!Idx->getType()->isIntOrIntVectorTy())
1716*da58b97aSjoerg     return nullptr;
1717*da58b97aSjoerg   if (auto *Array = dyn_cast<ArrayType>(Ty))
1718*da58b97aSjoerg     return Array->getElementType();
1719*da58b97aSjoerg   if (auto *Vector = dyn_cast<VectorType>(Ty))
1720*da58b97aSjoerg     return Vector->getElementType();
1721*da58b97aSjoerg   return nullptr;
1722*da58b97aSjoerg }
1723*da58b97aSjoerg 
getTypeAtIndex(Type * Ty,uint64_t Idx)1724*da58b97aSjoerg Type *GetElementPtrInst::getTypeAtIndex(Type *Ty, uint64_t Idx) {
1725*da58b97aSjoerg   if (auto *Struct = dyn_cast<StructType>(Ty)) {
1726*da58b97aSjoerg     if (Idx >= Struct->getNumElements())
1727*da58b97aSjoerg       return nullptr;
1728*da58b97aSjoerg     return Struct->getElementType(Idx);
1729*da58b97aSjoerg   }
1730*da58b97aSjoerg   if (auto *Array = dyn_cast<ArrayType>(Ty))
1731*da58b97aSjoerg     return Array->getElementType();
1732*da58b97aSjoerg   if (auto *Vector = dyn_cast<VectorType>(Ty))
1733*da58b97aSjoerg     return Vector->getElementType();
1734*da58b97aSjoerg   return nullptr;
1735*da58b97aSjoerg }
1736*da58b97aSjoerg 
1737*da58b97aSjoerg template <typename IndexTy>
getIndexedTypeInternal(Type * Ty,ArrayRef<IndexTy> IdxList)1738*da58b97aSjoerg static Type *getIndexedTypeInternal(Type *Ty, ArrayRef<IndexTy> IdxList) {
1739*da58b97aSjoerg   if (IdxList.empty())
1740*da58b97aSjoerg     return Ty;
1741*da58b97aSjoerg   for (IndexTy V : IdxList.slice(1)) {
1742*da58b97aSjoerg     Ty = GetElementPtrInst::getTypeAtIndex(Ty, V);
1743*da58b97aSjoerg     if (!Ty)
1744*da58b97aSjoerg       return Ty;
1745*da58b97aSjoerg   }
1746*da58b97aSjoerg   return Ty;
174706f32e7eSjoerg }
174806f32e7eSjoerg 
getIndexedType(Type * Ty,ArrayRef<Value * > IdxList)174906f32e7eSjoerg Type *GetElementPtrInst::getIndexedType(Type *Ty, ArrayRef<Value *> IdxList) {
175006f32e7eSjoerg   return getIndexedTypeInternal(Ty, IdxList);
175106f32e7eSjoerg }
175206f32e7eSjoerg 
getIndexedType(Type * Ty,ArrayRef<Constant * > IdxList)175306f32e7eSjoerg Type *GetElementPtrInst::getIndexedType(Type *Ty,
175406f32e7eSjoerg                                         ArrayRef<Constant *> IdxList) {
175506f32e7eSjoerg   return getIndexedTypeInternal(Ty, IdxList);
175606f32e7eSjoerg }
175706f32e7eSjoerg 
getIndexedType(Type * Ty,ArrayRef<uint64_t> IdxList)175806f32e7eSjoerg Type *GetElementPtrInst::getIndexedType(Type *Ty, ArrayRef<uint64_t> IdxList) {
175906f32e7eSjoerg   return getIndexedTypeInternal(Ty, IdxList);
176006f32e7eSjoerg }
176106f32e7eSjoerg 
176206f32e7eSjoerg /// hasAllZeroIndices - Return true if all of the indices of this GEP are
176306f32e7eSjoerg /// zeros.  If so, the result pointer and the first operand have the same
176406f32e7eSjoerg /// value, just potentially different types.
hasAllZeroIndices() const176506f32e7eSjoerg bool GetElementPtrInst::hasAllZeroIndices() const {
176606f32e7eSjoerg   for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
176706f32e7eSjoerg     if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(i))) {
176806f32e7eSjoerg       if (!CI->isZero()) return false;
176906f32e7eSjoerg     } else {
177006f32e7eSjoerg       return false;
177106f32e7eSjoerg     }
177206f32e7eSjoerg   }
177306f32e7eSjoerg   return true;
177406f32e7eSjoerg }
177506f32e7eSjoerg 
177606f32e7eSjoerg /// hasAllConstantIndices - Return true if all of the indices of this GEP are
177706f32e7eSjoerg /// constant integers.  If so, the result pointer and the first operand have
177806f32e7eSjoerg /// a constant offset between them.
hasAllConstantIndices() const177906f32e7eSjoerg bool GetElementPtrInst::hasAllConstantIndices() const {
178006f32e7eSjoerg   for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
178106f32e7eSjoerg     if (!isa<ConstantInt>(getOperand(i)))
178206f32e7eSjoerg       return false;
178306f32e7eSjoerg   }
178406f32e7eSjoerg   return true;
178506f32e7eSjoerg }
178606f32e7eSjoerg 
setIsInBounds(bool B)178706f32e7eSjoerg void GetElementPtrInst::setIsInBounds(bool B) {
178806f32e7eSjoerg   cast<GEPOperator>(this)->setIsInBounds(B);
178906f32e7eSjoerg }
179006f32e7eSjoerg 
isInBounds() const179106f32e7eSjoerg bool GetElementPtrInst::isInBounds() const {
179206f32e7eSjoerg   return cast<GEPOperator>(this)->isInBounds();
179306f32e7eSjoerg }
179406f32e7eSjoerg 
accumulateConstantOffset(const DataLayout & DL,APInt & Offset) const179506f32e7eSjoerg bool GetElementPtrInst::accumulateConstantOffset(const DataLayout &DL,
179606f32e7eSjoerg                                                  APInt &Offset) const {
179706f32e7eSjoerg   // Delegate to the generic GEPOperator implementation.
179806f32e7eSjoerg   return cast<GEPOperator>(this)->accumulateConstantOffset(DL, Offset);
179906f32e7eSjoerg }
180006f32e7eSjoerg 
collectOffset(const DataLayout & DL,unsigned BitWidth,SmallDenseMap<Value *,APInt,8> & VariableOffsets,APInt & ConstantOffset) const1801*da58b97aSjoerg bool GetElementPtrInst::collectOffset(
1802*da58b97aSjoerg     const DataLayout &DL, unsigned BitWidth,
1803*da58b97aSjoerg     SmallDenseMap<Value *, APInt, 8> &VariableOffsets,
1804*da58b97aSjoerg     APInt &ConstantOffset) const {
1805*da58b97aSjoerg   // Delegate to the generic GEPOperator implementation.
1806*da58b97aSjoerg   return cast<GEPOperator>(this)->collectOffset(DL, BitWidth, VariableOffsets,
1807*da58b97aSjoerg                                                 ConstantOffset);
1808*da58b97aSjoerg }
1809*da58b97aSjoerg 
181006f32e7eSjoerg //===----------------------------------------------------------------------===//
181106f32e7eSjoerg //                           ExtractElementInst Implementation
181206f32e7eSjoerg //===----------------------------------------------------------------------===//
181306f32e7eSjoerg 
ExtractElementInst(Value * Val,Value * Index,const Twine & Name,Instruction * InsertBef)181406f32e7eSjoerg ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
181506f32e7eSjoerg                                        const Twine &Name,
181606f32e7eSjoerg                                        Instruction *InsertBef)
181706f32e7eSjoerg   : Instruction(cast<VectorType>(Val->getType())->getElementType(),
181806f32e7eSjoerg                 ExtractElement,
181906f32e7eSjoerg                 OperandTraits<ExtractElementInst>::op_begin(this),
182006f32e7eSjoerg                 2, InsertBef) {
182106f32e7eSjoerg   assert(isValidOperands(Val, Index) &&
182206f32e7eSjoerg          "Invalid extractelement instruction operands!");
182306f32e7eSjoerg   Op<0>() = Val;
182406f32e7eSjoerg   Op<1>() = Index;
182506f32e7eSjoerg   setName(Name);
182606f32e7eSjoerg }
182706f32e7eSjoerg 
ExtractElementInst(Value * Val,Value * Index,const Twine & Name,BasicBlock * InsertAE)182806f32e7eSjoerg ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
182906f32e7eSjoerg                                        const Twine &Name,
183006f32e7eSjoerg                                        BasicBlock *InsertAE)
183106f32e7eSjoerg   : Instruction(cast<VectorType>(Val->getType())->getElementType(),
183206f32e7eSjoerg                 ExtractElement,
183306f32e7eSjoerg                 OperandTraits<ExtractElementInst>::op_begin(this),
183406f32e7eSjoerg                 2, InsertAE) {
183506f32e7eSjoerg   assert(isValidOperands(Val, Index) &&
183606f32e7eSjoerg          "Invalid extractelement instruction operands!");
183706f32e7eSjoerg 
183806f32e7eSjoerg   Op<0>() = Val;
183906f32e7eSjoerg   Op<1>() = Index;
184006f32e7eSjoerg   setName(Name);
184106f32e7eSjoerg }
184206f32e7eSjoerg 
isValidOperands(const Value * Val,const Value * Index)184306f32e7eSjoerg bool ExtractElementInst::isValidOperands(const Value *Val, const Value *Index) {
184406f32e7eSjoerg   if (!Val->getType()->isVectorTy() || !Index->getType()->isIntegerTy())
184506f32e7eSjoerg     return false;
184606f32e7eSjoerg   return true;
184706f32e7eSjoerg }
184806f32e7eSjoerg 
184906f32e7eSjoerg //===----------------------------------------------------------------------===//
185006f32e7eSjoerg //                           InsertElementInst Implementation
185106f32e7eSjoerg //===----------------------------------------------------------------------===//
185206f32e7eSjoerg 
InsertElementInst(Value * Vec,Value * Elt,Value * Index,const Twine & Name,Instruction * InsertBef)185306f32e7eSjoerg InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
185406f32e7eSjoerg                                      const Twine &Name,
185506f32e7eSjoerg                                      Instruction *InsertBef)
185606f32e7eSjoerg   : Instruction(Vec->getType(), InsertElement,
185706f32e7eSjoerg                 OperandTraits<InsertElementInst>::op_begin(this),
185806f32e7eSjoerg                 3, InsertBef) {
185906f32e7eSjoerg   assert(isValidOperands(Vec, Elt, Index) &&
186006f32e7eSjoerg          "Invalid insertelement instruction operands!");
186106f32e7eSjoerg   Op<0>() = Vec;
186206f32e7eSjoerg   Op<1>() = Elt;
186306f32e7eSjoerg   Op<2>() = Index;
186406f32e7eSjoerg   setName(Name);
186506f32e7eSjoerg }
186606f32e7eSjoerg 
InsertElementInst(Value * Vec,Value * Elt,Value * Index,const Twine & Name,BasicBlock * InsertAE)186706f32e7eSjoerg InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
186806f32e7eSjoerg                                      const Twine &Name,
186906f32e7eSjoerg                                      BasicBlock *InsertAE)
187006f32e7eSjoerg   : Instruction(Vec->getType(), InsertElement,
187106f32e7eSjoerg                 OperandTraits<InsertElementInst>::op_begin(this),
187206f32e7eSjoerg                 3, InsertAE) {
187306f32e7eSjoerg   assert(isValidOperands(Vec, Elt, Index) &&
187406f32e7eSjoerg          "Invalid insertelement instruction operands!");
187506f32e7eSjoerg 
187606f32e7eSjoerg   Op<0>() = Vec;
187706f32e7eSjoerg   Op<1>() = Elt;
187806f32e7eSjoerg   Op<2>() = Index;
187906f32e7eSjoerg   setName(Name);
188006f32e7eSjoerg }
188106f32e7eSjoerg 
isValidOperands(const Value * Vec,const Value * Elt,const Value * Index)188206f32e7eSjoerg bool InsertElementInst::isValidOperands(const Value *Vec, const Value *Elt,
188306f32e7eSjoerg                                         const Value *Index) {
188406f32e7eSjoerg   if (!Vec->getType()->isVectorTy())
188506f32e7eSjoerg     return false;   // First operand of insertelement must be vector type.
188606f32e7eSjoerg 
188706f32e7eSjoerg   if (Elt->getType() != cast<VectorType>(Vec->getType())->getElementType())
188806f32e7eSjoerg     return false;// Second operand of insertelement must be vector element type.
188906f32e7eSjoerg 
189006f32e7eSjoerg   if (!Index->getType()->isIntegerTy())
189106f32e7eSjoerg     return false;  // Third operand of insertelement must be i32.
189206f32e7eSjoerg   return true;
189306f32e7eSjoerg }
189406f32e7eSjoerg 
189506f32e7eSjoerg //===----------------------------------------------------------------------===//
189606f32e7eSjoerg //                      ShuffleVectorInst Implementation
189706f32e7eSjoerg //===----------------------------------------------------------------------===//
189806f32e7eSjoerg 
ShuffleVectorInst(Value * V1,Value * V2,Value * Mask,const Twine & Name,Instruction * InsertBefore)189906f32e7eSjoerg ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
190006f32e7eSjoerg                                      const Twine &Name,
190106f32e7eSjoerg                                      Instruction *InsertBefore)
1902*da58b97aSjoerg     : Instruction(
1903*da58b97aSjoerg           VectorType::get(cast<VectorType>(V1->getType())->getElementType(),
190406f32e7eSjoerg                           cast<VectorType>(Mask->getType())->getElementCount()),
1905*da58b97aSjoerg           ShuffleVector, OperandTraits<ShuffleVectorInst>::op_begin(this),
1906*da58b97aSjoerg           OperandTraits<ShuffleVectorInst>::operands(this), InsertBefore) {
190706f32e7eSjoerg   assert(isValidOperands(V1, V2, Mask) &&
190806f32e7eSjoerg          "Invalid shuffle vector instruction operands!");
1909*da58b97aSjoerg 
191006f32e7eSjoerg   Op<0>() = V1;
191106f32e7eSjoerg   Op<1>() = V2;
1912*da58b97aSjoerg   SmallVector<int, 16> MaskArr;
1913*da58b97aSjoerg   getShuffleMask(cast<Constant>(Mask), MaskArr);
1914*da58b97aSjoerg   setShuffleMask(MaskArr);
191506f32e7eSjoerg   setName(Name);
191606f32e7eSjoerg }
191706f32e7eSjoerg 
ShuffleVectorInst(Value * V1,Value * V2,Value * Mask,const Twine & Name,BasicBlock * InsertAtEnd)191806f32e7eSjoerg ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1919*da58b97aSjoerg                                      const Twine &Name, BasicBlock *InsertAtEnd)
1920*da58b97aSjoerg     : Instruction(
1921*da58b97aSjoerg           VectorType::get(cast<VectorType>(V1->getType())->getElementType(),
192206f32e7eSjoerg                           cast<VectorType>(Mask->getType())->getElementCount()),
1923*da58b97aSjoerg           ShuffleVector, OperandTraits<ShuffleVectorInst>::op_begin(this),
1924*da58b97aSjoerg           OperandTraits<ShuffleVectorInst>::operands(this), InsertAtEnd) {
192506f32e7eSjoerg   assert(isValidOperands(V1, V2, Mask) &&
192606f32e7eSjoerg          "Invalid shuffle vector instruction operands!");
192706f32e7eSjoerg 
192806f32e7eSjoerg   Op<0>() = V1;
192906f32e7eSjoerg   Op<1>() = V2;
1930*da58b97aSjoerg   SmallVector<int, 16> MaskArr;
1931*da58b97aSjoerg   getShuffleMask(cast<Constant>(Mask), MaskArr);
1932*da58b97aSjoerg   setShuffleMask(MaskArr);
1933*da58b97aSjoerg   setName(Name);
1934*da58b97aSjoerg }
1935*da58b97aSjoerg 
ShuffleVectorInst(Value * V1,Value * V2,ArrayRef<int> Mask,const Twine & Name,Instruction * InsertBefore)1936*da58b97aSjoerg ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, ArrayRef<int> Mask,
1937*da58b97aSjoerg                                      const Twine &Name,
1938*da58b97aSjoerg                                      Instruction *InsertBefore)
1939*da58b97aSjoerg     : Instruction(
1940*da58b97aSjoerg           VectorType::get(cast<VectorType>(V1->getType())->getElementType(),
1941*da58b97aSjoerg                           Mask.size(), isa<ScalableVectorType>(V1->getType())),
1942*da58b97aSjoerg           ShuffleVector, OperandTraits<ShuffleVectorInst>::op_begin(this),
1943*da58b97aSjoerg           OperandTraits<ShuffleVectorInst>::operands(this), InsertBefore) {
1944*da58b97aSjoerg   assert(isValidOperands(V1, V2, Mask) &&
1945*da58b97aSjoerg          "Invalid shuffle vector instruction operands!");
1946*da58b97aSjoerg   Op<0>() = V1;
1947*da58b97aSjoerg   Op<1>() = V2;
1948*da58b97aSjoerg   setShuffleMask(Mask);
1949*da58b97aSjoerg   setName(Name);
1950*da58b97aSjoerg }
1951*da58b97aSjoerg 
ShuffleVectorInst(Value * V1,Value * V2,ArrayRef<int> Mask,const Twine & Name,BasicBlock * InsertAtEnd)1952*da58b97aSjoerg ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, ArrayRef<int> Mask,
1953*da58b97aSjoerg                                      const Twine &Name, BasicBlock *InsertAtEnd)
1954*da58b97aSjoerg     : Instruction(
1955*da58b97aSjoerg           VectorType::get(cast<VectorType>(V1->getType())->getElementType(),
1956*da58b97aSjoerg                           Mask.size(), isa<ScalableVectorType>(V1->getType())),
1957*da58b97aSjoerg           ShuffleVector, OperandTraits<ShuffleVectorInst>::op_begin(this),
1958*da58b97aSjoerg           OperandTraits<ShuffleVectorInst>::operands(this), InsertAtEnd) {
1959*da58b97aSjoerg   assert(isValidOperands(V1, V2, Mask) &&
1960*da58b97aSjoerg          "Invalid shuffle vector instruction operands!");
1961*da58b97aSjoerg 
1962*da58b97aSjoerg   Op<0>() = V1;
1963*da58b97aSjoerg   Op<1>() = V2;
1964*da58b97aSjoerg   setShuffleMask(Mask);
196506f32e7eSjoerg   setName(Name);
196606f32e7eSjoerg }
196706f32e7eSjoerg 
commute()196806f32e7eSjoerg void ShuffleVectorInst::commute() {
1969*da58b97aSjoerg   int NumOpElts = cast<FixedVectorType>(Op<0>()->getType())->getNumElements();
1970*da58b97aSjoerg   int NumMaskElts = ShuffleMask.size();
1971*da58b97aSjoerg   SmallVector<int, 16> NewMask(NumMaskElts);
197206f32e7eSjoerg   for (int i = 0; i != NumMaskElts; ++i) {
197306f32e7eSjoerg     int MaskElt = getMaskValue(i);
1974*da58b97aSjoerg     if (MaskElt == UndefMaskElem) {
1975*da58b97aSjoerg       NewMask[i] = UndefMaskElem;
197606f32e7eSjoerg       continue;
197706f32e7eSjoerg     }
197806f32e7eSjoerg     assert(MaskElt >= 0 && MaskElt < 2 * NumOpElts && "Out-of-range mask");
197906f32e7eSjoerg     MaskElt = (MaskElt < NumOpElts) ? MaskElt + NumOpElts : MaskElt - NumOpElts;
1980*da58b97aSjoerg     NewMask[i] = MaskElt;
198106f32e7eSjoerg   }
1982*da58b97aSjoerg   setShuffleMask(NewMask);
198306f32e7eSjoerg   Op<0>().swap(Op<1>());
198406f32e7eSjoerg }
198506f32e7eSjoerg 
isValidOperands(const Value * V1,const Value * V2,ArrayRef<int> Mask)198606f32e7eSjoerg bool ShuffleVectorInst::isValidOperands(const Value *V1, const Value *V2,
1987*da58b97aSjoerg                                         ArrayRef<int> Mask) {
1988*da58b97aSjoerg   // V1 and V2 must be vectors of the same type.
1989*da58b97aSjoerg   if (!isa<VectorType>(V1->getType()) || V1->getType() != V2->getType())
1990*da58b97aSjoerg     return false;
1991*da58b97aSjoerg 
1992*da58b97aSjoerg   // Make sure the mask elements make sense.
1993*da58b97aSjoerg   int V1Size =
1994*da58b97aSjoerg       cast<VectorType>(V1->getType())->getElementCount().getKnownMinValue();
1995*da58b97aSjoerg   for (int Elem : Mask)
1996*da58b97aSjoerg     if (Elem != UndefMaskElem && Elem >= V1Size * 2)
1997*da58b97aSjoerg       return false;
1998*da58b97aSjoerg 
1999*da58b97aSjoerg   if (isa<ScalableVectorType>(V1->getType()))
2000*da58b97aSjoerg     if ((Mask[0] != 0 && Mask[0] != UndefMaskElem) || !is_splat(Mask))
2001*da58b97aSjoerg       return false;
2002*da58b97aSjoerg 
2003*da58b97aSjoerg   return true;
2004*da58b97aSjoerg }
2005*da58b97aSjoerg 
isValidOperands(const Value * V1,const Value * V2,const Value * Mask)2006*da58b97aSjoerg bool ShuffleVectorInst::isValidOperands(const Value *V1, const Value *V2,
200706f32e7eSjoerg                                         const Value *Mask) {
200806f32e7eSjoerg   // V1 and V2 must be vectors of the same type.
200906f32e7eSjoerg   if (!V1->getType()->isVectorTy() || V1->getType() != V2->getType())
201006f32e7eSjoerg     return false;
201106f32e7eSjoerg 
2012*da58b97aSjoerg   // Mask must be vector of i32, and must be the same kind of vector as the
2013*da58b97aSjoerg   // input vectors
201406f32e7eSjoerg   auto *MaskTy = dyn_cast<VectorType>(Mask->getType());
2015*da58b97aSjoerg   if (!MaskTy || !MaskTy->getElementType()->isIntegerTy(32) ||
2016*da58b97aSjoerg       isa<ScalableVectorType>(MaskTy) != isa<ScalableVectorType>(V1->getType()))
201706f32e7eSjoerg     return false;
201806f32e7eSjoerg 
201906f32e7eSjoerg   // Check to see if Mask is valid.
202006f32e7eSjoerg   if (isa<UndefValue>(Mask) || isa<ConstantAggregateZero>(Mask))
202106f32e7eSjoerg     return true;
202206f32e7eSjoerg 
202306f32e7eSjoerg   if (const auto *MV = dyn_cast<ConstantVector>(Mask)) {
2024*da58b97aSjoerg     unsigned V1Size = cast<FixedVectorType>(V1->getType())->getNumElements();
202506f32e7eSjoerg     for (Value *Op : MV->operands()) {
202606f32e7eSjoerg       if (auto *CI = dyn_cast<ConstantInt>(Op)) {
202706f32e7eSjoerg         if (CI->uge(V1Size*2))
202806f32e7eSjoerg           return false;
202906f32e7eSjoerg       } else if (!isa<UndefValue>(Op)) {
203006f32e7eSjoerg         return false;
203106f32e7eSjoerg       }
203206f32e7eSjoerg     }
203306f32e7eSjoerg     return true;
203406f32e7eSjoerg   }
203506f32e7eSjoerg 
203606f32e7eSjoerg   if (const auto *CDS = dyn_cast<ConstantDataSequential>(Mask)) {
2037*da58b97aSjoerg     unsigned V1Size = cast<FixedVectorType>(V1->getType())->getNumElements();
2038*da58b97aSjoerg     for (unsigned i = 0, e = cast<FixedVectorType>(MaskTy)->getNumElements();
2039*da58b97aSjoerg          i != e; ++i)
204006f32e7eSjoerg       if (CDS->getElementAsInteger(i) >= V1Size*2)
204106f32e7eSjoerg         return false;
204206f32e7eSjoerg     return true;
204306f32e7eSjoerg   }
204406f32e7eSjoerg 
204506f32e7eSjoerg   return false;
204606f32e7eSjoerg }
204706f32e7eSjoerg 
getShuffleMask(const Constant * Mask,SmallVectorImpl<int> & Result)204806f32e7eSjoerg void ShuffleVectorInst::getShuffleMask(const Constant *Mask,
204906f32e7eSjoerg                                        SmallVectorImpl<int> &Result) {
2050*da58b97aSjoerg   ElementCount EC = cast<VectorType>(Mask->getType())->getElementCount();
2051*da58b97aSjoerg 
2052*da58b97aSjoerg   if (isa<ConstantAggregateZero>(Mask)) {
2053*da58b97aSjoerg     Result.resize(EC.getKnownMinValue(), 0);
2054*da58b97aSjoerg     return;
2055*da58b97aSjoerg   }
2056*da58b97aSjoerg 
2057*da58b97aSjoerg   Result.reserve(EC.getKnownMinValue());
2058*da58b97aSjoerg 
2059*da58b97aSjoerg   if (EC.isScalable()) {
2060*da58b97aSjoerg     assert((isa<ConstantAggregateZero>(Mask) || isa<UndefValue>(Mask)) &&
2061*da58b97aSjoerg            "Scalable vector shuffle mask must be undef or zeroinitializer");
2062*da58b97aSjoerg     int MaskVal = isa<UndefValue>(Mask) ? -1 : 0;
2063*da58b97aSjoerg     for (unsigned I = 0; I < EC.getKnownMinValue(); ++I)
2064*da58b97aSjoerg       Result.emplace_back(MaskVal);
2065*da58b97aSjoerg     return;
2066*da58b97aSjoerg   }
2067*da58b97aSjoerg 
2068*da58b97aSjoerg   unsigned NumElts = EC.getKnownMinValue();
206906f32e7eSjoerg 
207006f32e7eSjoerg   if (auto *CDS = dyn_cast<ConstantDataSequential>(Mask)) {
207106f32e7eSjoerg     for (unsigned i = 0; i != NumElts; ++i)
207206f32e7eSjoerg       Result.push_back(CDS->getElementAsInteger(i));
207306f32e7eSjoerg     return;
207406f32e7eSjoerg   }
207506f32e7eSjoerg   for (unsigned i = 0; i != NumElts; ++i) {
207606f32e7eSjoerg     Constant *C = Mask->getAggregateElement(i);
207706f32e7eSjoerg     Result.push_back(isa<UndefValue>(C) ? -1 :
207806f32e7eSjoerg                      cast<ConstantInt>(C)->getZExtValue());
207906f32e7eSjoerg   }
208006f32e7eSjoerg }
208106f32e7eSjoerg 
setShuffleMask(ArrayRef<int> Mask)2082*da58b97aSjoerg void ShuffleVectorInst::setShuffleMask(ArrayRef<int> Mask) {
2083*da58b97aSjoerg   ShuffleMask.assign(Mask.begin(), Mask.end());
2084*da58b97aSjoerg   ShuffleMaskForBitcode = convertShuffleMaskForBitcode(Mask, getType());
2085*da58b97aSjoerg }
convertShuffleMaskForBitcode(ArrayRef<int> Mask,Type * ResultTy)2086*da58b97aSjoerg Constant *ShuffleVectorInst::convertShuffleMaskForBitcode(ArrayRef<int> Mask,
2087*da58b97aSjoerg                                                           Type *ResultTy) {
2088*da58b97aSjoerg   Type *Int32Ty = Type::getInt32Ty(ResultTy->getContext());
2089*da58b97aSjoerg   if (isa<ScalableVectorType>(ResultTy)) {
2090*da58b97aSjoerg     assert(is_splat(Mask) && "Unexpected shuffle");
2091*da58b97aSjoerg     Type *VecTy = VectorType::get(Int32Ty, Mask.size(), true);
2092*da58b97aSjoerg     if (Mask[0] == 0)
2093*da58b97aSjoerg       return Constant::getNullValue(VecTy);
2094*da58b97aSjoerg     return UndefValue::get(VecTy);
2095*da58b97aSjoerg   }
2096*da58b97aSjoerg   SmallVector<Constant *, 16> MaskConst;
2097*da58b97aSjoerg   for (int Elem : Mask) {
2098*da58b97aSjoerg     if (Elem == UndefMaskElem)
2099*da58b97aSjoerg       MaskConst.push_back(UndefValue::get(Int32Ty));
2100*da58b97aSjoerg     else
2101*da58b97aSjoerg       MaskConst.push_back(ConstantInt::get(Int32Ty, Elem));
2102*da58b97aSjoerg   }
2103*da58b97aSjoerg   return ConstantVector::get(MaskConst);
2104*da58b97aSjoerg }
2105*da58b97aSjoerg 
isSingleSourceMaskImpl(ArrayRef<int> Mask,int NumOpElts)210606f32e7eSjoerg static bool isSingleSourceMaskImpl(ArrayRef<int> Mask, int NumOpElts) {
210706f32e7eSjoerg   assert(!Mask.empty() && "Shuffle mask must contain elements");
210806f32e7eSjoerg   bool UsesLHS = false;
210906f32e7eSjoerg   bool UsesRHS = false;
2110*da58b97aSjoerg   for (int I : Mask) {
2111*da58b97aSjoerg     if (I == -1)
211206f32e7eSjoerg       continue;
2113*da58b97aSjoerg     assert(I >= 0 && I < (NumOpElts * 2) &&
211406f32e7eSjoerg            "Out-of-bounds shuffle mask element");
2115*da58b97aSjoerg     UsesLHS |= (I < NumOpElts);
2116*da58b97aSjoerg     UsesRHS |= (I >= NumOpElts);
211706f32e7eSjoerg     if (UsesLHS && UsesRHS)
211806f32e7eSjoerg       return false;
211906f32e7eSjoerg   }
2120*da58b97aSjoerg   // Allow for degenerate case: completely undef mask means neither source is used.
2121*da58b97aSjoerg   return UsesLHS || UsesRHS;
212206f32e7eSjoerg }
212306f32e7eSjoerg 
isSingleSourceMask(ArrayRef<int> Mask)212406f32e7eSjoerg bool ShuffleVectorInst::isSingleSourceMask(ArrayRef<int> Mask) {
212506f32e7eSjoerg   // We don't have vector operand size information, so assume operands are the
212606f32e7eSjoerg   // same size as the mask.
212706f32e7eSjoerg   return isSingleSourceMaskImpl(Mask, Mask.size());
212806f32e7eSjoerg }
212906f32e7eSjoerg 
isIdentityMaskImpl(ArrayRef<int> Mask,int NumOpElts)213006f32e7eSjoerg static bool isIdentityMaskImpl(ArrayRef<int> Mask, int NumOpElts) {
213106f32e7eSjoerg   if (!isSingleSourceMaskImpl(Mask, NumOpElts))
213206f32e7eSjoerg     return false;
213306f32e7eSjoerg   for (int i = 0, NumMaskElts = Mask.size(); i < NumMaskElts; ++i) {
213406f32e7eSjoerg     if (Mask[i] == -1)
213506f32e7eSjoerg       continue;
213606f32e7eSjoerg     if (Mask[i] != i && Mask[i] != (NumOpElts + i))
213706f32e7eSjoerg       return false;
213806f32e7eSjoerg   }
213906f32e7eSjoerg   return true;
214006f32e7eSjoerg }
214106f32e7eSjoerg 
isIdentityMask(ArrayRef<int> Mask)214206f32e7eSjoerg bool ShuffleVectorInst::isIdentityMask(ArrayRef<int> Mask) {
214306f32e7eSjoerg   // We don't have vector operand size information, so assume operands are the
214406f32e7eSjoerg   // same size as the mask.
214506f32e7eSjoerg   return isIdentityMaskImpl(Mask, Mask.size());
214606f32e7eSjoerg }
214706f32e7eSjoerg 
isReverseMask(ArrayRef<int> Mask)214806f32e7eSjoerg bool ShuffleVectorInst::isReverseMask(ArrayRef<int> Mask) {
214906f32e7eSjoerg   if (!isSingleSourceMask(Mask))
215006f32e7eSjoerg     return false;
215106f32e7eSjoerg   for (int i = 0, NumElts = Mask.size(); i < NumElts; ++i) {
215206f32e7eSjoerg     if (Mask[i] == -1)
215306f32e7eSjoerg       continue;
215406f32e7eSjoerg     if (Mask[i] != (NumElts - 1 - i) && Mask[i] != (NumElts + NumElts - 1 - i))
215506f32e7eSjoerg       return false;
215606f32e7eSjoerg   }
215706f32e7eSjoerg   return true;
215806f32e7eSjoerg }
215906f32e7eSjoerg 
isZeroEltSplatMask(ArrayRef<int> Mask)216006f32e7eSjoerg bool ShuffleVectorInst::isZeroEltSplatMask(ArrayRef<int> Mask) {
216106f32e7eSjoerg   if (!isSingleSourceMask(Mask))
216206f32e7eSjoerg     return false;
216306f32e7eSjoerg   for (int i = 0, NumElts = Mask.size(); i < NumElts; ++i) {
216406f32e7eSjoerg     if (Mask[i] == -1)
216506f32e7eSjoerg       continue;
216606f32e7eSjoerg     if (Mask[i] != 0 && Mask[i] != NumElts)
216706f32e7eSjoerg       return false;
216806f32e7eSjoerg   }
216906f32e7eSjoerg   return true;
217006f32e7eSjoerg }
217106f32e7eSjoerg 
isSelectMask(ArrayRef<int> Mask)217206f32e7eSjoerg bool ShuffleVectorInst::isSelectMask(ArrayRef<int> Mask) {
217306f32e7eSjoerg   // Select is differentiated from identity. It requires using both sources.
217406f32e7eSjoerg   if (isSingleSourceMask(Mask))
217506f32e7eSjoerg     return false;
217606f32e7eSjoerg   for (int i = 0, NumElts = Mask.size(); i < NumElts; ++i) {
217706f32e7eSjoerg     if (Mask[i] == -1)
217806f32e7eSjoerg       continue;
217906f32e7eSjoerg     if (Mask[i] != i && Mask[i] != (NumElts + i))
218006f32e7eSjoerg       return false;
218106f32e7eSjoerg   }
218206f32e7eSjoerg   return true;
218306f32e7eSjoerg }
218406f32e7eSjoerg 
isTransposeMask(ArrayRef<int> Mask)218506f32e7eSjoerg bool ShuffleVectorInst::isTransposeMask(ArrayRef<int> Mask) {
218606f32e7eSjoerg   // Example masks that will return true:
218706f32e7eSjoerg   // v1 = <a, b, c, d>
218806f32e7eSjoerg   // v2 = <e, f, g, h>
218906f32e7eSjoerg   // trn1 = shufflevector v1, v2 <0, 4, 2, 6> = <a, e, c, g>
219006f32e7eSjoerg   // trn2 = shufflevector v1, v2 <1, 5, 3, 7> = <b, f, d, h>
219106f32e7eSjoerg 
219206f32e7eSjoerg   // 1. The number of elements in the mask must be a power-of-2 and at least 2.
219306f32e7eSjoerg   int NumElts = Mask.size();
219406f32e7eSjoerg   if (NumElts < 2 || !isPowerOf2_32(NumElts))
219506f32e7eSjoerg     return false;
219606f32e7eSjoerg 
219706f32e7eSjoerg   // 2. The first element of the mask must be either a 0 or a 1.
219806f32e7eSjoerg   if (Mask[0] != 0 && Mask[0] != 1)
219906f32e7eSjoerg     return false;
220006f32e7eSjoerg 
220106f32e7eSjoerg   // 3. The difference between the first 2 elements must be equal to the
220206f32e7eSjoerg   // number of elements in the mask.
220306f32e7eSjoerg   if ((Mask[1] - Mask[0]) != NumElts)
220406f32e7eSjoerg     return false;
220506f32e7eSjoerg 
220606f32e7eSjoerg   // 4. The difference between consecutive even-numbered and odd-numbered
220706f32e7eSjoerg   // elements must be equal to 2.
220806f32e7eSjoerg   for (int i = 2; i < NumElts; ++i) {
220906f32e7eSjoerg     int MaskEltVal = Mask[i];
221006f32e7eSjoerg     if (MaskEltVal == -1)
221106f32e7eSjoerg       return false;
221206f32e7eSjoerg     int MaskEltPrevVal = Mask[i - 2];
221306f32e7eSjoerg     if (MaskEltVal - MaskEltPrevVal != 2)
221406f32e7eSjoerg       return false;
221506f32e7eSjoerg   }
221606f32e7eSjoerg   return true;
221706f32e7eSjoerg }
221806f32e7eSjoerg 
isExtractSubvectorMask(ArrayRef<int> Mask,int NumSrcElts,int & Index)221906f32e7eSjoerg bool ShuffleVectorInst::isExtractSubvectorMask(ArrayRef<int> Mask,
222006f32e7eSjoerg                                                int NumSrcElts, int &Index) {
222106f32e7eSjoerg   // Must extract from a single source.
222206f32e7eSjoerg   if (!isSingleSourceMaskImpl(Mask, NumSrcElts))
222306f32e7eSjoerg     return false;
222406f32e7eSjoerg 
222506f32e7eSjoerg   // Must be smaller (else this is an Identity shuffle).
222606f32e7eSjoerg   if (NumSrcElts <= (int)Mask.size())
222706f32e7eSjoerg     return false;
222806f32e7eSjoerg 
222906f32e7eSjoerg   // Find start of extraction, accounting that we may start with an UNDEF.
223006f32e7eSjoerg   int SubIndex = -1;
223106f32e7eSjoerg   for (int i = 0, e = Mask.size(); i != e; ++i) {
223206f32e7eSjoerg     int M = Mask[i];
223306f32e7eSjoerg     if (M < 0)
223406f32e7eSjoerg       continue;
223506f32e7eSjoerg     int Offset = (M % NumSrcElts) - i;
223606f32e7eSjoerg     if (0 <= SubIndex && SubIndex != Offset)
223706f32e7eSjoerg       return false;
223806f32e7eSjoerg     SubIndex = Offset;
223906f32e7eSjoerg   }
224006f32e7eSjoerg 
2241*da58b97aSjoerg   if (0 <= SubIndex && SubIndex + (int)Mask.size() <= NumSrcElts) {
224206f32e7eSjoerg     Index = SubIndex;
224306f32e7eSjoerg     return true;
224406f32e7eSjoerg   }
224506f32e7eSjoerg   return false;
224606f32e7eSjoerg }
224706f32e7eSjoerg 
isIdentityWithPadding() const224806f32e7eSjoerg bool ShuffleVectorInst::isIdentityWithPadding() const {
2249*da58b97aSjoerg   if (isa<UndefValue>(Op<2>()))
2250*da58b97aSjoerg     return false;
2251*da58b97aSjoerg 
2252*da58b97aSjoerg   // FIXME: Not currently possible to express a shuffle mask for a scalable
2253*da58b97aSjoerg   // vector for this case.
2254*da58b97aSjoerg   if (isa<ScalableVectorType>(getType()))
2255*da58b97aSjoerg     return false;
2256*da58b97aSjoerg 
2257*da58b97aSjoerg   int NumOpElts = cast<FixedVectorType>(Op<0>()->getType())->getNumElements();
2258*da58b97aSjoerg   int NumMaskElts = cast<FixedVectorType>(getType())->getNumElements();
225906f32e7eSjoerg   if (NumMaskElts <= NumOpElts)
226006f32e7eSjoerg     return false;
226106f32e7eSjoerg 
226206f32e7eSjoerg   // The first part of the mask must choose elements from exactly 1 source op.
2263*da58b97aSjoerg   ArrayRef<int> Mask = getShuffleMask();
226406f32e7eSjoerg   if (!isIdentityMaskImpl(Mask, NumOpElts))
226506f32e7eSjoerg     return false;
226606f32e7eSjoerg 
226706f32e7eSjoerg   // All extending must be with undef elements.
226806f32e7eSjoerg   for (int i = NumOpElts; i < NumMaskElts; ++i)
226906f32e7eSjoerg     if (Mask[i] != -1)
227006f32e7eSjoerg       return false;
227106f32e7eSjoerg 
227206f32e7eSjoerg   return true;
227306f32e7eSjoerg }
227406f32e7eSjoerg 
isIdentityWithExtract() const227506f32e7eSjoerg bool ShuffleVectorInst::isIdentityWithExtract() const {
2276*da58b97aSjoerg   if (isa<UndefValue>(Op<2>()))
2277*da58b97aSjoerg     return false;
2278*da58b97aSjoerg 
2279*da58b97aSjoerg   // FIXME: Not currently possible to express a shuffle mask for a scalable
2280*da58b97aSjoerg   // vector for this case.
2281*da58b97aSjoerg   if (isa<ScalableVectorType>(getType()))
2282*da58b97aSjoerg     return false;
2283*da58b97aSjoerg 
2284*da58b97aSjoerg   int NumOpElts = cast<FixedVectorType>(Op<0>()->getType())->getNumElements();
2285*da58b97aSjoerg   int NumMaskElts = cast<FixedVectorType>(getType())->getNumElements();
228606f32e7eSjoerg   if (NumMaskElts >= NumOpElts)
228706f32e7eSjoerg     return false;
228806f32e7eSjoerg 
228906f32e7eSjoerg   return isIdentityMaskImpl(getShuffleMask(), NumOpElts);
229006f32e7eSjoerg }
229106f32e7eSjoerg 
isConcat() const229206f32e7eSjoerg bool ShuffleVectorInst::isConcat() const {
229306f32e7eSjoerg   // Vector concatenation is differentiated from identity with padding.
2294*da58b97aSjoerg   if (isa<UndefValue>(Op<0>()) || isa<UndefValue>(Op<1>()) ||
2295*da58b97aSjoerg       isa<UndefValue>(Op<2>()))
229606f32e7eSjoerg     return false;
229706f32e7eSjoerg 
2298*da58b97aSjoerg   // FIXME: Not currently possible to express a shuffle mask for a scalable
2299*da58b97aSjoerg   // vector for this case.
2300*da58b97aSjoerg   if (isa<ScalableVectorType>(getType()))
2301*da58b97aSjoerg     return false;
2302*da58b97aSjoerg 
2303*da58b97aSjoerg   int NumOpElts = cast<FixedVectorType>(Op<0>()->getType())->getNumElements();
2304*da58b97aSjoerg   int NumMaskElts = cast<FixedVectorType>(getType())->getNumElements();
230506f32e7eSjoerg   if (NumMaskElts != NumOpElts * 2)
230606f32e7eSjoerg     return false;
230706f32e7eSjoerg 
230806f32e7eSjoerg   // Use the mask length rather than the operands' vector lengths here. We
230906f32e7eSjoerg   // already know that the shuffle returns a vector twice as long as the inputs,
231006f32e7eSjoerg   // and neither of the inputs are undef vectors. If the mask picks consecutive
231106f32e7eSjoerg   // elements from both inputs, then this is a concatenation of the inputs.
231206f32e7eSjoerg   return isIdentityMaskImpl(getShuffleMask(), NumMaskElts);
231306f32e7eSjoerg }
231406f32e7eSjoerg 
231506f32e7eSjoerg //===----------------------------------------------------------------------===//
231606f32e7eSjoerg //                             InsertValueInst Class
231706f32e7eSjoerg //===----------------------------------------------------------------------===//
231806f32e7eSjoerg 
init(Value * Agg,Value * Val,ArrayRef<unsigned> Idxs,const Twine & Name)231906f32e7eSjoerg void InsertValueInst::init(Value *Agg, Value *Val, ArrayRef<unsigned> Idxs,
232006f32e7eSjoerg                            const Twine &Name) {
232106f32e7eSjoerg   assert(getNumOperands() == 2 && "NumOperands not initialized?");
232206f32e7eSjoerg 
232306f32e7eSjoerg   // There's no fundamental reason why we require at least one index
232406f32e7eSjoerg   // (other than weirdness with &*IdxBegin being invalid; see
232506f32e7eSjoerg   // getelementptr's init routine for example). But there's no
232606f32e7eSjoerg   // present need to support it.
232706f32e7eSjoerg   assert(!Idxs.empty() && "InsertValueInst must have at least one index");
232806f32e7eSjoerg 
232906f32e7eSjoerg   assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs) ==
233006f32e7eSjoerg          Val->getType() && "Inserted value must match indexed type!");
233106f32e7eSjoerg   Op<0>() = Agg;
233206f32e7eSjoerg   Op<1>() = Val;
233306f32e7eSjoerg 
233406f32e7eSjoerg   Indices.append(Idxs.begin(), Idxs.end());
233506f32e7eSjoerg   setName(Name);
233606f32e7eSjoerg }
233706f32e7eSjoerg 
InsertValueInst(const InsertValueInst & IVI)233806f32e7eSjoerg InsertValueInst::InsertValueInst(const InsertValueInst &IVI)
233906f32e7eSjoerg   : Instruction(IVI.getType(), InsertValue,
234006f32e7eSjoerg                 OperandTraits<InsertValueInst>::op_begin(this), 2),
234106f32e7eSjoerg     Indices(IVI.Indices) {
234206f32e7eSjoerg   Op<0>() = IVI.getOperand(0);
234306f32e7eSjoerg   Op<1>() = IVI.getOperand(1);
234406f32e7eSjoerg   SubclassOptionalData = IVI.SubclassOptionalData;
234506f32e7eSjoerg }
234606f32e7eSjoerg 
234706f32e7eSjoerg //===----------------------------------------------------------------------===//
234806f32e7eSjoerg //                             ExtractValueInst Class
234906f32e7eSjoerg //===----------------------------------------------------------------------===//
235006f32e7eSjoerg 
init(ArrayRef<unsigned> Idxs,const Twine & Name)235106f32e7eSjoerg void ExtractValueInst::init(ArrayRef<unsigned> Idxs, const Twine &Name) {
235206f32e7eSjoerg   assert(getNumOperands() == 1 && "NumOperands not initialized?");
235306f32e7eSjoerg 
235406f32e7eSjoerg   // There's no fundamental reason why we require at least one index.
235506f32e7eSjoerg   // But there's no present need to support it.
235606f32e7eSjoerg   assert(!Idxs.empty() && "ExtractValueInst must have at least one index");
235706f32e7eSjoerg 
235806f32e7eSjoerg   Indices.append(Idxs.begin(), Idxs.end());
235906f32e7eSjoerg   setName(Name);
236006f32e7eSjoerg }
236106f32e7eSjoerg 
ExtractValueInst(const ExtractValueInst & EVI)236206f32e7eSjoerg ExtractValueInst::ExtractValueInst(const ExtractValueInst &EVI)
236306f32e7eSjoerg   : UnaryInstruction(EVI.getType(), ExtractValue, EVI.getOperand(0)),
236406f32e7eSjoerg     Indices(EVI.Indices) {
236506f32e7eSjoerg   SubclassOptionalData = EVI.SubclassOptionalData;
236606f32e7eSjoerg }
236706f32e7eSjoerg 
236806f32e7eSjoerg // getIndexedType - Returns the type of the element that would be extracted
236906f32e7eSjoerg // with an extractvalue instruction with the specified parameters.
237006f32e7eSjoerg //
237106f32e7eSjoerg // A null type is returned if the indices are invalid for the specified
237206f32e7eSjoerg // pointer type.
237306f32e7eSjoerg //
getIndexedType(Type * Agg,ArrayRef<unsigned> Idxs)237406f32e7eSjoerg Type *ExtractValueInst::getIndexedType(Type *Agg,
237506f32e7eSjoerg                                        ArrayRef<unsigned> Idxs) {
237606f32e7eSjoerg   for (unsigned Index : Idxs) {
237706f32e7eSjoerg     // We can't use CompositeType::indexValid(Index) here.
237806f32e7eSjoerg     // indexValid() always returns true for arrays because getelementptr allows
237906f32e7eSjoerg     // out-of-bounds indices. Since we don't allow those for extractvalue and
238006f32e7eSjoerg     // insertvalue we need to check array indexing manually.
238106f32e7eSjoerg     // Since the only other types we can index into are struct types it's just
238206f32e7eSjoerg     // as easy to check those manually as well.
238306f32e7eSjoerg     if (ArrayType *AT = dyn_cast<ArrayType>(Agg)) {
238406f32e7eSjoerg       if (Index >= AT->getNumElements())
238506f32e7eSjoerg         return nullptr;
2386*da58b97aSjoerg       Agg = AT->getElementType();
238706f32e7eSjoerg     } else if (StructType *ST = dyn_cast<StructType>(Agg)) {
238806f32e7eSjoerg       if (Index >= ST->getNumElements())
238906f32e7eSjoerg         return nullptr;
2390*da58b97aSjoerg       Agg = ST->getElementType(Index);
239106f32e7eSjoerg     } else {
239206f32e7eSjoerg       // Not a valid type to index into.
239306f32e7eSjoerg       return nullptr;
239406f32e7eSjoerg     }
239506f32e7eSjoerg   }
239606f32e7eSjoerg   return const_cast<Type*>(Agg);
239706f32e7eSjoerg }
239806f32e7eSjoerg 
239906f32e7eSjoerg //===----------------------------------------------------------------------===//
240006f32e7eSjoerg //                             UnaryOperator Class
240106f32e7eSjoerg //===----------------------------------------------------------------------===//
240206f32e7eSjoerg 
UnaryOperator(UnaryOps iType,Value * S,Type * Ty,const Twine & Name,Instruction * InsertBefore)240306f32e7eSjoerg UnaryOperator::UnaryOperator(UnaryOps iType, Value *S,
240406f32e7eSjoerg                              Type *Ty, const Twine &Name,
240506f32e7eSjoerg                              Instruction *InsertBefore)
240606f32e7eSjoerg   : UnaryInstruction(Ty, iType, S, InsertBefore) {
240706f32e7eSjoerg   Op<0>() = S;
240806f32e7eSjoerg   setName(Name);
240906f32e7eSjoerg   AssertOK();
241006f32e7eSjoerg }
241106f32e7eSjoerg 
UnaryOperator(UnaryOps iType,Value * S,Type * Ty,const Twine & Name,BasicBlock * InsertAtEnd)241206f32e7eSjoerg UnaryOperator::UnaryOperator(UnaryOps iType, Value *S,
241306f32e7eSjoerg                              Type *Ty, const Twine &Name,
241406f32e7eSjoerg                              BasicBlock *InsertAtEnd)
241506f32e7eSjoerg   : UnaryInstruction(Ty, iType, S, InsertAtEnd) {
241606f32e7eSjoerg   Op<0>() = S;
241706f32e7eSjoerg   setName(Name);
241806f32e7eSjoerg   AssertOK();
241906f32e7eSjoerg }
242006f32e7eSjoerg 
Create(UnaryOps Op,Value * S,const Twine & Name,Instruction * InsertBefore)242106f32e7eSjoerg UnaryOperator *UnaryOperator::Create(UnaryOps Op, Value *S,
242206f32e7eSjoerg                                      const Twine &Name,
242306f32e7eSjoerg                                      Instruction *InsertBefore) {
242406f32e7eSjoerg   return new UnaryOperator(Op, S, S->getType(), Name, InsertBefore);
242506f32e7eSjoerg }
242606f32e7eSjoerg 
Create(UnaryOps Op,Value * S,const Twine & Name,BasicBlock * InsertAtEnd)242706f32e7eSjoerg UnaryOperator *UnaryOperator::Create(UnaryOps Op, Value *S,
242806f32e7eSjoerg                                      const Twine &Name,
242906f32e7eSjoerg                                      BasicBlock *InsertAtEnd) {
243006f32e7eSjoerg   UnaryOperator *Res = Create(Op, S, Name);
243106f32e7eSjoerg   InsertAtEnd->getInstList().push_back(Res);
243206f32e7eSjoerg   return Res;
243306f32e7eSjoerg }
243406f32e7eSjoerg 
AssertOK()243506f32e7eSjoerg void UnaryOperator::AssertOK() {
243606f32e7eSjoerg   Value *LHS = getOperand(0);
243706f32e7eSjoerg   (void)LHS; // Silence warnings.
243806f32e7eSjoerg #ifndef NDEBUG
243906f32e7eSjoerg   switch (getOpcode()) {
244006f32e7eSjoerg   case FNeg:
244106f32e7eSjoerg     assert(getType() == LHS->getType() &&
244206f32e7eSjoerg            "Unary operation should return same type as operand!");
244306f32e7eSjoerg     assert(getType()->isFPOrFPVectorTy() &&
244406f32e7eSjoerg            "Tried to create a floating-point operation on a "
244506f32e7eSjoerg            "non-floating-point type!");
244606f32e7eSjoerg     break;
244706f32e7eSjoerg   default: llvm_unreachable("Invalid opcode provided");
244806f32e7eSjoerg   }
244906f32e7eSjoerg #endif
245006f32e7eSjoerg }
245106f32e7eSjoerg 
245206f32e7eSjoerg //===----------------------------------------------------------------------===//
245306f32e7eSjoerg //                             BinaryOperator Class
245406f32e7eSjoerg //===----------------------------------------------------------------------===//
245506f32e7eSjoerg 
BinaryOperator(BinaryOps iType,Value * S1,Value * S2,Type * Ty,const Twine & Name,Instruction * InsertBefore)245606f32e7eSjoerg BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
245706f32e7eSjoerg                                Type *Ty, const Twine &Name,
245806f32e7eSjoerg                                Instruction *InsertBefore)
245906f32e7eSjoerg   : Instruction(Ty, iType,
246006f32e7eSjoerg                 OperandTraits<BinaryOperator>::op_begin(this),
246106f32e7eSjoerg                 OperandTraits<BinaryOperator>::operands(this),
246206f32e7eSjoerg                 InsertBefore) {
246306f32e7eSjoerg   Op<0>() = S1;
246406f32e7eSjoerg   Op<1>() = S2;
246506f32e7eSjoerg   setName(Name);
246606f32e7eSjoerg   AssertOK();
246706f32e7eSjoerg }
246806f32e7eSjoerg 
BinaryOperator(BinaryOps iType,Value * S1,Value * S2,Type * Ty,const Twine & Name,BasicBlock * InsertAtEnd)246906f32e7eSjoerg BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
247006f32e7eSjoerg                                Type *Ty, const Twine &Name,
247106f32e7eSjoerg                                BasicBlock *InsertAtEnd)
247206f32e7eSjoerg   : Instruction(Ty, iType,
247306f32e7eSjoerg                 OperandTraits<BinaryOperator>::op_begin(this),
247406f32e7eSjoerg                 OperandTraits<BinaryOperator>::operands(this),
247506f32e7eSjoerg                 InsertAtEnd) {
247606f32e7eSjoerg   Op<0>() = S1;
247706f32e7eSjoerg   Op<1>() = S2;
247806f32e7eSjoerg   setName(Name);
247906f32e7eSjoerg   AssertOK();
248006f32e7eSjoerg }
248106f32e7eSjoerg 
AssertOK()248206f32e7eSjoerg void BinaryOperator::AssertOK() {
248306f32e7eSjoerg   Value *LHS = getOperand(0), *RHS = getOperand(1);
248406f32e7eSjoerg   (void)LHS; (void)RHS; // Silence warnings.
248506f32e7eSjoerg   assert(LHS->getType() == RHS->getType() &&
248606f32e7eSjoerg          "Binary operator operand types must match!");
248706f32e7eSjoerg #ifndef NDEBUG
248806f32e7eSjoerg   switch (getOpcode()) {
248906f32e7eSjoerg   case Add: case Sub:
249006f32e7eSjoerg   case Mul:
249106f32e7eSjoerg     assert(getType() == LHS->getType() &&
249206f32e7eSjoerg            "Arithmetic operation should return same type as operands!");
249306f32e7eSjoerg     assert(getType()->isIntOrIntVectorTy() &&
249406f32e7eSjoerg            "Tried to create an integer operation on a non-integer type!");
249506f32e7eSjoerg     break;
249606f32e7eSjoerg   case FAdd: case FSub:
249706f32e7eSjoerg   case FMul:
249806f32e7eSjoerg     assert(getType() == LHS->getType() &&
249906f32e7eSjoerg            "Arithmetic operation should return same type as operands!");
250006f32e7eSjoerg     assert(getType()->isFPOrFPVectorTy() &&
250106f32e7eSjoerg            "Tried to create a floating-point operation on a "
250206f32e7eSjoerg            "non-floating-point type!");
250306f32e7eSjoerg     break;
250406f32e7eSjoerg   case UDiv:
250506f32e7eSjoerg   case SDiv:
250606f32e7eSjoerg     assert(getType() == LHS->getType() &&
250706f32e7eSjoerg            "Arithmetic operation should return same type as operands!");
250806f32e7eSjoerg     assert(getType()->isIntOrIntVectorTy() &&
250906f32e7eSjoerg            "Incorrect operand type (not integer) for S/UDIV");
251006f32e7eSjoerg     break;
251106f32e7eSjoerg   case FDiv:
251206f32e7eSjoerg     assert(getType() == LHS->getType() &&
251306f32e7eSjoerg            "Arithmetic operation should return same type as operands!");
251406f32e7eSjoerg     assert(getType()->isFPOrFPVectorTy() &&
251506f32e7eSjoerg            "Incorrect operand type (not floating point) for FDIV");
251606f32e7eSjoerg     break;
251706f32e7eSjoerg   case URem:
251806f32e7eSjoerg   case SRem:
251906f32e7eSjoerg     assert(getType() == LHS->getType() &&
252006f32e7eSjoerg            "Arithmetic operation should return same type as operands!");
252106f32e7eSjoerg     assert(getType()->isIntOrIntVectorTy() &&
252206f32e7eSjoerg            "Incorrect operand type (not integer) for S/UREM");
252306f32e7eSjoerg     break;
252406f32e7eSjoerg   case FRem:
252506f32e7eSjoerg     assert(getType() == LHS->getType() &&
252606f32e7eSjoerg            "Arithmetic operation should return same type as operands!");
252706f32e7eSjoerg     assert(getType()->isFPOrFPVectorTy() &&
252806f32e7eSjoerg            "Incorrect operand type (not floating point) for FREM");
252906f32e7eSjoerg     break;
253006f32e7eSjoerg   case Shl:
253106f32e7eSjoerg   case LShr:
253206f32e7eSjoerg   case AShr:
253306f32e7eSjoerg     assert(getType() == LHS->getType() &&
253406f32e7eSjoerg            "Shift operation should return same type as operands!");
253506f32e7eSjoerg     assert(getType()->isIntOrIntVectorTy() &&
253606f32e7eSjoerg            "Tried to create a shift operation on a non-integral type!");
253706f32e7eSjoerg     break;
253806f32e7eSjoerg   case And: case Or:
253906f32e7eSjoerg   case Xor:
254006f32e7eSjoerg     assert(getType() == LHS->getType() &&
254106f32e7eSjoerg            "Logical operation should return same type as operands!");
254206f32e7eSjoerg     assert(getType()->isIntOrIntVectorTy() &&
254306f32e7eSjoerg            "Tried to create a logical operation on a non-integral type!");
254406f32e7eSjoerg     break;
254506f32e7eSjoerg   default: llvm_unreachable("Invalid opcode provided");
254606f32e7eSjoerg   }
254706f32e7eSjoerg #endif
254806f32e7eSjoerg }
254906f32e7eSjoerg 
Create(BinaryOps Op,Value * S1,Value * S2,const Twine & Name,Instruction * InsertBefore)255006f32e7eSjoerg BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2,
255106f32e7eSjoerg                                        const Twine &Name,
255206f32e7eSjoerg                                        Instruction *InsertBefore) {
255306f32e7eSjoerg   assert(S1->getType() == S2->getType() &&
255406f32e7eSjoerg          "Cannot create binary operator with two operands of differing type!");
255506f32e7eSjoerg   return new BinaryOperator(Op, S1, S2, S1->getType(), Name, InsertBefore);
255606f32e7eSjoerg }
255706f32e7eSjoerg 
Create(BinaryOps Op,Value * S1,Value * S2,const Twine & Name,BasicBlock * InsertAtEnd)255806f32e7eSjoerg BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2,
255906f32e7eSjoerg                                        const Twine &Name,
256006f32e7eSjoerg                                        BasicBlock *InsertAtEnd) {
256106f32e7eSjoerg   BinaryOperator *Res = Create(Op, S1, S2, Name);
256206f32e7eSjoerg   InsertAtEnd->getInstList().push_back(Res);
256306f32e7eSjoerg   return Res;
256406f32e7eSjoerg }
256506f32e7eSjoerg 
CreateNeg(Value * Op,const Twine & Name,Instruction * InsertBefore)256606f32e7eSjoerg BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const Twine &Name,
256706f32e7eSjoerg                                           Instruction *InsertBefore) {
256806f32e7eSjoerg   Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
256906f32e7eSjoerg   return new BinaryOperator(Instruction::Sub,
257006f32e7eSjoerg                             zero, Op,
257106f32e7eSjoerg                             Op->getType(), Name, InsertBefore);
257206f32e7eSjoerg }
257306f32e7eSjoerg 
CreateNeg(Value * Op,const Twine & Name,BasicBlock * InsertAtEnd)257406f32e7eSjoerg BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const Twine &Name,
257506f32e7eSjoerg                                           BasicBlock *InsertAtEnd) {
257606f32e7eSjoerg   Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
257706f32e7eSjoerg   return new BinaryOperator(Instruction::Sub,
257806f32e7eSjoerg                             zero, Op,
257906f32e7eSjoerg                             Op->getType(), Name, InsertAtEnd);
258006f32e7eSjoerg }
258106f32e7eSjoerg 
CreateNSWNeg(Value * Op,const Twine & Name,Instruction * InsertBefore)258206f32e7eSjoerg BinaryOperator *BinaryOperator::CreateNSWNeg(Value *Op, const Twine &Name,
258306f32e7eSjoerg                                              Instruction *InsertBefore) {
258406f32e7eSjoerg   Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
258506f32e7eSjoerg   return BinaryOperator::CreateNSWSub(zero, Op, Name, InsertBefore);
258606f32e7eSjoerg }
258706f32e7eSjoerg 
CreateNSWNeg(Value * Op,const Twine & Name,BasicBlock * InsertAtEnd)258806f32e7eSjoerg BinaryOperator *BinaryOperator::CreateNSWNeg(Value *Op, const Twine &Name,
258906f32e7eSjoerg                                              BasicBlock *InsertAtEnd) {
259006f32e7eSjoerg   Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
259106f32e7eSjoerg   return BinaryOperator::CreateNSWSub(zero, Op, Name, InsertAtEnd);
259206f32e7eSjoerg }
259306f32e7eSjoerg 
CreateNUWNeg(Value * Op,const Twine & Name,Instruction * InsertBefore)259406f32e7eSjoerg BinaryOperator *BinaryOperator::CreateNUWNeg(Value *Op, const Twine &Name,
259506f32e7eSjoerg                                              Instruction *InsertBefore) {
259606f32e7eSjoerg   Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
259706f32e7eSjoerg   return BinaryOperator::CreateNUWSub(zero, Op, Name, InsertBefore);
259806f32e7eSjoerg }
259906f32e7eSjoerg 
CreateNUWNeg(Value * Op,const Twine & Name,BasicBlock * InsertAtEnd)260006f32e7eSjoerg BinaryOperator *BinaryOperator::CreateNUWNeg(Value *Op, const Twine &Name,
260106f32e7eSjoerg                                              BasicBlock *InsertAtEnd) {
260206f32e7eSjoerg   Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
260306f32e7eSjoerg   return BinaryOperator::CreateNUWSub(zero, Op, Name, InsertAtEnd);
260406f32e7eSjoerg }
260506f32e7eSjoerg 
CreateNot(Value * Op,const Twine & Name,Instruction * InsertBefore)260606f32e7eSjoerg BinaryOperator *BinaryOperator::CreateNot(Value *Op, const Twine &Name,
260706f32e7eSjoerg                                           Instruction *InsertBefore) {
260806f32e7eSjoerg   Constant *C = Constant::getAllOnesValue(Op->getType());
260906f32e7eSjoerg   return new BinaryOperator(Instruction::Xor, Op, C,
261006f32e7eSjoerg                             Op->getType(), Name, InsertBefore);
261106f32e7eSjoerg }
261206f32e7eSjoerg 
CreateNot(Value * Op,const Twine & Name,BasicBlock * InsertAtEnd)261306f32e7eSjoerg BinaryOperator *BinaryOperator::CreateNot(Value *Op, const Twine &Name,
261406f32e7eSjoerg                                           BasicBlock *InsertAtEnd) {
261506f32e7eSjoerg   Constant *AllOnes = Constant::getAllOnesValue(Op->getType());
261606f32e7eSjoerg   return new BinaryOperator(Instruction::Xor, Op, AllOnes,
261706f32e7eSjoerg                             Op->getType(), Name, InsertAtEnd);
261806f32e7eSjoerg }
261906f32e7eSjoerg 
262006f32e7eSjoerg // Exchange the two operands to this instruction. This instruction is safe to
262106f32e7eSjoerg // use on any binary instruction and does not modify the semantics of the
262206f32e7eSjoerg // instruction. If the instruction is order-dependent (SetLT f.e.), the opcode
262306f32e7eSjoerg // is changed.
swapOperands()262406f32e7eSjoerg bool BinaryOperator::swapOperands() {
262506f32e7eSjoerg   if (!isCommutative())
262606f32e7eSjoerg     return true; // Can't commute operands
262706f32e7eSjoerg   Op<0>().swap(Op<1>());
262806f32e7eSjoerg   return false;
262906f32e7eSjoerg }
263006f32e7eSjoerg 
263106f32e7eSjoerg //===----------------------------------------------------------------------===//
263206f32e7eSjoerg //                             FPMathOperator Class
263306f32e7eSjoerg //===----------------------------------------------------------------------===//
263406f32e7eSjoerg 
getFPAccuracy() const263506f32e7eSjoerg float FPMathOperator::getFPAccuracy() const {
263606f32e7eSjoerg   const MDNode *MD =
263706f32e7eSjoerg       cast<Instruction>(this)->getMetadata(LLVMContext::MD_fpmath);
263806f32e7eSjoerg   if (!MD)
263906f32e7eSjoerg     return 0.0;
264006f32e7eSjoerg   ConstantFP *Accuracy = mdconst::extract<ConstantFP>(MD->getOperand(0));
264106f32e7eSjoerg   return Accuracy->getValueAPF().convertToFloat();
264206f32e7eSjoerg }
264306f32e7eSjoerg 
264406f32e7eSjoerg //===----------------------------------------------------------------------===//
264506f32e7eSjoerg //                                CastInst Class
264606f32e7eSjoerg //===----------------------------------------------------------------------===//
264706f32e7eSjoerg 
264806f32e7eSjoerg // Just determine if this cast only deals with integral->integral conversion.
isIntegerCast() const264906f32e7eSjoerg bool CastInst::isIntegerCast() const {
265006f32e7eSjoerg   switch (getOpcode()) {
265106f32e7eSjoerg     default: return false;
265206f32e7eSjoerg     case Instruction::ZExt:
265306f32e7eSjoerg     case Instruction::SExt:
265406f32e7eSjoerg     case Instruction::Trunc:
265506f32e7eSjoerg       return true;
265606f32e7eSjoerg     case Instruction::BitCast:
265706f32e7eSjoerg       return getOperand(0)->getType()->isIntegerTy() &&
265806f32e7eSjoerg         getType()->isIntegerTy();
265906f32e7eSjoerg   }
266006f32e7eSjoerg }
266106f32e7eSjoerg 
isLosslessCast() const266206f32e7eSjoerg bool CastInst::isLosslessCast() const {
266306f32e7eSjoerg   // Only BitCast can be lossless, exit fast if we're not BitCast
266406f32e7eSjoerg   if (getOpcode() != Instruction::BitCast)
266506f32e7eSjoerg     return false;
266606f32e7eSjoerg 
266706f32e7eSjoerg   // Identity cast is always lossless
266806f32e7eSjoerg   Type *SrcTy = getOperand(0)->getType();
266906f32e7eSjoerg   Type *DstTy = getType();
267006f32e7eSjoerg   if (SrcTy == DstTy)
267106f32e7eSjoerg     return true;
267206f32e7eSjoerg 
267306f32e7eSjoerg   // Pointer to pointer is always lossless.
267406f32e7eSjoerg   if (SrcTy->isPointerTy())
267506f32e7eSjoerg     return DstTy->isPointerTy();
267606f32e7eSjoerg   return false;  // Other types have no identity values
267706f32e7eSjoerg }
267806f32e7eSjoerg 
267906f32e7eSjoerg /// This function determines if the CastInst does not require any bits to be
268006f32e7eSjoerg /// changed in order to effect the cast. Essentially, it identifies cases where
268106f32e7eSjoerg /// no code gen is necessary for the cast, hence the name no-op cast.  For
268206f32e7eSjoerg /// example, the following are all no-op casts:
268306f32e7eSjoerg /// # bitcast i32* %x to i8*
268406f32e7eSjoerg /// # bitcast <2 x i32> %x to <4 x i16>
268506f32e7eSjoerg /// # ptrtoint i32* %x to i32     ; on 32-bit plaforms only
268606f32e7eSjoerg /// Determine if the described cast is a no-op.
isNoopCast(Instruction::CastOps Opcode,Type * SrcTy,Type * DestTy,const DataLayout & DL)268706f32e7eSjoerg bool CastInst::isNoopCast(Instruction::CastOps Opcode,
268806f32e7eSjoerg                           Type *SrcTy,
268906f32e7eSjoerg                           Type *DestTy,
269006f32e7eSjoerg                           const DataLayout &DL) {
2691*da58b97aSjoerg   assert(castIsValid(Opcode, SrcTy, DestTy) && "method precondition");
269206f32e7eSjoerg   switch (Opcode) {
269306f32e7eSjoerg     default: llvm_unreachable("Invalid CastOp");
269406f32e7eSjoerg     case Instruction::Trunc:
269506f32e7eSjoerg     case Instruction::ZExt:
269606f32e7eSjoerg     case Instruction::SExt:
269706f32e7eSjoerg     case Instruction::FPTrunc:
269806f32e7eSjoerg     case Instruction::FPExt:
269906f32e7eSjoerg     case Instruction::UIToFP:
270006f32e7eSjoerg     case Instruction::SIToFP:
270106f32e7eSjoerg     case Instruction::FPToUI:
270206f32e7eSjoerg     case Instruction::FPToSI:
270306f32e7eSjoerg     case Instruction::AddrSpaceCast:
270406f32e7eSjoerg       // TODO: Target informations may give a more accurate answer here.
270506f32e7eSjoerg       return false;
270606f32e7eSjoerg     case Instruction::BitCast:
270706f32e7eSjoerg       return true;  // BitCast never modifies bits.
270806f32e7eSjoerg     case Instruction::PtrToInt:
270906f32e7eSjoerg       return DL.getIntPtrType(SrcTy)->getScalarSizeInBits() ==
271006f32e7eSjoerg              DestTy->getScalarSizeInBits();
271106f32e7eSjoerg     case Instruction::IntToPtr:
271206f32e7eSjoerg       return DL.getIntPtrType(DestTy)->getScalarSizeInBits() ==
271306f32e7eSjoerg              SrcTy->getScalarSizeInBits();
271406f32e7eSjoerg   }
271506f32e7eSjoerg }
271606f32e7eSjoerg 
isNoopCast(const DataLayout & DL) const271706f32e7eSjoerg bool CastInst::isNoopCast(const DataLayout &DL) const {
271806f32e7eSjoerg   return isNoopCast(getOpcode(), getOperand(0)->getType(), getType(), DL);
271906f32e7eSjoerg }
272006f32e7eSjoerg 
272106f32e7eSjoerg /// This function determines if a pair of casts can be eliminated and what
272206f32e7eSjoerg /// opcode should be used in the elimination. This assumes that there are two
272306f32e7eSjoerg /// instructions like this:
272406f32e7eSjoerg /// *  %F = firstOpcode SrcTy %x to MidTy
272506f32e7eSjoerg /// *  %S = secondOpcode MidTy %F to DstTy
272606f32e7eSjoerg /// The function returns a resultOpcode so these two casts can be replaced with:
272706f32e7eSjoerg /// *  %Replacement = resultOpcode %SrcTy %x to DstTy
272806f32e7eSjoerg /// If no such cast is permitted, the function returns 0.
isEliminableCastPair(Instruction::CastOps firstOp,Instruction::CastOps secondOp,Type * SrcTy,Type * MidTy,Type * DstTy,Type * SrcIntPtrTy,Type * MidIntPtrTy,Type * DstIntPtrTy)272906f32e7eSjoerg unsigned CastInst::isEliminableCastPair(
273006f32e7eSjoerg   Instruction::CastOps firstOp, Instruction::CastOps secondOp,
273106f32e7eSjoerg   Type *SrcTy, Type *MidTy, Type *DstTy, Type *SrcIntPtrTy, Type *MidIntPtrTy,
273206f32e7eSjoerg   Type *DstIntPtrTy) {
273306f32e7eSjoerg   // Define the 144 possibilities for these two cast instructions. The values
273406f32e7eSjoerg   // in this matrix determine what to do in a given situation and select the
273506f32e7eSjoerg   // case in the switch below.  The rows correspond to firstOp, the columns
273606f32e7eSjoerg   // correspond to secondOp.  In looking at the table below, keep in mind
273706f32e7eSjoerg   // the following cast properties:
273806f32e7eSjoerg   //
273906f32e7eSjoerg   //          Size Compare       Source               Destination
274006f32e7eSjoerg   // Operator  Src ? Size   Type       Sign         Type       Sign
274106f32e7eSjoerg   // -------- ------------ -------------------   ---------------------
274206f32e7eSjoerg   // TRUNC         >       Integer      Any        Integral     Any
274306f32e7eSjoerg   // ZEXT          <       Integral   Unsigned     Integer      Any
274406f32e7eSjoerg   // SEXT          <       Integral    Signed      Integer      Any
274506f32e7eSjoerg   // FPTOUI       n/a      FloatPt      n/a        Integral   Unsigned
274606f32e7eSjoerg   // FPTOSI       n/a      FloatPt      n/a        Integral    Signed
274706f32e7eSjoerg   // UITOFP       n/a      Integral   Unsigned     FloatPt      n/a
274806f32e7eSjoerg   // SITOFP       n/a      Integral    Signed      FloatPt      n/a
274906f32e7eSjoerg   // FPTRUNC       >       FloatPt      n/a        FloatPt      n/a
275006f32e7eSjoerg   // FPEXT         <       FloatPt      n/a        FloatPt      n/a
275106f32e7eSjoerg   // PTRTOINT     n/a      Pointer      n/a        Integral   Unsigned
275206f32e7eSjoerg   // INTTOPTR     n/a      Integral   Unsigned     Pointer      n/a
275306f32e7eSjoerg   // BITCAST       =       FirstClass   n/a       FirstClass    n/a
275406f32e7eSjoerg   // ADDRSPCST    n/a      Pointer      n/a        Pointer      n/a
275506f32e7eSjoerg   //
275606f32e7eSjoerg   // NOTE: some transforms are safe, but we consider them to be non-profitable.
275706f32e7eSjoerg   // For example, we could merge "fptoui double to i32" + "zext i32 to i64",
275806f32e7eSjoerg   // into "fptoui double to i64", but this loses information about the range
275906f32e7eSjoerg   // of the produced value (we no longer know the top-part is all zeros).
276006f32e7eSjoerg   // Further this conversion is often much more expensive for typical hardware,
276106f32e7eSjoerg   // and causes issues when building libgcc.  We disallow fptosi+sext for the
276206f32e7eSjoerg   // same reason.
276306f32e7eSjoerg   const unsigned numCastOps =
276406f32e7eSjoerg     Instruction::CastOpsEnd - Instruction::CastOpsBegin;
276506f32e7eSjoerg   static const uint8_t CastResults[numCastOps][numCastOps] = {
276606f32e7eSjoerg     // T        F  F  U  S  F  F  P  I  B  A  -+
276706f32e7eSjoerg     // R  Z  S  P  P  I  I  T  P  2  N  T  S   |
276806f32e7eSjoerg     // U  E  E  2  2  2  2  R  E  I  T  C  C   +- secondOp
276906f32e7eSjoerg     // N  X  X  U  S  F  F  N  X  N  2  V  V   |
277006f32e7eSjoerg     // C  T  T  I  I  P  P  C  T  T  P  T  T  -+
277106f32e7eSjoerg     {  1, 0, 0,99,99, 0, 0,99,99,99, 0, 3, 0}, // Trunc         -+
277206f32e7eSjoerg     {  8, 1, 9,99,99, 2,17,99,99,99, 2, 3, 0}, // ZExt           |
277306f32e7eSjoerg     {  8, 0, 1,99,99, 0, 2,99,99,99, 0, 3, 0}, // SExt           |
277406f32e7eSjoerg     {  0, 0, 0,99,99, 0, 0,99,99,99, 0, 3, 0}, // FPToUI         |
277506f32e7eSjoerg     {  0, 0, 0,99,99, 0, 0,99,99,99, 0, 3, 0}, // FPToSI         |
277606f32e7eSjoerg     { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4, 0}, // UIToFP         +- firstOp
277706f32e7eSjoerg     { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4, 0}, // SIToFP         |
277806f32e7eSjoerg     { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4, 0}, // FPTrunc        |
277906f32e7eSjoerg     { 99,99,99, 2, 2,99,99, 8, 2,99,99, 4, 0}, // FPExt          |
278006f32e7eSjoerg     {  1, 0, 0,99,99, 0, 0,99,99,99, 7, 3, 0}, // PtrToInt       |
278106f32e7eSjoerg     { 99,99,99,99,99,99,99,99,99,11,99,15, 0}, // IntToPtr       |
278206f32e7eSjoerg     {  5, 5, 5, 6, 6, 5, 5, 6, 6,16, 5, 1,14}, // BitCast        |
278306f32e7eSjoerg     {  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,13,12}, // AddrSpaceCast -+
278406f32e7eSjoerg   };
278506f32e7eSjoerg 
278606f32e7eSjoerg   // TODO: This logic could be encoded into the table above and handled in the
278706f32e7eSjoerg   // switch below.
278806f32e7eSjoerg   // If either of the casts are a bitcast from scalar to vector, disallow the
278906f32e7eSjoerg   // merging. However, any pair of bitcasts are allowed.
279006f32e7eSjoerg   bool IsFirstBitcast  = (firstOp == Instruction::BitCast);
279106f32e7eSjoerg   bool IsSecondBitcast = (secondOp == Instruction::BitCast);
279206f32e7eSjoerg   bool AreBothBitcasts = IsFirstBitcast && IsSecondBitcast;
279306f32e7eSjoerg 
279406f32e7eSjoerg   // Check if any of the casts convert scalars <-> vectors.
279506f32e7eSjoerg   if ((IsFirstBitcast  && isa<VectorType>(SrcTy) != isa<VectorType>(MidTy)) ||
279606f32e7eSjoerg       (IsSecondBitcast && isa<VectorType>(MidTy) != isa<VectorType>(DstTy)))
279706f32e7eSjoerg     if (!AreBothBitcasts)
279806f32e7eSjoerg       return 0;
279906f32e7eSjoerg 
280006f32e7eSjoerg   int ElimCase = CastResults[firstOp-Instruction::CastOpsBegin]
280106f32e7eSjoerg                             [secondOp-Instruction::CastOpsBegin];
280206f32e7eSjoerg   switch (ElimCase) {
280306f32e7eSjoerg     case 0:
280406f32e7eSjoerg       // Categorically disallowed.
280506f32e7eSjoerg       return 0;
280606f32e7eSjoerg     case 1:
280706f32e7eSjoerg       // Allowed, use first cast's opcode.
280806f32e7eSjoerg       return firstOp;
280906f32e7eSjoerg     case 2:
281006f32e7eSjoerg       // Allowed, use second cast's opcode.
281106f32e7eSjoerg       return secondOp;
281206f32e7eSjoerg     case 3:
281306f32e7eSjoerg       // No-op cast in second op implies firstOp as long as the DestTy
281406f32e7eSjoerg       // is integer and we are not converting between a vector and a
281506f32e7eSjoerg       // non-vector type.
281606f32e7eSjoerg       if (!SrcTy->isVectorTy() && DstTy->isIntegerTy())
281706f32e7eSjoerg         return firstOp;
281806f32e7eSjoerg       return 0;
281906f32e7eSjoerg     case 4:
282006f32e7eSjoerg       // No-op cast in second op implies firstOp as long as the DestTy
282106f32e7eSjoerg       // is floating point.
282206f32e7eSjoerg       if (DstTy->isFloatingPointTy())
282306f32e7eSjoerg         return firstOp;
282406f32e7eSjoerg       return 0;
282506f32e7eSjoerg     case 5:
282606f32e7eSjoerg       // No-op cast in first op implies secondOp as long as the SrcTy
282706f32e7eSjoerg       // is an integer.
282806f32e7eSjoerg       if (SrcTy->isIntegerTy())
282906f32e7eSjoerg         return secondOp;
283006f32e7eSjoerg       return 0;
283106f32e7eSjoerg     case 6:
283206f32e7eSjoerg       // No-op cast in first op implies secondOp as long as the SrcTy
283306f32e7eSjoerg       // is a floating point.
283406f32e7eSjoerg       if (SrcTy->isFloatingPointTy())
283506f32e7eSjoerg         return secondOp;
283606f32e7eSjoerg       return 0;
283706f32e7eSjoerg     case 7: {
283806f32e7eSjoerg       // Cannot simplify if address spaces are different!
283906f32e7eSjoerg       if (SrcTy->getPointerAddressSpace() != DstTy->getPointerAddressSpace())
284006f32e7eSjoerg         return 0;
284106f32e7eSjoerg 
284206f32e7eSjoerg       unsigned MidSize = MidTy->getScalarSizeInBits();
284306f32e7eSjoerg       // We can still fold this without knowing the actual sizes as long we
284406f32e7eSjoerg       // know that the intermediate pointer is the largest possible
284506f32e7eSjoerg       // pointer size.
284606f32e7eSjoerg       // FIXME: Is this always true?
284706f32e7eSjoerg       if (MidSize == 64)
284806f32e7eSjoerg         return Instruction::BitCast;
284906f32e7eSjoerg 
285006f32e7eSjoerg       // ptrtoint, inttoptr -> bitcast (ptr -> ptr) if int size is >= ptr size.
285106f32e7eSjoerg       if (!SrcIntPtrTy || DstIntPtrTy != SrcIntPtrTy)
285206f32e7eSjoerg         return 0;
285306f32e7eSjoerg       unsigned PtrSize = SrcIntPtrTy->getScalarSizeInBits();
285406f32e7eSjoerg       if (MidSize >= PtrSize)
285506f32e7eSjoerg         return Instruction::BitCast;
285606f32e7eSjoerg       return 0;
285706f32e7eSjoerg     }
285806f32e7eSjoerg     case 8: {
285906f32e7eSjoerg       // ext, trunc -> bitcast,    if the SrcTy and DstTy are same size
286006f32e7eSjoerg       // ext, trunc -> ext,        if sizeof(SrcTy) < sizeof(DstTy)
286106f32e7eSjoerg       // ext, trunc -> trunc,      if sizeof(SrcTy) > sizeof(DstTy)
286206f32e7eSjoerg       unsigned SrcSize = SrcTy->getScalarSizeInBits();
286306f32e7eSjoerg       unsigned DstSize = DstTy->getScalarSizeInBits();
286406f32e7eSjoerg       if (SrcSize == DstSize)
286506f32e7eSjoerg         return Instruction::BitCast;
286606f32e7eSjoerg       else if (SrcSize < DstSize)
286706f32e7eSjoerg         return firstOp;
286806f32e7eSjoerg       return secondOp;
286906f32e7eSjoerg     }
287006f32e7eSjoerg     case 9:
287106f32e7eSjoerg       // zext, sext -> zext, because sext can't sign extend after zext
287206f32e7eSjoerg       return Instruction::ZExt;
287306f32e7eSjoerg     case 11: {
287406f32e7eSjoerg       // inttoptr, ptrtoint -> bitcast if SrcSize<=PtrSize and SrcSize==DstSize
287506f32e7eSjoerg       if (!MidIntPtrTy)
287606f32e7eSjoerg         return 0;
287706f32e7eSjoerg       unsigned PtrSize = MidIntPtrTy->getScalarSizeInBits();
287806f32e7eSjoerg       unsigned SrcSize = SrcTy->getScalarSizeInBits();
287906f32e7eSjoerg       unsigned DstSize = DstTy->getScalarSizeInBits();
288006f32e7eSjoerg       if (SrcSize <= PtrSize && SrcSize == DstSize)
288106f32e7eSjoerg         return Instruction::BitCast;
288206f32e7eSjoerg       return 0;
288306f32e7eSjoerg     }
288406f32e7eSjoerg     case 12:
288506f32e7eSjoerg       // addrspacecast, addrspacecast -> bitcast,       if SrcAS == DstAS
288606f32e7eSjoerg       // addrspacecast, addrspacecast -> addrspacecast, if SrcAS != DstAS
288706f32e7eSjoerg       if (SrcTy->getPointerAddressSpace() != DstTy->getPointerAddressSpace())
288806f32e7eSjoerg         return Instruction::AddrSpaceCast;
288906f32e7eSjoerg       return Instruction::BitCast;
289006f32e7eSjoerg     case 13:
289106f32e7eSjoerg       // FIXME: this state can be merged with (1), but the following assert
289206f32e7eSjoerg       // is useful to check the correcteness of the sequence due to semantic
289306f32e7eSjoerg       // change of bitcast.
289406f32e7eSjoerg       assert(
289506f32e7eSjoerg         SrcTy->isPtrOrPtrVectorTy() &&
289606f32e7eSjoerg         MidTy->isPtrOrPtrVectorTy() &&
289706f32e7eSjoerg         DstTy->isPtrOrPtrVectorTy() &&
289806f32e7eSjoerg         SrcTy->getPointerAddressSpace() != MidTy->getPointerAddressSpace() &&
289906f32e7eSjoerg         MidTy->getPointerAddressSpace() == DstTy->getPointerAddressSpace() &&
290006f32e7eSjoerg         "Illegal addrspacecast, bitcast sequence!");
290106f32e7eSjoerg       // Allowed, use first cast's opcode
290206f32e7eSjoerg       return firstOp;
290306f32e7eSjoerg     case 14:
290406f32e7eSjoerg       // bitcast, addrspacecast -> addrspacecast if the element type of
290506f32e7eSjoerg       // bitcast's source is the same as that of addrspacecast's destination.
290606f32e7eSjoerg       if (SrcTy->getScalarType()->getPointerElementType() ==
290706f32e7eSjoerg           DstTy->getScalarType()->getPointerElementType())
290806f32e7eSjoerg         return Instruction::AddrSpaceCast;
290906f32e7eSjoerg       return 0;
291006f32e7eSjoerg     case 15:
291106f32e7eSjoerg       // FIXME: this state can be merged with (1), but the following assert
291206f32e7eSjoerg       // is useful to check the correcteness of the sequence due to semantic
291306f32e7eSjoerg       // change of bitcast.
291406f32e7eSjoerg       assert(
291506f32e7eSjoerg         SrcTy->isIntOrIntVectorTy() &&
291606f32e7eSjoerg         MidTy->isPtrOrPtrVectorTy() &&
291706f32e7eSjoerg         DstTy->isPtrOrPtrVectorTy() &&
291806f32e7eSjoerg         MidTy->getPointerAddressSpace() == DstTy->getPointerAddressSpace() &&
291906f32e7eSjoerg         "Illegal inttoptr, bitcast sequence!");
292006f32e7eSjoerg       // Allowed, use first cast's opcode
292106f32e7eSjoerg       return firstOp;
292206f32e7eSjoerg     case 16:
292306f32e7eSjoerg       // FIXME: this state can be merged with (2), but the following assert
292406f32e7eSjoerg       // is useful to check the correcteness of the sequence due to semantic
292506f32e7eSjoerg       // change of bitcast.
292606f32e7eSjoerg       assert(
292706f32e7eSjoerg         SrcTy->isPtrOrPtrVectorTy() &&
292806f32e7eSjoerg         MidTy->isPtrOrPtrVectorTy() &&
292906f32e7eSjoerg         DstTy->isIntOrIntVectorTy() &&
293006f32e7eSjoerg         SrcTy->getPointerAddressSpace() == MidTy->getPointerAddressSpace() &&
293106f32e7eSjoerg         "Illegal bitcast, ptrtoint sequence!");
293206f32e7eSjoerg       // Allowed, use second cast's opcode
293306f32e7eSjoerg       return secondOp;
293406f32e7eSjoerg     case 17:
293506f32e7eSjoerg       // (sitofp (zext x)) -> (uitofp x)
293606f32e7eSjoerg       return Instruction::UIToFP;
293706f32e7eSjoerg     case 99:
293806f32e7eSjoerg       // Cast combination can't happen (error in input). This is for all cases
293906f32e7eSjoerg       // where the MidTy is not the same for the two cast instructions.
294006f32e7eSjoerg       llvm_unreachable("Invalid Cast Combination");
294106f32e7eSjoerg     default:
294206f32e7eSjoerg       llvm_unreachable("Error in CastResults table!!!");
294306f32e7eSjoerg   }
294406f32e7eSjoerg }
294506f32e7eSjoerg 
Create(Instruction::CastOps op,Value * S,Type * Ty,const Twine & Name,Instruction * InsertBefore)294606f32e7eSjoerg CastInst *CastInst::Create(Instruction::CastOps op, Value *S, Type *Ty,
294706f32e7eSjoerg   const Twine &Name, Instruction *InsertBefore) {
294806f32e7eSjoerg   assert(castIsValid(op, S, Ty) && "Invalid cast!");
294906f32e7eSjoerg   // Construct and return the appropriate CastInst subclass
295006f32e7eSjoerg   switch (op) {
295106f32e7eSjoerg   case Trunc:         return new TruncInst         (S, Ty, Name, InsertBefore);
295206f32e7eSjoerg   case ZExt:          return new ZExtInst          (S, Ty, Name, InsertBefore);
295306f32e7eSjoerg   case SExt:          return new SExtInst          (S, Ty, Name, InsertBefore);
295406f32e7eSjoerg   case FPTrunc:       return new FPTruncInst       (S, Ty, Name, InsertBefore);
295506f32e7eSjoerg   case FPExt:         return new FPExtInst         (S, Ty, Name, InsertBefore);
295606f32e7eSjoerg   case UIToFP:        return new UIToFPInst        (S, Ty, Name, InsertBefore);
295706f32e7eSjoerg   case SIToFP:        return new SIToFPInst        (S, Ty, Name, InsertBefore);
295806f32e7eSjoerg   case FPToUI:        return new FPToUIInst        (S, Ty, Name, InsertBefore);
295906f32e7eSjoerg   case FPToSI:        return new FPToSIInst        (S, Ty, Name, InsertBefore);
296006f32e7eSjoerg   case PtrToInt:      return new PtrToIntInst      (S, Ty, Name, InsertBefore);
296106f32e7eSjoerg   case IntToPtr:      return new IntToPtrInst      (S, Ty, Name, InsertBefore);
296206f32e7eSjoerg   case BitCast:       return new BitCastInst       (S, Ty, Name, InsertBefore);
296306f32e7eSjoerg   case AddrSpaceCast: return new AddrSpaceCastInst (S, Ty, Name, InsertBefore);
296406f32e7eSjoerg   default: llvm_unreachable("Invalid opcode provided");
296506f32e7eSjoerg   }
296606f32e7eSjoerg }
296706f32e7eSjoerg 
Create(Instruction::CastOps op,Value * S,Type * Ty,const Twine & Name,BasicBlock * InsertAtEnd)296806f32e7eSjoerg CastInst *CastInst::Create(Instruction::CastOps op, Value *S, Type *Ty,
296906f32e7eSjoerg   const Twine &Name, BasicBlock *InsertAtEnd) {
297006f32e7eSjoerg   assert(castIsValid(op, S, Ty) && "Invalid cast!");
297106f32e7eSjoerg   // Construct and return the appropriate CastInst subclass
297206f32e7eSjoerg   switch (op) {
297306f32e7eSjoerg   case Trunc:         return new TruncInst         (S, Ty, Name, InsertAtEnd);
297406f32e7eSjoerg   case ZExt:          return new ZExtInst          (S, Ty, Name, InsertAtEnd);
297506f32e7eSjoerg   case SExt:          return new SExtInst          (S, Ty, Name, InsertAtEnd);
297606f32e7eSjoerg   case FPTrunc:       return new FPTruncInst       (S, Ty, Name, InsertAtEnd);
297706f32e7eSjoerg   case FPExt:         return new FPExtInst         (S, Ty, Name, InsertAtEnd);
297806f32e7eSjoerg   case UIToFP:        return new UIToFPInst        (S, Ty, Name, InsertAtEnd);
297906f32e7eSjoerg   case SIToFP:        return new SIToFPInst        (S, Ty, Name, InsertAtEnd);
298006f32e7eSjoerg   case FPToUI:        return new FPToUIInst        (S, Ty, Name, InsertAtEnd);
298106f32e7eSjoerg   case FPToSI:        return new FPToSIInst        (S, Ty, Name, InsertAtEnd);
298206f32e7eSjoerg   case PtrToInt:      return new PtrToIntInst      (S, Ty, Name, InsertAtEnd);
298306f32e7eSjoerg   case IntToPtr:      return new IntToPtrInst      (S, Ty, Name, InsertAtEnd);
298406f32e7eSjoerg   case BitCast:       return new BitCastInst       (S, Ty, Name, InsertAtEnd);
298506f32e7eSjoerg   case AddrSpaceCast: return new AddrSpaceCastInst (S, Ty, Name, InsertAtEnd);
298606f32e7eSjoerg   default: llvm_unreachable("Invalid opcode provided");
298706f32e7eSjoerg   }
298806f32e7eSjoerg }
298906f32e7eSjoerg 
CreateZExtOrBitCast(Value * S,Type * Ty,const Twine & Name,Instruction * InsertBefore)299006f32e7eSjoerg CastInst *CastInst::CreateZExtOrBitCast(Value *S, Type *Ty,
299106f32e7eSjoerg                                         const Twine &Name,
299206f32e7eSjoerg                                         Instruction *InsertBefore) {
299306f32e7eSjoerg   if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
299406f32e7eSjoerg     return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
299506f32e7eSjoerg   return Create(Instruction::ZExt, S, Ty, Name, InsertBefore);
299606f32e7eSjoerg }
299706f32e7eSjoerg 
CreateZExtOrBitCast(Value * S,Type * Ty,const Twine & Name,BasicBlock * InsertAtEnd)299806f32e7eSjoerg CastInst *CastInst::CreateZExtOrBitCast(Value *S, Type *Ty,
299906f32e7eSjoerg                                         const Twine &Name,
300006f32e7eSjoerg                                         BasicBlock *InsertAtEnd) {
300106f32e7eSjoerg   if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
300206f32e7eSjoerg     return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
300306f32e7eSjoerg   return Create(Instruction::ZExt, S, Ty, Name, InsertAtEnd);
300406f32e7eSjoerg }
300506f32e7eSjoerg 
CreateSExtOrBitCast(Value * S,Type * Ty,const Twine & Name,Instruction * InsertBefore)300606f32e7eSjoerg CastInst *CastInst::CreateSExtOrBitCast(Value *S, Type *Ty,
300706f32e7eSjoerg                                         const Twine &Name,
300806f32e7eSjoerg                                         Instruction *InsertBefore) {
300906f32e7eSjoerg   if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
301006f32e7eSjoerg     return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
301106f32e7eSjoerg   return Create(Instruction::SExt, S, Ty, Name, InsertBefore);
301206f32e7eSjoerg }
301306f32e7eSjoerg 
CreateSExtOrBitCast(Value * S,Type * Ty,const Twine & Name,BasicBlock * InsertAtEnd)301406f32e7eSjoerg CastInst *CastInst::CreateSExtOrBitCast(Value *S, Type *Ty,
301506f32e7eSjoerg                                         const Twine &Name,
301606f32e7eSjoerg                                         BasicBlock *InsertAtEnd) {
301706f32e7eSjoerg   if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
301806f32e7eSjoerg     return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
301906f32e7eSjoerg   return Create(Instruction::SExt, S, Ty, Name, InsertAtEnd);
302006f32e7eSjoerg }
302106f32e7eSjoerg 
CreateTruncOrBitCast(Value * S,Type * Ty,const Twine & Name,Instruction * InsertBefore)302206f32e7eSjoerg CastInst *CastInst::CreateTruncOrBitCast(Value *S, Type *Ty,
302306f32e7eSjoerg                                          const Twine &Name,
302406f32e7eSjoerg                                          Instruction *InsertBefore) {
302506f32e7eSjoerg   if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
302606f32e7eSjoerg     return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
302706f32e7eSjoerg   return Create(Instruction::Trunc, S, Ty, Name, InsertBefore);
302806f32e7eSjoerg }
302906f32e7eSjoerg 
CreateTruncOrBitCast(Value * S,Type * Ty,const Twine & Name,BasicBlock * InsertAtEnd)303006f32e7eSjoerg CastInst *CastInst::CreateTruncOrBitCast(Value *S, Type *Ty,
303106f32e7eSjoerg                                          const Twine &Name,
303206f32e7eSjoerg                                          BasicBlock *InsertAtEnd) {
303306f32e7eSjoerg   if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
303406f32e7eSjoerg     return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
303506f32e7eSjoerg   return Create(Instruction::Trunc, S, Ty, Name, InsertAtEnd);
303606f32e7eSjoerg }
303706f32e7eSjoerg 
CreatePointerCast(Value * S,Type * Ty,const Twine & Name,BasicBlock * InsertAtEnd)303806f32e7eSjoerg CastInst *CastInst::CreatePointerCast(Value *S, Type *Ty,
303906f32e7eSjoerg                                       const Twine &Name,
304006f32e7eSjoerg                                       BasicBlock *InsertAtEnd) {
304106f32e7eSjoerg   assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
304206f32e7eSjoerg   assert((Ty->isIntOrIntVectorTy() || Ty->isPtrOrPtrVectorTy()) &&
304306f32e7eSjoerg          "Invalid cast");
304406f32e7eSjoerg   assert(Ty->isVectorTy() == S->getType()->isVectorTy() && "Invalid cast");
304506f32e7eSjoerg   assert((!Ty->isVectorTy() ||
3046*da58b97aSjoerg           cast<VectorType>(Ty)->getElementCount() ==
3047*da58b97aSjoerg               cast<VectorType>(S->getType())->getElementCount()) &&
304806f32e7eSjoerg          "Invalid cast");
304906f32e7eSjoerg 
305006f32e7eSjoerg   if (Ty->isIntOrIntVectorTy())
305106f32e7eSjoerg     return Create(Instruction::PtrToInt, S, Ty, Name, InsertAtEnd);
305206f32e7eSjoerg 
305306f32e7eSjoerg   return CreatePointerBitCastOrAddrSpaceCast(S, Ty, Name, InsertAtEnd);
305406f32e7eSjoerg }
305506f32e7eSjoerg 
305606f32e7eSjoerg /// Create a BitCast or a PtrToInt cast instruction
CreatePointerCast(Value * S,Type * Ty,const Twine & Name,Instruction * InsertBefore)305706f32e7eSjoerg CastInst *CastInst::CreatePointerCast(Value *S, Type *Ty,
305806f32e7eSjoerg                                       const Twine &Name,
305906f32e7eSjoerg                                       Instruction *InsertBefore) {
306006f32e7eSjoerg   assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
306106f32e7eSjoerg   assert((Ty->isIntOrIntVectorTy() || Ty->isPtrOrPtrVectorTy()) &&
306206f32e7eSjoerg          "Invalid cast");
306306f32e7eSjoerg   assert(Ty->isVectorTy() == S->getType()->isVectorTy() && "Invalid cast");
306406f32e7eSjoerg   assert((!Ty->isVectorTy() ||
3065*da58b97aSjoerg           cast<VectorType>(Ty)->getElementCount() ==
3066*da58b97aSjoerg               cast<VectorType>(S->getType())->getElementCount()) &&
306706f32e7eSjoerg          "Invalid cast");
306806f32e7eSjoerg 
306906f32e7eSjoerg   if (Ty->isIntOrIntVectorTy())
307006f32e7eSjoerg     return Create(Instruction::PtrToInt, S, Ty, Name, InsertBefore);
307106f32e7eSjoerg 
307206f32e7eSjoerg   return CreatePointerBitCastOrAddrSpaceCast(S, Ty, Name, InsertBefore);
307306f32e7eSjoerg }
307406f32e7eSjoerg 
CreatePointerBitCastOrAddrSpaceCast(Value * S,Type * Ty,const Twine & Name,BasicBlock * InsertAtEnd)307506f32e7eSjoerg CastInst *CastInst::CreatePointerBitCastOrAddrSpaceCast(
307606f32e7eSjoerg   Value *S, Type *Ty,
307706f32e7eSjoerg   const Twine &Name,
307806f32e7eSjoerg   BasicBlock *InsertAtEnd) {
307906f32e7eSjoerg   assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
308006f32e7eSjoerg   assert(Ty->isPtrOrPtrVectorTy() && "Invalid cast");
308106f32e7eSjoerg 
308206f32e7eSjoerg   if (S->getType()->getPointerAddressSpace() != Ty->getPointerAddressSpace())
308306f32e7eSjoerg     return Create(Instruction::AddrSpaceCast, S, Ty, Name, InsertAtEnd);
308406f32e7eSjoerg 
308506f32e7eSjoerg   return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
308606f32e7eSjoerg }
308706f32e7eSjoerg 
CreatePointerBitCastOrAddrSpaceCast(Value * S,Type * Ty,const Twine & Name,Instruction * InsertBefore)308806f32e7eSjoerg CastInst *CastInst::CreatePointerBitCastOrAddrSpaceCast(
308906f32e7eSjoerg   Value *S, Type *Ty,
309006f32e7eSjoerg   const Twine &Name,
309106f32e7eSjoerg   Instruction *InsertBefore) {
309206f32e7eSjoerg   assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
309306f32e7eSjoerg   assert(Ty->isPtrOrPtrVectorTy() && "Invalid cast");
309406f32e7eSjoerg 
309506f32e7eSjoerg   if (S->getType()->getPointerAddressSpace() != Ty->getPointerAddressSpace())
309606f32e7eSjoerg     return Create(Instruction::AddrSpaceCast, S, Ty, Name, InsertBefore);
309706f32e7eSjoerg 
309806f32e7eSjoerg   return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
309906f32e7eSjoerg }
310006f32e7eSjoerg 
CreateBitOrPointerCast(Value * S,Type * Ty,const Twine & Name,Instruction * InsertBefore)310106f32e7eSjoerg CastInst *CastInst::CreateBitOrPointerCast(Value *S, Type *Ty,
310206f32e7eSjoerg                                            const Twine &Name,
310306f32e7eSjoerg                                            Instruction *InsertBefore) {
310406f32e7eSjoerg   if (S->getType()->isPointerTy() && Ty->isIntegerTy())
310506f32e7eSjoerg     return Create(Instruction::PtrToInt, S, Ty, Name, InsertBefore);
310606f32e7eSjoerg   if (S->getType()->isIntegerTy() && Ty->isPointerTy())
310706f32e7eSjoerg     return Create(Instruction::IntToPtr, S, Ty, Name, InsertBefore);
310806f32e7eSjoerg 
310906f32e7eSjoerg   return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
311006f32e7eSjoerg }
311106f32e7eSjoerg 
CreateIntegerCast(Value * C,Type * Ty,bool isSigned,const Twine & Name,Instruction * InsertBefore)311206f32e7eSjoerg CastInst *CastInst::CreateIntegerCast(Value *C, Type *Ty,
311306f32e7eSjoerg                                       bool isSigned, const Twine &Name,
311406f32e7eSjoerg                                       Instruction *InsertBefore) {
311506f32e7eSjoerg   assert(C->getType()->isIntOrIntVectorTy() && Ty->isIntOrIntVectorTy() &&
311606f32e7eSjoerg          "Invalid integer cast");
311706f32e7eSjoerg   unsigned SrcBits = C->getType()->getScalarSizeInBits();
311806f32e7eSjoerg   unsigned DstBits = Ty->getScalarSizeInBits();
311906f32e7eSjoerg   Instruction::CastOps opcode =
312006f32e7eSjoerg     (SrcBits == DstBits ? Instruction::BitCast :
312106f32e7eSjoerg      (SrcBits > DstBits ? Instruction::Trunc :
312206f32e7eSjoerg       (isSigned ? Instruction::SExt : Instruction::ZExt)));
312306f32e7eSjoerg   return Create(opcode, C, Ty, Name, InsertBefore);
312406f32e7eSjoerg }
312506f32e7eSjoerg 
CreateIntegerCast(Value * C,Type * Ty,bool isSigned,const Twine & Name,BasicBlock * InsertAtEnd)312606f32e7eSjoerg CastInst *CastInst::CreateIntegerCast(Value *C, Type *Ty,
312706f32e7eSjoerg                                       bool isSigned, const Twine &Name,
312806f32e7eSjoerg                                       BasicBlock *InsertAtEnd) {
312906f32e7eSjoerg   assert(C->getType()->isIntOrIntVectorTy() && Ty->isIntOrIntVectorTy() &&
313006f32e7eSjoerg          "Invalid cast");
313106f32e7eSjoerg   unsigned SrcBits = C->getType()->getScalarSizeInBits();
313206f32e7eSjoerg   unsigned DstBits = Ty->getScalarSizeInBits();
313306f32e7eSjoerg   Instruction::CastOps opcode =
313406f32e7eSjoerg     (SrcBits == DstBits ? Instruction::BitCast :
313506f32e7eSjoerg      (SrcBits > DstBits ? Instruction::Trunc :
313606f32e7eSjoerg       (isSigned ? Instruction::SExt : Instruction::ZExt)));
313706f32e7eSjoerg   return Create(opcode, C, Ty, Name, InsertAtEnd);
313806f32e7eSjoerg }
313906f32e7eSjoerg 
CreateFPCast(Value * C,Type * Ty,const Twine & Name,Instruction * InsertBefore)314006f32e7eSjoerg CastInst *CastInst::CreateFPCast(Value *C, Type *Ty,
314106f32e7eSjoerg                                  const Twine &Name,
314206f32e7eSjoerg                                  Instruction *InsertBefore) {
314306f32e7eSjoerg   assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
314406f32e7eSjoerg          "Invalid cast");
314506f32e7eSjoerg   unsigned SrcBits = C->getType()->getScalarSizeInBits();
314606f32e7eSjoerg   unsigned DstBits = Ty->getScalarSizeInBits();
314706f32e7eSjoerg   Instruction::CastOps opcode =
314806f32e7eSjoerg     (SrcBits == DstBits ? Instruction::BitCast :
314906f32e7eSjoerg      (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
315006f32e7eSjoerg   return Create(opcode, C, Ty, Name, InsertBefore);
315106f32e7eSjoerg }
315206f32e7eSjoerg 
CreateFPCast(Value * C,Type * Ty,const Twine & Name,BasicBlock * InsertAtEnd)315306f32e7eSjoerg CastInst *CastInst::CreateFPCast(Value *C, Type *Ty,
315406f32e7eSjoerg                                  const Twine &Name,
315506f32e7eSjoerg                                  BasicBlock *InsertAtEnd) {
315606f32e7eSjoerg   assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
315706f32e7eSjoerg          "Invalid cast");
315806f32e7eSjoerg   unsigned SrcBits = C->getType()->getScalarSizeInBits();
315906f32e7eSjoerg   unsigned DstBits = Ty->getScalarSizeInBits();
316006f32e7eSjoerg   Instruction::CastOps opcode =
316106f32e7eSjoerg     (SrcBits == DstBits ? Instruction::BitCast :
316206f32e7eSjoerg      (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
316306f32e7eSjoerg   return Create(opcode, C, Ty, Name, InsertAtEnd);
316406f32e7eSjoerg }
316506f32e7eSjoerg 
isBitCastable(Type * SrcTy,Type * DestTy)316606f32e7eSjoerg bool CastInst::isBitCastable(Type *SrcTy, Type *DestTy) {
316706f32e7eSjoerg   if (!SrcTy->isFirstClassType() || !DestTy->isFirstClassType())
316806f32e7eSjoerg     return false;
316906f32e7eSjoerg 
317006f32e7eSjoerg   if (SrcTy == DestTy)
317106f32e7eSjoerg     return true;
317206f32e7eSjoerg 
317306f32e7eSjoerg   if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy)) {
317406f32e7eSjoerg     if (VectorType *DestVecTy = dyn_cast<VectorType>(DestTy)) {
317506f32e7eSjoerg       if (SrcVecTy->getElementCount() == DestVecTy->getElementCount()) {
317606f32e7eSjoerg         // An element by element cast. Valid if casting the elements is valid.
317706f32e7eSjoerg         SrcTy = SrcVecTy->getElementType();
317806f32e7eSjoerg         DestTy = DestVecTy->getElementType();
317906f32e7eSjoerg       }
318006f32e7eSjoerg     }
318106f32e7eSjoerg   }
318206f32e7eSjoerg 
318306f32e7eSjoerg   if (PointerType *DestPtrTy = dyn_cast<PointerType>(DestTy)) {
318406f32e7eSjoerg     if (PointerType *SrcPtrTy = dyn_cast<PointerType>(SrcTy)) {
318506f32e7eSjoerg       return SrcPtrTy->getAddressSpace() == DestPtrTy->getAddressSpace();
318606f32e7eSjoerg     }
318706f32e7eSjoerg   }
318806f32e7eSjoerg 
318906f32e7eSjoerg   TypeSize SrcBits = SrcTy->getPrimitiveSizeInBits();   // 0 for ptr
319006f32e7eSjoerg   TypeSize DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr
319106f32e7eSjoerg 
319206f32e7eSjoerg   // Could still have vectors of pointers if the number of elements doesn't
319306f32e7eSjoerg   // match
319406f32e7eSjoerg   if (SrcBits.getKnownMinSize() == 0 || DestBits.getKnownMinSize() == 0)
319506f32e7eSjoerg     return false;
319606f32e7eSjoerg 
319706f32e7eSjoerg   if (SrcBits != DestBits)
319806f32e7eSjoerg     return false;
319906f32e7eSjoerg 
320006f32e7eSjoerg   if (DestTy->isX86_MMXTy() || SrcTy->isX86_MMXTy())
320106f32e7eSjoerg     return false;
320206f32e7eSjoerg 
320306f32e7eSjoerg   return true;
320406f32e7eSjoerg }
320506f32e7eSjoerg 
isBitOrNoopPointerCastable(Type * SrcTy,Type * DestTy,const DataLayout & DL)320606f32e7eSjoerg bool CastInst::isBitOrNoopPointerCastable(Type *SrcTy, Type *DestTy,
320706f32e7eSjoerg                                           const DataLayout &DL) {
320806f32e7eSjoerg   // ptrtoint and inttoptr are not allowed on non-integral pointers
320906f32e7eSjoerg   if (auto *PtrTy = dyn_cast<PointerType>(SrcTy))
321006f32e7eSjoerg     if (auto *IntTy = dyn_cast<IntegerType>(DestTy))
321106f32e7eSjoerg       return (IntTy->getBitWidth() == DL.getPointerTypeSizeInBits(PtrTy) &&
321206f32e7eSjoerg               !DL.isNonIntegralPointerType(PtrTy));
321306f32e7eSjoerg   if (auto *PtrTy = dyn_cast<PointerType>(DestTy))
321406f32e7eSjoerg     if (auto *IntTy = dyn_cast<IntegerType>(SrcTy))
321506f32e7eSjoerg       return (IntTy->getBitWidth() == DL.getPointerTypeSizeInBits(PtrTy) &&
321606f32e7eSjoerg               !DL.isNonIntegralPointerType(PtrTy));
321706f32e7eSjoerg 
321806f32e7eSjoerg   return isBitCastable(SrcTy, DestTy);
321906f32e7eSjoerg }
322006f32e7eSjoerg 
322106f32e7eSjoerg // Provide a way to get a "cast" where the cast opcode is inferred from the
322206f32e7eSjoerg // types and size of the operand. This, basically, is a parallel of the
322306f32e7eSjoerg // logic in the castIsValid function below.  This axiom should hold:
322406f32e7eSjoerg //   castIsValid( getCastOpcode(Val, Ty), Val, Ty)
322506f32e7eSjoerg // should not assert in castIsValid. In other words, this produces a "correct"
322606f32e7eSjoerg // casting opcode for the arguments passed to it.
322706f32e7eSjoerg Instruction::CastOps
getCastOpcode(const Value * Src,bool SrcIsSigned,Type * DestTy,bool DestIsSigned)322806f32e7eSjoerg CastInst::getCastOpcode(
322906f32e7eSjoerg   const Value *Src, bool SrcIsSigned, Type *DestTy, bool DestIsSigned) {
323006f32e7eSjoerg   Type *SrcTy = Src->getType();
323106f32e7eSjoerg 
323206f32e7eSjoerg   assert(SrcTy->isFirstClassType() && DestTy->isFirstClassType() &&
323306f32e7eSjoerg          "Only first class types are castable!");
323406f32e7eSjoerg 
323506f32e7eSjoerg   if (SrcTy == DestTy)
323606f32e7eSjoerg     return BitCast;
323706f32e7eSjoerg 
323806f32e7eSjoerg   // FIXME: Check address space sizes here
323906f32e7eSjoerg   if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy))
324006f32e7eSjoerg     if (VectorType *DestVecTy = dyn_cast<VectorType>(DestTy))
3241*da58b97aSjoerg       if (SrcVecTy->getElementCount() == DestVecTy->getElementCount()) {
324206f32e7eSjoerg         // An element by element cast.  Find the appropriate opcode based on the
324306f32e7eSjoerg         // element types.
324406f32e7eSjoerg         SrcTy = SrcVecTy->getElementType();
324506f32e7eSjoerg         DestTy = DestVecTy->getElementType();
324606f32e7eSjoerg       }
324706f32e7eSjoerg 
324806f32e7eSjoerg   // Get the bit sizes, we'll need these
324906f32e7eSjoerg   unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();   // 0 for ptr
325006f32e7eSjoerg   unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr
325106f32e7eSjoerg 
325206f32e7eSjoerg   // Run through the possibilities ...
325306f32e7eSjoerg   if (DestTy->isIntegerTy()) {                      // Casting to integral
325406f32e7eSjoerg     if (SrcTy->isIntegerTy()) {                     // Casting from integral
325506f32e7eSjoerg       if (DestBits < SrcBits)
325606f32e7eSjoerg         return Trunc;                               // int -> smaller int
325706f32e7eSjoerg       else if (DestBits > SrcBits) {                // its an extension
325806f32e7eSjoerg         if (SrcIsSigned)
325906f32e7eSjoerg           return SExt;                              // signed -> SEXT
326006f32e7eSjoerg         else
326106f32e7eSjoerg           return ZExt;                              // unsigned -> ZEXT
326206f32e7eSjoerg       } else {
326306f32e7eSjoerg         return BitCast;                             // Same size, No-op cast
326406f32e7eSjoerg       }
326506f32e7eSjoerg     } else if (SrcTy->isFloatingPointTy()) {        // Casting from floating pt
326606f32e7eSjoerg       if (DestIsSigned)
326706f32e7eSjoerg         return FPToSI;                              // FP -> sint
326806f32e7eSjoerg       else
326906f32e7eSjoerg         return FPToUI;                              // FP -> uint
327006f32e7eSjoerg     } else if (SrcTy->isVectorTy()) {
327106f32e7eSjoerg       assert(DestBits == SrcBits &&
327206f32e7eSjoerg              "Casting vector to integer of different width");
327306f32e7eSjoerg       return BitCast;                             // Same size, no-op cast
327406f32e7eSjoerg     } else {
327506f32e7eSjoerg       assert(SrcTy->isPointerTy() &&
327606f32e7eSjoerg              "Casting from a value that is not first-class type");
327706f32e7eSjoerg       return PtrToInt;                              // ptr -> int
327806f32e7eSjoerg     }
327906f32e7eSjoerg   } else if (DestTy->isFloatingPointTy()) {         // Casting to floating pt
328006f32e7eSjoerg     if (SrcTy->isIntegerTy()) {                     // Casting from integral
328106f32e7eSjoerg       if (SrcIsSigned)
328206f32e7eSjoerg         return SIToFP;                              // sint -> FP
328306f32e7eSjoerg       else
328406f32e7eSjoerg         return UIToFP;                              // uint -> FP
328506f32e7eSjoerg     } else if (SrcTy->isFloatingPointTy()) {        // Casting from floating pt
328606f32e7eSjoerg       if (DestBits < SrcBits) {
328706f32e7eSjoerg         return FPTrunc;                             // FP -> smaller FP
328806f32e7eSjoerg       } else if (DestBits > SrcBits) {
328906f32e7eSjoerg         return FPExt;                               // FP -> larger FP
329006f32e7eSjoerg       } else  {
329106f32e7eSjoerg         return BitCast;                             // same size, no-op cast
329206f32e7eSjoerg       }
329306f32e7eSjoerg     } else if (SrcTy->isVectorTy()) {
329406f32e7eSjoerg       assert(DestBits == SrcBits &&
329506f32e7eSjoerg              "Casting vector to floating point of different width");
329606f32e7eSjoerg       return BitCast;                             // same size, no-op cast
329706f32e7eSjoerg     }
329806f32e7eSjoerg     llvm_unreachable("Casting pointer or non-first class to float");
329906f32e7eSjoerg   } else if (DestTy->isVectorTy()) {
330006f32e7eSjoerg     assert(DestBits == SrcBits &&
330106f32e7eSjoerg            "Illegal cast to vector (wrong type or size)");
330206f32e7eSjoerg     return BitCast;
330306f32e7eSjoerg   } else if (DestTy->isPointerTy()) {
330406f32e7eSjoerg     if (SrcTy->isPointerTy()) {
330506f32e7eSjoerg       if (DestTy->getPointerAddressSpace() != SrcTy->getPointerAddressSpace())
330606f32e7eSjoerg         return AddrSpaceCast;
330706f32e7eSjoerg       return BitCast;                               // ptr -> ptr
330806f32e7eSjoerg     } else if (SrcTy->isIntegerTy()) {
330906f32e7eSjoerg       return IntToPtr;                              // int -> ptr
331006f32e7eSjoerg     }
331106f32e7eSjoerg     llvm_unreachable("Casting pointer to other than pointer or int");
331206f32e7eSjoerg   } else if (DestTy->isX86_MMXTy()) {
331306f32e7eSjoerg     if (SrcTy->isVectorTy()) {
331406f32e7eSjoerg       assert(DestBits == SrcBits && "Casting vector of wrong width to X86_MMX");
331506f32e7eSjoerg       return BitCast;                               // 64-bit vector to MMX
331606f32e7eSjoerg     }
331706f32e7eSjoerg     llvm_unreachable("Illegal cast to X86_MMX");
331806f32e7eSjoerg   }
331906f32e7eSjoerg   llvm_unreachable("Casting to type that is not first-class");
332006f32e7eSjoerg }
332106f32e7eSjoerg 
332206f32e7eSjoerg //===----------------------------------------------------------------------===//
332306f32e7eSjoerg //                    CastInst SubClass Constructors
332406f32e7eSjoerg //===----------------------------------------------------------------------===//
332506f32e7eSjoerg 
332606f32e7eSjoerg /// Check that the construction parameters for a CastInst are correct. This
332706f32e7eSjoerg /// could be broken out into the separate constructors but it is useful to have
332806f32e7eSjoerg /// it in one place and to eliminate the redundant code for getting the sizes
332906f32e7eSjoerg /// of the types involved.
333006f32e7eSjoerg bool
castIsValid(Instruction::CastOps op,Type * SrcTy,Type * DstTy)3331*da58b97aSjoerg CastInst::castIsValid(Instruction::CastOps op, Type *SrcTy, Type *DstTy) {
333206f32e7eSjoerg   if (!SrcTy->isFirstClassType() || !DstTy->isFirstClassType() ||
333306f32e7eSjoerg       SrcTy->isAggregateType() || DstTy->isAggregateType())
333406f32e7eSjoerg     return false;
333506f32e7eSjoerg 
3336*da58b97aSjoerg   // Get the size of the types in bits, and whether we are dealing
3337*da58b97aSjoerg   // with vector types, we'll need this later.
3338*da58b97aSjoerg   bool SrcIsVec = isa<VectorType>(SrcTy);
3339*da58b97aSjoerg   bool DstIsVec = isa<VectorType>(DstTy);
3340*da58b97aSjoerg   unsigned SrcScalarBitSize = SrcTy->getScalarSizeInBits();
3341*da58b97aSjoerg   unsigned DstScalarBitSize = DstTy->getScalarSizeInBits();
334206f32e7eSjoerg 
334306f32e7eSjoerg   // If these are vector types, get the lengths of the vectors (using zero for
334406f32e7eSjoerg   // scalar types means that checking that vector lengths match also checks that
334506f32e7eSjoerg   // scalars are not being converted to vectors or vectors to scalars).
3346*da58b97aSjoerg   ElementCount SrcEC = SrcIsVec ? cast<VectorType>(SrcTy)->getElementCount()
3347*da58b97aSjoerg                                 : ElementCount::getFixed(0);
3348*da58b97aSjoerg   ElementCount DstEC = DstIsVec ? cast<VectorType>(DstTy)->getElementCount()
3349*da58b97aSjoerg                                 : ElementCount::getFixed(0);
335006f32e7eSjoerg 
335106f32e7eSjoerg   // Switch on the opcode provided
335206f32e7eSjoerg   switch (op) {
335306f32e7eSjoerg   default: return false; // This is an input error
335406f32e7eSjoerg   case Instruction::Trunc:
335506f32e7eSjoerg     return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() &&
3356*da58b97aSjoerg            SrcEC == DstEC && SrcScalarBitSize > DstScalarBitSize;
335706f32e7eSjoerg   case Instruction::ZExt:
335806f32e7eSjoerg     return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() &&
3359*da58b97aSjoerg            SrcEC == DstEC && SrcScalarBitSize < DstScalarBitSize;
336006f32e7eSjoerg   case Instruction::SExt:
336106f32e7eSjoerg     return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() &&
3362*da58b97aSjoerg            SrcEC == DstEC && SrcScalarBitSize < DstScalarBitSize;
336306f32e7eSjoerg   case Instruction::FPTrunc:
336406f32e7eSjoerg     return SrcTy->isFPOrFPVectorTy() && DstTy->isFPOrFPVectorTy() &&
3365*da58b97aSjoerg            SrcEC == DstEC && SrcScalarBitSize > DstScalarBitSize;
336606f32e7eSjoerg   case Instruction::FPExt:
336706f32e7eSjoerg     return SrcTy->isFPOrFPVectorTy() && DstTy->isFPOrFPVectorTy() &&
3368*da58b97aSjoerg            SrcEC == DstEC && SrcScalarBitSize < DstScalarBitSize;
336906f32e7eSjoerg   case Instruction::UIToFP:
337006f32e7eSjoerg   case Instruction::SIToFP:
337106f32e7eSjoerg     return SrcTy->isIntOrIntVectorTy() && DstTy->isFPOrFPVectorTy() &&
3372*da58b97aSjoerg            SrcEC == DstEC;
337306f32e7eSjoerg   case Instruction::FPToUI:
337406f32e7eSjoerg   case Instruction::FPToSI:
337506f32e7eSjoerg     return SrcTy->isFPOrFPVectorTy() && DstTy->isIntOrIntVectorTy() &&
3376*da58b97aSjoerg            SrcEC == DstEC;
337706f32e7eSjoerg   case Instruction::PtrToInt:
3378*da58b97aSjoerg     if (SrcEC != DstEC)
337906f32e7eSjoerg       return false;
338006f32e7eSjoerg     return SrcTy->isPtrOrPtrVectorTy() && DstTy->isIntOrIntVectorTy();
338106f32e7eSjoerg   case Instruction::IntToPtr:
3382*da58b97aSjoerg     if (SrcEC != DstEC)
338306f32e7eSjoerg       return false;
338406f32e7eSjoerg     return SrcTy->isIntOrIntVectorTy() && DstTy->isPtrOrPtrVectorTy();
338506f32e7eSjoerg   case Instruction::BitCast: {
338606f32e7eSjoerg     PointerType *SrcPtrTy = dyn_cast<PointerType>(SrcTy->getScalarType());
338706f32e7eSjoerg     PointerType *DstPtrTy = dyn_cast<PointerType>(DstTy->getScalarType());
338806f32e7eSjoerg 
338906f32e7eSjoerg     // BitCast implies a no-op cast of type only. No bits change.
339006f32e7eSjoerg     // However, you can't cast pointers to anything but pointers.
339106f32e7eSjoerg     if (!SrcPtrTy != !DstPtrTy)
339206f32e7eSjoerg       return false;
339306f32e7eSjoerg 
339406f32e7eSjoerg     // For non-pointer cases, the cast is okay if the source and destination bit
339506f32e7eSjoerg     // widths are identical.
339606f32e7eSjoerg     if (!SrcPtrTy)
339706f32e7eSjoerg       return SrcTy->getPrimitiveSizeInBits() == DstTy->getPrimitiveSizeInBits();
339806f32e7eSjoerg 
339906f32e7eSjoerg     // If both are pointers then the address spaces must match.
340006f32e7eSjoerg     if (SrcPtrTy->getAddressSpace() != DstPtrTy->getAddressSpace())
340106f32e7eSjoerg       return false;
340206f32e7eSjoerg 
340306f32e7eSjoerg     // A vector of pointers must have the same number of elements.
3404*da58b97aSjoerg     if (SrcIsVec && DstIsVec)
3405*da58b97aSjoerg       return SrcEC == DstEC;
3406*da58b97aSjoerg     if (SrcIsVec)
3407*da58b97aSjoerg       return SrcEC == ElementCount::getFixed(1);
3408*da58b97aSjoerg     if (DstIsVec)
3409*da58b97aSjoerg       return DstEC == ElementCount::getFixed(1);
341006f32e7eSjoerg 
341106f32e7eSjoerg     return true;
341206f32e7eSjoerg   }
341306f32e7eSjoerg   case Instruction::AddrSpaceCast: {
341406f32e7eSjoerg     PointerType *SrcPtrTy = dyn_cast<PointerType>(SrcTy->getScalarType());
341506f32e7eSjoerg     if (!SrcPtrTy)
341606f32e7eSjoerg       return false;
341706f32e7eSjoerg 
341806f32e7eSjoerg     PointerType *DstPtrTy = dyn_cast<PointerType>(DstTy->getScalarType());
341906f32e7eSjoerg     if (!DstPtrTy)
342006f32e7eSjoerg       return false;
342106f32e7eSjoerg 
342206f32e7eSjoerg     if (SrcPtrTy->getAddressSpace() == DstPtrTy->getAddressSpace())
342306f32e7eSjoerg       return false;
342406f32e7eSjoerg 
3425*da58b97aSjoerg     return SrcEC == DstEC;
342606f32e7eSjoerg   }
342706f32e7eSjoerg   }
342806f32e7eSjoerg }
342906f32e7eSjoerg 
TruncInst(Value * S,Type * Ty,const Twine & Name,Instruction * InsertBefore)343006f32e7eSjoerg TruncInst::TruncInst(
343106f32e7eSjoerg   Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
343206f32e7eSjoerg ) : CastInst(Ty, Trunc, S, Name, InsertBefore) {
343306f32e7eSjoerg   assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
343406f32e7eSjoerg }
343506f32e7eSjoerg 
TruncInst(Value * S,Type * Ty,const Twine & Name,BasicBlock * InsertAtEnd)343606f32e7eSjoerg TruncInst::TruncInst(
343706f32e7eSjoerg   Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
343806f32e7eSjoerg ) : CastInst(Ty, Trunc, S, Name, InsertAtEnd) {
343906f32e7eSjoerg   assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
344006f32e7eSjoerg }
344106f32e7eSjoerg 
ZExtInst(Value * S,Type * Ty,const Twine & Name,Instruction * InsertBefore)344206f32e7eSjoerg ZExtInst::ZExtInst(
344306f32e7eSjoerg   Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
344406f32e7eSjoerg )  : CastInst(Ty, ZExt, S, Name, InsertBefore) {
344506f32e7eSjoerg   assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
344606f32e7eSjoerg }
344706f32e7eSjoerg 
ZExtInst(Value * S,Type * Ty,const Twine & Name,BasicBlock * InsertAtEnd)344806f32e7eSjoerg ZExtInst::ZExtInst(
344906f32e7eSjoerg   Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
345006f32e7eSjoerg )  : CastInst(Ty, ZExt, S, Name, InsertAtEnd) {
345106f32e7eSjoerg   assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
345206f32e7eSjoerg }
SExtInst(Value * S,Type * Ty,const Twine & Name,Instruction * InsertBefore)345306f32e7eSjoerg SExtInst::SExtInst(
345406f32e7eSjoerg   Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
345506f32e7eSjoerg ) : CastInst(Ty, SExt, S, Name, InsertBefore) {
345606f32e7eSjoerg   assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
345706f32e7eSjoerg }
345806f32e7eSjoerg 
SExtInst(Value * S,Type * Ty,const Twine & Name,BasicBlock * InsertAtEnd)345906f32e7eSjoerg SExtInst::SExtInst(
346006f32e7eSjoerg   Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
346106f32e7eSjoerg )  : CastInst(Ty, SExt, S, Name, InsertAtEnd) {
346206f32e7eSjoerg   assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
346306f32e7eSjoerg }
346406f32e7eSjoerg 
FPTruncInst(Value * S,Type * Ty,const Twine & Name,Instruction * InsertBefore)346506f32e7eSjoerg FPTruncInst::FPTruncInst(
346606f32e7eSjoerg   Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
346706f32e7eSjoerg ) : CastInst(Ty, FPTrunc, S, Name, InsertBefore) {
346806f32e7eSjoerg   assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
346906f32e7eSjoerg }
347006f32e7eSjoerg 
FPTruncInst(Value * S,Type * Ty,const Twine & Name,BasicBlock * InsertAtEnd)347106f32e7eSjoerg FPTruncInst::FPTruncInst(
347206f32e7eSjoerg   Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
347306f32e7eSjoerg ) : CastInst(Ty, FPTrunc, S, Name, InsertAtEnd) {
347406f32e7eSjoerg   assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
347506f32e7eSjoerg }
347606f32e7eSjoerg 
FPExtInst(Value * S,Type * Ty,const Twine & Name,Instruction * InsertBefore)347706f32e7eSjoerg FPExtInst::FPExtInst(
347806f32e7eSjoerg   Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
347906f32e7eSjoerg ) : CastInst(Ty, FPExt, S, Name, InsertBefore) {
348006f32e7eSjoerg   assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
348106f32e7eSjoerg }
348206f32e7eSjoerg 
FPExtInst(Value * S,Type * Ty,const Twine & Name,BasicBlock * InsertAtEnd)348306f32e7eSjoerg FPExtInst::FPExtInst(
348406f32e7eSjoerg   Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
348506f32e7eSjoerg ) : CastInst(Ty, FPExt, S, Name, InsertAtEnd) {
348606f32e7eSjoerg   assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
348706f32e7eSjoerg }
348806f32e7eSjoerg 
UIToFPInst(Value * S,Type * Ty,const Twine & Name,Instruction * InsertBefore)348906f32e7eSjoerg UIToFPInst::UIToFPInst(
349006f32e7eSjoerg   Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
349106f32e7eSjoerg ) : CastInst(Ty, UIToFP, S, Name, InsertBefore) {
349206f32e7eSjoerg   assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
349306f32e7eSjoerg }
349406f32e7eSjoerg 
UIToFPInst(Value * S,Type * Ty,const Twine & Name,BasicBlock * InsertAtEnd)349506f32e7eSjoerg UIToFPInst::UIToFPInst(
349606f32e7eSjoerg   Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
349706f32e7eSjoerg ) : CastInst(Ty, UIToFP, S, Name, InsertAtEnd) {
349806f32e7eSjoerg   assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
349906f32e7eSjoerg }
350006f32e7eSjoerg 
SIToFPInst(Value * S,Type * Ty,const Twine & Name,Instruction * InsertBefore)350106f32e7eSjoerg SIToFPInst::SIToFPInst(
350206f32e7eSjoerg   Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
350306f32e7eSjoerg ) : CastInst(Ty, SIToFP, S, Name, InsertBefore) {
350406f32e7eSjoerg   assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
350506f32e7eSjoerg }
350606f32e7eSjoerg 
SIToFPInst(Value * S,Type * Ty,const Twine & Name,BasicBlock * InsertAtEnd)350706f32e7eSjoerg SIToFPInst::SIToFPInst(
350806f32e7eSjoerg   Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
350906f32e7eSjoerg ) : CastInst(Ty, SIToFP, S, Name, InsertAtEnd) {
351006f32e7eSjoerg   assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
351106f32e7eSjoerg }
351206f32e7eSjoerg 
FPToUIInst(Value * S,Type * Ty,const Twine & Name,Instruction * InsertBefore)351306f32e7eSjoerg FPToUIInst::FPToUIInst(
351406f32e7eSjoerg   Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
351506f32e7eSjoerg ) : CastInst(Ty, FPToUI, S, Name, InsertBefore) {
351606f32e7eSjoerg   assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
351706f32e7eSjoerg }
351806f32e7eSjoerg 
FPToUIInst(Value * S,Type * Ty,const Twine & Name,BasicBlock * InsertAtEnd)351906f32e7eSjoerg FPToUIInst::FPToUIInst(
352006f32e7eSjoerg   Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
352106f32e7eSjoerg ) : CastInst(Ty, FPToUI, S, Name, InsertAtEnd) {
352206f32e7eSjoerg   assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
352306f32e7eSjoerg }
352406f32e7eSjoerg 
FPToSIInst(Value * S,Type * Ty,const Twine & Name,Instruction * InsertBefore)352506f32e7eSjoerg FPToSIInst::FPToSIInst(
352606f32e7eSjoerg   Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
352706f32e7eSjoerg ) : CastInst(Ty, FPToSI, S, Name, InsertBefore) {
352806f32e7eSjoerg   assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
352906f32e7eSjoerg }
353006f32e7eSjoerg 
FPToSIInst(Value * S,Type * Ty,const Twine & Name,BasicBlock * InsertAtEnd)353106f32e7eSjoerg FPToSIInst::FPToSIInst(
353206f32e7eSjoerg   Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
353306f32e7eSjoerg ) : CastInst(Ty, FPToSI, S, Name, InsertAtEnd) {
353406f32e7eSjoerg   assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
353506f32e7eSjoerg }
353606f32e7eSjoerg 
PtrToIntInst(Value * S,Type * Ty,const Twine & Name,Instruction * InsertBefore)353706f32e7eSjoerg PtrToIntInst::PtrToIntInst(
353806f32e7eSjoerg   Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
353906f32e7eSjoerg ) : CastInst(Ty, PtrToInt, S, Name, InsertBefore) {
354006f32e7eSjoerg   assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
354106f32e7eSjoerg }
354206f32e7eSjoerg 
PtrToIntInst(Value * S,Type * Ty,const Twine & Name,BasicBlock * InsertAtEnd)354306f32e7eSjoerg PtrToIntInst::PtrToIntInst(
354406f32e7eSjoerg   Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
354506f32e7eSjoerg ) : CastInst(Ty, PtrToInt, S, Name, InsertAtEnd) {
354606f32e7eSjoerg   assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
354706f32e7eSjoerg }
354806f32e7eSjoerg 
IntToPtrInst(Value * S,Type * Ty,const Twine & Name,Instruction * InsertBefore)354906f32e7eSjoerg IntToPtrInst::IntToPtrInst(
355006f32e7eSjoerg   Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
355106f32e7eSjoerg ) : CastInst(Ty, IntToPtr, S, Name, InsertBefore) {
355206f32e7eSjoerg   assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
355306f32e7eSjoerg }
355406f32e7eSjoerg 
IntToPtrInst(Value * S,Type * Ty,const Twine & Name,BasicBlock * InsertAtEnd)355506f32e7eSjoerg IntToPtrInst::IntToPtrInst(
355606f32e7eSjoerg   Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
355706f32e7eSjoerg ) : CastInst(Ty, IntToPtr, S, Name, InsertAtEnd) {
355806f32e7eSjoerg   assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
355906f32e7eSjoerg }
356006f32e7eSjoerg 
BitCastInst(Value * S,Type * Ty,const Twine & Name,Instruction * InsertBefore)356106f32e7eSjoerg BitCastInst::BitCastInst(
356206f32e7eSjoerg   Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
356306f32e7eSjoerg ) : CastInst(Ty, BitCast, S, Name, InsertBefore) {
356406f32e7eSjoerg   assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
356506f32e7eSjoerg }
356606f32e7eSjoerg 
BitCastInst(Value * S,Type * Ty,const Twine & Name,BasicBlock * InsertAtEnd)356706f32e7eSjoerg BitCastInst::BitCastInst(
356806f32e7eSjoerg   Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
356906f32e7eSjoerg ) : CastInst(Ty, BitCast, S, Name, InsertAtEnd) {
357006f32e7eSjoerg   assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
357106f32e7eSjoerg }
357206f32e7eSjoerg 
AddrSpaceCastInst(Value * S,Type * Ty,const Twine & Name,Instruction * InsertBefore)357306f32e7eSjoerg AddrSpaceCastInst::AddrSpaceCastInst(
357406f32e7eSjoerg   Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
357506f32e7eSjoerg ) : CastInst(Ty, AddrSpaceCast, S, Name, InsertBefore) {
357606f32e7eSjoerg   assert(castIsValid(getOpcode(), S, Ty) && "Illegal AddrSpaceCast");
357706f32e7eSjoerg }
357806f32e7eSjoerg 
AddrSpaceCastInst(Value * S,Type * Ty,const Twine & Name,BasicBlock * InsertAtEnd)357906f32e7eSjoerg AddrSpaceCastInst::AddrSpaceCastInst(
358006f32e7eSjoerg   Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
358106f32e7eSjoerg ) : CastInst(Ty, AddrSpaceCast, S, Name, InsertAtEnd) {
358206f32e7eSjoerg   assert(castIsValid(getOpcode(), S, Ty) && "Illegal AddrSpaceCast");
358306f32e7eSjoerg }
358406f32e7eSjoerg 
358506f32e7eSjoerg //===----------------------------------------------------------------------===//
358606f32e7eSjoerg //                               CmpInst Classes
358706f32e7eSjoerg //===----------------------------------------------------------------------===//
358806f32e7eSjoerg 
CmpInst(Type * ty,OtherOps op,Predicate predicate,Value * LHS,Value * RHS,const Twine & Name,Instruction * InsertBefore,Instruction * FlagsSource)358906f32e7eSjoerg CmpInst::CmpInst(Type *ty, OtherOps op, Predicate predicate, Value *LHS,
359006f32e7eSjoerg                  Value *RHS, const Twine &Name, Instruction *InsertBefore,
359106f32e7eSjoerg                  Instruction *FlagsSource)
359206f32e7eSjoerg   : Instruction(ty, op,
359306f32e7eSjoerg                 OperandTraits<CmpInst>::op_begin(this),
359406f32e7eSjoerg                 OperandTraits<CmpInst>::operands(this),
359506f32e7eSjoerg                 InsertBefore) {
359606f32e7eSjoerg   Op<0>() = LHS;
359706f32e7eSjoerg   Op<1>() = RHS;
359806f32e7eSjoerg   setPredicate((Predicate)predicate);
359906f32e7eSjoerg   setName(Name);
360006f32e7eSjoerg   if (FlagsSource)
360106f32e7eSjoerg     copyIRFlags(FlagsSource);
360206f32e7eSjoerg }
360306f32e7eSjoerg 
CmpInst(Type * ty,OtherOps op,Predicate predicate,Value * LHS,Value * RHS,const Twine & Name,BasicBlock * InsertAtEnd)360406f32e7eSjoerg CmpInst::CmpInst(Type *ty, OtherOps op, Predicate predicate, Value *LHS,
360506f32e7eSjoerg                  Value *RHS, const Twine &Name, BasicBlock *InsertAtEnd)
360606f32e7eSjoerg   : Instruction(ty, op,
360706f32e7eSjoerg                 OperandTraits<CmpInst>::op_begin(this),
360806f32e7eSjoerg                 OperandTraits<CmpInst>::operands(this),
360906f32e7eSjoerg                 InsertAtEnd) {
361006f32e7eSjoerg   Op<0>() = LHS;
361106f32e7eSjoerg   Op<1>() = RHS;
361206f32e7eSjoerg   setPredicate((Predicate)predicate);
361306f32e7eSjoerg   setName(Name);
361406f32e7eSjoerg }
361506f32e7eSjoerg 
361606f32e7eSjoerg CmpInst *
Create(OtherOps Op,Predicate predicate,Value * S1,Value * S2,const Twine & Name,Instruction * InsertBefore)361706f32e7eSjoerg CmpInst::Create(OtherOps Op, Predicate predicate, Value *S1, Value *S2,
361806f32e7eSjoerg                 const Twine &Name, Instruction *InsertBefore) {
361906f32e7eSjoerg   if (Op == Instruction::ICmp) {
362006f32e7eSjoerg     if (InsertBefore)
362106f32e7eSjoerg       return new ICmpInst(InsertBefore, CmpInst::Predicate(predicate),
362206f32e7eSjoerg                           S1, S2, Name);
362306f32e7eSjoerg     else
362406f32e7eSjoerg       return new ICmpInst(CmpInst::Predicate(predicate),
362506f32e7eSjoerg                           S1, S2, Name);
362606f32e7eSjoerg   }
362706f32e7eSjoerg 
362806f32e7eSjoerg   if (InsertBefore)
362906f32e7eSjoerg     return new FCmpInst(InsertBefore, CmpInst::Predicate(predicate),
363006f32e7eSjoerg                         S1, S2, Name);
363106f32e7eSjoerg   else
363206f32e7eSjoerg     return new FCmpInst(CmpInst::Predicate(predicate),
363306f32e7eSjoerg                         S1, S2, Name);
363406f32e7eSjoerg }
363506f32e7eSjoerg 
363606f32e7eSjoerg CmpInst *
Create(OtherOps Op,Predicate predicate,Value * S1,Value * S2,const Twine & Name,BasicBlock * InsertAtEnd)363706f32e7eSjoerg CmpInst::Create(OtherOps Op, Predicate predicate, Value *S1, Value *S2,
363806f32e7eSjoerg                 const Twine &Name, BasicBlock *InsertAtEnd) {
363906f32e7eSjoerg   if (Op == Instruction::ICmp) {
364006f32e7eSjoerg     return new ICmpInst(*InsertAtEnd, CmpInst::Predicate(predicate),
364106f32e7eSjoerg                         S1, S2, Name);
364206f32e7eSjoerg   }
364306f32e7eSjoerg   return new FCmpInst(*InsertAtEnd, CmpInst::Predicate(predicate),
364406f32e7eSjoerg                       S1, S2, Name);
364506f32e7eSjoerg }
364606f32e7eSjoerg 
swapOperands()364706f32e7eSjoerg void CmpInst::swapOperands() {
364806f32e7eSjoerg   if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
364906f32e7eSjoerg     IC->swapOperands();
365006f32e7eSjoerg   else
365106f32e7eSjoerg     cast<FCmpInst>(this)->swapOperands();
365206f32e7eSjoerg }
365306f32e7eSjoerg 
isCommutative() const365406f32e7eSjoerg bool CmpInst::isCommutative() const {
365506f32e7eSjoerg   if (const ICmpInst *IC = dyn_cast<ICmpInst>(this))
365606f32e7eSjoerg     return IC->isCommutative();
365706f32e7eSjoerg   return cast<FCmpInst>(this)->isCommutative();
365806f32e7eSjoerg }
365906f32e7eSjoerg 
isEquality(Predicate P)3660*da58b97aSjoerg bool CmpInst::isEquality(Predicate P) {
3661*da58b97aSjoerg   if (ICmpInst::isIntPredicate(P))
3662*da58b97aSjoerg     return ICmpInst::isEquality(P);
3663*da58b97aSjoerg   if (FCmpInst::isFPPredicate(P))
3664*da58b97aSjoerg     return FCmpInst::isEquality(P);
3665*da58b97aSjoerg   llvm_unreachable("Unsupported predicate kind");
366606f32e7eSjoerg }
366706f32e7eSjoerg 
getInversePredicate(Predicate pred)366806f32e7eSjoerg CmpInst::Predicate CmpInst::getInversePredicate(Predicate pred) {
366906f32e7eSjoerg   switch (pred) {
367006f32e7eSjoerg     default: llvm_unreachable("Unknown cmp predicate!");
367106f32e7eSjoerg     case ICMP_EQ: return ICMP_NE;
367206f32e7eSjoerg     case ICMP_NE: return ICMP_EQ;
367306f32e7eSjoerg     case ICMP_UGT: return ICMP_ULE;
367406f32e7eSjoerg     case ICMP_ULT: return ICMP_UGE;
367506f32e7eSjoerg     case ICMP_UGE: return ICMP_ULT;
367606f32e7eSjoerg     case ICMP_ULE: return ICMP_UGT;
367706f32e7eSjoerg     case ICMP_SGT: return ICMP_SLE;
367806f32e7eSjoerg     case ICMP_SLT: return ICMP_SGE;
367906f32e7eSjoerg     case ICMP_SGE: return ICMP_SLT;
368006f32e7eSjoerg     case ICMP_SLE: return ICMP_SGT;
368106f32e7eSjoerg 
368206f32e7eSjoerg     case FCMP_OEQ: return FCMP_UNE;
368306f32e7eSjoerg     case FCMP_ONE: return FCMP_UEQ;
368406f32e7eSjoerg     case FCMP_OGT: return FCMP_ULE;
368506f32e7eSjoerg     case FCMP_OLT: return FCMP_UGE;
368606f32e7eSjoerg     case FCMP_OGE: return FCMP_ULT;
368706f32e7eSjoerg     case FCMP_OLE: return FCMP_UGT;
368806f32e7eSjoerg     case FCMP_UEQ: return FCMP_ONE;
368906f32e7eSjoerg     case FCMP_UNE: return FCMP_OEQ;
369006f32e7eSjoerg     case FCMP_UGT: return FCMP_OLE;
369106f32e7eSjoerg     case FCMP_ULT: return FCMP_OGE;
369206f32e7eSjoerg     case FCMP_UGE: return FCMP_OLT;
369306f32e7eSjoerg     case FCMP_ULE: return FCMP_OGT;
369406f32e7eSjoerg     case FCMP_ORD: return FCMP_UNO;
369506f32e7eSjoerg     case FCMP_UNO: return FCMP_ORD;
369606f32e7eSjoerg     case FCMP_TRUE: return FCMP_FALSE;
369706f32e7eSjoerg     case FCMP_FALSE: return FCMP_TRUE;
369806f32e7eSjoerg   }
369906f32e7eSjoerg }
370006f32e7eSjoerg 
getPredicateName(Predicate Pred)370106f32e7eSjoerg StringRef CmpInst::getPredicateName(Predicate Pred) {
370206f32e7eSjoerg   switch (Pred) {
370306f32e7eSjoerg   default:                   return "unknown";
370406f32e7eSjoerg   case FCmpInst::FCMP_FALSE: return "false";
370506f32e7eSjoerg   case FCmpInst::FCMP_OEQ:   return "oeq";
370606f32e7eSjoerg   case FCmpInst::FCMP_OGT:   return "ogt";
370706f32e7eSjoerg   case FCmpInst::FCMP_OGE:   return "oge";
370806f32e7eSjoerg   case FCmpInst::FCMP_OLT:   return "olt";
370906f32e7eSjoerg   case FCmpInst::FCMP_OLE:   return "ole";
371006f32e7eSjoerg   case FCmpInst::FCMP_ONE:   return "one";
371106f32e7eSjoerg   case FCmpInst::FCMP_ORD:   return "ord";
371206f32e7eSjoerg   case FCmpInst::FCMP_UNO:   return "uno";
371306f32e7eSjoerg   case FCmpInst::FCMP_UEQ:   return "ueq";
371406f32e7eSjoerg   case FCmpInst::FCMP_UGT:   return "ugt";
371506f32e7eSjoerg   case FCmpInst::FCMP_UGE:   return "uge";
371606f32e7eSjoerg   case FCmpInst::FCMP_ULT:   return "ult";
371706f32e7eSjoerg   case FCmpInst::FCMP_ULE:   return "ule";
371806f32e7eSjoerg   case FCmpInst::FCMP_UNE:   return "une";
371906f32e7eSjoerg   case FCmpInst::FCMP_TRUE:  return "true";
372006f32e7eSjoerg   case ICmpInst::ICMP_EQ:    return "eq";
372106f32e7eSjoerg   case ICmpInst::ICMP_NE:    return "ne";
372206f32e7eSjoerg   case ICmpInst::ICMP_SGT:   return "sgt";
372306f32e7eSjoerg   case ICmpInst::ICMP_SGE:   return "sge";
372406f32e7eSjoerg   case ICmpInst::ICMP_SLT:   return "slt";
372506f32e7eSjoerg   case ICmpInst::ICMP_SLE:   return "sle";
372606f32e7eSjoerg   case ICmpInst::ICMP_UGT:   return "ugt";
372706f32e7eSjoerg   case ICmpInst::ICMP_UGE:   return "uge";
372806f32e7eSjoerg   case ICmpInst::ICMP_ULT:   return "ult";
372906f32e7eSjoerg   case ICmpInst::ICMP_ULE:   return "ule";
373006f32e7eSjoerg   }
373106f32e7eSjoerg }
373206f32e7eSjoerg 
getSignedPredicate(Predicate pred)373306f32e7eSjoerg ICmpInst::Predicate ICmpInst::getSignedPredicate(Predicate pred) {
373406f32e7eSjoerg   switch (pred) {
373506f32e7eSjoerg     default: llvm_unreachable("Unknown icmp predicate!");
373606f32e7eSjoerg     case ICMP_EQ: case ICMP_NE:
373706f32e7eSjoerg     case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE:
373806f32e7eSjoerg        return pred;
373906f32e7eSjoerg     case ICMP_UGT: return ICMP_SGT;
374006f32e7eSjoerg     case ICMP_ULT: return ICMP_SLT;
374106f32e7eSjoerg     case ICMP_UGE: return ICMP_SGE;
374206f32e7eSjoerg     case ICMP_ULE: return ICMP_SLE;
374306f32e7eSjoerg   }
374406f32e7eSjoerg }
374506f32e7eSjoerg 
getUnsignedPredicate(Predicate pred)374606f32e7eSjoerg ICmpInst::Predicate ICmpInst::getUnsignedPredicate(Predicate pred) {
374706f32e7eSjoerg   switch (pred) {
374806f32e7eSjoerg     default: llvm_unreachable("Unknown icmp predicate!");
374906f32e7eSjoerg     case ICMP_EQ: case ICMP_NE:
375006f32e7eSjoerg     case ICMP_UGT: case ICMP_ULT: case ICMP_UGE: case ICMP_ULE:
375106f32e7eSjoerg        return pred;
375206f32e7eSjoerg     case ICMP_SGT: return ICMP_UGT;
375306f32e7eSjoerg     case ICMP_SLT: return ICMP_ULT;
375406f32e7eSjoerg     case ICMP_SGE: return ICMP_UGE;
375506f32e7eSjoerg     case ICMP_SLE: return ICMP_ULE;
375606f32e7eSjoerg   }
375706f32e7eSjoerg }
375806f32e7eSjoerg 
getSwappedPredicate(Predicate pred)375906f32e7eSjoerg CmpInst::Predicate CmpInst::getSwappedPredicate(Predicate pred) {
376006f32e7eSjoerg   switch (pred) {
376106f32e7eSjoerg     default: llvm_unreachable("Unknown cmp predicate!");
376206f32e7eSjoerg     case ICMP_EQ: case ICMP_NE:
376306f32e7eSjoerg       return pred;
376406f32e7eSjoerg     case ICMP_SGT: return ICMP_SLT;
376506f32e7eSjoerg     case ICMP_SLT: return ICMP_SGT;
376606f32e7eSjoerg     case ICMP_SGE: return ICMP_SLE;
376706f32e7eSjoerg     case ICMP_SLE: return ICMP_SGE;
376806f32e7eSjoerg     case ICMP_UGT: return ICMP_ULT;
376906f32e7eSjoerg     case ICMP_ULT: return ICMP_UGT;
377006f32e7eSjoerg     case ICMP_UGE: return ICMP_ULE;
377106f32e7eSjoerg     case ICMP_ULE: return ICMP_UGE;
377206f32e7eSjoerg 
377306f32e7eSjoerg     case FCMP_FALSE: case FCMP_TRUE:
377406f32e7eSjoerg     case FCMP_OEQ: case FCMP_ONE:
377506f32e7eSjoerg     case FCMP_UEQ: case FCMP_UNE:
377606f32e7eSjoerg     case FCMP_ORD: case FCMP_UNO:
377706f32e7eSjoerg       return pred;
377806f32e7eSjoerg     case FCMP_OGT: return FCMP_OLT;
377906f32e7eSjoerg     case FCMP_OLT: return FCMP_OGT;
378006f32e7eSjoerg     case FCMP_OGE: return FCMP_OLE;
378106f32e7eSjoerg     case FCMP_OLE: return FCMP_OGE;
378206f32e7eSjoerg     case FCMP_UGT: return FCMP_ULT;
378306f32e7eSjoerg     case FCMP_ULT: return FCMP_UGT;
378406f32e7eSjoerg     case FCMP_UGE: return FCMP_ULE;
378506f32e7eSjoerg     case FCMP_ULE: return FCMP_UGE;
378606f32e7eSjoerg   }
378706f32e7eSjoerg }
378806f32e7eSjoerg 
isNonStrictPredicate(Predicate pred)3789*da58b97aSjoerg bool CmpInst::isNonStrictPredicate(Predicate pred) {
379006f32e7eSjoerg   switch (pred) {
3791*da58b97aSjoerg   case ICMP_SGE:
3792*da58b97aSjoerg   case ICMP_SLE:
3793*da58b97aSjoerg   case ICMP_UGE:
3794*da58b97aSjoerg   case ICMP_ULE:
3795*da58b97aSjoerg   case FCMP_OGE:
3796*da58b97aSjoerg   case FCMP_OLE:
3797*da58b97aSjoerg   case FCMP_UGE:
3798*da58b97aSjoerg   case FCMP_ULE:
3799*da58b97aSjoerg     return true;
3800*da58b97aSjoerg   default:
3801*da58b97aSjoerg     return false;
380206f32e7eSjoerg   }
380306f32e7eSjoerg }
380406f32e7eSjoerg 
isStrictPredicate(Predicate pred)3805*da58b97aSjoerg bool CmpInst::isStrictPredicate(Predicate pred) {
3806*da58b97aSjoerg   switch (pred) {
3807*da58b97aSjoerg   case ICMP_SGT:
3808*da58b97aSjoerg   case ICMP_SLT:
3809*da58b97aSjoerg   case ICMP_UGT:
3810*da58b97aSjoerg   case ICMP_ULT:
3811*da58b97aSjoerg   case FCMP_OGT:
3812*da58b97aSjoerg   case FCMP_OLT:
3813*da58b97aSjoerg   case FCMP_UGT:
3814*da58b97aSjoerg   case FCMP_ULT:
3815*da58b97aSjoerg     return true;
3816*da58b97aSjoerg   default:
3817*da58b97aSjoerg     return false;
3818*da58b97aSjoerg   }
3819*da58b97aSjoerg }
3820*da58b97aSjoerg 
getStrictPredicate(Predicate pred)3821*da58b97aSjoerg CmpInst::Predicate CmpInst::getStrictPredicate(Predicate pred) {
3822*da58b97aSjoerg   switch (pred) {
3823*da58b97aSjoerg   case ICMP_SGE:
3824*da58b97aSjoerg     return ICMP_SGT;
3825*da58b97aSjoerg   case ICMP_SLE:
3826*da58b97aSjoerg     return ICMP_SLT;
3827*da58b97aSjoerg   case ICMP_UGE:
3828*da58b97aSjoerg     return ICMP_UGT;
3829*da58b97aSjoerg   case ICMP_ULE:
3830*da58b97aSjoerg     return ICMP_ULT;
3831*da58b97aSjoerg   case FCMP_OGE:
3832*da58b97aSjoerg     return FCMP_OGT;
3833*da58b97aSjoerg   case FCMP_OLE:
3834*da58b97aSjoerg     return FCMP_OLT;
3835*da58b97aSjoerg   case FCMP_UGE:
3836*da58b97aSjoerg     return FCMP_UGT;
3837*da58b97aSjoerg   case FCMP_ULE:
3838*da58b97aSjoerg     return FCMP_ULT;
3839*da58b97aSjoerg   default:
3840*da58b97aSjoerg     return pred;
3841*da58b97aSjoerg   }
3842*da58b97aSjoerg }
3843*da58b97aSjoerg 
getNonStrictPredicate(Predicate pred)3844*da58b97aSjoerg CmpInst::Predicate CmpInst::getNonStrictPredicate(Predicate pred) {
3845*da58b97aSjoerg   switch (pred) {
3846*da58b97aSjoerg   case ICMP_SGT:
3847*da58b97aSjoerg     return ICMP_SGE;
3848*da58b97aSjoerg   case ICMP_SLT:
3849*da58b97aSjoerg     return ICMP_SLE;
3850*da58b97aSjoerg   case ICMP_UGT:
3851*da58b97aSjoerg     return ICMP_UGE;
3852*da58b97aSjoerg   case ICMP_ULT:
3853*da58b97aSjoerg     return ICMP_ULE;
3854*da58b97aSjoerg   case FCMP_OGT:
3855*da58b97aSjoerg     return FCMP_OGE;
3856*da58b97aSjoerg   case FCMP_OLT:
3857*da58b97aSjoerg     return FCMP_OLE;
3858*da58b97aSjoerg   case FCMP_UGT:
3859*da58b97aSjoerg     return FCMP_UGE;
3860*da58b97aSjoerg   case FCMP_ULT:
3861*da58b97aSjoerg     return FCMP_ULE;
3862*da58b97aSjoerg   default:
3863*da58b97aSjoerg     return pred;
3864*da58b97aSjoerg   }
3865*da58b97aSjoerg }
3866*da58b97aSjoerg 
getFlippedStrictnessPredicate(Predicate pred)3867*da58b97aSjoerg CmpInst::Predicate CmpInst::getFlippedStrictnessPredicate(Predicate pred) {
3868*da58b97aSjoerg   assert(CmpInst::isRelational(pred) && "Call only with relational predicate!");
3869*da58b97aSjoerg 
3870*da58b97aSjoerg   if (isStrictPredicate(pred))
3871*da58b97aSjoerg     return getNonStrictPredicate(pred);
3872*da58b97aSjoerg   if (isNonStrictPredicate(pred))
3873*da58b97aSjoerg     return getStrictPredicate(pred);
3874*da58b97aSjoerg 
3875*da58b97aSjoerg   llvm_unreachable("Unknown predicate!");
3876*da58b97aSjoerg }
3877*da58b97aSjoerg 
getSignedPredicate(Predicate pred)387806f32e7eSjoerg CmpInst::Predicate CmpInst::getSignedPredicate(Predicate pred) {
3879*da58b97aSjoerg   assert(CmpInst::isUnsigned(pred) && "Call only with unsigned predicates!");
388006f32e7eSjoerg 
388106f32e7eSjoerg   switch (pred) {
388206f32e7eSjoerg   default:
388306f32e7eSjoerg     llvm_unreachable("Unknown predicate!");
388406f32e7eSjoerg   case CmpInst::ICMP_ULT:
388506f32e7eSjoerg     return CmpInst::ICMP_SLT;
388606f32e7eSjoerg   case CmpInst::ICMP_ULE:
388706f32e7eSjoerg     return CmpInst::ICMP_SLE;
388806f32e7eSjoerg   case CmpInst::ICMP_UGT:
388906f32e7eSjoerg     return CmpInst::ICMP_SGT;
389006f32e7eSjoerg   case CmpInst::ICMP_UGE:
389106f32e7eSjoerg     return CmpInst::ICMP_SGE;
389206f32e7eSjoerg   }
389306f32e7eSjoerg }
389406f32e7eSjoerg 
getUnsignedPredicate(Predicate pred)3895*da58b97aSjoerg CmpInst::Predicate CmpInst::getUnsignedPredicate(Predicate pred) {
3896*da58b97aSjoerg   assert(CmpInst::isSigned(pred) && "Call only with signed predicates!");
3897*da58b97aSjoerg 
3898*da58b97aSjoerg   switch (pred) {
3899*da58b97aSjoerg   default:
3900*da58b97aSjoerg     llvm_unreachable("Unknown predicate!");
3901*da58b97aSjoerg   case CmpInst::ICMP_SLT:
3902*da58b97aSjoerg     return CmpInst::ICMP_ULT;
3903*da58b97aSjoerg   case CmpInst::ICMP_SLE:
3904*da58b97aSjoerg     return CmpInst::ICMP_ULE;
3905*da58b97aSjoerg   case CmpInst::ICMP_SGT:
3906*da58b97aSjoerg     return CmpInst::ICMP_UGT;
3907*da58b97aSjoerg   case CmpInst::ICMP_SGE:
3908*da58b97aSjoerg     return CmpInst::ICMP_UGE;
3909*da58b97aSjoerg   }
3910*da58b97aSjoerg }
3911*da58b97aSjoerg 
isUnsigned(Predicate predicate)391206f32e7eSjoerg bool CmpInst::isUnsigned(Predicate predicate) {
391306f32e7eSjoerg   switch (predicate) {
391406f32e7eSjoerg     default: return false;
391506f32e7eSjoerg     case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE: case ICmpInst::ICMP_UGT:
391606f32e7eSjoerg     case ICmpInst::ICMP_UGE: return true;
391706f32e7eSjoerg   }
391806f32e7eSjoerg }
391906f32e7eSjoerg 
isSigned(Predicate predicate)392006f32e7eSjoerg bool CmpInst::isSigned(Predicate predicate) {
392106f32e7eSjoerg   switch (predicate) {
392206f32e7eSjoerg     default: return false;
392306f32e7eSjoerg     case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_SLE: case ICmpInst::ICMP_SGT:
392406f32e7eSjoerg     case ICmpInst::ICMP_SGE: return true;
392506f32e7eSjoerg   }
392606f32e7eSjoerg }
392706f32e7eSjoerg 
getFlippedSignednessPredicate(Predicate pred)3928*da58b97aSjoerg CmpInst::Predicate CmpInst::getFlippedSignednessPredicate(Predicate pred) {
3929*da58b97aSjoerg   assert(CmpInst::isRelational(pred) &&
3930*da58b97aSjoerg          "Call only with non-equality predicates!");
3931*da58b97aSjoerg 
3932*da58b97aSjoerg   if (isSigned(pred))
3933*da58b97aSjoerg     return getUnsignedPredicate(pred);
3934*da58b97aSjoerg   if (isUnsigned(pred))
3935*da58b97aSjoerg     return getSignedPredicate(pred);
3936*da58b97aSjoerg 
3937*da58b97aSjoerg   llvm_unreachable("Unknown predicate!");
3938*da58b97aSjoerg }
3939*da58b97aSjoerg 
isOrdered(Predicate predicate)394006f32e7eSjoerg bool CmpInst::isOrdered(Predicate predicate) {
394106f32e7eSjoerg   switch (predicate) {
394206f32e7eSjoerg     default: return false;
394306f32e7eSjoerg     case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_OGT:
394406f32e7eSjoerg     case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLE:
394506f32e7eSjoerg     case FCmpInst::FCMP_ORD: return true;
394606f32e7eSjoerg   }
394706f32e7eSjoerg }
394806f32e7eSjoerg 
isUnordered(Predicate predicate)394906f32e7eSjoerg bool CmpInst::isUnordered(Predicate predicate) {
395006f32e7eSjoerg   switch (predicate) {
395106f32e7eSjoerg     default: return false;
395206f32e7eSjoerg     case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UNE: case FCmpInst::FCMP_UGT:
395306f32e7eSjoerg     case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_UGE: case FCmpInst::FCMP_ULE:
395406f32e7eSjoerg     case FCmpInst::FCMP_UNO: return true;
395506f32e7eSjoerg   }
395606f32e7eSjoerg }
395706f32e7eSjoerg 
isTrueWhenEqual(Predicate predicate)395806f32e7eSjoerg bool CmpInst::isTrueWhenEqual(Predicate predicate) {
395906f32e7eSjoerg   switch(predicate) {
396006f32e7eSjoerg     default: return false;
396106f32e7eSjoerg     case ICMP_EQ:   case ICMP_UGE: case ICMP_ULE: case ICMP_SGE: case ICMP_SLE:
396206f32e7eSjoerg     case FCMP_TRUE: case FCMP_UEQ: case FCMP_UGE: case FCMP_ULE: return true;
396306f32e7eSjoerg   }
396406f32e7eSjoerg }
396506f32e7eSjoerg 
isFalseWhenEqual(Predicate predicate)396606f32e7eSjoerg bool CmpInst::isFalseWhenEqual(Predicate predicate) {
396706f32e7eSjoerg   switch(predicate) {
396806f32e7eSjoerg   case ICMP_NE:    case ICMP_UGT: case ICMP_ULT: case ICMP_SGT: case ICMP_SLT:
396906f32e7eSjoerg   case FCMP_FALSE: case FCMP_ONE: case FCMP_OGT: case FCMP_OLT: return true;
397006f32e7eSjoerg   default: return false;
397106f32e7eSjoerg   }
397206f32e7eSjoerg }
397306f32e7eSjoerg 
isImpliedTrueByMatchingCmp(Predicate Pred1,Predicate Pred2)397406f32e7eSjoerg bool CmpInst::isImpliedTrueByMatchingCmp(Predicate Pred1, Predicate Pred2) {
397506f32e7eSjoerg   // If the predicates match, then we know the first condition implies the
397606f32e7eSjoerg   // second is true.
397706f32e7eSjoerg   if (Pred1 == Pred2)
397806f32e7eSjoerg     return true;
397906f32e7eSjoerg 
398006f32e7eSjoerg   switch (Pred1) {
398106f32e7eSjoerg   default:
398206f32e7eSjoerg     break;
398306f32e7eSjoerg   case ICMP_EQ:
398406f32e7eSjoerg     // A == B implies A >=u B, A <=u B, A >=s B, and A <=s B are true.
398506f32e7eSjoerg     return Pred2 == ICMP_UGE || Pred2 == ICMP_ULE || Pred2 == ICMP_SGE ||
398606f32e7eSjoerg            Pred2 == ICMP_SLE;
398706f32e7eSjoerg   case ICMP_UGT: // A >u B implies A != B and A >=u B are true.
398806f32e7eSjoerg     return Pred2 == ICMP_NE || Pred2 == ICMP_UGE;
398906f32e7eSjoerg   case ICMP_ULT: // A <u B implies A != B and A <=u B are true.
399006f32e7eSjoerg     return Pred2 == ICMP_NE || Pred2 == ICMP_ULE;
399106f32e7eSjoerg   case ICMP_SGT: // A >s B implies A != B and A >=s B are true.
399206f32e7eSjoerg     return Pred2 == ICMP_NE || Pred2 == ICMP_SGE;
399306f32e7eSjoerg   case ICMP_SLT: // A <s B implies A != B and A <=s B are true.
399406f32e7eSjoerg     return Pred2 == ICMP_NE || Pred2 == ICMP_SLE;
399506f32e7eSjoerg   }
399606f32e7eSjoerg   return false;
399706f32e7eSjoerg }
399806f32e7eSjoerg 
isImpliedFalseByMatchingCmp(Predicate Pred1,Predicate Pred2)399906f32e7eSjoerg bool CmpInst::isImpliedFalseByMatchingCmp(Predicate Pred1, Predicate Pred2) {
400006f32e7eSjoerg   return isImpliedTrueByMatchingCmp(Pred1, getInversePredicate(Pred2));
400106f32e7eSjoerg }
400206f32e7eSjoerg 
400306f32e7eSjoerg //===----------------------------------------------------------------------===//
400406f32e7eSjoerg //                        SwitchInst Implementation
400506f32e7eSjoerg //===----------------------------------------------------------------------===//
400606f32e7eSjoerg 
init(Value * Value,BasicBlock * Default,unsigned NumReserved)400706f32e7eSjoerg void SwitchInst::init(Value *Value, BasicBlock *Default, unsigned NumReserved) {
400806f32e7eSjoerg   assert(Value && Default && NumReserved);
400906f32e7eSjoerg   ReservedSpace = NumReserved;
401006f32e7eSjoerg   setNumHungOffUseOperands(2);
401106f32e7eSjoerg   allocHungoffUses(ReservedSpace);
401206f32e7eSjoerg 
401306f32e7eSjoerg   Op<0>() = Value;
401406f32e7eSjoerg   Op<1>() = Default;
401506f32e7eSjoerg }
401606f32e7eSjoerg 
401706f32e7eSjoerg /// SwitchInst ctor - Create a new switch instruction, specifying a value to
401806f32e7eSjoerg /// switch on and a default destination.  The number of additional cases can
401906f32e7eSjoerg /// be specified here to make memory allocation more efficient.  This
402006f32e7eSjoerg /// constructor can also autoinsert before another instruction.
SwitchInst(Value * Value,BasicBlock * Default,unsigned NumCases,Instruction * InsertBefore)402106f32e7eSjoerg SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
402206f32e7eSjoerg                        Instruction *InsertBefore)
402306f32e7eSjoerg     : Instruction(Type::getVoidTy(Value->getContext()), Instruction::Switch,
402406f32e7eSjoerg                   nullptr, 0, InsertBefore) {
402506f32e7eSjoerg   init(Value, Default, 2+NumCases*2);
402606f32e7eSjoerg }
402706f32e7eSjoerg 
402806f32e7eSjoerg /// SwitchInst ctor - Create a new switch instruction, specifying a value to
402906f32e7eSjoerg /// switch on and a default destination.  The number of additional cases can
403006f32e7eSjoerg /// be specified here to make memory allocation more efficient.  This
403106f32e7eSjoerg /// constructor also autoinserts at the end of the specified BasicBlock.
SwitchInst(Value * Value,BasicBlock * Default,unsigned NumCases,BasicBlock * InsertAtEnd)403206f32e7eSjoerg SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
403306f32e7eSjoerg                        BasicBlock *InsertAtEnd)
403406f32e7eSjoerg     : Instruction(Type::getVoidTy(Value->getContext()), Instruction::Switch,
403506f32e7eSjoerg                   nullptr, 0, InsertAtEnd) {
403606f32e7eSjoerg   init(Value, Default, 2+NumCases*2);
403706f32e7eSjoerg }
403806f32e7eSjoerg 
SwitchInst(const SwitchInst & SI)403906f32e7eSjoerg SwitchInst::SwitchInst(const SwitchInst &SI)
404006f32e7eSjoerg     : Instruction(SI.getType(), Instruction::Switch, nullptr, 0) {
404106f32e7eSjoerg   init(SI.getCondition(), SI.getDefaultDest(), SI.getNumOperands());
404206f32e7eSjoerg   setNumHungOffUseOperands(SI.getNumOperands());
404306f32e7eSjoerg   Use *OL = getOperandList();
404406f32e7eSjoerg   const Use *InOL = SI.getOperandList();
404506f32e7eSjoerg   for (unsigned i = 2, E = SI.getNumOperands(); i != E; i += 2) {
404606f32e7eSjoerg     OL[i] = InOL[i];
404706f32e7eSjoerg     OL[i+1] = InOL[i+1];
404806f32e7eSjoerg   }
404906f32e7eSjoerg   SubclassOptionalData = SI.SubclassOptionalData;
405006f32e7eSjoerg }
405106f32e7eSjoerg 
405206f32e7eSjoerg /// addCase - Add an entry to the switch instruction...
405306f32e7eSjoerg ///
addCase(ConstantInt * OnVal,BasicBlock * Dest)405406f32e7eSjoerg void SwitchInst::addCase(ConstantInt *OnVal, BasicBlock *Dest) {
405506f32e7eSjoerg   unsigned NewCaseIdx = getNumCases();
405606f32e7eSjoerg   unsigned OpNo = getNumOperands();
405706f32e7eSjoerg   if (OpNo+2 > ReservedSpace)
405806f32e7eSjoerg     growOperands();  // Get more space!
405906f32e7eSjoerg   // Initialize some new operands.
406006f32e7eSjoerg   assert(OpNo+1 < ReservedSpace && "Growing didn't work!");
406106f32e7eSjoerg   setNumHungOffUseOperands(OpNo+2);
406206f32e7eSjoerg   CaseHandle Case(this, NewCaseIdx);
406306f32e7eSjoerg   Case.setValue(OnVal);
406406f32e7eSjoerg   Case.setSuccessor(Dest);
406506f32e7eSjoerg }
406606f32e7eSjoerg 
406706f32e7eSjoerg /// removeCase - This method removes the specified case and its successor
406806f32e7eSjoerg /// from the switch instruction.
removeCase(CaseIt I)406906f32e7eSjoerg SwitchInst::CaseIt SwitchInst::removeCase(CaseIt I) {
407006f32e7eSjoerg   unsigned idx = I->getCaseIndex();
407106f32e7eSjoerg 
407206f32e7eSjoerg   assert(2 + idx*2 < getNumOperands() && "Case index out of range!!!");
407306f32e7eSjoerg 
407406f32e7eSjoerg   unsigned NumOps = getNumOperands();
407506f32e7eSjoerg   Use *OL = getOperandList();
407606f32e7eSjoerg 
407706f32e7eSjoerg   // Overwrite this case with the end of the list.
407806f32e7eSjoerg   if (2 + (idx + 1) * 2 != NumOps) {
407906f32e7eSjoerg     OL[2 + idx * 2] = OL[NumOps - 2];
408006f32e7eSjoerg     OL[2 + idx * 2 + 1] = OL[NumOps - 1];
408106f32e7eSjoerg   }
408206f32e7eSjoerg 
408306f32e7eSjoerg   // Nuke the last value.
408406f32e7eSjoerg   OL[NumOps-2].set(nullptr);
408506f32e7eSjoerg   OL[NumOps-2+1].set(nullptr);
408606f32e7eSjoerg   setNumHungOffUseOperands(NumOps-2);
408706f32e7eSjoerg 
408806f32e7eSjoerg   return CaseIt(this, idx);
408906f32e7eSjoerg }
409006f32e7eSjoerg 
409106f32e7eSjoerg /// growOperands - grow operands - This grows the operand list in response
409206f32e7eSjoerg /// to a push_back style of operation.  This grows the number of ops by 3 times.
409306f32e7eSjoerg ///
growOperands()409406f32e7eSjoerg void SwitchInst::growOperands() {
409506f32e7eSjoerg   unsigned e = getNumOperands();
409606f32e7eSjoerg   unsigned NumOps = e*3;
409706f32e7eSjoerg 
409806f32e7eSjoerg   ReservedSpace = NumOps;
409906f32e7eSjoerg   growHungoffUses(ReservedSpace);
410006f32e7eSjoerg }
410106f32e7eSjoerg 
410206f32e7eSjoerg MDNode *
getProfBranchWeightsMD(const SwitchInst & SI)410306f32e7eSjoerg SwitchInstProfUpdateWrapper::getProfBranchWeightsMD(const SwitchInst &SI) {
410406f32e7eSjoerg   if (MDNode *ProfileData = SI.getMetadata(LLVMContext::MD_prof))
410506f32e7eSjoerg     if (auto *MDName = dyn_cast<MDString>(ProfileData->getOperand(0)))
410606f32e7eSjoerg       if (MDName->getString() == "branch_weights")
410706f32e7eSjoerg         return ProfileData;
410806f32e7eSjoerg   return nullptr;
410906f32e7eSjoerg }
411006f32e7eSjoerg 
buildProfBranchWeightsMD()411106f32e7eSjoerg MDNode *SwitchInstProfUpdateWrapper::buildProfBranchWeightsMD() {
411206f32e7eSjoerg   assert(Changed && "called only if metadata has changed");
411306f32e7eSjoerg 
411406f32e7eSjoerg   if (!Weights)
411506f32e7eSjoerg     return nullptr;
411606f32e7eSjoerg 
411706f32e7eSjoerg   assert(SI.getNumSuccessors() == Weights->size() &&
411806f32e7eSjoerg          "num of prof branch_weights must accord with num of successors");
411906f32e7eSjoerg 
412006f32e7eSjoerg   bool AllZeroes =
412106f32e7eSjoerg       all_of(Weights.getValue(), [](uint32_t W) { return W == 0; });
412206f32e7eSjoerg 
412306f32e7eSjoerg   if (AllZeroes || Weights.getValue().size() < 2)
412406f32e7eSjoerg     return nullptr;
412506f32e7eSjoerg 
412606f32e7eSjoerg   return MDBuilder(SI.getParent()->getContext()).createBranchWeights(*Weights);
412706f32e7eSjoerg }
412806f32e7eSjoerg 
init()412906f32e7eSjoerg void SwitchInstProfUpdateWrapper::init() {
413006f32e7eSjoerg   MDNode *ProfileData = getProfBranchWeightsMD(SI);
413106f32e7eSjoerg   if (!ProfileData)
413206f32e7eSjoerg     return;
413306f32e7eSjoerg 
413406f32e7eSjoerg   if (ProfileData->getNumOperands() != SI.getNumSuccessors() + 1) {
413506f32e7eSjoerg     llvm_unreachable("number of prof branch_weights metadata operands does "
413606f32e7eSjoerg                      "not correspond to number of succesors");
413706f32e7eSjoerg   }
413806f32e7eSjoerg 
413906f32e7eSjoerg   SmallVector<uint32_t, 8> Weights;
414006f32e7eSjoerg   for (unsigned CI = 1, CE = SI.getNumSuccessors(); CI <= CE; ++CI) {
414106f32e7eSjoerg     ConstantInt *C = mdconst::extract<ConstantInt>(ProfileData->getOperand(CI));
414206f32e7eSjoerg     uint32_t CW = C->getValue().getZExtValue();
414306f32e7eSjoerg     Weights.push_back(CW);
414406f32e7eSjoerg   }
414506f32e7eSjoerg   this->Weights = std::move(Weights);
414606f32e7eSjoerg }
414706f32e7eSjoerg 
414806f32e7eSjoerg SwitchInst::CaseIt
removeCase(SwitchInst::CaseIt I)414906f32e7eSjoerg SwitchInstProfUpdateWrapper::removeCase(SwitchInst::CaseIt I) {
415006f32e7eSjoerg   if (Weights) {
415106f32e7eSjoerg     assert(SI.getNumSuccessors() == Weights->size() &&
415206f32e7eSjoerg            "num of prof branch_weights must accord with num of successors");
415306f32e7eSjoerg     Changed = true;
415406f32e7eSjoerg     // Copy the last case to the place of the removed one and shrink.
415506f32e7eSjoerg     // This is tightly coupled with the way SwitchInst::removeCase() removes
415606f32e7eSjoerg     // the cases in SwitchInst::removeCase(CaseIt).
415706f32e7eSjoerg     Weights.getValue()[I->getCaseIndex() + 1] = Weights.getValue().back();
415806f32e7eSjoerg     Weights.getValue().pop_back();
415906f32e7eSjoerg   }
416006f32e7eSjoerg   return SI.removeCase(I);
416106f32e7eSjoerg }
416206f32e7eSjoerg 
addCase(ConstantInt * OnVal,BasicBlock * Dest,SwitchInstProfUpdateWrapper::CaseWeightOpt W)416306f32e7eSjoerg void SwitchInstProfUpdateWrapper::addCase(
416406f32e7eSjoerg     ConstantInt *OnVal, BasicBlock *Dest,
416506f32e7eSjoerg     SwitchInstProfUpdateWrapper::CaseWeightOpt W) {
416606f32e7eSjoerg   SI.addCase(OnVal, Dest);
416706f32e7eSjoerg 
416806f32e7eSjoerg   if (!Weights && W && *W) {
416906f32e7eSjoerg     Changed = true;
417006f32e7eSjoerg     Weights = SmallVector<uint32_t, 8>(SI.getNumSuccessors(), 0);
417106f32e7eSjoerg     Weights.getValue()[SI.getNumSuccessors() - 1] = *W;
417206f32e7eSjoerg   } else if (Weights) {
417306f32e7eSjoerg     Changed = true;
417406f32e7eSjoerg     Weights.getValue().push_back(W ? *W : 0);
417506f32e7eSjoerg   }
417606f32e7eSjoerg   if (Weights)
417706f32e7eSjoerg     assert(SI.getNumSuccessors() == Weights->size() &&
417806f32e7eSjoerg            "num of prof branch_weights must accord with num of successors");
417906f32e7eSjoerg }
418006f32e7eSjoerg 
418106f32e7eSjoerg SymbolTableList<Instruction>::iterator
eraseFromParent()418206f32e7eSjoerg SwitchInstProfUpdateWrapper::eraseFromParent() {
418306f32e7eSjoerg   // Instruction is erased. Mark as unchanged to not touch it in the destructor.
418406f32e7eSjoerg   Changed = false;
418506f32e7eSjoerg   if (Weights)
418606f32e7eSjoerg     Weights->resize(0);
418706f32e7eSjoerg   return SI.eraseFromParent();
418806f32e7eSjoerg }
418906f32e7eSjoerg 
419006f32e7eSjoerg SwitchInstProfUpdateWrapper::CaseWeightOpt
getSuccessorWeight(unsigned idx)419106f32e7eSjoerg SwitchInstProfUpdateWrapper::getSuccessorWeight(unsigned idx) {
419206f32e7eSjoerg   if (!Weights)
419306f32e7eSjoerg     return None;
419406f32e7eSjoerg   return Weights.getValue()[idx];
419506f32e7eSjoerg }
419606f32e7eSjoerg 
setSuccessorWeight(unsigned idx,SwitchInstProfUpdateWrapper::CaseWeightOpt W)419706f32e7eSjoerg void SwitchInstProfUpdateWrapper::setSuccessorWeight(
419806f32e7eSjoerg     unsigned idx, SwitchInstProfUpdateWrapper::CaseWeightOpt W) {
419906f32e7eSjoerg   if (!W)
420006f32e7eSjoerg     return;
420106f32e7eSjoerg 
420206f32e7eSjoerg   if (!Weights && *W)
420306f32e7eSjoerg     Weights = SmallVector<uint32_t, 8>(SI.getNumSuccessors(), 0);
420406f32e7eSjoerg 
420506f32e7eSjoerg   if (Weights) {
420606f32e7eSjoerg     auto &OldW = Weights.getValue()[idx];
420706f32e7eSjoerg     if (*W != OldW) {
420806f32e7eSjoerg       Changed = true;
420906f32e7eSjoerg       OldW = *W;
421006f32e7eSjoerg     }
421106f32e7eSjoerg   }
421206f32e7eSjoerg }
421306f32e7eSjoerg 
421406f32e7eSjoerg SwitchInstProfUpdateWrapper::CaseWeightOpt
getSuccessorWeight(const SwitchInst & SI,unsigned idx)421506f32e7eSjoerg SwitchInstProfUpdateWrapper::getSuccessorWeight(const SwitchInst &SI,
421606f32e7eSjoerg                                                 unsigned idx) {
421706f32e7eSjoerg   if (MDNode *ProfileData = getProfBranchWeightsMD(SI))
421806f32e7eSjoerg     if (ProfileData->getNumOperands() == SI.getNumSuccessors() + 1)
421906f32e7eSjoerg       return mdconst::extract<ConstantInt>(ProfileData->getOperand(idx + 1))
422006f32e7eSjoerg           ->getValue()
422106f32e7eSjoerg           .getZExtValue();
422206f32e7eSjoerg 
422306f32e7eSjoerg   return None;
422406f32e7eSjoerg }
422506f32e7eSjoerg 
422606f32e7eSjoerg //===----------------------------------------------------------------------===//
422706f32e7eSjoerg //                        IndirectBrInst Implementation
422806f32e7eSjoerg //===----------------------------------------------------------------------===//
422906f32e7eSjoerg 
init(Value * Address,unsigned NumDests)423006f32e7eSjoerg void IndirectBrInst::init(Value *Address, unsigned NumDests) {
423106f32e7eSjoerg   assert(Address && Address->getType()->isPointerTy() &&
423206f32e7eSjoerg          "Address of indirectbr must be a pointer");
423306f32e7eSjoerg   ReservedSpace = 1+NumDests;
423406f32e7eSjoerg   setNumHungOffUseOperands(1);
423506f32e7eSjoerg   allocHungoffUses(ReservedSpace);
423606f32e7eSjoerg 
423706f32e7eSjoerg   Op<0>() = Address;
423806f32e7eSjoerg }
423906f32e7eSjoerg 
424006f32e7eSjoerg 
424106f32e7eSjoerg /// growOperands - grow operands - This grows the operand list in response
424206f32e7eSjoerg /// to a push_back style of operation.  This grows the number of ops by 2 times.
424306f32e7eSjoerg ///
growOperands()424406f32e7eSjoerg void IndirectBrInst::growOperands() {
424506f32e7eSjoerg   unsigned e = getNumOperands();
424606f32e7eSjoerg   unsigned NumOps = e*2;
424706f32e7eSjoerg 
424806f32e7eSjoerg   ReservedSpace = NumOps;
424906f32e7eSjoerg   growHungoffUses(ReservedSpace);
425006f32e7eSjoerg }
425106f32e7eSjoerg 
IndirectBrInst(Value * Address,unsigned NumCases,Instruction * InsertBefore)425206f32e7eSjoerg IndirectBrInst::IndirectBrInst(Value *Address, unsigned NumCases,
425306f32e7eSjoerg                                Instruction *InsertBefore)
425406f32e7eSjoerg     : Instruction(Type::getVoidTy(Address->getContext()),
425506f32e7eSjoerg                   Instruction::IndirectBr, nullptr, 0, InsertBefore) {
425606f32e7eSjoerg   init(Address, NumCases);
425706f32e7eSjoerg }
425806f32e7eSjoerg 
IndirectBrInst(Value * Address,unsigned NumCases,BasicBlock * InsertAtEnd)425906f32e7eSjoerg IndirectBrInst::IndirectBrInst(Value *Address, unsigned NumCases,
426006f32e7eSjoerg                                BasicBlock *InsertAtEnd)
426106f32e7eSjoerg     : Instruction(Type::getVoidTy(Address->getContext()),
426206f32e7eSjoerg                   Instruction::IndirectBr, nullptr, 0, InsertAtEnd) {
426306f32e7eSjoerg   init(Address, NumCases);
426406f32e7eSjoerg }
426506f32e7eSjoerg 
IndirectBrInst(const IndirectBrInst & IBI)426606f32e7eSjoerg IndirectBrInst::IndirectBrInst(const IndirectBrInst &IBI)
426706f32e7eSjoerg     : Instruction(Type::getVoidTy(IBI.getContext()), Instruction::IndirectBr,
426806f32e7eSjoerg                   nullptr, IBI.getNumOperands()) {
426906f32e7eSjoerg   allocHungoffUses(IBI.getNumOperands());
427006f32e7eSjoerg   Use *OL = getOperandList();
427106f32e7eSjoerg   const Use *InOL = IBI.getOperandList();
427206f32e7eSjoerg   for (unsigned i = 0, E = IBI.getNumOperands(); i != E; ++i)
427306f32e7eSjoerg     OL[i] = InOL[i];
427406f32e7eSjoerg   SubclassOptionalData = IBI.SubclassOptionalData;
427506f32e7eSjoerg }
427606f32e7eSjoerg 
427706f32e7eSjoerg /// addDestination - Add a destination.
427806f32e7eSjoerg ///
addDestination(BasicBlock * DestBB)427906f32e7eSjoerg void IndirectBrInst::addDestination(BasicBlock *DestBB) {
428006f32e7eSjoerg   unsigned OpNo = getNumOperands();
428106f32e7eSjoerg   if (OpNo+1 > ReservedSpace)
428206f32e7eSjoerg     growOperands();  // Get more space!
428306f32e7eSjoerg   // Initialize some new operands.
428406f32e7eSjoerg   assert(OpNo < ReservedSpace && "Growing didn't work!");
428506f32e7eSjoerg   setNumHungOffUseOperands(OpNo+1);
428606f32e7eSjoerg   getOperandList()[OpNo] = DestBB;
428706f32e7eSjoerg }
428806f32e7eSjoerg 
428906f32e7eSjoerg /// removeDestination - This method removes the specified successor from the
429006f32e7eSjoerg /// indirectbr instruction.
removeDestination(unsigned idx)429106f32e7eSjoerg void IndirectBrInst::removeDestination(unsigned idx) {
429206f32e7eSjoerg   assert(idx < getNumOperands()-1 && "Successor index out of range!");
429306f32e7eSjoerg 
429406f32e7eSjoerg   unsigned NumOps = getNumOperands();
429506f32e7eSjoerg   Use *OL = getOperandList();
429606f32e7eSjoerg 
429706f32e7eSjoerg   // Replace this value with the last one.
429806f32e7eSjoerg   OL[idx+1] = OL[NumOps-1];
429906f32e7eSjoerg 
430006f32e7eSjoerg   // Nuke the last value.
430106f32e7eSjoerg   OL[NumOps-1].set(nullptr);
430206f32e7eSjoerg   setNumHungOffUseOperands(NumOps-1);
430306f32e7eSjoerg }
430406f32e7eSjoerg 
430506f32e7eSjoerg //===----------------------------------------------------------------------===//
4306*da58b97aSjoerg //                            FreezeInst Implementation
4307*da58b97aSjoerg //===----------------------------------------------------------------------===//
4308*da58b97aSjoerg 
FreezeInst(Value * S,const Twine & Name,Instruction * InsertBefore)4309*da58b97aSjoerg FreezeInst::FreezeInst(Value *S,
4310*da58b97aSjoerg                        const Twine &Name, Instruction *InsertBefore)
4311*da58b97aSjoerg     : UnaryInstruction(S->getType(), Freeze, S, InsertBefore) {
4312*da58b97aSjoerg   setName(Name);
4313*da58b97aSjoerg }
4314*da58b97aSjoerg 
FreezeInst(Value * S,const Twine & Name,BasicBlock * InsertAtEnd)4315*da58b97aSjoerg FreezeInst::FreezeInst(Value *S,
4316*da58b97aSjoerg                        const Twine &Name, BasicBlock *InsertAtEnd)
4317*da58b97aSjoerg     : UnaryInstruction(S->getType(), Freeze, S, InsertAtEnd) {
4318*da58b97aSjoerg   setName(Name);
4319*da58b97aSjoerg }
4320*da58b97aSjoerg 
4321*da58b97aSjoerg //===----------------------------------------------------------------------===//
432206f32e7eSjoerg //                           cloneImpl() implementations
432306f32e7eSjoerg //===----------------------------------------------------------------------===//
432406f32e7eSjoerg 
432506f32e7eSjoerg // Define these methods here so vtables don't get emitted into every translation
432606f32e7eSjoerg // unit that uses these classes.
432706f32e7eSjoerg 
cloneImpl() const432806f32e7eSjoerg GetElementPtrInst *GetElementPtrInst::cloneImpl() const {
432906f32e7eSjoerg   return new (getNumOperands()) GetElementPtrInst(*this);
433006f32e7eSjoerg }
433106f32e7eSjoerg 
cloneImpl() const433206f32e7eSjoerg UnaryOperator *UnaryOperator::cloneImpl() const {
433306f32e7eSjoerg   return Create(getOpcode(), Op<0>());
433406f32e7eSjoerg }
433506f32e7eSjoerg 
cloneImpl() const433606f32e7eSjoerg BinaryOperator *BinaryOperator::cloneImpl() const {
433706f32e7eSjoerg   return Create(getOpcode(), Op<0>(), Op<1>());
433806f32e7eSjoerg }
433906f32e7eSjoerg 
cloneImpl() const434006f32e7eSjoerg FCmpInst *FCmpInst::cloneImpl() const {
434106f32e7eSjoerg   return new FCmpInst(getPredicate(), Op<0>(), Op<1>());
434206f32e7eSjoerg }
434306f32e7eSjoerg 
cloneImpl() const434406f32e7eSjoerg ICmpInst *ICmpInst::cloneImpl() const {
434506f32e7eSjoerg   return new ICmpInst(getPredicate(), Op<0>(), Op<1>());
434606f32e7eSjoerg }
434706f32e7eSjoerg 
cloneImpl() const434806f32e7eSjoerg ExtractValueInst *ExtractValueInst::cloneImpl() const {
434906f32e7eSjoerg   return new ExtractValueInst(*this);
435006f32e7eSjoerg }
435106f32e7eSjoerg 
cloneImpl() const435206f32e7eSjoerg InsertValueInst *InsertValueInst::cloneImpl() const {
435306f32e7eSjoerg   return new InsertValueInst(*this);
435406f32e7eSjoerg }
435506f32e7eSjoerg 
cloneImpl() const435606f32e7eSjoerg AllocaInst *AllocaInst::cloneImpl() const {
435706f32e7eSjoerg   AllocaInst *Result =
435806f32e7eSjoerg       new AllocaInst(getAllocatedType(), getType()->getAddressSpace(),
4359*da58b97aSjoerg                      getOperand(0), getAlign());
436006f32e7eSjoerg   Result->setUsedWithInAlloca(isUsedWithInAlloca());
436106f32e7eSjoerg   Result->setSwiftError(isSwiftError());
436206f32e7eSjoerg   return Result;
436306f32e7eSjoerg }
436406f32e7eSjoerg 
cloneImpl() const436506f32e7eSjoerg LoadInst *LoadInst::cloneImpl() const {
436606f32e7eSjoerg   return new LoadInst(getType(), getOperand(0), Twine(), isVolatile(),
4367*da58b97aSjoerg                       getAlign(), getOrdering(), getSyncScopeID());
436806f32e7eSjoerg }
436906f32e7eSjoerg 
cloneImpl() const437006f32e7eSjoerg StoreInst *StoreInst::cloneImpl() const {
4371*da58b97aSjoerg   return new StoreInst(getOperand(0), getOperand(1), isVolatile(), getAlign(),
4372*da58b97aSjoerg                        getOrdering(), getSyncScopeID());
437306f32e7eSjoerg }
437406f32e7eSjoerg 
cloneImpl() const437506f32e7eSjoerg AtomicCmpXchgInst *AtomicCmpXchgInst::cloneImpl() const {
4376*da58b97aSjoerg   AtomicCmpXchgInst *Result = new AtomicCmpXchgInst(
4377*da58b97aSjoerg       getOperand(0), getOperand(1), getOperand(2), getAlign(),
4378*da58b97aSjoerg       getSuccessOrdering(), getFailureOrdering(), getSyncScopeID());
437906f32e7eSjoerg   Result->setVolatile(isVolatile());
438006f32e7eSjoerg   Result->setWeak(isWeak());
438106f32e7eSjoerg   return Result;
438206f32e7eSjoerg }
438306f32e7eSjoerg 
cloneImpl() const438406f32e7eSjoerg AtomicRMWInst *AtomicRMWInst::cloneImpl() const {
438506f32e7eSjoerg   AtomicRMWInst *Result =
438606f32e7eSjoerg       new AtomicRMWInst(getOperation(), getOperand(0), getOperand(1),
4387*da58b97aSjoerg                         getAlign(), getOrdering(), getSyncScopeID());
438806f32e7eSjoerg   Result->setVolatile(isVolatile());
438906f32e7eSjoerg   return Result;
439006f32e7eSjoerg }
439106f32e7eSjoerg 
cloneImpl() const439206f32e7eSjoerg FenceInst *FenceInst::cloneImpl() const {
439306f32e7eSjoerg   return new FenceInst(getContext(), getOrdering(), getSyncScopeID());
439406f32e7eSjoerg }
439506f32e7eSjoerg 
cloneImpl() const439606f32e7eSjoerg TruncInst *TruncInst::cloneImpl() const {
439706f32e7eSjoerg   return new TruncInst(getOperand(0), getType());
439806f32e7eSjoerg }
439906f32e7eSjoerg 
cloneImpl() const440006f32e7eSjoerg ZExtInst *ZExtInst::cloneImpl() const {
440106f32e7eSjoerg   return new ZExtInst(getOperand(0), getType());
440206f32e7eSjoerg }
440306f32e7eSjoerg 
cloneImpl() const440406f32e7eSjoerg SExtInst *SExtInst::cloneImpl() const {
440506f32e7eSjoerg   return new SExtInst(getOperand(0), getType());
440606f32e7eSjoerg }
440706f32e7eSjoerg 
cloneImpl() const440806f32e7eSjoerg FPTruncInst *FPTruncInst::cloneImpl() const {
440906f32e7eSjoerg   return new FPTruncInst(getOperand(0), getType());
441006f32e7eSjoerg }
441106f32e7eSjoerg 
cloneImpl() const441206f32e7eSjoerg FPExtInst *FPExtInst::cloneImpl() const {
441306f32e7eSjoerg   return new FPExtInst(getOperand(0), getType());
441406f32e7eSjoerg }
441506f32e7eSjoerg 
cloneImpl() const441606f32e7eSjoerg UIToFPInst *UIToFPInst::cloneImpl() const {
441706f32e7eSjoerg   return new UIToFPInst(getOperand(0), getType());
441806f32e7eSjoerg }
441906f32e7eSjoerg 
cloneImpl() const442006f32e7eSjoerg SIToFPInst *SIToFPInst::cloneImpl() const {
442106f32e7eSjoerg   return new SIToFPInst(getOperand(0), getType());
442206f32e7eSjoerg }
442306f32e7eSjoerg 
cloneImpl() const442406f32e7eSjoerg FPToUIInst *FPToUIInst::cloneImpl() const {
442506f32e7eSjoerg   return new FPToUIInst(getOperand(0), getType());
442606f32e7eSjoerg }
442706f32e7eSjoerg 
cloneImpl() const442806f32e7eSjoerg FPToSIInst *FPToSIInst::cloneImpl() const {
442906f32e7eSjoerg   return new FPToSIInst(getOperand(0), getType());
443006f32e7eSjoerg }
443106f32e7eSjoerg 
cloneImpl() const443206f32e7eSjoerg PtrToIntInst *PtrToIntInst::cloneImpl() const {
443306f32e7eSjoerg   return new PtrToIntInst(getOperand(0), getType());
443406f32e7eSjoerg }
443506f32e7eSjoerg 
cloneImpl() const443606f32e7eSjoerg IntToPtrInst *IntToPtrInst::cloneImpl() const {
443706f32e7eSjoerg   return new IntToPtrInst(getOperand(0), getType());
443806f32e7eSjoerg }
443906f32e7eSjoerg 
cloneImpl() const444006f32e7eSjoerg BitCastInst *BitCastInst::cloneImpl() const {
444106f32e7eSjoerg   return new BitCastInst(getOperand(0), getType());
444206f32e7eSjoerg }
444306f32e7eSjoerg 
cloneImpl() const444406f32e7eSjoerg AddrSpaceCastInst *AddrSpaceCastInst::cloneImpl() const {
444506f32e7eSjoerg   return new AddrSpaceCastInst(getOperand(0), getType());
444606f32e7eSjoerg }
444706f32e7eSjoerg 
cloneImpl() const444806f32e7eSjoerg CallInst *CallInst::cloneImpl() const {
444906f32e7eSjoerg   if (hasOperandBundles()) {
445006f32e7eSjoerg     unsigned DescriptorBytes = getNumOperandBundles() * sizeof(BundleOpInfo);
445106f32e7eSjoerg     return new(getNumOperands(), DescriptorBytes) CallInst(*this);
445206f32e7eSjoerg   }
445306f32e7eSjoerg   return  new(getNumOperands()) CallInst(*this);
445406f32e7eSjoerg }
445506f32e7eSjoerg 
cloneImpl() const445606f32e7eSjoerg SelectInst *SelectInst::cloneImpl() const {
445706f32e7eSjoerg   return SelectInst::Create(getOperand(0), getOperand(1), getOperand(2));
445806f32e7eSjoerg }
445906f32e7eSjoerg 
cloneImpl() const446006f32e7eSjoerg VAArgInst *VAArgInst::cloneImpl() const {
446106f32e7eSjoerg   return new VAArgInst(getOperand(0), getType());
446206f32e7eSjoerg }
446306f32e7eSjoerg 
cloneImpl() const446406f32e7eSjoerg ExtractElementInst *ExtractElementInst::cloneImpl() const {
446506f32e7eSjoerg   return ExtractElementInst::Create(getOperand(0), getOperand(1));
446606f32e7eSjoerg }
446706f32e7eSjoerg 
cloneImpl() const446806f32e7eSjoerg InsertElementInst *InsertElementInst::cloneImpl() const {
446906f32e7eSjoerg   return InsertElementInst::Create(getOperand(0), getOperand(1), getOperand(2));
447006f32e7eSjoerg }
447106f32e7eSjoerg 
cloneImpl() const447206f32e7eSjoerg ShuffleVectorInst *ShuffleVectorInst::cloneImpl() const {
4473*da58b97aSjoerg   return new ShuffleVectorInst(getOperand(0), getOperand(1), getShuffleMask());
447406f32e7eSjoerg }
447506f32e7eSjoerg 
cloneImpl() const447606f32e7eSjoerg PHINode *PHINode::cloneImpl() const { return new PHINode(*this); }
447706f32e7eSjoerg 
cloneImpl() const447806f32e7eSjoerg LandingPadInst *LandingPadInst::cloneImpl() const {
447906f32e7eSjoerg   return new LandingPadInst(*this);
448006f32e7eSjoerg }
448106f32e7eSjoerg 
cloneImpl() const448206f32e7eSjoerg ReturnInst *ReturnInst::cloneImpl() const {
448306f32e7eSjoerg   return new(getNumOperands()) ReturnInst(*this);
448406f32e7eSjoerg }
448506f32e7eSjoerg 
cloneImpl() const448606f32e7eSjoerg BranchInst *BranchInst::cloneImpl() const {
448706f32e7eSjoerg   return new(getNumOperands()) BranchInst(*this);
448806f32e7eSjoerg }
448906f32e7eSjoerg 
cloneImpl() const449006f32e7eSjoerg SwitchInst *SwitchInst::cloneImpl() const { return new SwitchInst(*this); }
449106f32e7eSjoerg 
cloneImpl() const449206f32e7eSjoerg IndirectBrInst *IndirectBrInst::cloneImpl() const {
449306f32e7eSjoerg   return new IndirectBrInst(*this);
449406f32e7eSjoerg }
449506f32e7eSjoerg 
cloneImpl() const449606f32e7eSjoerg InvokeInst *InvokeInst::cloneImpl() const {
449706f32e7eSjoerg   if (hasOperandBundles()) {
449806f32e7eSjoerg     unsigned DescriptorBytes = getNumOperandBundles() * sizeof(BundleOpInfo);
449906f32e7eSjoerg     return new(getNumOperands(), DescriptorBytes) InvokeInst(*this);
450006f32e7eSjoerg   }
450106f32e7eSjoerg   return new(getNumOperands()) InvokeInst(*this);
450206f32e7eSjoerg }
450306f32e7eSjoerg 
cloneImpl() const450406f32e7eSjoerg CallBrInst *CallBrInst::cloneImpl() const {
450506f32e7eSjoerg   if (hasOperandBundles()) {
450606f32e7eSjoerg     unsigned DescriptorBytes = getNumOperandBundles() * sizeof(BundleOpInfo);
450706f32e7eSjoerg     return new (getNumOperands(), DescriptorBytes) CallBrInst(*this);
450806f32e7eSjoerg   }
450906f32e7eSjoerg   return new (getNumOperands()) CallBrInst(*this);
451006f32e7eSjoerg }
451106f32e7eSjoerg 
cloneImpl() const451206f32e7eSjoerg ResumeInst *ResumeInst::cloneImpl() const { return new (1) ResumeInst(*this); }
451306f32e7eSjoerg 
cloneImpl() const451406f32e7eSjoerg CleanupReturnInst *CleanupReturnInst::cloneImpl() const {
451506f32e7eSjoerg   return new (getNumOperands()) CleanupReturnInst(*this);
451606f32e7eSjoerg }
451706f32e7eSjoerg 
cloneImpl() const451806f32e7eSjoerg CatchReturnInst *CatchReturnInst::cloneImpl() const {
451906f32e7eSjoerg   return new (getNumOperands()) CatchReturnInst(*this);
452006f32e7eSjoerg }
452106f32e7eSjoerg 
cloneImpl() const452206f32e7eSjoerg CatchSwitchInst *CatchSwitchInst::cloneImpl() const {
452306f32e7eSjoerg   return new CatchSwitchInst(*this);
452406f32e7eSjoerg }
452506f32e7eSjoerg 
cloneImpl() const452606f32e7eSjoerg FuncletPadInst *FuncletPadInst::cloneImpl() const {
452706f32e7eSjoerg   return new (getNumOperands()) FuncletPadInst(*this);
452806f32e7eSjoerg }
452906f32e7eSjoerg 
cloneImpl() const453006f32e7eSjoerg UnreachableInst *UnreachableInst::cloneImpl() const {
453106f32e7eSjoerg   LLVMContext &Context = getContext();
453206f32e7eSjoerg   return new UnreachableInst(Context);
453306f32e7eSjoerg }
4534*da58b97aSjoerg 
cloneImpl() const4535*da58b97aSjoerg FreezeInst *FreezeInst::cloneImpl() const {
4536*da58b97aSjoerg   return new FreezeInst(getOperand(0));
4537*da58b97aSjoerg }
4538