1d761e2c2SEugene Zelenko //===- Instructions.cpp - Implement the LLVM instructions -----------------===//
2ef860a24SChandler Carruth //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6ef860a24SChandler Carruth //
7ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
8ef860a24SChandler Carruth //
9ef860a24SChandler Carruth // This file implements all of the non-inline methods for the LLVM instruction
10ef860a24SChandler Carruth // classes.
11ef860a24SChandler Carruth //
12ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
13ef860a24SChandler Carruth 
146bda14b3SChandler Carruth #include "llvm/IR/Instructions.h"
15ef860a24SChandler Carruth #include "LLVMContextImpl.h"
16d761e2c2SEugene Zelenko #include "llvm/ADT/None.h"
17d761e2c2SEugene Zelenko #include "llvm/ADT/SmallVector.h"
18d761e2c2SEugene Zelenko #include "llvm/ADT/Twine.h"
19d761e2c2SEugene Zelenko #include "llvm/IR/Attributes.h"
20d761e2c2SEugene Zelenko #include "llvm/IR/BasicBlock.h"
21219b89b9SChandler Carruth #include "llvm/IR/CallSite.h"
22d761e2c2SEugene Zelenko #include "llvm/IR/Constant.h"
239fb823bbSChandler Carruth #include "llvm/IR/Constants.h"
249fb823bbSChandler Carruth #include "llvm/IR/DataLayout.h"
259fb823bbSChandler Carruth #include "llvm/IR/DerivedTypes.h"
269fb823bbSChandler Carruth #include "llvm/IR/Function.h"
27d761e2c2SEugene Zelenko #include "llvm/IR/InstrTypes.h"
28d761e2c2SEugene Zelenko #include "llvm/IR/Instruction.h"
2905b5bd8bSChandler Carruth #include "llvm/IR/Intrinsics.h"
30d761e2c2SEugene Zelenko #include "llvm/IR/LLVMContext.h"
3101f8d556SWei Mi #include "llvm/IR/MDBuilder.h"
32d761e2c2SEugene Zelenko #include "llvm/IR/Metadata.h"
339fb823bbSChandler Carruth #include "llvm/IR/Module.h"
349fb823bbSChandler Carruth #include "llvm/IR/Operator.h"
35d761e2c2SEugene Zelenko #include "llvm/IR/Type.h"
36d761e2c2SEugene Zelenko #include "llvm/IR/Value.h"
37d761e2c2SEugene Zelenko #include "llvm/Support/AtomicOrdering.h"
38d761e2c2SEugene Zelenko #include "llvm/Support/Casting.h"
39ef860a24SChandler Carruth #include "llvm/Support/ErrorHandling.h"
40ef860a24SChandler Carruth #include "llvm/Support/MathExtras.h"
41b302561bSGraham Hunter #include "llvm/Support/TypeSize.h"
42d761e2c2SEugene Zelenko #include <algorithm>
43d761e2c2SEugene Zelenko #include <cassert>
44d761e2c2SEugene Zelenko #include <cstdint>
45d761e2c2SEugene Zelenko #include <vector>
46d761e2c2SEugene Zelenko 
47ef860a24SChandler Carruth using namespace llvm;
48ef860a24SChandler Carruth 
49ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
50550517bcSBjorn Pettersson //                            AllocaInst Class
51550517bcSBjorn Pettersson //===----------------------------------------------------------------------===//
52550517bcSBjorn Pettersson 
53550517bcSBjorn Pettersson Optional<uint64_t>
54550517bcSBjorn Pettersson AllocaInst::getAllocationSizeInBits(const DataLayout &DL) const {
55550517bcSBjorn Pettersson   uint64_t Size = DL.getTypeAllocSizeInBits(getAllocatedType());
56550517bcSBjorn Pettersson   if (isArrayAllocation()) {
57550517bcSBjorn Pettersson     auto C = dyn_cast<ConstantInt>(getArraySize());
58550517bcSBjorn Pettersson     if (!C)
59550517bcSBjorn Pettersson       return None;
60550517bcSBjorn Pettersson     Size *= C->getZExtValue();
61550517bcSBjorn Pettersson   }
62550517bcSBjorn Pettersson   return Size;
63550517bcSBjorn Pettersson }
64550517bcSBjorn Pettersson 
65550517bcSBjorn Pettersson //===----------------------------------------------------------------------===//
66ef860a24SChandler Carruth //                            CallSite Class
67ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
68ef860a24SChandler Carruth 
69ef860a24SChandler Carruth User::op_iterator CallSite::getCallee() const {
70e429c794SChandler Carruth   return cast<CallBase>(getInstruction())->op_end() - 1;
71ef860a24SChandler Carruth }
72ef860a24SChandler Carruth 
73ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
74ef860a24SChandler Carruth //                              SelectInst Class
75ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
76ef860a24SChandler Carruth 
77ef860a24SChandler Carruth /// areInvalidOperands - Return a string if the specified operands are invalid
78ef860a24SChandler Carruth /// for a select operation, otherwise return null.
79ef860a24SChandler Carruth const char *SelectInst::areInvalidOperands(Value *Op0, Value *Op1, Value *Op2) {
80ef860a24SChandler Carruth   if (Op1->getType() != Op2->getType())
81ef860a24SChandler Carruth     return "both values to select must have same type";
82ef860a24SChandler Carruth 
83b611e3f5SDavid Majnemer   if (Op1->getType()->isTokenTy())
84b611e3f5SDavid Majnemer     return "select values cannot have token type";
85b611e3f5SDavid Majnemer 
86ef860a24SChandler Carruth   if (VectorType *VT = dyn_cast<VectorType>(Op0->getType())) {
87ef860a24SChandler Carruth     // Vector select.
88ef860a24SChandler Carruth     if (VT->getElementType() != Type::getInt1Ty(Op0->getContext()))
89ef860a24SChandler Carruth       return "vector select condition element type must be i1";
90ef860a24SChandler Carruth     VectorType *ET = dyn_cast<VectorType>(Op1->getType());
91c620761cSCraig Topper     if (!ET)
92ef860a24SChandler Carruth       return "selected values for vector select must be vectors";
93ef860a24SChandler Carruth     if (ET->getNumElements() != VT->getNumElements())
94ef860a24SChandler Carruth       return "vector select requires selected vectors to have "
95ef860a24SChandler Carruth                    "the same vector length as select condition";
96ef860a24SChandler Carruth   } else if (Op0->getType() != Type::getInt1Ty(Op0->getContext())) {
97ef860a24SChandler Carruth     return "select condition must be i1 or <n x i1>";
98ef860a24SChandler Carruth   }
99c620761cSCraig Topper   return nullptr;
100ef860a24SChandler Carruth }
101ef860a24SChandler Carruth 
102ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
103ef860a24SChandler Carruth //                               PHINode Class
104ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
105ef860a24SChandler Carruth 
106ef860a24SChandler Carruth PHINode::PHINode(const PHINode &PN)
1073fc30408SPete Cooper     : Instruction(PN.getType(), Instruction::PHI, nullptr, PN.getNumOperands()),
108ef860a24SChandler Carruth       ReservedSpace(PN.getNumOperands()) {
1093fc30408SPete Cooper   allocHungoffUses(PN.getNumOperands());
110ef860a24SChandler Carruth   std::copy(PN.op_begin(), PN.op_end(), op_begin());
111ef860a24SChandler Carruth   std::copy(PN.block_begin(), PN.block_end(), block_begin());
112ef860a24SChandler Carruth   SubclassOptionalData = PN.SubclassOptionalData;
113ef860a24SChandler Carruth }
114ef860a24SChandler Carruth 
115ef860a24SChandler Carruth // removeIncomingValue - Remove an incoming value.  This is useful if a
116ef860a24SChandler Carruth // predecessor basic block is deleted.
117ef860a24SChandler Carruth Value *PHINode::removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty) {
118ef860a24SChandler Carruth   Value *Removed = getIncomingValue(Idx);
119ef860a24SChandler Carruth 
120ef860a24SChandler Carruth   // Move everything after this operand down.
121ef860a24SChandler Carruth   //
122ef860a24SChandler Carruth   // FIXME: we could just swap with the end of the list, then erase.  However,
123ef860a24SChandler Carruth   // clients might not expect this to happen.  The code as it is thrashes the
124ef860a24SChandler Carruth   // use/def lists, which is kinda lame.
125ef860a24SChandler Carruth   std::copy(op_begin() + Idx + 1, op_end(), op_begin() + Idx);
126ef860a24SChandler Carruth   std::copy(block_begin() + Idx + 1, block_end(), block_begin() + Idx);
127ef860a24SChandler Carruth 
128ef860a24SChandler Carruth   // Nuke the last value.
129c620761cSCraig Topper   Op<-1>().set(nullptr);
130b4eede2cSPete Cooper   setNumHungOffUseOperands(getNumOperands() - 1);
131ef860a24SChandler Carruth 
132ef860a24SChandler Carruth   // If the PHI node is dead, because it has zero entries, nuke it now.
133ef860a24SChandler Carruth   if (getNumOperands() == 0 && DeletePHIIfEmpty) {
134ef860a24SChandler Carruth     // If anyone is using this PHI, make them use a dummy value instead...
135ef860a24SChandler Carruth     replaceAllUsesWith(UndefValue::get(getType()));
136ef860a24SChandler Carruth     eraseFromParent();
137ef860a24SChandler Carruth   }
138ef860a24SChandler Carruth   return Removed;
139ef860a24SChandler Carruth }
140ef860a24SChandler Carruth 
141ef860a24SChandler Carruth /// growOperands - grow operands - This grows the operand list in response
142ef860a24SChandler Carruth /// to a push_back style of operation.  This grows the number of ops by 1.5
143ef860a24SChandler Carruth /// times.
144ef860a24SChandler Carruth ///
145ef860a24SChandler Carruth void PHINode::growOperands() {
146ef860a24SChandler Carruth   unsigned e = getNumOperands();
147ef860a24SChandler Carruth   unsigned NumOps = e + e / 2;
148ef860a24SChandler Carruth   if (NumOps < 2) NumOps = 2;      // 2 op PHI nodes are VERY common.
149ef860a24SChandler Carruth 
150ef860a24SChandler Carruth   ReservedSpace = NumOps;
15193f9ff57SPete Cooper   growHungoffUses(ReservedSpace, /* IsPhi */ true);
152ef860a24SChandler Carruth }
153ef860a24SChandler Carruth 
154ef860a24SChandler Carruth /// hasConstantValue - If the specified PHI node always merges together the same
155ef860a24SChandler Carruth /// value, return the value, otherwise return null.
156ef860a24SChandler Carruth Value *PHINode::hasConstantValue() const {
157ef860a24SChandler Carruth   // Exploit the fact that phi nodes always have at least one entry.
158ef860a24SChandler Carruth   Value *ConstantValue = getIncomingValue(0);
159ef860a24SChandler Carruth   for (unsigned i = 1, e = getNumIncomingValues(); i != e; ++i)
160ef860a24SChandler Carruth     if (getIncomingValue(i) != ConstantValue && getIncomingValue(i) != this) {
161ef860a24SChandler Carruth       if (ConstantValue != this)
162c620761cSCraig Topper         return nullptr; // Incoming values not all the same.
163ef860a24SChandler Carruth        // The case where the first value is this PHI.
164ef860a24SChandler Carruth       ConstantValue = getIncomingValue(i);
165ef860a24SChandler Carruth     }
166ef860a24SChandler Carruth   if (ConstantValue == this)
167ef860a24SChandler Carruth     return UndefValue::get(getType());
168ef860a24SChandler Carruth   return ConstantValue;
169ef860a24SChandler Carruth }
170ef860a24SChandler Carruth 
17113d90f32SNicolai Haehnle /// hasConstantOrUndefValue - Whether the specified PHI node always merges
17213d90f32SNicolai Haehnle /// together the same value, assuming that undefs result in the same value as
17313d90f32SNicolai Haehnle /// non-undefs.
17413d90f32SNicolai Haehnle /// Unlike \ref hasConstantValue, this does not return a value because the
17513d90f32SNicolai Haehnle /// unique non-undef incoming value need not dominate the PHI node.
17613d90f32SNicolai Haehnle bool PHINode::hasConstantOrUndefValue() const {
17713d90f32SNicolai Haehnle   Value *ConstantValue = nullptr;
17813d90f32SNicolai Haehnle   for (unsigned i = 0, e = getNumIncomingValues(); i != e; ++i) {
17913d90f32SNicolai Haehnle     Value *Incoming = getIncomingValue(i);
18013d90f32SNicolai Haehnle     if (Incoming != this && !isa<UndefValue>(Incoming)) {
18113d90f32SNicolai Haehnle       if (ConstantValue && ConstantValue != Incoming)
18213d90f32SNicolai Haehnle         return false;
18313d90f32SNicolai Haehnle       ConstantValue = Incoming;
18413d90f32SNicolai Haehnle     }
18513d90f32SNicolai Haehnle   }
18613d90f32SNicolai Haehnle   return true;
18713d90f32SNicolai Haehnle }
18813d90f32SNicolai Haehnle 
189ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
190ef860a24SChandler Carruth //                       LandingPadInst Implementation
191ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
192ef860a24SChandler Carruth 
1937fddeccbSDavid Majnemer LandingPadInst::LandingPadInst(Type *RetTy, unsigned NumReservedValues,
1947fddeccbSDavid Majnemer                                const Twine &NameStr, Instruction *InsertBefore)
195c620761cSCraig Topper     : Instruction(RetTy, Instruction::LandingPad, nullptr, 0, InsertBefore) {
1967fddeccbSDavid Majnemer   init(NumReservedValues, NameStr);
197ef860a24SChandler Carruth }
198ef860a24SChandler Carruth 
1997fddeccbSDavid Majnemer LandingPadInst::LandingPadInst(Type *RetTy, unsigned NumReservedValues,
2007fddeccbSDavid Majnemer                                const Twine &NameStr, BasicBlock *InsertAtEnd)
201c620761cSCraig Topper     : Instruction(RetTy, Instruction::LandingPad, nullptr, 0, InsertAtEnd) {
2027fddeccbSDavid Majnemer   init(NumReservedValues, NameStr);
203ef860a24SChandler Carruth }
204ef860a24SChandler Carruth 
205ef860a24SChandler Carruth LandingPadInst::LandingPadInst(const LandingPadInst &LP)
2063fc30408SPete Cooper     : Instruction(LP.getType(), Instruction::LandingPad, nullptr,
2073fc30408SPete Cooper                   LP.getNumOperands()),
208ef860a24SChandler Carruth       ReservedSpace(LP.getNumOperands()) {
2093fc30408SPete Cooper   allocHungoffUses(LP.getNumOperands());
21074510a40SPete Cooper   Use *OL = getOperandList();
21174510a40SPete Cooper   const Use *InOL = LP.getOperandList();
212ef860a24SChandler Carruth   for (unsigned I = 0, E = ReservedSpace; I != E; ++I)
213ef860a24SChandler Carruth     OL[I] = InOL[I];
214ef860a24SChandler Carruth 
215ef860a24SChandler Carruth   setCleanup(LP.isCleanup());
216ef860a24SChandler Carruth }
217ef860a24SChandler Carruth 
2187fddeccbSDavid Majnemer LandingPadInst *LandingPadInst::Create(Type *RetTy, unsigned NumReservedClauses,
219ef860a24SChandler Carruth                                        const Twine &NameStr,
220ef860a24SChandler Carruth                                        Instruction *InsertBefore) {
2217fddeccbSDavid Majnemer   return new LandingPadInst(RetTy, NumReservedClauses, NameStr, InsertBefore);
222ef860a24SChandler Carruth }
223ef860a24SChandler Carruth 
2247fddeccbSDavid Majnemer LandingPadInst *LandingPadInst::Create(Type *RetTy, unsigned NumReservedClauses,
225ef860a24SChandler Carruth                                        const Twine &NameStr,
226ef860a24SChandler Carruth                                        BasicBlock *InsertAtEnd) {
2277fddeccbSDavid Majnemer   return new LandingPadInst(RetTy, NumReservedClauses, NameStr, InsertAtEnd);
228ef860a24SChandler Carruth }
229ef860a24SChandler Carruth 
2307fddeccbSDavid Majnemer void LandingPadInst::init(unsigned NumReservedValues, const Twine &NameStr) {
231ef860a24SChandler Carruth   ReservedSpace = NumReservedValues;
2327fddeccbSDavid Majnemer   setNumHungOffUseOperands(0);
2333fc30408SPete Cooper   allocHungoffUses(ReservedSpace);
234ef860a24SChandler Carruth   setName(NameStr);
235ef860a24SChandler Carruth   setCleanup(false);
236ef860a24SChandler Carruth }
237ef860a24SChandler Carruth 
238ef860a24SChandler Carruth /// growOperands - grow operands - This grows the operand list in response to a
239ef860a24SChandler Carruth /// push_back style of operation. This grows the number of ops by 2 times.
240ef860a24SChandler Carruth void LandingPadInst::growOperands(unsigned Size) {
241ef860a24SChandler Carruth   unsigned e = getNumOperands();
242ef860a24SChandler Carruth   if (ReservedSpace >= e + Size) return;
2437fddeccbSDavid Majnemer   ReservedSpace = (std::max(e, 1U) + Size / 2) * 2;
24493f9ff57SPete Cooper   growHungoffUses(ReservedSpace);
245ef860a24SChandler Carruth }
246ef860a24SChandler Carruth 
2474dc5dfc5SRafael Espindola void LandingPadInst::addClause(Constant *Val) {
248ef860a24SChandler Carruth   unsigned OpNo = getNumOperands();
249ef860a24SChandler Carruth   growOperands(1);
250ef860a24SChandler Carruth   assert(OpNo < ReservedSpace && "Growing didn't work!");
251b4eede2cSPete Cooper   setNumHungOffUseOperands(getNumOperands() + 1);
25274510a40SPete Cooper   getOperandList()[OpNo] = Val;
253ef860a24SChandler Carruth }
254ef860a24SChandler Carruth 
255ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
256e429c794SChandler Carruth //                        CallBase Implementation
257e429c794SChandler Carruth //===----------------------------------------------------------------------===//
258e429c794SChandler Carruth 
25905b5bd8bSChandler Carruth Function *CallBase::getCaller() { return getParent()->getParent(); }
26005b5bd8bSChandler Carruth 
261784929d0SCraig Topper unsigned CallBase::getNumSubclassExtraOperandsDynamic() const {
262784929d0SCraig Topper   assert(getOpcode() == Instruction::CallBr && "Unexpected opcode!");
263784929d0SCraig Topper   return cast<CallBrInst>(this)->getNumIndirectDests() + 1;
264784929d0SCraig Topper }
265784929d0SCraig Topper 
26657578aafSChandler Carruth bool CallBase::isIndirectCall() const {
26757578aafSChandler Carruth   const Value *V = getCalledValue();
26857578aafSChandler Carruth   if (isa<Function>(V) || isa<Constant>(V))
26957578aafSChandler Carruth     return false;
27057578aafSChandler Carruth   if (const CallInst *CI = dyn_cast<CallInst>(this))
27157578aafSChandler Carruth     if (CI->isInlineAsm())
27257578aafSChandler Carruth       return false;
27357578aafSChandler Carruth   return true;
27457578aafSChandler Carruth }
27557578aafSChandler Carruth 
276c1892ec1SCraig Topper /// Tests if this call site must be tail call optimized. Only a CallInst can
277c1892ec1SCraig Topper /// be tail call optimized.
278c1892ec1SCraig Topper bool CallBase::isMustTailCall() const {
279c1892ec1SCraig Topper   if (auto *CI = dyn_cast<CallInst>(this))
280c1892ec1SCraig Topper     return CI->isMustTailCall();
281c1892ec1SCraig Topper   return false;
282c1892ec1SCraig Topper }
283c1892ec1SCraig Topper 
284c1892ec1SCraig Topper /// Tests if this call site is marked as a tail call.
285c1892ec1SCraig Topper bool CallBase::isTailCall() const {
286c1892ec1SCraig Topper   if (auto *CI = dyn_cast<CallInst>(this))
287c1892ec1SCraig Topper     return CI->isTailCall();
288c1892ec1SCraig Topper   return false;
289c1892ec1SCraig Topper }
290c1892ec1SCraig Topper 
29105b5bd8bSChandler Carruth Intrinsic::ID CallBase::getIntrinsicID() const {
29205b5bd8bSChandler Carruth   if (auto *F = getCalledFunction())
29305b5bd8bSChandler Carruth     return F->getIntrinsicID();
29405b5bd8bSChandler Carruth   return Intrinsic::not_intrinsic;
29505b5bd8bSChandler Carruth }
29605b5bd8bSChandler Carruth 
29705b5bd8bSChandler Carruth bool CallBase::isReturnNonNull() const {
29805b5bd8bSChandler Carruth   if (hasRetAttr(Attribute::NonNull))
29905b5bd8bSChandler Carruth     return true;
30005b5bd8bSChandler Carruth 
30105b5bd8bSChandler Carruth   if (getDereferenceableBytes(AttributeList::ReturnIndex) > 0 &&
30205b5bd8bSChandler Carruth            !NullPointerIsDefined(getCaller(),
30305b5bd8bSChandler Carruth                                  getType()->getPointerAddressSpace()))
30405b5bd8bSChandler Carruth     return true;
30505b5bd8bSChandler Carruth 
30605b5bd8bSChandler Carruth   return false;
30705b5bd8bSChandler Carruth }
30805b5bd8bSChandler Carruth 
309e429c794SChandler Carruth Value *CallBase::getReturnedArgOperand() const {
310e429c794SChandler Carruth   unsigned Index;
311e429c794SChandler Carruth 
312e429c794SChandler Carruth   if (Attrs.hasAttrSomewhere(Attribute::Returned, &Index) && Index)
313e429c794SChandler Carruth     return getArgOperand(Index - AttributeList::FirstArgIndex);
314e429c794SChandler Carruth   if (const Function *F = getCalledFunction())
315e429c794SChandler Carruth     if (F->getAttributes().hasAttrSomewhere(Attribute::Returned, &Index) &&
316e429c794SChandler Carruth         Index)
317e429c794SChandler Carruth       return getArgOperand(Index - AttributeList::FirstArgIndex);
318e429c794SChandler Carruth 
319e429c794SChandler Carruth   return nullptr;
320e429c794SChandler Carruth }
321e429c794SChandler Carruth 
322e429c794SChandler Carruth bool CallBase::hasRetAttr(Attribute::AttrKind Kind) const {
323e429c794SChandler Carruth   if (Attrs.hasAttribute(AttributeList::ReturnIndex, Kind))
324e429c794SChandler Carruth     return true;
325e429c794SChandler Carruth 
326e429c794SChandler Carruth   // Look at the callee, if available.
327e429c794SChandler Carruth   if (const Function *F = getCalledFunction())
328e429c794SChandler Carruth     return F->getAttributes().hasAttribute(AttributeList::ReturnIndex, Kind);
329e429c794SChandler Carruth   return false;
330e429c794SChandler Carruth }
331e429c794SChandler Carruth 
332e429c794SChandler Carruth /// Determine whether the argument or parameter has the given attribute.
333e429c794SChandler Carruth bool CallBase::paramHasAttr(unsigned ArgNo, Attribute::AttrKind Kind) const {
334e429c794SChandler Carruth   assert(ArgNo < getNumArgOperands() && "Param index out of bounds!");
335e429c794SChandler Carruth 
336e429c794SChandler Carruth   if (Attrs.hasParamAttribute(ArgNo, Kind))
337e429c794SChandler Carruth     return true;
338e429c794SChandler Carruth   if (const Function *F = getCalledFunction())
339e429c794SChandler Carruth     return F->getAttributes().hasParamAttribute(ArgNo, Kind);
340e429c794SChandler Carruth   return false;
341e429c794SChandler Carruth }
342e429c794SChandler Carruth 
343e429c794SChandler Carruth bool CallBase::hasFnAttrOnCalledFunction(Attribute::AttrKind Kind) const {
344e429c794SChandler Carruth   if (const Function *F = getCalledFunction())
345e429c794SChandler Carruth     return F->getAttributes().hasAttribute(AttributeList::FunctionIndex, Kind);
346e429c794SChandler Carruth   return false;
347e429c794SChandler Carruth }
348e429c794SChandler Carruth 
349e429c794SChandler Carruth bool CallBase::hasFnAttrOnCalledFunction(StringRef Kind) const {
350e429c794SChandler Carruth   if (const Function *F = getCalledFunction())
351e429c794SChandler Carruth     return F->getAttributes().hasAttribute(AttributeList::FunctionIndex, Kind);
352e429c794SChandler Carruth   return false;
353e429c794SChandler Carruth }
354e429c794SChandler Carruth 
355e429c794SChandler Carruth CallBase::op_iterator
356e429c794SChandler Carruth CallBase::populateBundleOperandInfos(ArrayRef<OperandBundleDef> Bundles,
357e429c794SChandler Carruth                                      const unsigned BeginIndex) {
358e429c794SChandler Carruth   auto It = op_begin() + BeginIndex;
359e429c794SChandler Carruth   for (auto &B : Bundles)
360e429c794SChandler Carruth     It = std::copy(B.input_begin(), B.input_end(), It);
361e429c794SChandler Carruth 
362e429c794SChandler Carruth   auto *ContextImpl = getContext().pImpl;
363e429c794SChandler Carruth   auto BI = Bundles.begin();
364e429c794SChandler Carruth   unsigned CurrentIndex = BeginIndex;
365e429c794SChandler Carruth 
366e429c794SChandler Carruth   for (auto &BOI : bundle_op_infos()) {
367e429c794SChandler Carruth     assert(BI != Bundles.end() && "Incorrect allocation?");
368e429c794SChandler Carruth 
369e429c794SChandler Carruth     BOI.Tag = ContextImpl->getOrInsertBundleTag(BI->getTag());
370e429c794SChandler Carruth     BOI.Begin = CurrentIndex;
371e429c794SChandler Carruth     BOI.End = CurrentIndex + BI->input_size();
372e429c794SChandler Carruth     CurrentIndex = BOI.End;
373e429c794SChandler Carruth     BI++;
374e429c794SChandler Carruth   }
375e429c794SChandler Carruth 
376e429c794SChandler Carruth   assert(BI == Bundles.end() && "Incorrect allocation?");
377e429c794SChandler Carruth 
378e429c794SChandler Carruth   return It;
379e429c794SChandler Carruth }
380e429c794SChandler Carruth 
381e429c794SChandler Carruth //===----------------------------------------------------------------------===//
382ef860a24SChandler Carruth //                        CallInst Implementation
383ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
384ef860a24SChandler Carruth 
385348de69aSDavid Blaikie void CallInst::init(FunctionType *FTy, Value *Func, ArrayRef<Value *> Args,
3869303c246SSanjoy Das                     ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr) {
387348de69aSDavid Blaikie   this->FTy = FTy;
3889303c246SSanjoy Das   assert(getNumOperands() == Args.size() + CountBundleInputs(Bundles) + 1 &&
3899303c246SSanjoy Das          "NumOperands not set up?");
390e429c794SChandler Carruth   setCalledOperand(Func);
391ef860a24SChandler Carruth 
392ef860a24SChandler Carruth #ifndef NDEBUG
393ef860a24SChandler Carruth   assert((Args.size() == FTy->getNumParams() ||
394ef860a24SChandler Carruth           (FTy->isVarArg() && Args.size() > FTy->getNumParams())) &&
395ef860a24SChandler Carruth          "Calling a function with bad signature!");
396ef860a24SChandler Carruth 
397ef860a24SChandler Carruth   for (unsigned i = 0; i != Args.size(); ++i)
398ef860a24SChandler Carruth     assert((i >= FTy->getNumParams() ||
399ef860a24SChandler Carruth             FTy->getParamType(i) == Args[i]->getType()) &&
400ef860a24SChandler Carruth            "Calling a function with a bad signature!");
401ef860a24SChandler Carruth #endif
402ef860a24SChandler Carruth 
40375709329SFangrui Song   llvm::copy(Args, op_begin());
4049303c246SSanjoy Das 
4059303c246SSanjoy Das   auto It = populateBundleOperandInfos(Bundles, Args.size());
4069303c246SSanjoy Das   (void)It;
4079303c246SSanjoy Das   assert(It + 1 == op_end() && "Should add up!");
4089303c246SSanjoy Das 
409ef860a24SChandler Carruth   setName(NameStr);
410ef860a24SChandler Carruth }
411ef860a24SChandler Carruth 
412f9563909SJames Y Knight void CallInst::init(FunctionType *FTy, Value *Func, const Twine &NameStr) {
413f9563909SJames Y Knight   this->FTy = FTy;
414b4eede2cSPete Cooper   assert(getNumOperands() == 1 && "NumOperands not set up?");
415e429c794SChandler Carruth   setCalledOperand(Func);
416ef860a24SChandler Carruth 
417ef860a24SChandler Carruth   assert(FTy->getNumParams() == 0 && "Calling a function with bad signature");
418ef860a24SChandler Carruth 
419ef860a24SChandler Carruth   setName(NameStr);
420ef860a24SChandler Carruth }
421ef860a24SChandler Carruth 
422f9563909SJames Y Knight CallInst::CallInst(FunctionType *Ty, Value *Func, const Twine &Name,
423f9563909SJames Y Knight                    Instruction *InsertBefore)
424f9563909SJames Y Knight     : CallBase(Ty->getReturnType(), Instruction::Call,
425f9563909SJames Y Knight                OperandTraits<CallBase>::op_end(this) - 1, 1, InsertBefore) {
426f9563909SJames Y Knight   init(Ty, Func, Name);
427ef860a24SChandler Carruth }
428ef860a24SChandler Carruth 
429f9563909SJames Y Knight CallInst::CallInst(FunctionType *Ty, Value *Func, const Twine &Name,
430f9563909SJames Y Knight                    BasicBlock *InsertAtEnd)
431f9563909SJames Y Knight     : CallBase(Ty->getReturnType(), Instruction::Call,
432f9563909SJames Y Knight                OperandTraits<CallBase>::op_end(this) - 1, 1, InsertAtEnd) {
433f9563909SJames Y Knight   init(Ty, Func, Name);
434ef860a24SChandler Carruth }
435ef860a24SChandler Carruth 
436ef860a24SChandler Carruth CallInst::CallInst(const CallInst &CI)
437e429c794SChandler Carruth     : CallBase(CI.Attrs, CI.FTy, CI.getType(), Instruction::Call,
438e429c794SChandler Carruth                OperandTraits<CallBase>::op_end(this) - CI.getNumOperands(),
4391fb81bcbSSerge Guelton                CI.getNumOperands()) {
440118e1bf8SReid Kleckner   setTailCallKind(CI.getTailCallKind());
441ef860a24SChandler Carruth   setCallingConv(CI.getCallingConv());
442ef860a24SChandler Carruth 
443ef860a24SChandler Carruth   std::copy(CI.op_begin(), CI.op_end(), op_begin());
4449303c246SSanjoy Das   std::copy(CI.bundle_op_info_begin(), CI.bundle_op_info_end(),
4459303c246SSanjoy Das             bundle_op_info_begin());
446ef860a24SChandler Carruth   SubclassOptionalData = CI.SubclassOptionalData;
447ef860a24SChandler Carruth }
448ef860a24SChandler Carruth 
4492d16145aSSanjoy Das CallInst *CallInst::Create(CallInst *CI, ArrayRef<OperandBundleDef> OpB,
4502d16145aSSanjoy Das                            Instruction *InsertPt) {
451ccd14566SSanjoy Das   std::vector<Value *> Args(CI->arg_begin(), CI->arg_end());
4522d16145aSSanjoy Das 
4537976eb58SJames Y Knight   auto *NewCI = CallInst::Create(CI->getFunctionType(), CI->getCalledValue(),
4547976eb58SJames Y Knight                                  Args, OpB, CI->getName(), InsertPt);
4552d16145aSSanjoy Das   NewCI->setTailCallKind(CI->getTailCallKind());
4562d16145aSSanjoy Das   NewCI->setCallingConv(CI->getCallingConv());
4572d16145aSSanjoy Das   NewCI->SubclassOptionalData = CI->SubclassOptionalData;
458b8dced5dSSanjoy Das   NewCI->setAttributes(CI->getAttributes());
459bba70e44SJoseph Tremoulet   NewCI->setDebugLoc(CI->getDebugLoc());
4602d16145aSSanjoy Das   return NewCI;
4612d16145aSSanjoy Das }
4622d16145aSSanjoy Das 
46301f8d556SWei Mi // Update profile weight for call instruction by scaling it using the ratio
46401f8d556SWei Mi // of S/T. The meaning of "branch_weights" meta data for call instruction is
46501f8d556SWei Mi // transfered to represent call count.
46601f8d556SWei Mi void CallInst::updateProfWeight(uint64_t S, uint64_t T) {
46701f8d556SWei Mi   auto *ProfileData = getMetadata(LLVMContext::MD_prof);
46801f8d556SWei Mi   if (ProfileData == nullptr)
46901f8d556SWei Mi     return;
47001f8d556SWei Mi 
47101f8d556SWei Mi   auto *ProfDataName = dyn_cast<MDString>(ProfileData->getOperand(0));
47201f8d556SWei Mi   if (!ProfDataName || (!ProfDataName->getString().equals("branch_weights") &&
47301f8d556SWei Mi                         !ProfDataName->getString().equals("VP")))
47401f8d556SWei Mi     return;
47501f8d556SWei Mi 
4760a753938SMircea Trofin   if (T == 0) {
4770a753938SMircea Trofin     LLVM_DEBUG(dbgs() << "Attempting to update profile weights will result in "
4780a753938SMircea Trofin                          "div by 0. Ignoring. Likely the function "
4790a753938SMircea Trofin                       << getParent()->getParent()->getName()
4800a753938SMircea Trofin                       << " has 0 entry count, and contains call instructions "
4810a753938SMircea Trofin                          "with non-zero prof info.");
4820a753938SMircea Trofin     return;
4830a753938SMircea Trofin   }
4840a753938SMircea Trofin 
48501f8d556SWei Mi   MDBuilder MDB(getContext());
48601f8d556SWei Mi   SmallVector<Metadata *, 3> Vals;
48701f8d556SWei Mi   Vals.push_back(ProfileData->getOperand(0));
48801f8d556SWei Mi   APInt APS(128, S), APT(128, T);
48901f8d556SWei Mi   if (ProfDataName->getString().equals("branch_weights") &&
49001f8d556SWei Mi       ProfileData->getNumOperands() > 0) {
49101f8d556SWei Mi     // Using APInt::div may be expensive, but most cases should fit 64 bits.
49201f8d556SWei Mi     APInt Val(128, mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(1))
49301f8d556SWei Mi                        ->getValue()
49401f8d556SWei Mi                        .getZExtValue());
49501f8d556SWei Mi     Val *= APS;
49601f8d556SWei Mi     Vals.push_back(MDB.createConstant(ConstantInt::get(
49701f8d556SWei Mi         Type::getInt64Ty(getContext()), Val.udiv(APT).getLimitedValue())));
49801f8d556SWei Mi   } else if (ProfDataName->getString().equals("VP"))
49901f8d556SWei Mi     for (unsigned i = 1; i < ProfileData->getNumOperands(); i += 2) {
50001f8d556SWei Mi       // The first value is the key of the value profile, which will not change.
50101f8d556SWei Mi       Vals.push_back(ProfileData->getOperand(i));
50201f8d556SWei Mi       // Using APInt::div may be expensive, but most cases should fit 64 bits.
50301f8d556SWei Mi       APInt Val(128,
50401f8d556SWei Mi                 mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(i + 1))
50501f8d556SWei Mi                     ->getValue()
50601f8d556SWei Mi                     .getZExtValue());
50701f8d556SWei Mi       Val *= APS;
50801f8d556SWei Mi       Vals.push_back(MDB.createConstant(
50901f8d556SWei Mi           ConstantInt::get(Type::getInt64Ty(getContext()),
51001f8d556SWei Mi                            Val.udiv(APT).getLimitedValue())));
51101f8d556SWei Mi     }
51201f8d556SWei Mi   setMetadata(LLVMContext::MD_prof, MDNode::get(getContext(), Vals));
51301f8d556SWei Mi }
51401f8d556SWei Mi 
515ef860a24SChandler Carruth /// IsConstantOne - Return true only if val is constant int 1
516ef860a24SChandler Carruth static bool IsConstantOne(Value *val) {
517971c3ea6SReid Kleckner   assert(val && "IsConstantOne does not work with nullptr val");
5186941785eSMatt Arsenault   const ConstantInt *CVal = dyn_cast<ConstantInt>(val);
5196941785eSMatt Arsenault   return CVal && CVal->isOne();
520ef860a24SChandler Carruth }
521ef860a24SChandler Carruth 
522ef860a24SChandler Carruth static Instruction *createMalloc(Instruction *InsertBefore,
523ef860a24SChandler Carruth                                  BasicBlock *InsertAtEnd, Type *IntPtrTy,
524ef860a24SChandler Carruth                                  Type *AllocTy, Value *AllocSize,
525fadc6db0SDavid Majnemer                                  Value *ArraySize,
526fadc6db0SDavid Majnemer                                  ArrayRef<OperandBundleDef> OpB,
527fadc6db0SDavid Majnemer                                  Function *MallocF, const Twine &Name) {
528ef860a24SChandler Carruth   assert(((!InsertBefore && InsertAtEnd) || (InsertBefore && !InsertAtEnd)) &&
529ef860a24SChandler Carruth          "createMalloc needs either InsertBefore or InsertAtEnd");
530ef860a24SChandler Carruth 
531ef860a24SChandler Carruth   // malloc(type) becomes:
532ef860a24SChandler Carruth   //       bitcast (i8* malloc(typeSize)) to type*
533ef860a24SChandler Carruth   // malloc(type, arraySize) becomes:
534ef860a24SChandler Carruth   //       bitcast (i8* malloc(typeSize*arraySize)) to type*
535ef860a24SChandler Carruth   if (!ArraySize)
536ef860a24SChandler Carruth     ArraySize = ConstantInt::get(IntPtrTy, 1);
537ef860a24SChandler Carruth   else if (ArraySize->getType() != IntPtrTy) {
538ef860a24SChandler Carruth     if (InsertBefore)
539ef860a24SChandler Carruth       ArraySize = CastInst::CreateIntegerCast(ArraySize, IntPtrTy, false,
540ef860a24SChandler Carruth                                               "", InsertBefore);
541ef860a24SChandler Carruth     else
542ef860a24SChandler Carruth       ArraySize = CastInst::CreateIntegerCast(ArraySize, IntPtrTy, false,
543ef860a24SChandler Carruth                                               "", InsertAtEnd);
544ef860a24SChandler Carruth   }
545ef860a24SChandler Carruth 
546ef860a24SChandler Carruth   if (!IsConstantOne(ArraySize)) {
547ef860a24SChandler Carruth     if (IsConstantOne(AllocSize)) {
548ef860a24SChandler Carruth       AllocSize = ArraySize;         // Operand * 1 = Operand
549ef860a24SChandler Carruth     } else if (Constant *CO = dyn_cast<Constant>(ArraySize)) {
550ef860a24SChandler Carruth       Constant *Scale = ConstantExpr::getIntegerCast(CO, IntPtrTy,
551ef860a24SChandler Carruth                                                      false /*ZExt*/);
552ef860a24SChandler Carruth       // Malloc arg is constant product of type size and array size
553ef860a24SChandler Carruth       AllocSize = ConstantExpr::getMul(Scale, cast<Constant>(AllocSize));
554ef860a24SChandler Carruth     } else {
555ef860a24SChandler Carruth       // Multiply type size by the array size...
556ef860a24SChandler Carruth       if (InsertBefore)
557ef860a24SChandler Carruth         AllocSize = BinaryOperator::CreateMul(ArraySize, AllocSize,
558ef860a24SChandler Carruth                                               "mallocsize", InsertBefore);
559ef860a24SChandler Carruth       else
560ef860a24SChandler Carruth         AllocSize = BinaryOperator::CreateMul(ArraySize, AllocSize,
561ef860a24SChandler Carruth                                               "mallocsize", InsertAtEnd);
562ef860a24SChandler Carruth     }
563ef860a24SChandler Carruth   }
564ef860a24SChandler Carruth 
565ef860a24SChandler Carruth   assert(AllocSize->getType() == IntPtrTy && "malloc arg is wrong size");
566ef860a24SChandler Carruth   // Create the call to Malloc.
567ef860a24SChandler Carruth   BasicBlock *BB = InsertBefore ? InsertBefore->getParent() : InsertAtEnd;
568ef860a24SChandler Carruth   Module *M = BB->getParent()->getParent();
569ef860a24SChandler Carruth   Type *BPTy = Type::getInt8PtrTy(BB->getContext());
57013680223SJames Y Knight   FunctionCallee MallocFunc = MallocF;
571ef860a24SChandler Carruth   if (!MallocFunc)
572ef860a24SChandler Carruth     // prototype malloc as "void *malloc(size_t)"
57359a2d7b9SSerge Guelton     MallocFunc = M->getOrInsertFunction("malloc", BPTy, IntPtrTy);
574ef860a24SChandler Carruth   PointerType *AllocPtrType = PointerType::getUnqual(AllocTy);
575c620761cSCraig Topper   CallInst *MCall = nullptr;
576c620761cSCraig Topper   Instruction *Result = nullptr;
577ef860a24SChandler Carruth   if (InsertBefore) {
578fadc6db0SDavid Majnemer     MCall = CallInst::Create(MallocFunc, AllocSize, OpB, "malloccall",
579fadc6db0SDavid Majnemer                              InsertBefore);
580ef860a24SChandler Carruth     Result = MCall;
581ef860a24SChandler Carruth     if (Result->getType() != AllocPtrType)
582ef860a24SChandler Carruth       // Create a cast instruction to convert to the right type...
583ef860a24SChandler Carruth       Result = new BitCastInst(MCall, AllocPtrType, Name, InsertBefore);
584ef860a24SChandler Carruth   } else {
585fadc6db0SDavid Majnemer     MCall = CallInst::Create(MallocFunc, AllocSize, OpB, "malloccall");
586ef860a24SChandler Carruth     Result = MCall;
587ef860a24SChandler Carruth     if (Result->getType() != AllocPtrType) {
588ef860a24SChandler Carruth       InsertAtEnd->getInstList().push_back(MCall);
589ef860a24SChandler Carruth       // Create a cast instruction to convert to the right type...
590ef860a24SChandler Carruth       Result = new BitCastInst(MCall, AllocPtrType, Name);
591ef860a24SChandler Carruth     }
592ef860a24SChandler Carruth   }
593ef860a24SChandler Carruth   MCall->setTailCall();
59413680223SJames Y Knight   if (Function *F = dyn_cast<Function>(MallocFunc.getCallee())) {
595ef860a24SChandler Carruth     MCall->setCallingConv(F->getCallingConv());
596a0b45f4bSReid Kleckner     if (!F->returnDoesNotAlias())
597a0b45f4bSReid Kleckner       F->setReturnDoesNotAlias();
598ef860a24SChandler Carruth   }
599ef860a24SChandler Carruth   assert(!MCall->getType()->isVoidTy() && "Malloc has void return type");
600ef860a24SChandler Carruth 
601ef860a24SChandler Carruth   return Result;
602ef860a24SChandler Carruth }
603ef860a24SChandler Carruth 
604ef860a24SChandler Carruth /// CreateMalloc - Generate the IR for a call to malloc:
605ef860a24SChandler Carruth /// 1. Compute the malloc call's argument as the specified type's size,
606ef860a24SChandler Carruth ///    possibly multiplied by the array size if the array size is not
607ef860a24SChandler Carruth ///    constant 1.
608ef860a24SChandler Carruth /// 2. Call malloc with that argument.
609ef860a24SChandler Carruth /// 3. Bitcast the result of the malloc call to the specified type.
610ef860a24SChandler Carruth Instruction *CallInst::CreateMalloc(Instruction *InsertBefore,
611ef860a24SChandler Carruth                                     Type *IntPtrTy, Type *AllocTy,
612ef860a24SChandler Carruth                                     Value *AllocSize, Value *ArraySize,
613ef860a24SChandler Carruth                                     Function *MallocF,
614ef860a24SChandler Carruth                                     const Twine &Name) {
615c620761cSCraig Topper   return createMalloc(InsertBefore, nullptr, IntPtrTy, AllocTy, AllocSize,
616fadc6db0SDavid Majnemer                       ArraySize, None, MallocF, Name);
617ef860a24SChandler Carruth }
618fadc6db0SDavid Majnemer Instruction *CallInst::CreateMalloc(Instruction *InsertBefore,
619fadc6db0SDavid Majnemer                                     Type *IntPtrTy, Type *AllocTy,
620fadc6db0SDavid Majnemer                                     Value *AllocSize, Value *ArraySize,
621fadc6db0SDavid Majnemer                                     ArrayRef<OperandBundleDef> OpB,
622fadc6db0SDavid Majnemer                                     Function *MallocF,
623fadc6db0SDavid Majnemer                                     const Twine &Name) {
624fadc6db0SDavid Majnemer   return createMalloc(InsertBefore, nullptr, IntPtrTy, AllocTy, AllocSize,
625fadc6db0SDavid Majnemer                       ArraySize, OpB, MallocF, Name);
626fadc6db0SDavid Majnemer }
627fadc6db0SDavid Majnemer 
628ef860a24SChandler Carruth /// CreateMalloc - Generate the IR for a call to malloc:
629ef860a24SChandler Carruth /// 1. Compute the malloc call's argument as the specified type's size,
630ef860a24SChandler Carruth ///    possibly multiplied by the array size if the array size is not
631ef860a24SChandler Carruth ///    constant 1.
632ef860a24SChandler Carruth /// 2. Call malloc with that argument.
633ef860a24SChandler Carruth /// 3. Bitcast the result of the malloc call to the specified type.
634ef860a24SChandler Carruth /// Note: This function does not add the bitcast to the basic block, that is the
635ef860a24SChandler Carruth /// responsibility of the caller.
636ef860a24SChandler Carruth Instruction *CallInst::CreateMalloc(BasicBlock *InsertAtEnd,
637ef860a24SChandler Carruth                                     Type *IntPtrTy, Type *AllocTy,
638ef860a24SChandler Carruth                                     Value *AllocSize, Value *ArraySize,
639ef860a24SChandler Carruth                                     Function *MallocF, const Twine &Name) {
640c620761cSCraig Topper   return createMalloc(nullptr, InsertAtEnd, IntPtrTy, AllocTy, AllocSize,
641fadc6db0SDavid Majnemer                       ArraySize, None, MallocF, Name);
642fadc6db0SDavid Majnemer }
643fadc6db0SDavid Majnemer Instruction *CallInst::CreateMalloc(BasicBlock *InsertAtEnd,
644fadc6db0SDavid Majnemer                                     Type *IntPtrTy, Type *AllocTy,
645fadc6db0SDavid Majnemer                                     Value *AllocSize, Value *ArraySize,
646fadc6db0SDavid Majnemer                                     ArrayRef<OperandBundleDef> OpB,
647fadc6db0SDavid Majnemer                                     Function *MallocF, const Twine &Name) {
648fadc6db0SDavid Majnemer   return createMalloc(nullptr, InsertAtEnd, IntPtrTy, AllocTy, AllocSize,
649fadc6db0SDavid Majnemer                       ArraySize, OpB, MallocF, Name);
650ef860a24SChandler Carruth }
651ef860a24SChandler Carruth 
652fadc6db0SDavid Majnemer static Instruction *createFree(Value *Source,
653fadc6db0SDavid Majnemer                                ArrayRef<OperandBundleDef> Bundles,
654fadc6db0SDavid Majnemer                                Instruction *InsertBefore,
655ef860a24SChandler Carruth                                BasicBlock *InsertAtEnd) {
656ef860a24SChandler Carruth   assert(((!InsertBefore && InsertAtEnd) || (InsertBefore && !InsertAtEnd)) &&
657ef860a24SChandler Carruth          "createFree needs either InsertBefore or InsertAtEnd");
658ef860a24SChandler Carruth   assert(Source->getType()->isPointerTy() &&
659ef860a24SChandler Carruth          "Can not free something of nonpointer type!");
660ef860a24SChandler Carruth 
661ef860a24SChandler Carruth   BasicBlock *BB = InsertBefore ? InsertBefore->getParent() : InsertAtEnd;
662ef860a24SChandler Carruth   Module *M = BB->getParent()->getParent();
663ef860a24SChandler Carruth 
664ef860a24SChandler Carruth   Type *VoidTy = Type::getVoidTy(M->getContext());
665ef860a24SChandler Carruth   Type *IntPtrTy = Type::getInt8PtrTy(M->getContext());
666ef860a24SChandler Carruth   // prototype free as "void free(void*)"
66713680223SJames Y Knight   FunctionCallee FreeFunc = M->getOrInsertFunction("free", VoidTy, IntPtrTy);
668c620761cSCraig Topper   CallInst *Result = nullptr;
669ef860a24SChandler Carruth   Value *PtrCast = Source;
670ef860a24SChandler Carruth   if (InsertBefore) {
671ef860a24SChandler Carruth     if (Source->getType() != IntPtrTy)
672ef860a24SChandler Carruth       PtrCast = new BitCastInst(Source, IntPtrTy, "", InsertBefore);
673fadc6db0SDavid Majnemer     Result = CallInst::Create(FreeFunc, PtrCast, Bundles, "", InsertBefore);
674ef860a24SChandler Carruth   } else {
675ef860a24SChandler Carruth     if (Source->getType() != IntPtrTy)
676ef860a24SChandler Carruth       PtrCast = new BitCastInst(Source, IntPtrTy, "", InsertAtEnd);
677fadc6db0SDavid Majnemer     Result = CallInst::Create(FreeFunc, PtrCast, Bundles, "");
678ef860a24SChandler Carruth   }
679ef860a24SChandler Carruth   Result->setTailCall();
68013680223SJames Y Knight   if (Function *F = dyn_cast<Function>(FreeFunc.getCallee()))
681ef860a24SChandler Carruth     Result->setCallingConv(F->getCallingConv());
682ef860a24SChandler Carruth 
683ef860a24SChandler Carruth   return Result;
684ef860a24SChandler Carruth }
685ef860a24SChandler Carruth 
686ef860a24SChandler Carruth /// CreateFree - Generate the IR for a call to the builtin free function.
687ef860a24SChandler Carruth Instruction *CallInst::CreateFree(Value *Source, Instruction *InsertBefore) {
688fadc6db0SDavid Majnemer   return createFree(Source, None, InsertBefore, nullptr);
689fadc6db0SDavid Majnemer }
690fadc6db0SDavid Majnemer Instruction *CallInst::CreateFree(Value *Source,
691fadc6db0SDavid Majnemer                                   ArrayRef<OperandBundleDef> Bundles,
692fadc6db0SDavid Majnemer                                   Instruction *InsertBefore) {
693fadc6db0SDavid Majnemer   return createFree(Source, Bundles, InsertBefore, nullptr);
694ef860a24SChandler Carruth }
695ef860a24SChandler Carruth 
696ef860a24SChandler Carruth /// CreateFree - Generate the IR for a call to the builtin free function.
697ef860a24SChandler Carruth /// Note: This function does not add the call to the basic block, that is the
698ef860a24SChandler Carruth /// responsibility of the caller.
699ef860a24SChandler Carruth Instruction *CallInst::CreateFree(Value *Source, BasicBlock *InsertAtEnd) {
700fadc6db0SDavid Majnemer   Instruction *FreeCall = createFree(Source, None, nullptr, InsertAtEnd);
701fadc6db0SDavid Majnemer   assert(FreeCall && "CreateFree did not create a CallInst");
702fadc6db0SDavid Majnemer   return FreeCall;
703fadc6db0SDavid Majnemer }
704fadc6db0SDavid Majnemer Instruction *CallInst::CreateFree(Value *Source,
705fadc6db0SDavid Majnemer                                   ArrayRef<OperandBundleDef> Bundles,
706fadc6db0SDavid Majnemer                                   BasicBlock *InsertAtEnd) {
707fadc6db0SDavid Majnemer   Instruction *FreeCall = createFree(Source, Bundles, nullptr, InsertAtEnd);
708ef860a24SChandler Carruth   assert(FreeCall && "CreateFree did not create a CallInst");
709ef860a24SChandler Carruth   return FreeCall;
710ef860a24SChandler Carruth }
711ef860a24SChandler Carruth 
712ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
713ef860a24SChandler Carruth //                        InvokeInst Implementation
714ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
715ef860a24SChandler Carruth 
7163e80709eSDavid Blaikie void InvokeInst::init(FunctionType *FTy, Value *Fn, BasicBlock *IfNormal,
7173e80709eSDavid Blaikie                       BasicBlock *IfException, ArrayRef<Value *> Args,
7189303c246SSanjoy Das                       ArrayRef<OperandBundleDef> Bundles,
7193e80709eSDavid Blaikie                       const Twine &NameStr) {
7203e80709eSDavid Blaikie   this->FTy = FTy;
721348de69aSDavid Blaikie 
722e429c794SChandler Carruth   assert((int)getNumOperands() ==
723e429c794SChandler Carruth              ComputeNumOperands(Args.size(), CountBundleInputs(Bundles)) &&
7249303c246SSanjoy Das          "NumOperands not set up?");
725e429c794SChandler Carruth   setNormalDest(IfNormal);
726e429c794SChandler Carruth   setUnwindDest(IfException);
727e429c794SChandler Carruth   setCalledOperand(Fn);
728ef860a24SChandler Carruth 
729ef860a24SChandler Carruth #ifndef NDEBUG
730ef860a24SChandler Carruth   assert(((Args.size() == FTy->getNumParams()) ||
731ef860a24SChandler Carruth           (FTy->isVarArg() && Args.size() > FTy->getNumParams())) &&
732ef860a24SChandler Carruth          "Invoking a function with bad signature");
733ef860a24SChandler Carruth 
734ef860a24SChandler Carruth   for (unsigned i = 0, e = Args.size(); i != e; i++)
735ef860a24SChandler Carruth     assert((i >= FTy->getNumParams() ||
736ef860a24SChandler Carruth             FTy->getParamType(i) == Args[i]->getType()) &&
737ef860a24SChandler Carruth            "Invoking a function with a bad signature!");
738ef860a24SChandler Carruth #endif
739ef860a24SChandler Carruth 
74075709329SFangrui Song   llvm::copy(Args, op_begin());
7419303c246SSanjoy Das 
7429303c246SSanjoy Das   auto It = populateBundleOperandInfos(Bundles, Args.size());
7439303c246SSanjoy Das   (void)It;
7449303c246SSanjoy Das   assert(It + 3 == op_end() && "Should add up!");
7459303c246SSanjoy Das 
746ef860a24SChandler Carruth   setName(NameStr);
747ef860a24SChandler Carruth }
748ef860a24SChandler Carruth 
749ef860a24SChandler Carruth InvokeInst::InvokeInst(const InvokeInst &II)
750e429c794SChandler Carruth     : CallBase(II.Attrs, II.FTy, II.getType(), Instruction::Invoke,
751e429c794SChandler Carruth                OperandTraits<CallBase>::op_end(this) - II.getNumOperands(),
7521fb81bcbSSerge Guelton                II.getNumOperands()) {
753ef860a24SChandler Carruth   setCallingConv(II.getCallingConv());
754ef860a24SChandler Carruth   std::copy(II.op_begin(), II.op_end(), op_begin());
7559303c246SSanjoy Das   std::copy(II.bundle_op_info_begin(), II.bundle_op_info_end(),
7569303c246SSanjoy Das             bundle_op_info_begin());
757ef860a24SChandler Carruth   SubclassOptionalData = II.SubclassOptionalData;
758ef860a24SChandler Carruth }
759ef860a24SChandler Carruth 
7602d16145aSSanjoy Das InvokeInst *InvokeInst::Create(InvokeInst *II, ArrayRef<OperandBundleDef> OpB,
7612d16145aSSanjoy Das                                Instruction *InsertPt) {
762ccd14566SSanjoy Das   std::vector<Value *> Args(II->arg_begin(), II->arg_end());
7632d16145aSSanjoy Das 
764d9e85a08SJames Y Knight   auto *NewII = InvokeInst::Create(II->getFunctionType(), II->getCalledValue(),
765d9e85a08SJames Y Knight                                    II->getNormalDest(), II->getUnwindDest(),
766d9e85a08SJames Y Knight                                    Args, OpB, II->getName(), InsertPt);
7672d16145aSSanjoy Das   NewII->setCallingConv(II->getCallingConv());
7682d16145aSSanjoy Das   NewII->SubclassOptionalData = II->SubclassOptionalData;
769b8dced5dSSanjoy Das   NewII->setAttributes(II->getAttributes());
770bba70e44SJoseph Tremoulet   NewII->setDebugLoc(II->getDebugLoc());
7712d16145aSSanjoy Das   return NewII;
7722d16145aSSanjoy Das }
7732d16145aSSanjoy Das 
77431ea6d15SSanjoy Das 
775ef860a24SChandler Carruth LandingPadInst *InvokeInst::getLandingPadInst() const {
776ef860a24SChandler Carruth   return cast<LandingPadInst>(getUnwindDest()->getFirstNonPHI());
777ef860a24SChandler Carruth }
778ef860a24SChandler Carruth 
779ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
780784929d0SCraig Topper //                        CallBrInst Implementation
781784929d0SCraig Topper //===----------------------------------------------------------------------===//
782784929d0SCraig Topper 
783784929d0SCraig Topper void CallBrInst::init(FunctionType *FTy, Value *Fn, BasicBlock *Fallthrough,
784784929d0SCraig Topper                       ArrayRef<BasicBlock *> IndirectDests,
785784929d0SCraig Topper                       ArrayRef<Value *> Args,
786784929d0SCraig Topper                       ArrayRef<OperandBundleDef> Bundles,
787784929d0SCraig Topper                       const Twine &NameStr) {
788784929d0SCraig Topper   this->FTy = FTy;
789784929d0SCraig Topper 
790784929d0SCraig Topper   assert((int)getNumOperands() ==
791784929d0SCraig Topper              ComputeNumOperands(Args.size(), IndirectDests.size(),
792784929d0SCraig Topper                                 CountBundleInputs(Bundles)) &&
793784929d0SCraig Topper          "NumOperands not set up?");
794784929d0SCraig Topper   NumIndirectDests = IndirectDests.size();
795784929d0SCraig Topper   setDefaultDest(Fallthrough);
796784929d0SCraig Topper   for (unsigned i = 0; i != NumIndirectDests; ++i)
797784929d0SCraig Topper     setIndirectDest(i, IndirectDests[i]);
798784929d0SCraig Topper   setCalledOperand(Fn);
799784929d0SCraig Topper 
800784929d0SCraig Topper #ifndef NDEBUG
801784929d0SCraig Topper   assert(((Args.size() == FTy->getNumParams()) ||
802784929d0SCraig Topper           (FTy->isVarArg() && Args.size() > FTy->getNumParams())) &&
803784929d0SCraig Topper          "Calling a function with bad signature");
804784929d0SCraig Topper 
805784929d0SCraig Topper   for (unsigned i = 0, e = Args.size(); i != e; i++)
806784929d0SCraig Topper     assert((i >= FTy->getNumParams() ||
807784929d0SCraig Topper             FTy->getParamType(i) == Args[i]->getType()) &&
808784929d0SCraig Topper            "Calling a function with a bad signature!");
809784929d0SCraig Topper #endif
810784929d0SCraig Topper 
811784929d0SCraig Topper   std::copy(Args.begin(), Args.end(), op_begin());
812784929d0SCraig Topper 
813784929d0SCraig Topper   auto It = populateBundleOperandInfos(Bundles, Args.size());
814784929d0SCraig Topper   (void)It;
815784929d0SCraig Topper   assert(It + 2 + IndirectDests.size() == op_end() && "Should add up!");
816784929d0SCraig Topper 
817784929d0SCraig Topper   setName(NameStr);
818784929d0SCraig Topper }
819784929d0SCraig Topper 
8207a7bba28SNick Desaulniers void CallBrInst::updateArgBlockAddresses(unsigned i, BasicBlock *B) {
8217a7bba28SNick Desaulniers   assert(getNumIndirectDests() > i && "IndirectDest # out of range for callbr");
8227a7bba28SNick Desaulniers   if (BasicBlock *OldBB = getIndirectDest(i)) {
8237a7bba28SNick Desaulniers     BlockAddress *Old = BlockAddress::get(OldBB);
8247a7bba28SNick Desaulniers     BlockAddress *New = BlockAddress::get(B);
8257a7bba28SNick Desaulniers     for (unsigned ArgNo = 0, e = getNumArgOperands(); ArgNo != e; ++ArgNo)
8267a7bba28SNick Desaulniers       if (dyn_cast<BlockAddress>(getArgOperand(ArgNo)) == Old)
8277a7bba28SNick Desaulniers         setArgOperand(ArgNo, New);
8287a7bba28SNick Desaulniers   }
8297a7bba28SNick Desaulniers }
8307a7bba28SNick Desaulniers 
831784929d0SCraig Topper CallBrInst::CallBrInst(const CallBrInst &CBI)
832784929d0SCraig Topper     : CallBase(CBI.Attrs, CBI.FTy, CBI.getType(), Instruction::CallBr,
833784929d0SCraig Topper                OperandTraits<CallBase>::op_end(this) - CBI.getNumOperands(),
834784929d0SCraig Topper                CBI.getNumOperands()) {
835784929d0SCraig Topper   setCallingConv(CBI.getCallingConv());
836784929d0SCraig Topper   std::copy(CBI.op_begin(), CBI.op_end(), op_begin());
837784929d0SCraig Topper   std::copy(CBI.bundle_op_info_begin(), CBI.bundle_op_info_end(),
838784929d0SCraig Topper             bundle_op_info_begin());
839784929d0SCraig Topper   SubclassOptionalData = CBI.SubclassOptionalData;
840784929d0SCraig Topper   NumIndirectDests = CBI.NumIndirectDests;
841784929d0SCraig Topper }
842784929d0SCraig Topper 
843784929d0SCraig Topper CallBrInst *CallBrInst::Create(CallBrInst *CBI, ArrayRef<OperandBundleDef> OpB,
844784929d0SCraig Topper                                Instruction *InsertPt) {
845784929d0SCraig Topper   std::vector<Value *> Args(CBI->arg_begin(), CBI->arg_end());
846784929d0SCraig Topper 
847784929d0SCraig Topper   auto *NewCBI = CallBrInst::Create(CBI->getFunctionType(),
848784929d0SCraig Topper                                     CBI->getCalledValue(),
849784929d0SCraig Topper                                     CBI->getDefaultDest(),
850784929d0SCraig Topper                                     CBI->getIndirectDests(),
851784929d0SCraig Topper                                     Args, OpB, CBI->getName(), InsertPt);
852784929d0SCraig Topper   NewCBI->setCallingConv(CBI->getCallingConv());
853784929d0SCraig Topper   NewCBI->SubclassOptionalData = CBI->SubclassOptionalData;
854784929d0SCraig Topper   NewCBI->setAttributes(CBI->getAttributes());
855784929d0SCraig Topper   NewCBI->setDebugLoc(CBI->getDebugLoc());
856784929d0SCraig Topper   NewCBI->NumIndirectDests = CBI->NumIndirectDests;
857784929d0SCraig Topper   return NewCBI;
858784929d0SCraig Topper }
859784929d0SCraig Topper 
860784929d0SCraig Topper //===----------------------------------------------------------------------===//
861ef860a24SChandler Carruth //                        ReturnInst Implementation
862ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
863ef860a24SChandler Carruth 
864ef860a24SChandler Carruth ReturnInst::ReturnInst(const ReturnInst &RI)
865509e20e0SChandler Carruth     : Instruction(Type::getVoidTy(RI.getContext()), Instruction::Ret,
866509e20e0SChandler Carruth                   OperandTraits<ReturnInst>::op_end(this) - RI.getNumOperands(),
867ef860a24SChandler Carruth                   RI.getNumOperands()) {
868ef860a24SChandler Carruth   if (RI.getNumOperands())
869ef860a24SChandler Carruth     Op<0>() = RI.Op<0>();
870ef860a24SChandler Carruth   SubclassOptionalData = RI.SubclassOptionalData;
871ef860a24SChandler Carruth }
872ef860a24SChandler Carruth 
873ef860a24SChandler Carruth ReturnInst::ReturnInst(LLVMContext &C, Value *retVal, Instruction *InsertBefore)
874509e20e0SChandler Carruth     : Instruction(Type::getVoidTy(C), Instruction::Ret,
875ef860a24SChandler Carruth                   OperandTraits<ReturnInst>::op_end(this) - !!retVal, !!retVal,
876ef860a24SChandler Carruth                   InsertBefore) {
877ef860a24SChandler Carruth   if (retVal)
878ef860a24SChandler Carruth     Op<0>() = retVal;
879ef860a24SChandler Carruth }
880d761e2c2SEugene Zelenko 
881ef860a24SChandler Carruth ReturnInst::ReturnInst(LLVMContext &C, Value *retVal, BasicBlock *InsertAtEnd)
882509e20e0SChandler Carruth     : Instruction(Type::getVoidTy(C), Instruction::Ret,
883ef860a24SChandler Carruth                   OperandTraits<ReturnInst>::op_end(this) - !!retVal, !!retVal,
884ef860a24SChandler Carruth                   InsertAtEnd) {
885ef860a24SChandler Carruth   if (retVal)
886ef860a24SChandler Carruth     Op<0>() = retVal;
887ef860a24SChandler Carruth }
888d761e2c2SEugene Zelenko 
889ef860a24SChandler Carruth ReturnInst::ReturnInst(LLVMContext &Context, BasicBlock *InsertAtEnd)
890509e20e0SChandler Carruth     : Instruction(Type::getVoidTy(Context), Instruction::Ret,
891509e20e0SChandler Carruth                   OperandTraits<ReturnInst>::op_end(this), 0, InsertAtEnd) {}
892ef860a24SChandler Carruth 
893ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
894ef860a24SChandler Carruth //                        ResumeInst Implementation
895ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
896ef860a24SChandler Carruth 
897ef860a24SChandler Carruth ResumeInst::ResumeInst(const ResumeInst &RI)
898509e20e0SChandler Carruth     : Instruction(Type::getVoidTy(RI.getContext()), Instruction::Resume,
899ef860a24SChandler Carruth                   OperandTraits<ResumeInst>::op_begin(this), 1) {
900ef860a24SChandler Carruth   Op<0>() = RI.Op<0>();
901ef860a24SChandler Carruth }
902ef860a24SChandler Carruth 
903ef860a24SChandler Carruth ResumeInst::ResumeInst(Value *Exn, Instruction *InsertBefore)
904509e20e0SChandler Carruth     : Instruction(Type::getVoidTy(Exn->getContext()), Instruction::Resume,
905ef860a24SChandler Carruth                   OperandTraits<ResumeInst>::op_begin(this), 1, InsertBefore) {
906ef860a24SChandler Carruth   Op<0>() = Exn;
907ef860a24SChandler Carruth }
908ef860a24SChandler Carruth 
909ef860a24SChandler Carruth ResumeInst::ResumeInst(Value *Exn, BasicBlock *InsertAtEnd)
910509e20e0SChandler Carruth     : Instruction(Type::getVoidTy(Exn->getContext()), Instruction::Resume,
911ef860a24SChandler Carruth                   OperandTraits<ResumeInst>::op_begin(this), 1, InsertAtEnd) {
912ef860a24SChandler Carruth   Op<0>() = Exn;
913ef860a24SChandler Carruth }
914ef860a24SChandler Carruth 
915ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
916654e130bSDavid Majnemer //                        CleanupReturnInst Implementation
917654e130bSDavid Majnemer //===----------------------------------------------------------------------===//
918654e130bSDavid Majnemer 
919654e130bSDavid Majnemer CleanupReturnInst::CleanupReturnInst(const CleanupReturnInst &CRI)
920509e20e0SChandler Carruth     : Instruction(CRI.getType(), Instruction::CleanupRet,
921654e130bSDavid Majnemer                   OperandTraits<CleanupReturnInst>::op_end(this) -
922654e130bSDavid Majnemer                       CRI.getNumOperands(),
923654e130bSDavid Majnemer                   CRI.getNumOperands()) {
924eb518bd5SDavid Majnemer   setInstructionSubclassData(CRI.getSubclassDataFromInstruction());
9258a1c45d6SDavid Majnemer   Op<0>() = CRI.Op<0>();
9268220bcc5SJoseph Tremoulet   if (CRI.hasUnwindDest())
9278a1c45d6SDavid Majnemer     Op<1>() = CRI.Op<1>();
928654e130bSDavid Majnemer }
929654e130bSDavid Majnemer 
9308a1c45d6SDavid Majnemer void CleanupReturnInst::init(Value *CleanupPad, BasicBlock *UnwindBB) {
931654e130bSDavid Majnemer   if (UnwindBB)
932654e130bSDavid Majnemer     setInstructionSubclassData(getSubclassDataFromInstruction() | 1);
933654e130bSDavid Majnemer 
9348a1c45d6SDavid Majnemer   Op<0>() = CleanupPad;
935654e130bSDavid Majnemer   if (UnwindBB)
9368a1c45d6SDavid Majnemer     Op<1>() = UnwindBB;
937654e130bSDavid Majnemer }
938654e130bSDavid Majnemer 
9398a1c45d6SDavid Majnemer CleanupReturnInst::CleanupReturnInst(Value *CleanupPad, BasicBlock *UnwindBB,
9408a1c45d6SDavid Majnemer                                      unsigned Values, Instruction *InsertBefore)
941509e20e0SChandler Carruth     : Instruction(Type::getVoidTy(CleanupPad->getContext()),
9428220bcc5SJoseph Tremoulet                   Instruction::CleanupRet,
943654e130bSDavid Majnemer                   OperandTraits<CleanupReturnInst>::op_end(this) - Values,
944654e130bSDavid Majnemer                   Values, InsertBefore) {
9458220bcc5SJoseph Tremoulet   init(CleanupPad, UnwindBB);
946654e130bSDavid Majnemer }
947654e130bSDavid Majnemer 
9488a1c45d6SDavid Majnemer CleanupReturnInst::CleanupReturnInst(Value *CleanupPad, BasicBlock *UnwindBB,
9498a1c45d6SDavid Majnemer                                      unsigned Values, BasicBlock *InsertAtEnd)
950509e20e0SChandler Carruth     : Instruction(Type::getVoidTy(CleanupPad->getContext()),
9518220bcc5SJoseph Tremoulet                   Instruction::CleanupRet,
952654e130bSDavid Majnemer                   OperandTraits<CleanupReturnInst>::op_end(this) - Values,
953654e130bSDavid Majnemer                   Values, InsertAtEnd) {
9548220bcc5SJoseph Tremoulet   init(CleanupPad, UnwindBB);
955654e130bSDavid Majnemer }
956654e130bSDavid Majnemer 
957654e130bSDavid Majnemer //===----------------------------------------------------------------------===//
958654e130bSDavid Majnemer //                        CatchReturnInst Implementation
959654e130bSDavid Majnemer //===----------------------------------------------------------------------===//
9608a1c45d6SDavid Majnemer void CatchReturnInst::init(Value *CatchPad, BasicBlock *BB) {
9618220bcc5SJoseph Tremoulet   Op<0>() = CatchPad;
9628220bcc5SJoseph Tremoulet   Op<1>() = BB;
9630bc0eef7SDavid Majnemer }
964654e130bSDavid Majnemer 
965654e130bSDavid Majnemer CatchReturnInst::CatchReturnInst(const CatchReturnInst &CRI)
966509e20e0SChandler Carruth     : Instruction(Type::getVoidTy(CRI.getContext()), Instruction::CatchRet,
9678220bcc5SJoseph Tremoulet                   OperandTraits<CatchReturnInst>::op_begin(this), 2) {
9688220bcc5SJoseph Tremoulet   Op<0>() = CRI.Op<0>();
9698220bcc5SJoseph Tremoulet   Op<1>() = CRI.Op<1>();
970654e130bSDavid Majnemer }
971654e130bSDavid Majnemer 
9728a1c45d6SDavid Majnemer CatchReturnInst::CatchReturnInst(Value *CatchPad, BasicBlock *BB,
9730bc0eef7SDavid Majnemer                                  Instruction *InsertBefore)
974509e20e0SChandler Carruth     : Instruction(Type::getVoidTy(BB->getContext()), Instruction::CatchRet,
9758220bcc5SJoseph Tremoulet                   OperandTraits<CatchReturnInst>::op_begin(this), 2,
9768220bcc5SJoseph Tremoulet                   InsertBefore) {
9778220bcc5SJoseph Tremoulet   init(CatchPad, BB);
978654e130bSDavid Majnemer }
979654e130bSDavid Majnemer 
9808a1c45d6SDavid Majnemer CatchReturnInst::CatchReturnInst(Value *CatchPad, BasicBlock *BB,
9810bc0eef7SDavid Majnemer                                  BasicBlock *InsertAtEnd)
982509e20e0SChandler Carruth     : Instruction(Type::getVoidTy(BB->getContext()), Instruction::CatchRet,
9838220bcc5SJoseph Tremoulet                   OperandTraits<CatchReturnInst>::op_begin(this), 2,
9848220bcc5SJoseph Tremoulet                   InsertAtEnd) {
9858220bcc5SJoseph Tremoulet   init(CatchPad, BB);
986654e130bSDavid Majnemer }
987654e130bSDavid Majnemer 
988654e130bSDavid Majnemer //===----------------------------------------------------------------------===//
9898a1c45d6SDavid Majnemer //                       CatchSwitchInst Implementation
990654e130bSDavid Majnemer //===----------------------------------------------------------------------===//
9918a1c45d6SDavid Majnemer 
9928a1c45d6SDavid Majnemer CatchSwitchInst::CatchSwitchInst(Value *ParentPad, BasicBlock *UnwindDest,
9938a1c45d6SDavid Majnemer                                  unsigned NumReservedValues,
9948a1c45d6SDavid Majnemer                                  const Twine &NameStr,
9958a1c45d6SDavid Majnemer                                  Instruction *InsertBefore)
996509e20e0SChandler Carruth     : Instruction(ParentPad->getType(), Instruction::CatchSwitch, nullptr, 0,
9978a1c45d6SDavid Majnemer                   InsertBefore) {
9988a1c45d6SDavid Majnemer   if (UnwindDest)
9998a1c45d6SDavid Majnemer     ++NumReservedValues;
10008a1c45d6SDavid Majnemer   init(ParentPad, UnwindDest, NumReservedValues + 1);
1001654e130bSDavid Majnemer   setName(NameStr);
1002654e130bSDavid Majnemer }
1003654e130bSDavid Majnemer 
10048a1c45d6SDavid Majnemer CatchSwitchInst::CatchSwitchInst(Value *ParentPad, BasicBlock *UnwindDest,
10058a1c45d6SDavid Majnemer                                  unsigned NumReservedValues,
10068220bcc5SJoseph Tremoulet                                  const Twine &NameStr, BasicBlock *InsertAtEnd)
1007509e20e0SChandler Carruth     : Instruction(ParentPad->getType(), Instruction::CatchSwitch, nullptr, 0,
10085c73c941SDavid Majnemer                   InsertAtEnd) {
10098a1c45d6SDavid Majnemer   if (UnwindDest)
10108a1c45d6SDavid Majnemer     ++NumReservedValues;
10118a1c45d6SDavid Majnemer   init(ParentPad, UnwindDest, NumReservedValues + 1);
10128a1c45d6SDavid Majnemer   setName(NameStr);
1013654e130bSDavid Majnemer }
1014654e130bSDavid Majnemer 
10158a1c45d6SDavid Majnemer CatchSwitchInst::CatchSwitchInst(const CatchSwitchInst &CSI)
1016509e20e0SChandler Carruth     : Instruction(CSI.getType(), Instruction::CatchSwitch, nullptr,
10178a1c45d6SDavid Majnemer                   CSI.getNumOperands()) {
10188a1c45d6SDavid Majnemer   init(CSI.getParentPad(), CSI.getUnwindDest(), CSI.getNumOperands());
10198a1c45d6SDavid Majnemer   setNumHungOffUseOperands(ReservedSpace);
10208a1c45d6SDavid Majnemer   Use *OL = getOperandList();
10218a1c45d6SDavid Majnemer   const Use *InOL = CSI.getOperandList();
10228a1c45d6SDavid Majnemer   for (unsigned I = 1, E = ReservedSpace; I != E; ++I)
10238a1c45d6SDavid Majnemer     OL[I] = InOL[I];
1024654e130bSDavid Majnemer }
10258a1c45d6SDavid Majnemer 
10268a1c45d6SDavid Majnemer void CatchSwitchInst::init(Value *ParentPad, BasicBlock *UnwindDest,
10278a1c45d6SDavid Majnemer                            unsigned NumReservedValues) {
10288a1c45d6SDavid Majnemer   assert(ParentPad && NumReservedValues);
10298a1c45d6SDavid Majnemer 
10308a1c45d6SDavid Majnemer   ReservedSpace = NumReservedValues;
10318a1c45d6SDavid Majnemer   setNumHungOffUseOperands(UnwindDest ? 2 : 1);
10328a1c45d6SDavid Majnemer   allocHungoffUses(ReservedSpace);
10338a1c45d6SDavid Majnemer 
10348a1c45d6SDavid Majnemer   Op<0>() = ParentPad;
10358a1c45d6SDavid Majnemer   if (UnwindDest) {
10368a1c45d6SDavid Majnemer     setInstructionSubclassData(getSubclassDataFromInstruction() | 1);
10378a1c45d6SDavid Majnemer     setUnwindDest(UnwindDest);
10388a1c45d6SDavid Majnemer   }
10398a1c45d6SDavid Majnemer }
10408a1c45d6SDavid Majnemer 
10418a1c45d6SDavid Majnemer /// growOperands - grow operands - This grows the operand list in response to a
10428a1c45d6SDavid Majnemer /// push_back style of operation. This grows the number of ops by 2 times.
10438a1c45d6SDavid Majnemer void CatchSwitchInst::growOperands(unsigned Size) {
10448a1c45d6SDavid Majnemer   unsigned NumOperands = getNumOperands();
10458a1c45d6SDavid Majnemer   assert(NumOperands >= 1);
10468a1c45d6SDavid Majnemer   if (ReservedSpace >= NumOperands + Size)
10478a1c45d6SDavid Majnemer     return;
10488a1c45d6SDavid Majnemer   ReservedSpace = (NumOperands + Size / 2) * 2;
10498a1c45d6SDavid Majnemer   growHungoffUses(ReservedSpace);
10508a1c45d6SDavid Majnemer }
10518a1c45d6SDavid Majnemer 
10528a1c45d6SDavid Majnemer void CatchSwitchInst::addHandler(BasicBlock *Handler) {
10538a1c45d6SDavid Majnemer   unsigned OpNo = getNumOperands();
10548a1c45d6SDavid Majnemer   growOperands(1);
10558a1c45d6SDavid Majnemer   assert(OpNo < ReservedSpace && "Growing didn't work!");
10568a1c45d6SDavid Majnemer   setNumHungOffUseOperands(getNumOperands() + 1);
10578a1c45d6SDavid Majnemer   getOperandList()[OpNo] = Handler;
10588a1c45d6SDavid Majnemer }
10598a1c45d6SDavid Majnemer 
10600d808888SJoseph Tremoulet void CatchSwitchInst::removeHandler(handler_iterator HI) {
10610d808888SJoseph Tremoulet   // Move all subsequent handlers up one.
10620d808888SJoseph Tremoulet   Use *EndDst = op_end() - 1;
10630d808888SJoseph Tremoulet   for (Use *CurDst = HI.getCurrent(); CurDst != EndDst; ++CurDst)
10640d808888SJoseph Tremoulet     *CurDst = *(CurDst + 1);
10650d808888SJoseph Tremoulet   // Null out the last handler use.
10660d808888SJoseph Tremoulet   *EndDst = nullptr;
10670d808888SJoseph Tremoulet 
10680d808888SJoseph Tremoulet   setNumHungOffUseOperands(getNumOperands() - 1);
10690d808888SJoseph Tremoulet }
10700d808888SJoseph Tremoulet 
10718a1c45d6SDavid Majnemer //===----------------------------------------------------------------------===//
10728a1c45d6SDavid Majnemer //                        FuncletPadInst Implementation
10738a1c45d6SDavid Majnemer //===----------------------------------------------------------------------===//
10748a1c45d6SDavid Majnemer void FuncletPadInst::init(Value *ParentPad, ArrayRef<Value *> Args,
10758a1c45d6SDavid Majnemer                           const Twine &NameStr) {
10768a1c45d6SDavid Majnemer   assert(getNumOperands() == 1 + Args.size() && "NumOperands not set up?");
107775709329SFangrui Song   llvm::copy(Args, op_begin());
10788a1c45d6SDavid Majnemer   setParentPad(ParentPad);
10798a1c45d6SDavid Majnemer   setName(NameStr);
10808a1c45d6SDavid Majnemer }
10818a1c45d6SDavid Majnemer 
10828a1c45d6SDavid Majnemer FuncletPadInst::FuncletPadInst(const FuncletPadInst &FPI)
10838a1c45d6SDavid Majnemer     : Instruction(FPI.getType(), FPI.getOpcode(),
10848a1c45d6SDavid Majnemer                   OperandTraits<FuncletPadInst>::op_end(this) -
10858a1c45d6SDavid Majnemer                       FPI.getNumOperands(),
10868a1c45d6SDavid Majnemer                   FPI.getNumOperands()) {
10878a1c45d6SDavid Majnemer   std::copy(FPI.op_begin(), FPI.op_end(), op_begin());
10888a1c45d6SDavid Majnemer   setParentPad(FPI.getParentPad());
10898a1c45d6SDavid Majnemer }
10908a1c45d6SDavid Majnemer 
10918a1c45d6SDavid Majnemer FuncletPadInst::FuncletPadInst(Instruction::FuncletPadOps Op, Value *ParentPad,
10928a1c45d6SDavid Majnemer                                ArrayRef<Value *> Args, unsigned Values,
10938a1c45d6SDavid Majnemer                                const Twine &NameStr, Instruction *InsertBefore)
10948a1c45d6SDavid Majnemer     : Instruction(ParentPad->getType(), Op,
10958a1c45d6SDavid Majnemer                   OperandTraits<FuncletPadInst>::op_end(this) - Values, Values,
10968a1c45d6SDavid Majnemer                   InsertBefore) {
10978a1c45d6SDavid Majnemer   init(ParentPad, Args, NameStr);
10988a1c45d6SDavid Majnemer }
10998a1c45d6SDavid Majnemer 
11008a1c45d6SDavid Majnemer FuncletPadInst::FuncletPadInst(Instruction::FuncletPadOps Op, Value *ParentPad,
11018a1c45d6SDavid Majnemer                                ArrayRef<Value *> Args, unsigned Values,
11028a1c45d6SDavid Majnemer                                const Twine &NameStr, BasicBlock *InsertAtEnd)
11038a1c45d6SDavid Majnemer     : Instruction(ParentPad->getType(), Op,
11048a1c45d6SDavid Majnemer                   OperandTraits<FuncletPadInst>::op_end(this) - Values, Values,
11058a1c45d6SDavid Majnemer                   InsertAtEnd) {
11068a1c45d6SDavid Majnemer   init(ParentPad, Args, NameStr);
1107654e130bSDavid Majnemer }
1108654e130bSDavid Majnemer 
1109654e130bSDavid Majnemer //===----------------------------------------------------------------------===//
1110ef860a24SChandler Carruth //                      UnreachableInst Implementation
1111ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
1112ef860a24SChandler Carruth 
1113ef860a24SChandler Carruth UnreachableInst::UnreachableInst(LLVMContext &Context,
1114ef860a24SChandler Carruth                                  Instruction *InsertBefore)
1115509e20e0SChandler Carruth     : Instruction(Type::getVoidTy(Context), Instruction::Unreachable, nullptr,
1116509e20e0SChandler Carruth                   0, InsertBefore) {}
1117ef860a24SChandler Carruth UnreachableInst::UnreachableInst(LLVMContext &Context, BasicBlock *InsertAtEnd)
1118509e20e0SChandler Carruth     : Instruction(Type::getVoidTy(Context), Instruction::Unreachable, nullptr,
1119509e20e0SChandler Carruth                   0, InsertAtEnd) {}
1120ef860a24SChandler Carruth 
1121ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
1122ef860a24SChandler Carruth //                        BranchInst Implementation
1123ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
1124ef860a24SChandler Carruth 
1125ef860a24SChandler Carruth void BranchInst::AssertOK() {
1126ef860a24SChandler Carruth   if (isConditional())
1127ef860a24SChandler Carruth     assert(getCondition()->getType()->isIntegerTy(1) &&
1128ef860a24SChandler Carruth            "May only branch on boolean predicates!");
1129ef860a24SChandler Carruth }
1130ef860a24SChandler Carruth 
1131ef860a24SChandler Carruth BranchInst::BranchInst(BasicBlock *IfTrue, Instruction *InsertBefore)
1132509e20e0SChandler Carruth     : Instruction(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
1133509e20e0SChandler Carruth                   OperandTraits<BranchInst>::op_end(this) - 1, 1,
1134509e20e0SChandler Carruth                   InsertBefore) {
11352617dcceSCraig Topper   assert(IfTrue && "Branch destination may not be null!");
1136ef860a24SChandler Carruth   Op<-1>() = IfTrue;
1137ef860a24SChandler Carruth }
1138d761e2c2SEugene Zelenko 
1139ef860a24SChandler Carruth BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
1140ef860a24SChandler Carruth                        Instruction *InsertBefore)
1141509e20e0SChandler Carruth     : Instruction(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
1142509e20e0SChandler Carruth                   OperandTraits<BranchInst>::op_end(this) - 3, 3,
1143509e20e0SChandler Carruth                   InsertBefore) {
1144ef860a24SChandler Carruth   Op<-1>() = IfTrue;
1145ef860a24SChandler Carruth   Op<-2>() = IfFalse;
1146ef860a24SChandler Carruth   Op<-3>() = Cond;
1147ef860a24SChandler Carruth #ifndef NDEBUG
1148ef860a24SChandler Carruth   AssertOK();
1149ef860a24SChandler Carruth #endif
1150ef860a24SChandler Carruth }
1151ef860a24SChandler Carruth 
1152ef860a24SChandler Carruth BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *InsertAtEnd)
1153509e20e0SChandler Carruth     : Instruction(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
1154509e20e0SChandler Carruth                   OperandTraits<BranchInst>::op_end(this) - 1, 1, InsertAtEnd) {
11552617dcceSCraig Topper   assert(IfTrue && "Branch destination may not be null!");
1156ef860a24SChandler Carruth   Op<-1>() = IfTrue;
1157ef860a24SChandler Carruth }
1158ef860a24SChandler Carruth 
1159ef860a24SChandler Carruth BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
1160ef860a24SChandler Carruth                        BasicBlock *InsertAtEnd)
1161509e20e0SChandler Carruth     : Instruction(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
1162509e20e0SChandler Carruth                   OperandTraits<BranchInst>::op_end(this) - 3, 3, InsertAtEnd) {
1163ef860a24SChandler Carruth   Op<-1>() = IfTrue;
1164ef860a24SChandler Carruth   Op<-2>() = IfFalse;
1165ef860a24SChandler Carruth   Op<-3>() = Cond;
1166ef860a24SChandler Carruth #ifndef NDEBUG
1167ef860a24SChandler Carruth   AssertOK();
1168ef860a24SChandler Carruth #endif
1169ef860a24SChandler Carruth }
1170ef860a24SChandler Carruth 
1171509e20e0SChandler Carruth BranchInst::BranchInst(const BranchInst &BI)
1172509e20e0SChandler Carruth     : Instruction(Type::getVoidTy(BI.getContext()), Instruction::Br,
1173ef860a24SChandler Carruth                   OperandTraits<BranchInst>::op_end(this) - BI.getNumOperands(),
1174ef860a24SChandler Carruth                   BI.getNumOperands()) {
1175ef860a24SChandler Carruth   Op<-1>() = BI.Op<-1>();
1176ef860a24SChandler Carruth   if (BI.getNumOperands() != 1) {
1177ef860a24SChandler Carruth     assert(BI.getNumOperands() == 3 && "BR can have 1 or 3 operands!");
1178ef860a24SChandler Carruth     Op<-3>() = BI.Op<-3>();
1179ef860a24SChandler Carruth     Op<-2>() = BI.Op<-2>();
1180ef860a24SChandler Carruth   }
1181ef860a24SChandler Carruth   SubclassOptionalData = BI.SubclassOptionalData;
1182ef860a24SChandler Carruth }
1183ef860a24SChandler Carruth 
1184ef860a24SChandler Carruth void BranchInst::swapSuccessors() {
1185ef860a24SChandler Carruth   assert(isConditional() &&
1186ef860a24SChandler Carruth          "Cannot swap successors of an unconditional branch");
1187ef860a24SChandler Carruth   Op<-1>().swap(Op<-2>());
1188ef860a24SChandler Carruth 
1189ef860a24SChandler Carruth   // Update profile metadata if present and it matches our structural
1190ef860a24SChandler Carruth   // expectations.
1191dc49140bSXinliang David Li   swapProfMetadata();
1192ef860a24SChandler Carruth }
1193ef860a24SChandler Carruth 
1194ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
1195ef860a24SChandler Carruth //                        AllocaInst Implementation
1196ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
1197ef860a24SChandler Carruth 
1198ef860a24SChandler Carruth static Value *getAISize(LLVMContext &Context, Value *Amt) {
1199ef860a24SChandler Carruth   if (!Amt)
1200ef860a24SChandler Carruth     Amt = ConstantInt::get(Type::getInt32Ty(Context), 1);
1201ef860a24SChandler Carruth   else {
1202ef860a24SChandler Carruth     assert(!isa<BasicBlock>(Amt) &&
1203ef860a24SChandler Carruth            "Passed basic block into allocation size parameter! Use other ctor");
1204ef860a24SChandler Carruth     assert(Amt->getType()->isIntegerTy() &&
1205ef860a24SChandler Carruth            "Allocation array size is not an integer!");
1206ef860a24SChandler Carruth   }
1207ef860a24SChandler Carruth   return Amt;
1208ef860a24SChandler Carruth }
1209ef860a24SChandler Carruth 
12103c1fc768SMatt Arsenault AllocaInst::AllocaInst(Type *Ty, unsigned AddrSpace, const Twine &Name,
1211ef860a24SChandler Carruth                        Instruction *InsertBefore)
12123c1fc768SMatt Arsenault   : AllocaInst(Ty, AddrSpace, /*ArraySize=*/nullptr, Name, InsertBefore) {}
1213ef860a24SChandler Carruth 
12143c1fc768SMatt Arsenault AllocaInst::AllocaInst(Type *Ty, unsigned AddrSpace, const Twine &Name,
1215ef860a24SChandler Carruth                        BasicBlock *InsertAtEnd)
12163c1fc768SMatt Arsenault   : AllocaInst(Ty, AddrSpace, /*ArraySize=*/nullptr, Name, InsertAtEnd) {}
1217ef860a24SChandler Carruth 
12183c1fc768SMatt Arsenault AllocaInst::AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize,
1219ef860a24SChandler Carruth                        const Twine &Name, Instruction *InsertBefore)
12203c1fc768SMatt Arsenault   : AllocaInst(Ty, AddrSpace, ArraySize, /*Align=*/0, Name, InsertBefore) {}
12213c1fc768SMatt Arsenault 
12223c1fc768SMatt Arsenault AllocaInst::AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize,
12233c1fc768SMatt Arsenault                        const Twine &Name, BasicBlock *InsertAtEnd)
12243c1fc768SMatt Arsenault   : AllocaInst(Ty, AddrSpace, ArraySize, /*Align=*/0, Name, InsertAtEnd) {}
12253c1fc768SMatt Arsenault 
12263c1fc768SMatt Arsenault AllocaInst::AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize,
12273c1fc768SMatt Arsenault                        unsigned Align, const Twine &Name,
12283c1fc768SMatt Arsenault                        Instruction *InsertBefore)
12293c1fc768SMatt Arsenault   : UnaryInstruction(PointerType::get(Ty, AddrSpace), Alloca,
1230bf0a42acSDavid Blaikie                      getAISize(Ty->getContext(), ArraySize), InsertBefore),
1231bf0a42acSDavid Blaikie     AllocatedType(Ty) {
1232ab11b918SGuillaume Chatelet   setAlignment(MaybeAlign(Align));
1233ef860a24SChandler Carruth   assert(!Ty->isVoidTy() && "Cannot allocate void!");
1234ef860a24SChandler Carruth   setName(Name);
1235ef860a24SChandler Carruth }
1236ef860a24SChandler Carruth 
12373c1fc768SMatt Arsenault AllocaInst::AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize,
12383c1fc768SMatt Arsenault                        unsigned Align, const Twine &Name,
12393c1fc768SMatt Arsenault                        BasicBlock *InsertAtEnd)
12403c1fc768SMatt Arsenault   : UnaryInstruction(PointerType::get(Ty, AddrSpace), Alloca,
1241bf0a42acSDavid Blaikie                      getAISize(Ty->getContext(), ArraySize), InsertAtEnd),
1242bf0a42acSDavid Blaikie       AllocatedType(Ty) {
1243ab11b918SGuillaume Chatelet   setAlignment(MaybeAlign(Align));
1244ef860a24SChandler Carruth   assert(!Ty->isVoidTy() && "Cannot allocate void!");
1245ef860a24SChandler Carruth   setName(Name);
1246ef860a24SChandler Carruth }
1247ef860a24SChandler Carruth 
124818f805a7SGuillaume Chatelet void AllocaInst::setAlignment(MaybeAlign Align) {
1249a06c13b1SGuillaume Chatelet   assert((!Align || *Align <= MaximumAlignment) &&
1250ef860a24SChandler Carruth          "Alignment is greater than MaximumAlignment!");
1251436c42ecSReid Kleckner   setInstructionSubclassData((getSubclassDataFromInstruction() & ~31) |
1252a06c13b1SGuillaume Chatelet                              encode(Align));
1253a06c13b1SGuillaume Chatelet   if (Align)
1254a06c13b1SGuillaume Chatelet     assert(getAlignment() == Align->value() &&
1255a06c13b1SGuillaume Chatelet            "Alignment representation error!");
1256a06c13b1SGuillaume Chatelet   else
1257a06c13b1SGuillaume Chatelet     assert(getAlignment() == 0 && "Alignment representation error!");
1258ef860a24SChandler Carruth }
1259ef860a24SChandler Carruth 
1260ef860a24SChandler Carruth bool AllocaInst::isArrayAllocation() const {
1261ef860a24SChandler Carruth   if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(0)))
1262ef860a24SChandler Carruth     return !CI->isOne();
1263ef860a24SChandler Carruth   return true;
1264ef860a24SChandler Carruth }
1265ef860a24SChandler Carruth 
1266ef860a24SChandler Carruth /// isStaticAlloca - Return true if this alloca is in the entry block of the
1267ef860a24SChandler Carruth /// function and is a constant size.  If so, the code generator will fold it
1268ef860a24SChandler Carruth /// into the prolog/epilog code, so it is basically free.
1269ef860a24SChandler Carruth bool AllocaInst::isStaticAlloca() const {
1270ef860a24SChandler Carruth   // Must be constant size.
1271ef860a24SChandler Carruth   if (!isa<ConstantInt>(getArraySize())) return false;
1272ef860a24SChandler Carruth 
1273ef860a24SChandler Carruth   // Must be in the entry block.
1274ef860a24SChandler Carruth   const BasicBlock *Parent = getParent();
1275436c42ecSReid Kleckner   return Parent == &Parent->getParent()->front() && !isUsedWithInAlloca();
1276ef860a24SChandler Carruth }
1277ef860a24SChandler Carruth 
1278ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
1279ef860a24SChandler Carruth //                           LoadInst Implementation
1280ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
1281ef860a24SChandler Carruth 
1282ef860a24SChandler Carruth void LoadInst::AssertOK() {
1283ef860a24SChandler Carruth   assert(getOperand(0)->getType()->isPointerTy() &&
1284ef860a24SChandler Carruth          "Ptr must have pointer type.");
1285ef860a24SChandler Carruth   assert(!(isAtomic() && getAlignment() == 0) &&
1286ef860a24SChandler Carruth          "Alignment required for atomic load");
1287ef860a24SChandler Carruth }
1288ef860a24SChandler Carruth 
128984c1dbdeSJames Y Knight LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name,
129084c1dbdeSJames Y Knight                    Instruction *InsertBef)
129184c1dbdeSJames Y Knight     : LoadInst(Ty, Ptr, Name, /*isVolatile=*/false, InsertBef) {}
1292ef860a24SChandler Carruth 
129384c1dbdeSJames Y Knight LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name,
129484c1dbdeSJames Y Knight                    BasicBlock *InsertAE)
129584c1dbdeSJames Y Knight     : LoadInst(Ty, Ptr, Name, /*isVolatile=*/false, InsertAE) {}
1296ef860a24SChandler Carruth 
12970c28fd7fSDavid Blaikie LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile,
1298ef860a24SChandler Carruth                    Instruction *InsertBef)
1299734c74baSGuillaume Chatelet     : LoadInst(Ty, Ptr, Name, isVolatile, /*Align=*/None, InsertBef) {}
1300ef860a24SChandler Carruth 
130184c1dbdeSJames Y Knight LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile,
1302ef860a24SChandler Carruth                    BasicBlock *InsertAE)
1303734c74baSGuillaume Chatelet     : LoadInst(Ty, Ptr, Name, isVolatile, /*Align=*/None, InsertAE) {}
1304ef860a24SChandler Carruth 
1305b7a02987SDavid Blaikie LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile,
1306734c74baSGuillaume Chatelet                    MaybeAlign Align, Instruction *InsertBef)
1307800f87a8SJF Bastien     : LoadInst(Ty, Ptr, Name, isVolatile, Align, AtomicOrdering::NotAtomic,
1308bb80d3e1SKonstantin Zhuravlyov                SyncScope::System, InsertBef) {}
1309ef860a24SChandler Carruth 
131084c1dbdeSJames Y Knight LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile,
1311734c74baSGuillaume Chatelet                    MaybeAlign Align, BasicBlock *InsertAE)
131284c1dbdeSJames Y Knight     : LoadInst(Ty, Ptr, Name, isVolatile, Align, AtomicOrdering::NotAtomic,
1313bb80d3e1SKonstantin Zhuravlyov                SyncScope::System, InsertAE) {}
1314ef860a24SChandler Carruth 
131515d9a4c4SDavid Blaikie LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile,
1316734c74baSGuillaume Chatelet                    MaybeAlign Align, AtomicOrdering Order, SyncScope::ID SSID,
1317734c74baSGuillaume Chatelet                    Instruction *InsertBef)
131815d9a4c4SDavid Blaikie     : UnaryInstruction(Ty, Load, Ptr, InsertBef) {
131979009f88SDavid Blaikie   assert(Ty == cast<PointerType>(Ptr->getType())->getElementType());
1320ef860a24SChandler Carruth   setVolatile(isVolatile);
132117380227SGuillaume Chatelet   setAlignment(MaybeAlign(Align));
1322bb80d3e1SKonstantin Zhuravlyov   setAtomic(Order, SSID);
1323ef860a24SChandler Carruth   AssertOK();
1324ef860a24SChandler Carruth   setName(Name);
1325ef860a24SChandler Carruth }
1326ef860a24SChandler Carruth 
132784c1dbdeSJames Y Knight LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile,
1328734c74baSGuillaume Chatelet                    MaybeAlign Align, AtomicOrdering Order, SyncScope::ID SSID,
1329ef860a24SChandler Carruth                    BasicBlock *InsertAE)
133084c1dbdeSJames Y Knight     : UnaryInstruction(Ty, Load, Ptr, InsertAE) {
133184c1dbdeSJames Y Knight   assert(Ty == cast<PointerType>(Ptr->getType())->getElementType());
1332ef860a24SChandler Carruth   setVolatile(isVolatile);
1333734c74baSGuillaume Chatelet   setAlignment(Align);
1334bb80d3e1SKonstantin Zhuravlyov   setAtomic(Order, SSID);
1335ef860a24SChandler Carruth   AssertOK();
1336ef860a24SChandler Carruth   setName(Name);
1337ef860a24SChandler Carruth }
1338ef860a24SChandler Carruth 
133918f805a7SGuillaume Chatelet void LoadInst::setAlignment(MaybeAlign Align) {
1340a06c13b1SGuillaume Chatelet   assert((!Align || *Align <= MaximumAlignment) &&
1341ef860a24SChandler Carruth          "Alignment is greater than MaximumAlignment!");
1342ef860a24SChandler Carruth   setInstructionSubclassData((getSubclassDataFromInstruction() & ~(31 << 1)) |
1343a06c13b1SGuillaume Chatelet                              (encode(Align) << 1));
1344a06c13b1SGuillaume Chatelet   if (Align)
1345a06c13b1SGuillaume Chatelet     assert(getAlignment() == Align->value() &&
1346a06c13b1SGuillaume Chatelet            "Alignment representation error!");
1347a06c13b1SGuillaume Chatelet   else
1348a06c13b1SGuillaume Chatelet     assert(getAlignment() == 0 && "Alignment representation error!");
1349ef860a24SChandler Carruth }
1350ef860a24SChandler Carruth 
1351ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
1352ef860a24SChandler Carruth //                           StoreInst Implementation
1353ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
1354ef860a24SChandler Carruth 
1355ef860a24SChandler Carruth void StoreInst::AssertOK() {
1356ef860a24SChandler Carruth   assert(getOperand(0) && getOperand(1) && "Both operands must be non-null!");
1357ef860a24SChandler Carruth   assert(getOperand(1)->getType()->isPointerTy() &&
1358ef860a24SChandler Carruth          "Ptr must have pointer type!");
1359ef860a24SChandler Carruth   assert(getOperand(0)->getType() ==
1360ef860a24SChandler Carruth                  cast<PointerType>(getOperand(1)->getType())->getElementType()
1361ef860a24SChandler Carruth          && "Ptr must be a pointer to Val type!");
1362ef860a24SChandler Carruth   assert(!(isAtomic() && getAlignment() == 0) &&
13631d7c97efSMark Lacey          "Alignment required for atomic store");
1364ef860a24SChandler Carruth }
1365ef860a24SChandler Carruth 
1366ef860a24SChandler Carruth StoreInst::StoreInst(Value *val, Value *addr, Instruction *InsertBefore)
1367fc165f14SBenjamin Kramer     : StoreInst(val, addr, /*isVolatile=*/false, InsertBefore) {}
1368ef860a24SChandler Carruth 
1369ef860a24SChandler Carruth StoreInst::StoreInst(Value *val, Value *addr, BasicBlock *InsertAtEnd)
1370fc165f14SBenjamin Kramer     : StoreInst(val, addr, /*isVolatile=*/false, InsertAtEnd) {}
1371ef860a24SChandler Carruth 
1372ef860a24SChandler Carruth StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1373ef860a24SChandler Carruth                      Instruction *InsertBefore)
1374*5b99c189SGuillaume Chatelet     : StoreInst(val, addr, isVolatile, /*Align=*/None, InsertBefore) {}
1375ef860a24SChandler Carruth 
1376ef860a24SChandler Carruth StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1377fc165f14SBenjamin Kramer                      BasicBlock *InsertAtEnd)
1378*5b99c189SGuillaume Chatelet     : StoreInst(val, addr, isVolatile, /*Align=*/None, InsertAtEnd) {}
1379fc165f14SBenjamin Kramer 
1380*5b99c189SGuillaume Chatelet StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile, MaybeAlign Align,
1381fc165f14SBenjamin Kramer                      Instruction *InsertBefore)
1382800f87a8SJF Bastien     : StoreInst(val, addr, isVolatile, Align, AtomicOrdering::NotAtomic,
1383bb80d3e1SKonstantin Zhuravlyov                 SyncScope::System, InsertBefore) {}
1384fc165f14SBenjamin Kramer 
1385*5b99c189SGuillaume Chatelet StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile, MaybeAlign Align,
1386fc165f14SBenjamin Kramer                      BasicBlock *InsertAtEnd)
1387800f87a8SJF Bastien     : StoreInst(val, addr, isVolatile, Align, AtomicOrdering::NotAtomic,
1388bb80d3e1SKonstantin Zhuravlyov                 SyncScope::System, InsertAtEnd) {}
1389ef860a24SChandler Carruth 
1390*5b99c189SGuillaume Chatelet StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile, MaybeAlign Align,
1391*5b99c189SGuillaume Chatelet                      AtomicOrdering Order, SyncScope::ID SSID,
1392ef860a24SChandler Carruth                      Instruction *InsertBefore)
1393ef860a24SChandler Carruth     : Instruction(Type::getVoidTy(val->getContext()), Store,
1394ef860a24SChandler Carruth                   OperandTraits<StoreInst>::op_begin(this),
1395*5b99c189SGuillaume Chatelet                   OperandTraits<StoreInst>::operands(this), InsertBefore) {
1396ef860a24SChandler Carruth   Op<0>() = val;
1397ef860a24SChandler Carruth   Op<1>() = addr;
1398ef860a24SChandler Carruth   setVolatile(isVolatile);
1399*5b99c189SGuillaume Chatelet   setAlignment(Align);
1400bb80d3e1SKonstantin Zhuravlyov   setAtomic(Order, SSID);
1401ef860a24SChandler Carruth   AssertOK();
1402ef860a24SChandler Carruth }
1403ef860a24SChandler Carruth 
1404*5b99c189SGuillaume Chatelet StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile, MaybeAlign Align,
1405*5b99c189SGuillaume Chatelet                      AtomicOrdering Order, SyncScope::ID SSID,
1406ef860a24SChandler Carruth                      BasicBlock *InsertAtEnd)
1407ef860a24SChandler Carruth     : Instruction(Type::getVoidTy(val->getContext()), Store,
1408ef860a24SChandler Carruth                   OperandTraits<StoreInst>::op_begin(this),
1409*5b99c189SGuillaume Chatelet                   OperandTraits<StoreInst>::operands(this), InsertAtEnd) {
1410ef860a24SChandler Carruth   Op<0>() = val;
1411ef860a24SChandler Carruth   Op<1>() = addr;
1412ef860a24SChandler Carruth   setVolatile(isVolatile);
1413*5b99c189SGuillaume Chatelet   setAlignment(Align);
1414bb80d3e1SKonstantin Zhuravlyov   setAtomic(Order, SSID);
1415ef860a24SChandler Carruth   AssertOK();
1416ef860a24SChandler Carruth }
1417ef860a24SChandler Carruth 
141818f805a7SGuillaume Chatelet void StoreInst::setAlignment(MaybeAlign Align) {
1419a06c13b1SGuillaume Chatelet   assert((!Align || *Align <= MaximumAlignment) &&
1420ef860a24SChandler Carruth          "Alignment is greater than MaximumAlignment!");
1421ef860a24SChandler Carruth   setInstructionSubclassData((getSubclassDataFromInstruction() & ~(31 << 1)) |
1422a06c13b1SGuillaume Chatelet                              (encode(Align) << 1));
1423a06c13b1SGuillaume Chatelet   if (Align)
1424a06c13b1SGuillaume Chatelet     assert(getAlignment() == Align->value() &&
1425a06c13b1SGuillaume Chatelet            "Alignment representation error!");
1426a06c13b1SGuillaume Chatelet   else
1427a06c13b1SGuillaume Chatelet     assert(getAlignment() == 0 && "Alignment representation error!");
1428ef860a24SChandler Carruth }
1429ef860a24SChandler Carruth 
1430ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
1431ef860a24SChandler Carruth //                       AtomicCmpXchgInst Implementation
1432ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
1433ef860a24SChandler Carruth 
1434ef860a24SChandler Carruth void AtomicCmpXchgInst::Init(Value *Ptr, Value *Cmp, Value *NewVal,
1435e94a518aSTim Northover                              AtomicOrdering SuccessOrdering,
1436e94a518aSTim Northover                              AtomicOrdering FailureOrdering,
1437bb80d3e1SKonstantin Zhuravlyov                              SyncScope::ID SSID) {
1438ef860a24SChandler Carruth   Op<0>() = Ptr;
1439ef860a24SChandler Carruth   Op<1>() = Cmp;
1440ef860a24SChandler Carruth   Op<2>() = NewVal;
1441e94a518aSTim Northover   setSuccessOrdering(SuccessOrdering);
1442e94a518aSTim Northover   setFailureOrdering(FailureOrdering);
1443bb80d3e1SKonstantin Zhuravlyov   setSyncScopeID(SSID);
1444ef860a24SChandler Carruth 
1445ef860a24SChandler Carruth   assert(getOperand(0) && getOperand(1) && getOperand(2) &&
1446ef860a24SChandler Carruth          "All operands must be non-null!");
1447ef860a24SChandler Carruth   assert(getOperand(0)->getType()->isPointerTy() &&
1448ef860a24SChandler Carruth          "Ptr must have pointer type!");
1449ef860a24SChandler Carruth   assert(getOperand(1)->getType() ==
1450ef860a24SChandler Carruth                  cast<PointerType>(getOperand(0)->getType())->getElementType()
1451ef860a24SChandler Carruth          && "Ptr must be a pointer to Cmp type!");
1452ef860a24SChandler Carruth   assert(getOperand(2)->getType() ==
1453ef860a24SChandler Carruth                  cast<PointerType>(getOperand(0)->getType())->getElementType()
1454ef860a24SChandler Carruth          && "Ptr must be a pointer to NewVal type!");
1455800f87a8SJF Bastien   assert(SuccessOrdering != AtomicOrdering::NotAtomic &&
1456ef860a24SChandler Carruth          "AtomicCmpXchg instructions must be atomic!");
1457800f87a8SJF Bastien   assert(FailureOrdering != AtomicOrdering::NotAtomic &&
1458e94a518aSTim Northover          "AtomicCmpXchg instructions must be atomic!");
1459800f87a8SJF Bastien   assert(!isStrongerThan(FailureOrdering, SuccessOrdering) &&
1460800f87a8SJF Bastien          "AtomicCmpXchg failure argument shall be no stronger than the success "
1461800f87a8SJF Bastien          "argument");
1462800f87a8SJF Bastien   assert(FailureOrdering != AtomicOrdering::Release &&
1463800f87a8SJF Bastien          FailureOrdering != AtomicOrdering::AcquireRelease &&
1464e94a518aSTim Northover          "AtomicCmpXchg failure ordering cannot include release semantics");
1465ef860a24SChandler Carruth }
1466ef860a24SChandler Carruth 
1467ef860a24SChandler Carruth AtomicCmpXchgInst::AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal,
1468e94a518aSTim Northover                                      AtomicOrdering SuccessOrdering,
1469e94a518aSTim Northover                                      AtomicOrdering FailureOrdering,
1470bb80d3e1SKonstantin Zhuravlyov                                      SyncScope::ID SSID,
1471ef860a24SChandler Carruth                                      Instruction *InsertBefore)
1472420a2168STim Northover     : Instruction(
1473e38003f8SSerge Guelton           StructType::get(Cmp->getType(), Type::getInt1Ty(Cmp->getContext())),
1474420a2168STim Northover           AtomicCmpXchg, OperandTraits<AtomicCmpXchgInst>::op_begin(this),
1475420a2168STim Northover           OperandTraits<AtomicCmpXchgInst>::operands(this), InsertBefore) {
1476bb80d3e1SKonstantin Zhuravlyov   Init(Ptr, Cmp, NewVal, SuccessOrdering, FailureOrdering, SSID);
1477ef860a24SChandler Carruth }
1478ef860a24SChandler Carruth 
1479ef860a24SChandler Carruth AtomicCmpXchgInst::AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal,
1480e94a518aSTim Northover                                      AtomicOrdering SuccessOrdering,
1481e94a518aSTim Northover                                      AtomicOrdering FailureOrdering,
1482bb80d3e1SKonstantin Zhuravlyov                                      SyncScope::ID SSID,
1483ef860a24SChandler Carruth                                      BasicBlock *InsertAtEnd)
1484420a2168STim Northover     : Instruction(
1485e38003f8SSerge Guelton           StructType::get(Cmp->getType(), Type::getInt1Ty(Cmp->getContext())),
1486420a2168STim Northover           AtomicCmpXchg, OperandTraits<AtomicCmpXchgInst>::op_begin(this),
1487420a2168STim Northover           OperandTraits<AtomicCmpXchgInst>::operands(this), InsertAtEnd) {
1488bb80d3e1SKonstantin Zhuravlyov   Init(Ptr, Cmp, NewVal, SuccessOrdering, FailureOrdering, SSID);
1489ef860a24SChandler Carruth }
1490ef860a24SChandler Carruth 
1491ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
1492ef860a24SChandler Carruth //                       AtomicRMWInst Implementation
1493ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
1494ef860a24SChandler Carruth 
1495ef860a24SChandler Carruth void AtomicRMWInst::Init(BinOp Operation, Value *Ptr, Value *Val,
1496ef860a24SChandler Carruth                          AtomicOrdering Ordering,
1497bb80d3e1SKonstantin Zhuravlyov                          SyncScope::ID SSID) {
1498ef860a24SChandler Carruth   Op<0>() = Ptr;
1499ef860a24SChandler Carruth   Op<1>() = Val;
1500ef860a24SChandler Carruth   setOperation(Operation);
1501ef860a24SChandler Carruth   setOrdering(Ordering);
1502bb80d3e1SKonstantin Zhuravlyov   setSyncScopeID(SSID);
1503ef860a24SChandler Carruth 
1504ef860a24SChandler Carruth   assert(getOperand(0) && getOperand(1) &&
1505ef860a24SChandler Carruth          "All operands must be non-null!");
1506ef860a24SChandler Carruth   assert(getOperand(0)->getType()->isPointerTy() &&
1507ef860a24SChandler Carruth          "Ptr must have pointer type!");
1508ef860a24SChandler Carruth   assert(getOperand(1)->getType() ==
1509ef860a24SChandler Carruth          cast<PointerType>(getOperand(0)->getType())->getElementType()
1510ef860a24SChandler Carruth          && "Ptr must be a pointer to Val type!");
1511800f87a8SJF Bastien   assert(Ordering != AtomicOrdering::NotAtomic &&
1512ef860a24SChandler Carruth          "AtomicRMW instructions must be atomic!");
1513ef860a24SChandler Carruth }
1514ef860a24SChandler Carruth 
1515ef860a24SChandler Carruth AtomicRMWInst::AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val,
1516ef860a24SChandler Carruth                              AtomicOrdering Ordering,
1517bb80d3e1SKonstantin Zhuravlyov                              SyncScope::ID SSID,
1518ef860a24SChandler Carruth                              Instruction *InsertBefore)
1519ef860a24SChandler Carruth   : Instruction(Val->getType(), AtomicRMW,
1520ef860a24SChandler Carruth                 OperandTraits<AtomicRMWInst>::op_begin(this),
1521ef860a24SChandler Carruth                 OperandTraits<AtomicRMWInst>::operands(this),
1522ef860a24SChandler Carruth                 InsertBefore) {
1523bb80d3e1SKonstantin Zhuravlyov   Init(Operation, Ptr, Val, Ordering, SSID);
1524ef860a24SChandler Carruth }
1525ef860a24SChandler Carruth 
1526ef860a24SChandler Carruth AtomicRMWInst::AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val,
1527ef860a24SChandler Carruth                              AtomicOrdering Ordering,
1528bb80d3e1SKonstantin Zhuravlyov                              SyncScope::ID SSID,
1529ef860a24SChandler Carruth                              BasicBlock *InsertAtEnd)
1530ef860a24SChandler Carruth   : Instruction(Val->getType(), AtomicRMW,
1531ef860a24SChandler Carruth                 OperandTraits<AtomicRMWInst>::op_begin(this),
1532ef860a24SChandler Carruth                 OperandTraits<AtomicRMWInst>::operands(this),
1533ef860a24SChandler Carruth                 InsertAtEnd) {
1534bb80d3e1SKonstantin Zhuravlyov   Init(Operation, Ptr, Val, Ordering, SSID);
1535ef860a24SChandler Carruth }
1536ef860a24SChandler Carruth 
1537b02ba99eSMatt Arsenault StringRef AtomicRMWInst::getOperationName(BinOp Op) {
1538b02ba99eSMatt Arsenault   switch (Op) {
1539b02ba99eSMatt Arsenault   case AtomicRMWInst::Xchg:
1540b02ba99eSMatt Arsenault     return "xchg";
1541b02ba99eSMatt Arsenault   case AtomicRMWInst::Add:
1542b02ba99eSMatt Arsenault     return "add";
1543b02ba99eSMatt Arsenault   case AtomicRMWInst::Sub:
1544b02ba99eSMatt Arsenault     return "sub";
1545b02ba99eSMatt Arsenault   case AtomicRMWInst::And:
1546b02ba99eSMatt Arsenault     return "and";
1547b02ba99eSMatt Arsenault   case AtomicRMWInst::Nand:
1548b02ba99eSMatt Arsenault     return "nand";
1549b02ba99eSMatt Arsenault   case AtomicRMWInst::Or:
1550b02ba99eSMatt Arsenault     return "or";
1551b02ba99eSMatt Arsenault   case AtomicRMWInst::Xor:
1552b02ba99eSMatt Arsenault     return "xor";
1553b02ba99eSMatt Arsenault   case AtomicRMWInst::Max:
1554b02ba99eSMatt Arsenault     return "max";
1555b02ba99eSMatt Arsenault   case AtomicRMWInst::Min:
1556b02ba99eSMatt Arsenault     return "min";
1557b02ba99eSMatt Arsenault   case AtomicRMWInst::UMax:
1558b02ba99eSMatt Arsenault     return "umax";
1559b02ba99eSMatt Arsenault   case AtomicRMWInst::UMin:
1560b02ba99eSMatt Arsenault     return "umin";
156139508331SMatt Arsenault   case AtomicRMWInst::FAdd:
156239508331SMatt Arsenault     return "fadd";
156339508331SMatt Arsenault   case AtomicRMWInst::FSub:
156439508331SMatt Arsenault     return "fsub";
1565b02ba99eSMatt Arsenault   case AtomicRMWInst::BAD_BINOP:
1566b02ba99eSMatt Arsenault     return "<invalid operation>";
1567b02ba99eSMatt Arsenault   }
1568b02ba99eSMatt Arsenault 
1569b02ba99eSMatt Arsenault   llvm_unreachable("invalid atomicrmw operation");
1570b02ba99eSMatt Arsenault }
1571b02ba99eSMatt Arsenault 
1572ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
1573ef860a24SChandler Carruth //                       FenceInst Implementation
1574ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
1575ef860a24SChandler Carruth 
1576ef860a24SChandler Carruth FenceInst::FenceInst(LLVMContext &C, AtomicOrdering Ordering,
1577bb80d3e1SKonstantin Zhuravlyov                      SyncScope::ID SSID,
1578ef860a24SChandler Carruth                      Instruction *InsertBefore)
1579c620761cSCraig Topper   : Instruction(Type::getVoidTy(C), Fence, nullptr, 0, InsertBefore) {
1580ef860a24SChandler Carruth   setOrdering(Ordering);
1581bb80d3e1SKonstantin Zhuravlyov   setSyncScopeID(SSID);
1582ef860a24SChandler Carruth }
1583ef860a24SChandler Carruth 
1584ef860a24SChandler Carruth FenceInst::FenceInst(LLVMContext &C, AtomicOrdering Ordering,
1585bb80d3e1SKonstantin Zhuravlyov                      SyncScope::ID SSID,
1586ef860a24SChandler Carruth                      BasicBlock *InsertAtEnd)
1587c620761cSCraig Topper   : Instruction(Type::getVoidTy(C), Fence, nullptr, 0, InsertAtEnd) {
1588ef860a24SChandler Carruth   setOrdering(Ordering);
1589bb80d3e1SKonstantin Zhuravlyov   setSyncScopeID(SSID);
1590ef860a24SChandler Carruth }
1591ef860a24SChandler Carruth 
1592ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
1593ef860a24SChandler Carruth //                       GetElementPtrInst Implementation
1594ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
1595ef860a24SChandler Carruth 
1596ef860a24SChandler Carruth void GetElementPtrInst::init(Value *Ptr, ArrayRef<Value *> IdxList,
1597ef860a24SChandler Carruth                              const Twine &Name) {
1598b4eede2cSPete Cooper   assert(getNumOperands() == 1 + IdxList.size() &&
1599b4eede2cSPete Cooper          "NumOperands not initialized?");
1600eb31b68cSPete Cooper   Op<0>() = Ptr;
160175709329SFangrui Song   llvm::copy(IdxList, op_begin() + 1);
1602ef860a24SChandler Carruth   setName(Name);
1603ef860a24SChandler Carruth }
1604ef860a24SChandler Carruth 
1605ef860a24SChandler Carruth GetElementPtrInst::GetElementPtrInst(const GetElementPtrInst &GEPI)
1606ef860a24SChandler Carruth     : Instruction(GEPI.getType(), GetElementPtr,
160773cf872aSDavid Blaikie                   OperandTraits<GetElementPtrInst>::op_end(this) -
160873cf872aSDavid Blaikie                       GEPI.getNumOperands(),
160973cf872aSDavid Blaikie                   GEPI.getNumOperands()),
1610f5147ef0SDavid Blaikie       SourceElementType(GEPI.SourceElementType),
1611f5147ef0SDavid Blaikie       ResultElementType(GEPI.ResultElementType) {
1612ef860a24SChandler Carruth   std::copy(GEPI.op_begin(), GEPI.op_end(), op_begin());
1613ef860a24SChandler Carruth   SubclassOptionalData = GEPI.SubclassOptionalData;
1614ef860a24SChandler Carruth }
1615ef860a24SChandler Carruth 
1616ef860a24SChandler Carruth /// getIndexedType - Returns the type of the element that would be accessed with
1617ef860a24SChandler Carruth /// a gep instruction with the specified parameters.
1618ef860a24SChandler Carruth ///
1619ef860a24SChandler Carruth /// The Idxs pointer should point to a continuous piece of memory containing the
1620ef860a24SChandler Carruth /// indices, either as Value* or uint64_t.
1621ef860a24SChandler Carruth ///
1622ef860a24SChandler Carruth /// A null type is returned if the indices are invalid for the specified
1623ef860a24SChandler Carruth /// pointer type.
1624ef860a24SChandler Carruth ///
1625ef860a24SChandler Carruth template <typename IndexTy>
1626d288fb86SDavid Blaikie static Type *getIndexedTypeInternal(Type *Agg, ArrayRef<IndexTy> IdxList) {
1627ef860a24SChandler Carruth   // Handle the special case of the empty set index set, which is always valid.
1628ef860a24SChandler Carruth   if (IdxList.empty())
1629ef860a24SChandler Carruth     return Agg;
1630ef860a24SChandler Carruth 
1631ef860a24SChandler Carruth   // If there is at least one index, the top level type must be sized, otherwise
1632ef860a24SChandler Carruth   // it cannot be 'stepped over'.
1633ef860a24SChandler Carruth   if (!Agg->isSized())
1634c620761cSCraig Topper     return nullptr;
1635ef860a24SChandler Carruth 
1636ef860a24SChandler Carruth   unsigned CurIdx = 1;
1637ef860a24SChandler Carruth   for (; CurIdx != IdxList.size(); ++CurIdx) {
1638ef860a24SChandler Carruth     CompositeType *CT = dyn_cast<CompositeType>(Agg);
1639c620761cSCraig Topper     if (!CT || CT->isPointerTy()) return nullptr;
1640ef860a24SChandler Carruth     IndexTy Index = IdxList[CurIdx];
1641c620761cSCraig Topper     if (!CT->indexValid(Index)) return nullptr;
1642ef860a24SChandler Carruth     Agg = CT->getTypeAtIndex(Index);
1643ef860a24SChandler Carruth   }
1644c620761cSCraig Topper   return CurIdx == IdxList.size() ? Agg : nullptr;
1645ef860a24SChandler Carruth }
1646ef860a24SChandler Carruth 
1647d288fb86SDavid Blaikie Type *GetElementPtrInst::getIndexedType(Type *Ty, ArrayRef<Value *> IdxList) {
1648d288fb86SDavid Blaikie   return getIndexedTypeInternal(Ty, IdxList);
1649ef860a24SChandler Carruth }
1650ef860a24SChandler Carruth 
1651d288fb86SDavid Blaikie Type *GetElementPtrInst::getIndexedType(Type *Ty,
1652ef860a24SChandler Carruth                                         ArrayRef<Constant *> IdxList) {
1653d288fb86SDavid Blaikie   return getIndexedTypeInternal(Ty, IdxList);
1654ef860a24SChandler Carruth }
1655ef860a24SChandler Carruth 
1656d288fb86SDavid Blaikie Type *GetElementPtrInst::getIndexedType(Type *Ty, ArrayRef<uint64_t> IdxList) {
1657d288fb86SDavid Blaikie   return getIndexedTypeInternal(Ty, IdxList);
1658ef860a24SChandler Carruth }
1659ef860a24SChandler Carruth 
1660ef860a24SChandler Carruth /// hasAllZeroIndices - Return true if all of the indices of this GEP are
1661ef860a24SChandler Carruth /// zeros.  If so, the result pointer and the first operand have the same
1662ef860a24SChandler Carruth /// value, just potentially different types.
1663ef860a24SChandler Carruth bool GetElementPtrInst::hasAllZeroIndices() const {
1664ef860a24SChandler Carruth   for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1665ef860a24SChandler Carruth     if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(i))) {
1666ef860a24SChandler Carruth       if (!CI->isZero()) return false;
1667ef860a24SChandler Carruth     } else {
1668ef860a24SChandler Carruth       return false;
1669ef860a24SChandler Carruth     }
1670ef860a24SChandler Carruth   }
1671ef860a24SChandler Carruth   return true;
1672ef860a24SChandler Carruth }
1673ef860a24SChandler Carruth 
1674ef860a24SChandler Carruth /// hasAllConstantIndices - Return true if all of the indices of this GEP are
1675ef860a24SChandler Carruth /// constant integers.  If so, the result pointer and the first operand have
1676ef860a24SChandler Carruth /// a constant offset between them.
1677ef860a24SChandler Carruth bool GetElementPtrInst::hasAllConstantIndices() const {
1678ef860a24SChandler Carruth   for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1679ef860a24SChandler Carruth     if (!isa<ConstantInt>(getOperand(i)))
1680ef860a24SChandler Carruth       return false;
1681ef860a24SChandler Carruth   }
1682ef860a24SChandler Carruth   return true;
1683ef860a24SChandler Carruth }
1684ef860a24SChandler Carruth 
1685ef860a24SChandler Carruth void GetElementPtrInst::setIsInBounds(bool B) {
1686ef860a24SChandler Carruth   cast<GEPOperator>(this)->setIsInBounds(B);
1687ef860a24SChandler Carruth }
1688ef860a24SChandler Carruth 
1689ef860a24SChandler Carruth bool GetElementPtrInst::isInBounds() const {
1690ef860a24SChandler Carruth   return cast<GEPOperator>(this)->isInBounds();
1691ef860a24SChandler Carruth }
1692ef860a24SChandler Carruth 
1693ef860a24SChandler Carruth bool GetElementPtrInst::accumulateConstantOffset(const DataLayout &DL,
1694ef860a24SChandler Carruth                                                  APInt &Offset) const {
1695ef860a24SChandler Carruth   // Delegate to the generic GEPOperator implementation.
1696ef860a24SChandler Carruth   return cast<GEPOperator>(this)->accumulateConstantOffset(DL, Offset);
1697ef860a24SChandler Carruth }
1698ef860a24SChandler Carruth 
1699ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
1700ef860a24SChandler Carruth //                           ExtractElementInst Implementation
1701ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
1702ef860a24SChandler Carruth 
1703ef860a24SChandler Carruth ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1704ef860a24SChandler Carruth                                        const Twine &Name,
1705ef860a24SChandler Carruth                                        Instruction *InsertBef)
1706ef860a24SChandler Carruth   : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1707ef860a24SChandler Carruth                 ExtractElement,
1708ef860a24SChandler Carruth                 OperandTraits<ExtractElementInst>::op_begin(this),
1709ef860a24SChandler Carruth                 2, InsertBef) {
1710ef860a24SChandler Carruth   assert(isValidOperands(Val, Index) &&
1711ef860a24SChandler Carruth          "Invalid extractelement instruction operands!");
1712ef860a24SChandler Carruth   Op<0>() = Val;
1713ef860a24SChandler Carruth   Op<1>() = Index;
1714ef860a24SChandler Carruth   setName(Name);
1715ef860a24SChandler Carruth }
1716ef860a24SChandler Carruth 
1717ef860a24SChandler Carruth ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1718ef860a24SChandler Carruth                                        const Twine &Name,
1719ef860a24SChandler Carruth                                        BasicBlock *InsertAE)
1720ef860a24SChandler Carruth   : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1721ef860a24SChandler Carruth                 ExtractElement,
1722ef860a24SChandler Carruth                 OperandTraits<ExtractElementInst>::op_begin(this),
1723ef860a24SChandler Carruth                 2, InsertAE) {
1724ef860a24SChandler Carruth   assert(isValidOperands(Val, Index) &&
1725ef860a24SChandler Carruth          "Invalid extractelement instruction operands!");
1726ef860a24SChandler Carruth 
1727ef860a24SChandler Carruth   Op<0>() = Val;
1728ef860a24SChandler Carruth   Op<1>() = Index;
1729ef860a24SChandler Carruth   setName(Name);
1730ef860a24SChandler Carruth }
1731ef860a24SChandler Carruth 
1732ef860a24SChandler Carruth bool ExtractElementInst::isValidOperands(const Value *Val, const Value *Index) {
17331f10c5eaSMichael J. Spencer   if (!Val->getType()->isVectorTy() || !Index->getType()->isIntegerTy())
1734ef860a24SChandler Carruth     return false;
1735ef860a24SChandler Carruth   return true;
1736ef860a24SChandler Carruth }
1737ef860a24SChandler Carruth 
1738ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
1739ef860a24SChandler Carruth //                           InsertElementInst Implementation
1740ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
1741ef860a24SChandler Carruth 
1742ef860a24SChandler Carruth InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1743ef860a24SChandler Carruth                                      const Twine &Name,
1744ef860a24SChandler Carruth                                      Instruction *InsertBef)
1745ef860a24SChandler Carruth   : Instruction(Vec->getType(), InsertElement,
1746ef860a24SChandler Carruth                 OperandTraits<InsertElementInst>::op_begin(this),
1747ef860a24SChandler Carruth                 3, InsertBef) {
1748ef860a24SChandler Carruth   assert(isValidOperands(Vec, Elt, Index) &&
1749ef860a24SChandler Carruth          "Invalid insertelement instruction operands!");
1750ef860a24SChandler Carruth   Op<0>() = Vec;
1751ef860a24SChandler Carruth   Op<1>() = Elt;
1752ef860a24SChandler Carruth   Op<2>() = Index;
1753ef860a24SChandler Carruth   setName(Name);
1754ef860a24SChandler Carruth }
1755ef860a24SChandler Carruth 
1756ef860a24SChandler Carruth InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1757ef860a24SChandler Carruth                                      const Twine &Name,
1758ef860a24SChandler Carruth                                      BasicBlock *InsertAE)
1759ef860a24SChandler Carruth   : Instruction(Vec->getType(), InsertElement,
1760ef860a24SChandler Carruth                 OperandTraits<InsertElementInst>::op_begin(this),
1761ef860a24SChandler Carruth                 3, InsertAE) {
1762ef860a24SChandler Carruth   assert(isValidOperands(Vec, Elt, Index) &&
1763ef860a24SChandler Carruth          "Invalid insertelement instruction operands!");
1764ef860a24SChandler Carruth 
1765ef860a24SChandler Carruth   Op<0>() = Vec;
1766ef860a24SChandler Carruth   Op<1>() = Elt;
1767ef860a24SChandler Carruth   Op<2>() = Index;
1768ef860a24SChandler Carruth   setName(Name);
1769ef860a24SChandler Carruth }
1770ef860a24SChandler Carruth 
1771ef860a24SChandler Carruth bool InsertElementInst::isValidOperands(const Value *Vec, const Value *Elt,
1772ef860a24SChandler Carruth                                         const Value *Index) {
1773ef860a24SChandler Carruth   if (!Vec->getType()->isVectorTy())
1774ef860a24SChandler Carruth     return false;   // First operand of insertelement must be vector type.
1775ef860a24SChandler Carruth 
1776ef860a24SChandler Carruth   if (Elt->getType() != cast<VectorType>(Vec->getType())->getElementType())
1777ef860a24SChandler Carruth     return false;// Second operand of insertelement must be vector element type.
1778ef860a24SChandler Carruth 
17791f10c5eaSMichael J. Spencer   if (!Index->getType()->isIntegerTy())
1780ef860a24SChandler Carruth     return false;  // Third operand of insertelement must be i32.
1781ef860a24SChandler Carruth   return true;
1782ef860a24SChandler Carruth }
1783ef860a24SChandler Carruth 
1784ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
1785ef860a24SChandler Carruth //                      ShuffleVectorInst Implementation
1786ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
1787ef860a24SChandler Carruth 
1788ef860a24SChandler Carruth ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1789ef860a24SChandler Carruth                                      const Twine &Name,
1790ef860a24SChandler Carruth                                      Instruction *InsertBefore)
1791ef860a24SChandler Carruth : Instruction(VectorType::get(cast<VectorType>(V1->getType())->getElementType(),
1792b302561bSGraham Hunter                 cast<VectorType>(Mask->getType())->getElementCount()),
1793ef860a24SChandler Carruth               ShuffleVector,
1794ef860a24SChandler Carruth               OperandTraits<ShuffleVectorInst>::op_begin(this),
1795ef860a24SChandler Carruth               OperandTraits<ShuffleVectorInst>::operands(this),
1796ef860a24SChandler Carruth               InsertBefore) {
1797ef860a24SChandler Carruth   assert(isValidOperands(V1, V2, Mask) &&
1798ef860a24SChandler Carruth          "Invalid shuffle vector instruction operands!");
1799ef860a24SChandler Carruth   Op<0>() = V1;
1800ef860a24SChandler Carruth   Op<1>() = V2;
1801ef860a24SChandler Carruth   Op<2>() = Mask;
1802ef860a24SChandler Carruth   setName(Name);
1803ef860a24SChandler Carruth }
1804ef860a24SChandler Carruth 
1805ef860a24SChandler Carruth ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1806ef860a24SChandler Carruth                                      const Twine &Name,
1807ef860a24SChandler Carruth                                      BasicBlock *InsertAtEnd)
1808ef860a24SChandler Carruth : Instruction(VectorType::get(cast<VectorType>(V1->getType())->getElementType(),
1809b302561bSGraham Hunter                 cast<VectorType>(Mask->getType())->getElementCount()),
1810ef860a24SChandler Carruth               ShuffleVector,
1811ef860a24SChandler Carruth               OperandTraits<ShuffleVectorInst>::op_begin(this),
1812ef860a24SChandler Carruth               OperandTraits<ShuffleVectorInst>::operands(this),
1813ef860a24SChandler Carruth               InsertAtEnd) {
1814ef860a24SChandler Carruth   assert(isValidOperands(V1, V2, Mask) &&
1815ef860a24SChandler Carruth          "Invalid shuffle vector instruction operands!");
1816ef860a24SChandler Carruth 
1817ef860a24SChandler Carruth   Op<0>() = V1;
1818ef860a24SChandler Carruth   Op<1>() = V2;
1819ef860a24SChandler Carruth   Op<2>() = Mask;
1820ef860a24SChandler Carruth   setName(Name);
1821ef860a24SChandler Carruth }
1822ef860a24SChandler Carruth 
1823b276dd19SSanjay Patel void ShuffleVectorInst::commute() {
1824b276dd19SSanjay Patel   int NumOpElts = Op<0>()->getType()->getVectorNumElements();
1825b276dd19SSanjay Patel   int NumMaskElts = getMask()->getType()->getVectorNumElements();
1826b276dd19SSanjay Patel   SmallVector<Constant*, 16> NewMask(NumMaskElts);
1827b276dd19SSanjay Patel   Type *Int32Ty = Type::getInt32Ty(getContext());
1828b276dd19SSanjay Patel   for (int i = 0; i != NumMaskElts; ++i) {
1829b276dd19SSanjay Patel     int MaskElt = getMaskValue(i);
1830b276dd19SSanjay Patel     if (MaskElt == -1) {
1831b276dd19SSanjay Patel       NewMask[i] = UndefValue::get(Int32Ty);
1832b276dd19SSanjay Patel       continue;
1833b276dd19SSanjay Patel     }
1834b276dd19SSanjay Patel     assert(MaskElt >= 0 && MaskElt < 2 * NumOpElts && "Out-of-range mask");
1835b276dd19SSanjay Patel     MaskElt = (MaskElt < NumOpElts) ? MaskElt + NumOpElts : MaskElt - NumOpElts;
1836b276dd19SSanjay Patel     NewMask[i] = ConstantInt::get(Int32Ty, MaskElt);
1837b276dd19SSanjay Patel   }
1838b276dd19SSanjay Patel   Op<2>() = ConstantVector::get(NewMask);
1839b276dd19SSanjay Patel   Op<0>().swap(Op<1>());
1840b276dd19SSanjay Patel }
1841b276dd19SSanjay Patel 
1842ef860a24SChandler Carruth bool ShuffleVectorInst::isValidOperands(const Value *V1, const Value *V2,
1843ef860a24SChandler Carruth                                         const Value *Mask) {
1844ef860a24SChandler Carruth   // V1 and V2 must be vectors of the same type.
1845ef860a24SChandler Carruth   if (!V1->getType()->isVectorTy() || V1->getType() != V2->getType())
1846ef860a24SChandler Carruth     return false;
1847ef860a24SChandler Carruth 
1848ef860a24SChandler Carruth   // Mask must be vector of i32.
18498bd52286SSanjay Patel   auto *MaskTy = dyn_cast<VectorType>(Mask->getType());
1850c620761cSCraig Topper   if (!MaskTy || !MaskTy->getElementType()->isIntegerTy(32))
1851ef860a24SChandler Carruth     return false;
1852ef860a24SChandler Carruth 
1853ef860a24SChandler Carruth   // Check to see if Mask is valid.
1854ef860a24SChandler Carruth   if (isa<UndefValue>(Mask) || isa<ConstantAggregateZero>(Mask))
1855ef860a24SChandler Carruth     return true;
1856ef860a24SChandler Carruth 
18578bd52286SSanjay Patel   if (const auto *MV = dyn_cast<ConstantVector>(Mask)) {
1858ef860a24SChandler Carruth     unsigned V1Size = cast<VectorType>(V1->getType())->getNumElements();
18593ad5c962SBenjamin Kramer     for (Value *Op : MV->operands()) {
18608bd52286SSanjay Patel       if (auto *CI = dyn_cast<ConstantInt>(Op)) {
1861ef860a24SChandler Carruth         if (CI->uge(V1Size*2))
1862ef860a24SChandler Carruth           return false;
18633ad5c962SBenjamin Kramer       } else if (!isa<UndefValue>(Op)) {
1864ef860a24SChandler Carruth         return false;
1865ef860a24SChandler Carruth       }
1866ef860a24SChandler Carruth     }
1867ef860a24SChandler Carruth     return true;
1868ef860a24SChandler Carruth   }
1869ef860a24SChandler Carruth 
18708bd52286SSanjay Patel   if (const auto *CDS = dyn_cast<ConstantDataSequential>(Mask)) {
1871ef860a24SChandler Carruth     unsigned V1Size = cast<VectorType>(V1->getType())->getNumElements();
1872ef860a24SChandler Carruth     for (unsigned i = 0, e = MaskTy->getNumElements(); i != e; ++i)
1873ef860a24SChandler Carruth       if (CDS->getElementAsInteger(i) >= V1Size*2)
1874ef860a24SChandler Carruth         return false;
1875ef860a24SChandler Carruth     return true;
1876ef860a24SChandler Carruth   }
1877ef860a24SChandler Carruth 
1878ef860a24SChandler Carruth   // The bitcode reader can create a place holder for a forward reference
1879ef860a24SChandler Carruth   // used as the shuffle mask. When this occurs, the shuffle mask will
1880ef860a24SChandler Carruth   // fall into this case and fail. To avoid this error, do this bit of
1881ef860a24SChandler Carruth   // ugliness to allow such a mask pass.
18828bd52286SSanjay Patel   if (const auto *CE = dyn_cast<ConstantExpr>(Mask))
1883ef860a24SChandler Carruth     if (CE->getOpcode() == Instruction::UserOp1)
1884ef860a24SChandler Carruth       return true;
1885ef860a24SChandler Carruth 
1886ef860a24SChandler Carruth   return false;
1887ef860a24SChandler Carruth }
1888ef860a24SChandler Carruth 
18892ca3360bSSanjay Patel int ShuffleVectorInst::getMaskValue(const Constant *Mask, unsigned i) {
1890ef860a24SChandler Carruth   assert(i < Mask->getType()->getVectorNumElements() && "Index out of range");
18918bd52286SSanjay Patel   if (auto *CDS = dyn_cast<ConstantDataSequential>(Mask))
1892ef860a24SChandler Carruth     return CDS->getElementAsInteger(i);
1893ef860a24SChandler Carruth   Constant *C = Mask->getAggregateElement(i);
1894ef860a24SChandler Carruth   if (isa<UndefValue>(C))
1895ef860a24SChandler Carruth     return -1;
1896ef860a24SChandler Carruth   return cast<ConstantInt>(C)->getZExtValue();
1897ef860a24SChandler Carruth }
1898ef860a24SChandler Carruth 
18992ca3360bSSanjay Patel void ShuffleVectorInst::getShuffleMask(const Constant *Mask,
1900ef860a24SChandler Carruth                                        SmallVectorImpl<int> &Result) {
1901ef860a24SChandler Carruth   unsigned NumElts = Mask->getType()->getVectorNumElements();
1902ef860a24SChandler Carruth 
19038bd52286SSanjay Patel   if (auto *CDS = dyn_cast<ConstantDataSequential>(Mask)) {
1904ef860a24SChandler Carruth     for (unsigned i = 0; i != NumElts; ++i)
1905ef860a24SChandler Carruth       Result.push_back(CDS->getElementAsInteger(i));
1906ef860a24SChandler Carruth     return;
1907ef860a24SChandler Carruth   }
1908ef860a24SChandler Carruth   for (unsigned i = 0; i != NumElts; ++i) {
1909ef860a24SChandler Carruth     Constant *C = Mask->getAggregateElement(i);
1910ef860a24SChandler Carruth     Result.push_back(isa<UndefValue>(C) ? -1 :
1911ef860a24SChandler Carruth                      cast<ConstantInt>(C)->getZExtValue());
1912ef860a24SChandler Carruth   }
1913ef860a24SChandler Carruth }
1914ef860a24SChandler Carruth 
1915ac619a09SSanjay Patel static bool isSingleSourceMaskImpl(ArrayRef<int> Mask, int NumOpElts) {
19162ca3360bSSanjay Patel   assert(!Mask.empty() && "Shuffle mask must contain elements");
19172ca3360bSSanjay Patel   bool UsesLHS = false;
19182ca3360bSSanjay Patel   bool UsesRHS = false;
1919ac619a09SSanjay Patel   for (int i = 0, NumMaskElts = Mask.size(); i < NumMaskElts; ++i) {
19202ca3360bSSanjay Patel     if (Mask[i] == -1)
19212ca3360bSSanjay Patel       continue;
1922ac619a09SSanjay Patel     assert(Mask[i] >= 0 && Mask[i] < (NumOpElts * 2) &&
19232ca3360bSSanjay Patel            "Out-of-bounds shuffle mask element");
1924ac619a09SSanjay Patel     UsesLHS |= (Mask[i] < NumOpElts);
1925ac619a09SSanjay Patel     UsesRHS |= (Mask[i] >= NumOpElts);
19262ca3360bSSanjay Patel     if (UsesLHS && UsesRHS)
19272ca3360bSSanjay Patel       return false;
19282ca3360bSSanjay Patel   }
19292ca3360bSSanjay Patel   assert((UsesLHS ^ UsesRHS) && "Should have selected from exactly 1 source");
19302ca3360bSSanjay Patel   return true;
19312ca3360bSSanjay Patel }
19322ca3360bSSanjay Patel 
1933ac619a09SSanjay Patel bool ShuffleVectorInst::isSingleSourceMask(ArrayRef<int> Mask) {
1934ac619a09SSanjay Patel   // We don't have vector operand size information, so assume operands are the
1935ac619a09SSanjay Patel   // same size as the mask.
1936ac619a09SSanjay Patel   return isSingleSourceMaskImpl(Mask, Mask.size());
1937ac619a09SSanjay Patel }
1938ac619a09SSanjay Patel 
1939ac619a09SSanjay Patel static bool isIdentityMaskImpl(ArrayRef<int> Mask, int NumOpElts) {
1940ac619a09SSanjay Patel   if (!isSingleSourceMaskImpl(Mask, NumOpElts))
19412ca3360bSSanjay Patel     return false;
1942ac619a09SSanjay Patel   for (int i = 0, NumMaskElts = Mask.size(); i < NumMaskElts; ++i) {
19432ca3360bSSanjay Patel     if (Mask[i] == -1)
19442ca3360bSSanjay Patel       continue;
1945ac619a09SSanjay Patel     if (Mask[i] != i && Mask[i] != (NumOpElts + i))
19462ca3360bSSanjay Patel       return false;
19472ca3360bSSanjay Patel   }
19482ca3360bSSanjay Patel   return true;
19492ca3360bSSanjay Patel }
19502ca3360bSSanjay Patel 
1951ac619a09SSanjay Patel bool ShuffleVectorInst::isIdentityMask(ArrayRef<int> Mask) {
1952ac619a09SSanjay Patel   // We don't have vector operand size information, so assume operands are the
1953ac619a09SSanjay Patel   // same size as the mask.
1954ac619a09SSanjay Patel   return isIdentityMaskImpl(Mask, Mask.size());
1955ac619a09SSanjay Patel }
1956ac619a09SSanjay Patel 
19572ca3360bSSanjay Patel bool ShuffleVectorInst::isReverseMask(ArrayRef<int> Mask) {
19582ca3360bSSanjay Patel   if (!isSingleSourceMask(Mask))
19592ca3360bSSanjay Patel     return false;
19602ca3360bSSanjay Patel   for (int i = 0, NumElts = Mask.size(); i < NumElts; ++i) {
19612ca3360bSSanjay Patel     if (Mask[i] == -1)
19622ca3360bSSanjay Patel       continue;
19632ca3360bSSanjay Patel     if (Mask[i] != (NumElts - 1 - i) && Mask[i] != (NumElts + NumElts - 1 - i))
19642ca3360bSSanjay Patel       return false;
19652ca3360bSSanjay Patel   }
19662ca3360bSSanjay Patel   return true;
19672ca3360bSSanjay Patel }
19682ca3360bSSanjay Patel 
19692ca3360bSSanjay Patel bool ShuffleVectorInst::isZeroEltSplatMask(ArrayRef<int> Mask) {
19702ca3360bSSanjay Patel   if (!isSingleSourceMask(Mask))
19712ca3360bSSanjay Patel     return false;
19722ca3360bSSanjay Patel   for (int i = 0, NumElts = Mask.size(); i < NumElts; ++i) {
19732ca3360bSSanjay Patel     if (Mask[i] == -1)
19742ca3360bSSanjay Patel       continue;
19752ca3360bSSanjay Patel     if (Mask[i] != 0 && Mask[i] != NumElts)
19762ca3360bSSanjay Patel       return false;
19772ca3360bSSanjay Patel   }
19782ca3360bSSanjay Patel   return true;
19792ca3360bSSanjay Patel }
19802ca3360bSSanjay Patel 
19812ca3360bSSanjay Patel bool ShuffleVectorInst::isSelectMask(ArrayRef<int> Mask) {
19822ca3360bSSanjay Patel   // Select is differentiated from identity. It requires using both sources.
19832ca3360bSSanjay Patel   if (isSingleSourceMask(Mask))
19842ca3360bSSanjay Patel     return false;
19852ca3360bSSanjay Patel   for (int i = 0, NumElts = Mask.size(); i < NumElts; ++i) {
19862ca3360bSSanjay Patel     if (Mask[i] == -1)
19872ca3360bSSanjay Patel       continue;
19882ca3360bSSanjay Patel     if (Mask[i] != i && Mask[i] != (NumElts + i))
19892ca3360bSSanjay Patel       return false;
19902ca3360bSSanjay Patel   }
19912ca3360bSSanjay Patel   return true;
19922ca3360bSSanjay Patel }
19932ca3360bSSanjay Patel 
19942ca3360bSSanjay Patel bool ShuffleVectorInst::isTransposeMask(ArrayRef<int> Mask) {
19952ca3360bSSanjay Patel   // Example masks that will return true:
19962ca3360bSSanjay Patel   // v1 = <a, b, c, d>
19972ca3360bSSanjay Patel   // v2 = <e, f, g, h>
19982ca3360bSSanjay Patel   // trn1 = shufflevector v1, v2 <0, 4, 2, 6> = <a, e, c, g>
19992ca3360bSSanjay Patel   // trn2 = shufflevector v1, v2 <1, 5, 3, 7> = <b, f, d, h>
20002ca3360bSSanjay Patel 
20012ca3360bSSanjay Patel   // 1. The number of elements in the mask must be a power-of-2 and at least 2.
20022ca3360bSSanjay Patel   int NumElts = Mask.size();
20032ca3360bSSanjay Patel   if (NumElts < 2 || !isPowerOf2_32(NumElts))
20042ca3360bSSanjay Patel     return false;
20052ca3360bSSanjay Patel 
20062ca3360bSSanjay Patel   // 2. The first element of the mask must be either a 0 or a 1.
20072ca3360bSSanjay Patel   if (Mask[0] != 0 && Mask[0] != 1)
20082ca3360bSSanjay Patel     return false;
20092ca3360bSSanjay Patel 
20102ca3360bSSanjay Patel   // 3. The difference between the first 2 elements must be equal to the
20112ca3360bSSanjay Patel   // number of elements in the mask.
20122ca3360bSSanjay Patel   if ((Mask[1] - Mask[0]) != NumElts)
20132ca3360bSSanjay Patel     return false;
20142ca3360bSSanjay Patel 
20152ca3360bSSanjay Patel   // 4. The difference between consecutive even-numbered and odd-numbered
20162ca3360bSSanjay Patel   // elements must be equal to 2.
20172ca3360bSSanjay Patel   for (int i = 2; i < NumElts; ++i) {
20182ca3360bSSanjay Patel     int MaskEltVal = Mask[i];
20192ca3360bSSanjay Patel     if (MaskEltVal == -1)
20202ca3360bSSanjay Patel       return false;
20212ca3360bSSanjay Patel     int MaskEltPrevVal = Mask[i - 2];
20222ca3360bSSanjay Patel     if (MaskEltVal - MaskEltPrevVal != 2)
20232ca3360bSSanjay Patel       return false;
20242ca3360bSSanjay Patel   }
20252ca3360bSSanjay Patel   return true;
20262ca3360bSSanjay Patel }
20272ca3360bSSanjay Patel 
2028d0c71609SSimon Pilgrim bool ShuffleVectorInst::isExtractSubvectorMask(ArrayRef<int> Mask,
2029d0c71609SSimon Pilgrim                                                int NumSrcElts, int &Index) {
2030d0c71609SSimon Pilgrim   // Must extract from a single source.
2031d0c71609SSimon Pilgrim   if (!isSingleSourceMaskImpl(Mask, NumSrcElts))
2032d0c71609SSimon Pilgrim     return false;
2033d0c71609SSimon Pilgrim 
2034d0c71609SSimon Pilgrim   // Must be smaller (else this is an Identity shuffle).
20354f2e66c0SFangrui Song   if (NumSrcElts <= (int)Mask.size())
2036d0c71609SSimon Pilgrim     return false;
2037d0c71609SSimon Pilgrim 
2038d0c71609SSimon Pilgrim   // Find start of extraction, accounting that we may start with an UNDEF.
2039d0c71609SSimon Pilgrim   int SubIndex = -1;
2040d0c71609SSimon Pilgrim   for (int i = 0, e = Mask.size(); i != e; ++i) {
2041d0c71609SSimon Pilgrim     int M = Mask[i];
2042d0c71609SSimon Pilgrim     if (M < 0)
2043d0c71609SSimon Pilgrim       continue;
2044d0c71609SSimon Pilgrim     int Offset = (M % NumSrcElts) - i;
2045d0c71609SSimon Pilgrim     if (0 <= SubIndex && SubIndex != Offset)
2046d0c71609SSimon Pilgrim       return false;
2047d0c71609SSimon Pilgrim     SubIndex = Offset;
2048d0c71609SSimon Pilgrim   }
2049d0c71609SSimon Pilgrim 
2050d0c71609SSimon Pilgrim   if (0 <= SubIndex) {
2051d0c71609SSimon Pilgrim     Index = SubIndex;
2052d0c71609SSimon Pilgrim     return true;
2053d0c71609SSimon Pilgrim   }
2054d0c71609SSimon Pilgrim   return false;
2055d0c71609SSimon Pilgrim }
2056d0c71609SSimon Pilgrim 
2057ac619a09SSanjay Patel bool ShuffleVectorInst::isIdentityWithPadding() const {
2058ac619a09SSanjay Patel   int NumOpElts = Op<0>()->getType()->getVectorNumElements();
2059ac619a09SSanjay Patel   int NumMaskElts = getType()->getVectorNumElements();
2060ac619a09SSanjay Patel   if (NumMaskElts <= NumOpElts)
2061ac619a09SSanjay Patel     return false;
2062ac619a09SSanjay Patel 
2063ac619a09SSanjay Patel   // The first part of the mask must choose elements from exactly 1 source op.
20648d39ed89SSanjay Patel   SmallVector<int, 16> Mask = getShuffleMask();
2065ac619a09SSanjay Patel   if (!isIdentityMaskImpl(Mask, NumOpElts))
2066ac619a09SSanjay Patel     return false;
2067ac619a09SSanjay Patel 
2068ac619a09SSanjay Patel   // All extending must be with undef elements.
2069ac619a09SSanjay Patel   for (int i = NumOpElts; i < NumMaskElts; ++i)
2070ac619a09SSanjay Patel     if (Mask[i] != -1)
2071ac619a09SSanjay Patel       return false;
2072ac619a09SSanjay Patel 
2073ac619a09SSanjay Patel   return true;
2074ac619a09SSanjay Patel }
2075ac619a09SSanjay Patel 
2076ac619a09SSanjay Patel bool ShuffleVectorInst::isIdentityWithExtract() const {
2077ac619a09SSanjay Patel   int NumOpElts = Op<0>()->getType()->getVectorNumElements();
2078ac619a09SSanjay Patel   int NumMaskElts = getType()->getVectorNumElements();
2079ac619a09SSanjay Patel   if (NumMaskElts >= NumOpElts)
2080ac619a09SSanjay Patel     return false;
2081ac619a09SSanjay Patel 
2082ac619a09SSanjay Patel   return isIdentityMaskImpl(getShuffleMask(), NumOpElts);
2083ac619a09SSanjay Patel }
20842ca3360bSSanjay Patel 
2085fd4976bdSSanjay Patel bool ShuffleVectorInst::isConcat() const {
2086fd4976bdSSanjay Patel   // Vector concatenation is differentiated from identity with padding.
2087fd4976bdSSanjay Patel   if (isa<UndefValue>(Op<0>()) || isa<UndefValue>(Op<1>()))
2088fd4976bdSSanjay Patel     return false;
2089fd4976bdSSanjay Patel 
2090fd4976bdSSanjay Patel   int NumOpElts = Op<0>()->getType()->getVectorNumElements();
2091fd4976bdSSanjay Patel   int NumMaskElts = getType()->getVectorNumElements();
2092fd4976bdSSanjay Patel   if (NumMaskElts != NumOpElts * 2)
2093fd4976bdSSanjay Patel     return false;
2094fd4976bdSSanjay Patel 
2095fd4976bdSSanjay Patel   // Use the mask length rather than the operands' vector lengths here. We
2096fd4976bdSSanjay Patel   // already know that the shuffle returns a vector twice as long as the inputs,
2097fd4976bdSSanjay Patel   // and neither of the inputs are undef vectors. If the mask picks consecutive
2098fd4976bdSSanjay Patel   // elements from both inputs, then this is a concatenation of the inputs.
2099fd4976bdSSanjay Patel   return isIdentityMaskImpl(getShuffleMask(), NumMaskElts);
2100fd4976bdSSanjay Patel }
2101fd4976bdSSanjay Patel 
2102ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
2103ef860a24SChandler Carruth //                             InsertValueInst Class
2104ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
2105ef860a24SChandler Carruth 
2106ef860a24SChandler Carruth void InsertValueInst::init(Value *Agg, Value *Val, ArrayRef<unsigned> Idxs,
2107ef860a24SChandler Carruth                            const Twine &Name) {
2108b4eede2cSPete Cooper   assert(getNumOperands() == 2 && "NumOperands not initialized?");
2109ef860a24SChandler Carruth 
2110ef860a24SChandler Carruth   // There's no fundamental reason why we require at least one index
2111ef860a24SChandler Carruth   // (other than weirdness with &*IdxBegin being invalid; see
2112ef860a24SChandler Carruth   // getelementptr's init routine for example). But there's no
2113ef860a24SChandler Carruth   // present need to support it.
2114d761e2c2SEugene Zelenko   assert(!Idxs.empty() && "InsertValueInst must have at least one index");
2115ef860a24SChandler Carruth 
2116ef860a24SChandler Carruth   assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs) ==
2117ef860a24SChandler Carruth          Val->getType() && "Inserted value must match indexed type!");
2118ef860a24SChandler Carruth   Op<0>() = Agg;
2119ef860a24SChandler Carruth   Op<1>() = Val;
2120ef860a24SChandler Carruth 
2121ef860a24SChandler Carruth   Indices.append(Idxs.begin(), Idxs.end());
2122ef860a24SChandler Carruth   setName(Name);
2123ef860a24SChandler Carruth }
2124ef860a24SChandler Carruth 
2125ef860a24SChandler Carruth InsertValueInst::InsertValueInst(const InsertValueInst &IVI)
2126ef860a24SChandler Carruth   : Instruction(IVI.getType(), InsertValue,
2127ef860a24SChandler Carruth                 OperandTraits<InsertValueInst>::op_begin(this), 2),
2128ef860a24SChandler Carruth     Indices(IVI.Indices) {
2129ef860a24SChandler Carruth   Op<0>() = IVI.getOperand(0);
2130ef860a24SChandler Carruth   Op<1>() = IVI.getOperand(1);
2131ef860a24SChandler Carruth   SubclassOptionalData = IVI.SubclassOptionalData;
2132ef860a24SChandler Carruth }
2133ef860a24SChandler Carruth 
2134ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
2135ef860a24SChandler Carruth //                             ExtractValueInst Class
2136ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
2137ef860a24SChandler Carruth 
2138ef860a24SChandler Carruth void ExtractValueInst::init(ArrayRef<unsigned> Idxs, const Twine &Name) {
2139b4eede2cSPete Cooper   assert(getNumOperands() == 1 && "NumOperands not initialized?");
2140ef860a24SChandler Carruth 
2141ef860a24SChandler Carruth   // There's no fundamental reason why we require at least one index.
2142ef860a24SChandler Carruth   // But there's no present need to support it.
2143d761e2c2SEugene Zelenko   assert(!Idxs.empty() && "ExtractValueInst must have at least one index");
2144ef860a24SChandler Carruth 
2145ef860a24SChandler Carruth   Indices.append(Idxs.begin(), Idxs.end());
2146ef860a24SChandler Carruth   setName(Name);
2147ef860a24SChandler Carruth }
2148ef860a24SChandler Carruth 
2149ef860a24SChandler Carruth ExtractValueInst::ExtractValueInst(const ExtractValueInst &EVI)
2150ef860a24SChandler Carruth   : UnaryInstruction(EVI.getType(), ExtractValue, EVI.getOperand(0)),
2151ef860a24SChandler Carruth     Indices(EVI.Indices) {
2152ef860a24SChandler Carruth   SubclassOptionalData = EVI.SubclassOptionalData;
2153ef860a24SChandler Carruth }
2154ef860a24SChandler Carruth 
2155ef860a24SChandler Carruth // getIndexedType - Returns the type of the element that would be extracted
2156ef860a24SChandler Carruth // with an extractvalue instruction with the specified parameters.
2157ef860a24SChandler Carruth //
2158ef860a24SChandler Carruth // A null type is returned if the indices are invalid for the specified
2159ef860a24SChandler Carruth // pointer type.
2160ef860a24SChandler Carruth //
2161ef860a24SChandler Carruth Type *ExtractValueInst::getIndexedType(Type *Agg,
2162ef860a24SChandler Carruth                                        ArrayRef<unsigned> Idxs) {
21633ad5c962SBenjamin Kramer   for (unsigned Index : Idxs) {
2164ef860a24SChandler Carruth     // We can't use CompositeType::indexValid(Index) here.
2165ef860a24SChandler Carruth     // indexValid() always returns true for arrays because getelementptr allows
2166ef860a24SChandler Carruth     // out-of-bounds indices. Since we don't allow those for extractvalue and
2167ef860a24SChandler Carruth     // insertvalue we need to check array indexing manually.
2168ef860a24SChandler Carruth     // Since the only other types we can index into are struct types it's just
2169ef860a24SChandler Carruth     // as easy to check those manually as well.
2170ef860a24SChandler Carruth     if (ArrayType *AT = dyn_cast<ArrayType>(Agg)) {
2171ef860a24SChandler Carruth       if (Index >= AT->getNumElements())
2172c620761cSCraig Topper         return nullptr;
2173ef860a24SChandler Carruth     } else if (StructType *ST = dyn_cast<StructType>(Agg)) {
2174ef860a24SChandler Carruth       if (Index >= ST->getNumElements())
2175c620761cSCraig Topper         return nullptr;
2176ef860a24SChandler Carruth     } else {
2177ef860a24SChandler Carruth       // Not a valid type to index into.
2178c620761cSCraig Topper       return nullptr;
2179ef860a24SChandler Carruth     }
2180ef860a24SChandler Carruth 
2181ef860a24SChandler Carruth     Agg = cast<CompositeType>(Agg)->getTypeAtIndex(Index);
2182ef860a24SChandler Carruth   }
2183ef860a24SChandler Carruth   return const_cast<Type*>(Agg);
2184ef860a24SChandler Carruth }
2185ef860a24SChandler Carruth 
2186ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
2187cbde0d9cSCameron McInally //                             UnaryOperator Class
2188cbde0d9cSCameron McInally //===----------------------------------------------------------------------===//
2189cbde0d9cSCameron McInally 
2190cbde0d9cSCameron McInally UnaryOperator::UnaryOperator(UnaryOps iType, Value *S,
2191cbde0d9cSCameron McInally                              Type *Ty, const Twine &Name,
2192cbde0d9cSCameron McInally                              Instruction *InsertBefore)
2193cbde0d9cSCameron McInally   : UnaryInstruction(Ty, iType, S, InsertBefore) {
2194cbde0d9cSCameron McInally   Op<0>() = S;
2195cbde0d9cSCameron McInally   setName(Name);
2196cbde0d9cSCameron McInally   AssertOK();
2197cbde0d9cSCameron McInally }
2198cbde0d9cSCameron McInally 
2199cbde0d9cSCameron McInally UnaryOperator::UnaryOperator(UnaryOps iType, Value *S,
2200cbde0d9cSCameron McInally                              Type *Ty, const Twine &Name,
2201cbde0d9cSCameron McInally                              BasicBlock *InsertAtEnd)
2202cbde0d9cSCameron McInally   : UnaryInstruction(Ty, iType, S, InsertAtEnd) {
2203cbde0d9cSCameron McInally   Op<0>() = S;
2204cbde0d9cSCameron McInally   setName(Name);
2205cbde0d9cSCameron McInally   AssertOK();
2206cbde0d9cSCameron McInally }
2207cbde0d9cSCameron McInally 
2208cbde0d9cSCameron McInally UnaryOperator *UnaryOperator::Create(UnaryOps Op, Value *S,
2209cbde0d9cSCameron McInally                                      const Twine &Name,
2210cbde0d9cSCameron McInally                                      Instruction *InsertBefore) {
2211cbde0d9cSCameron McInally   return new UnaryOperator(Op, S, S->getType(), Name, InsertBefore);
2212cbde0d9cSCameron McInally }
2213cbde0d9cSCameron McInally 
2214cbde0d9cSCameron McInally UnaryOperator *UnaryOperator::Create(UnaryOps Op, Value *S,
2215cbde0d9cSCameron McInally                                      const Twine &Name,
2216cbde0d9cSCameron McInally                                      BasicBlock *InsertAtEnd) {
2217cbde0d9cSCameron McInally   UnaryOperator *Res = Create(Op, S, Name);
2218cbde0d9cSCameron McInally   InsertAtEnd->getInstList().push_back(Res);
2219cbde0d9cSCameron McInally   return Res;
2220cbde0d9cSCameron McInally }
2221cbde0d9cSCameron McInally 
2222cbde0d9cSCameron McInally void UnaryOperator::AssertOK() {
2223cbde0d9cSCameron McInally   Value *LHS = getOperand(0);
2224cbde0d9cSCameron McInally   (void)LHS; // Silence warnings.
2225cbde0d9cSCameron McInally #ifndef NDEBUG
2226cbde0d9cSCameron McInally   switch (getOpcode()) {
2227cbde0d9cSCameron McInally   case FNeg:
2228cbde0d9cSCameron McInally     assert(getType() == LHS->getType() &&
2229cbde0d9cSCameron McInally            "Unary operation should return same type as operand!");
2230cbde0d9cSCameron McInally     assert(getType()->isFPOrFPVectorTy() &&
2231cbde0d9cSCameron McInally            "Tried to create a floating-point operation on a "
2232cbde0d9cSCameron McInally            "non-floating-point type!");
2233cbde0d9cSCameron McInally     break;
2234cbde0d9cSCameron McInally   default: llvm_unreachable("Invalid opcode provided");
2235cbde0d9cSCameron McInally   }
2236cbde0d9cSCameron McInally #endif
2237cbde0d9cSCameron McInally }
2238cbde0d9cSCameron McInally 
2239cbde0d9cSCameron McInally //===----------------------------------------------------------------------===//
2240ef860a24SChandler Carruth //                             BinaryOperator Class
2241ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
2242ef860a24SChandler Carruth 
2243ef860a24SChandler Carruth BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
2244ef860a24SChandler Carruth                                Type *Ty, const Twine &Name,
2245ef860a24SChandler Carruth                                Instruction *InsertBefore)
2246ef860a24SChandler Carruth   : Instruction(Ty, iType,
2247ef860a24SChandler Carruth                 OperandTraits<BinaryOperator>::op_begin(this),
2248ef860a24SChandler Carruth                 OperandTraits<BinaryOperator>::operands(this),
2249ef860a24SChandler Carruth                 InsertBefore) {
2250ef860a24SChandler Carruth   Op<0>() = S1;
2251ef860a24SChandler Carruth   Op<1>() = S2;
2252ef860a24SChandler Carruth   setName(Name);
2253700892fdSCraig Topper   AssertOK();
2254ef860a24SChandler Carruth }
2255ef860a24SChandler Carruth 
2256ef860a24SChandler Carruth BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
2257ef860a24SChandler Carruth                                Type *Ty, const Twine &Name,
2258ef860a24SChandler Carruth                                BasicBlock *InsertAtEnd)
2259ef860a24SChandler Carruth   : Instruction(Ty, iType,
2260ef860a24SChandler Carruth                 OperandTraits<BinaryOperator>::op_begin(this),
2261ef860a24SChandler Carruth                 OperandTraits<BinaryOperator>::operands(this),
2262ef860a24SChandler Carruth                 InsertAtEnd) {
2263ef860a24SChandler Carruth   Op<0>() = S1;
2264ef860a24SChandler Carruth   Op<1>() = S2;
2265ef860a24SChandler Carruth   setName(Name);
2266700892fdSCraig Topper   AssertOK();
2267ef860a24SChandler Carruth }
2268ef860a24SChandler Carruth 
2269700892fdSCraig Topper void BinaryOperator::AssertOK() {
2270ef860a24SChandler Carruth   Value *LHS = getOperand(0), *RHS = getOperand(1);
2271ef860a24SChandler Carruth   (void)LHS; (void)RHS; // Silence warnings.
2272ef860a24SChandler Carruth   assert(LHS->getType() == RHS->getType() &&
2273ef860a24SChandler Carruth          "Binary operator operand types must match!");
2274ef860a24SChandler Carruth #ifndef NDEBUG
2275700892fdSCraig Topper   switch (getOpcode()) {
2276ef860a24SChandler Carruth   case Add: case Sub:
2277ef860a24SChandler Carruth   case Mul:
2278ef860a24SChandler Carruth     assert(getType() == LHS->getType() &&
2279ef860a24SChandler Carruth            "Arithmetic operation should return same type as operands!");
2280ef860a24SChandler Carruth     assert(getType()->isIntOrIntVectorTy() &&
2281ef860a24SChandler Carruth            "Tried to create an integer operation on a non-integer type!");
2282ef860a24SChandler Carruth     break;
2283ef860a24SChandler Carruth   case FAdd: case FSub:
2284ef860a24SChandler Carruth   case FMul:
2285ef860a24SChandler Carruth     assert(getType() == LHS->getType() &&
2286ef860a24SChandler Carruth            "Arithmetic operation should return same type as operands!");
2287ef860a24SChandler Carruth     assert(getType()->isFPOrFPVectorTy() &&
2288ef860a24SChandler Carruth            "Tried to create a floating-point operation on a "
2289ef860a24SChandler Carruth            "non-floating-point type!");
2290ef860a24SChandler Carruth     break;
2291ef860a24SChandler Carruth   case UDiv:
2292ef860a24SChandler Carruth   case SDiv:
2293ef860a24SChandler Carruth     assert(getType() == LHS->getType() &&
2294ef860a24SChandler Carruth            "Arithmetic operation should return same type as operands!");
2295d1fbb384SCraig Topper     assert(getType()->isIntOrIntVectorTy() &&
2296ef860a24SChandler Carruth            "Incorrect operand type (not integer) for S/UDIV");
2297ef860a24SChandler Carruth     break;
2298ef860a24SChandler Carruth   case FDiv:
2299ef860a24SChandler Carruth     assert(getType() == LHS->getType() &&
2300ef860a24SChandler Carruth            "Arithmetic operation should return same type as operands!");
2301ef860a24SChandler Carruth     assert(getType()->isFPOrFPVectorTy() &&
2302ef860a24SChandler Carruth            "Incorrect operand type (not floating point) for FDIV");
2303ef860a24SChandler Carruth     break;
2304ef860a24SChandler Carruth   case URem:
2305ef860a24SChandler Carruth   case SRem:
2306ef860a24SChandler Carruth     assert(getType() == LHS->getType() &&
2307ef860a24SChandler Carruth            "Arithmetic operation should return same type as operands!");
2308d1fbb384SCraig Topper     assert(getType()->isIntOrIntVectorTy() &&
2309ef860a24SChandler Carruth            "Incorrect operand type (not integer) for S/UREM");
2310ef860a24SChandler Carruth     break;
2311ef860a24SChandler Carruth   case FRem:
2312ef860a24SChandler Carruth     assert(getType() == LHS->getType() &&
2313ef860a24SChandler Carruth            "Arithmetic operation should return same type as operands!");
2314ef860a24SChandler Carruth     assert(getType()->isFPOrFPVectorTy() &&
2315ef860a24SChandler Carruth            "Incorrect operand type (not floating point) for FREM");
2316ef860a24SChandler Carruth     break;
2317ef860a24SChandler Carruth   case Shl:
2318ef860a24SChandler Carruth   case LShr:
2319ef860a24SChandler Carruth   case AShr:
2320ef860a24SChandler Carruth     assert(getType() == LHS->getType() &&
2321ef860a24SChandler Carruth            "Shift operation should return same type as operands!");
2322d1fbb384SCraig Topper     assert(getType()->isIntOrIntVectorTy() &&
2323ef860a24SChandler Carruth            "Tried to create a shift operation on a non-integral type!");
2324ef860a24SChandler Carruth     break;
2325ef860a24SChandler Carruth   case And: case Or:
2326ef860a24SChandler Carruth   case Xor:
2327ef860a24SChandler Carruth     assert(getType() == LHS->getType() &&
2328ef860a24SChandler Carruth            "Logical operation should return same type as operands!");
2329d1fbb384SCraig Topper     assert(getType()->isIntOrIntVectorTy() &&
2330ef860a24SChandler Carruth            "Tried to create a logical operation on a non-integral type!");
2331ef860a24SChandler Carruth     break;
2332700892fdSCraig Topper   default: llvm_unreachable("Invalid opcode provided");
2333ef860a24SChandler Carruth   }
2334ef860a24SChandler Carruth #endif
2335ef860a24SChandler Carruth }
2336ef860a24SChandler Carruth 
2337ef860a24SChandler Carruth BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2,
2338ef860a24SChandler Carruth                                        const Twine &Name,
2339ef860a24SChandler Carruth                                        Instruction *InsertBefore) {
2340ef860a24SChandler Carruth   assert(S1->getType() == S2->getType() &&
2341ef860a24SChandler Carruth          "Cannot create binary operator with two operands of differing type!");
2342ef860a24SChandler Carruth   return new BinaryOperator(Op, S1, S2, S1->getType(), Name, InsertBefore);
2343ef860a24SChandler Carruth }
2344ef860a24SChandler Carruth 
2345ef860a24SChandler Carruth BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2,
2346ef860a24SChandler Carruth                                        const Twine &Name,
2347ef860a24SChandler Carruth                                        BasicBlock *InsertAtEnd) {
2348ef860a24SChandler Carruth   BinaryOperator *Res = Create(Op, S1, S2, Name);
2349ef860a24SChandler Carruth   InsertAtEnd->getInstList().push_back(Res);
2350ef860a24SChandler Carruth   return Res;
2351ef860a24SChandler Carruth }
2352ef860a24SChandler Carruth 
2353ef860a24SChandler Carruth BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const Twine &Name,
2354ef860a24SChandler Carruth                                           Instruction *InsertBefore) {
2355ef860a24SChandler Carruth   Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
2356ef860a24SChandler Carruth   return new BinaryOperator(Instruction::Sub,
2357ef860a24SChandler Carruth                             zero, Op,
2358ef860a24SChandler Carruth                             Op->getType(), Name, InsertBefore);
2359ef860a24SChandler Carruth }
2360ef860a24SChandler Carruth 
2361ef860a24SChandler Carruth BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const Twine &Name,
2362ef860a24SChandler Carruth                                           BasicBlock *InsertAtEnd) {
2363ef860a24SChandler Carruth   Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
2364ef860a24SChandler Carruth   return new BinaryOperator(Instruction::Sub,
2365ef860a24SChandler Carruth                             zero, Op,
2366ef860a24SChandler Carruth                             Op->getType(), Name, InsertAtEnd);
2367ef860a24SChandler Carruth }
2368ef860a24SChandler Carruth 
2369ef860a24SChandler Carruth BinaryOperator *BinaryOperator::CreateNSWNeg(Value *Op, const Twine &Name,
2370ef860a24SChandler Carruth                                              Instruction *InsertBefore) {
2371ef860a24SChandler Carruth   Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
2372ef860a24SChandler Carruth   return BinaryOperator::CreateNSWSub(zero, Op, Name, InsertBefore);
2373ef860a24SChandler Carruth }
2374ef860a24SChandler Carruth 
2375ef860a24SChandler Carruth BinaryOperator *BinaryOperator::CreateNSWNeg(Value *Op, const Twine &Name,
2376ef860a24SChandler Carruth                                              BasicBlock *InsertAtEnd) {
2377ef860a24SChandler Carruth   Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
2378ef860a24SChandler Carruth   return BinaryOperator::CreateNSWSub(zero, Op, Name, InsertAtEnd);
2379ef860a24SChandler Carruth }
2380ef860a24SChandler Carruth 
2381ef860a24SChandler Carruth BinaryOperator *BinaryOperator::CreateNUWNeg(Value *Op, const Twine &Name,
2382ef860a24SChandler Carruth                                              Instruction *InsertBefore) {
2383ef860a24SChandler Carruth   Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
2384ef860a24SChandler Carruth   return BinaryOperator::CreateNUWSub(zero, Op, Name, InsertBefore);
2385ef860a24SChandler Carruth }
2386ef860a24SChandler Carruth 
2387ef860a24SChandler Carruth BinaryOperator *BinaryOperator::CreateNUWNeg(Value *Op, const Twine &Name,
2388ef860a24SChandler Carruth                                              BasicBlock *InsertAtEnd) {
2389ef860a24SChandler Carruth   Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
2390ef860a24SChandler Carruth   return BinaryOperator::CreateNUWSub(zero, Op, Name, InsertAtEnd);
2391ef860a24SChandler Carruth }
2392ef860a24SChandler Carruth 
2393ef860a24SChandler Carruth BinaryOperator *BinaryOperator::CreateFNeg(Value *Op, const Twine &Name,
2394ef860a24SChandler Carruth                                            Instruction *InsertBefore) {
2395ef860a24SChandler Carruth   Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
2396ef860a24SChandler Carruth   return new BinaryOperator(Instruction::FSub, zero, Op,
2397ef860a24SChandler Carruth                             Op->getType(), Name, InsertBefore);
2398ef860a24SChandler Carruth }
2399ef860a24SChandler Carruth 
2400ef860a24SChandler Carruth BinaryOperator *BinaryOperator::CreateFNeg(Value *Op, const Twine &Name,
2401ef860a24SChandler Carruth                                            BasicBlock *InsertAtEnd) {
2402ef860a24SChandler Carruth   Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
2403ef860a24SChandler Carruth   return new BinaryOperator(Instruction::FSub, zero, Op,
2404ef860a24SChandler Carruth                             Op->getType(), Name, InsertAtEnd);
2405ef860a24SChandler Carruth }
2406ef860a24SChandler Carruth 
2407ef860a24SChandler Carruth BinaryOperator *BinaryOperator::CreateNot(Value *Op, const Twine &Name,
2408ef860a24SChandler Carruth                                           Instruction *InsertBefore) {
2409ef860a24SChandler Carruth   Constant *C = Constant::getAllOnesValue(Op->getType());
2410ef860a24SChandler Carruth   return new BinaryOperator(Instruction::Xor, Op, C,
2411ef860a24SChandler Carruth                             Op->getType(), Name, InsertBefore);
2412ef860a24SChandler Carruth }
2413ef860a24SChandler Carruth 
2414ef860a24SChandler Carruth BinaryOperator *BinaryOperator::CreateNot(Value *Op, const Twine &Name,
2415ef860a24SChandler Carruth                                           BasicBlock *InsertAtEnd) {
2416ef860a24SChandler Carruth   Constant *AllOnes = Constant::getAllOnesValue(Op->getType());
2417ef860a24SChandler Carruth   return new BinaryOperator(Instruction::Xor, Op, AllOnes,
2418ef860a24SChandler Carruth                             Op->getType(), Name, InsertAtEnd);
2419ef860a24SChandler Carruth }
2420ef860a24SChandler Carruth 
24214ce99d4dSSanjay Patel // Exchange the two operands to this instruction. This instruction is safe to
24224ce99d4dSSanjay Patel // use on any binary instruction and does not modify the semantics of the
24234ce99d4dSSanjay Patel // instruction. If the instruction is order-dependent (SetLT f.e.), the opcode
24244ce99d4dSSanjay Patel // is changed.
2425ef860a24SChandler Carruth bool BinaryOperator::swapOperands() {
2426ef860a24SChandler Carruth   if (!isCommutative())
2427ef860a24SChandler Carruth     return true; // Can't commute operands
2428ef860a24SChandler Carruth   Op<0>().swap(Op<1>());
2429ef860a24SChandler Carruth   return false;
2430ef860a24SChandler Carruth }
2431ef860a24SChandler Carruth 
2432ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
2433ef860a24SChandler Carruth //                             FPMathOperator Class
2434ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
2435ef860a24SChandler Carruth 
2436ef860a24SChandler Carruth float FPMathOperator::getFPAccuracy() const {
2437de36e804SDuncan P. N. Exon Smith   const MDNode *MD =
2438de36e804SDuncan P. N. Exon Smith       cast<Instruction>(this)->getMetadata(LLVMContext::MD_fpmath);
2439ef860a24SChandler Carruth   if (!MD)
2440ef860a24SChandler Carruth     return 0.0;
24415bf8fef5SDuncan P. N. Exon Smith   ConstantFP *Accuracy = mdconst::extract<ConstantFP>(MD->getOperand(0));
2442ef860a24SChandler Carruth   return Accuracy->getValueAPF().convertToFloat();
2443ef860a24SChandler Carruth }
2444ef860a24SChandler Carruth 
2445ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
2446ef860a24SChandler Carruth //                                CastInst Class
2447ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
2448ef860a24SChandler Carruth 
2449ef860a24SChandler Carruth // Just determine if this cast only deals with integral->integral conversion.
2450ef860a24SChandler Carruth bool CastInst::isIntegerCast() const {
2451ef860a24SChandler Carruth   switch (getOpcode()) {
2452ef860a24SChandler Carruth     default: return false;
2453ef860a24SChandler Carruth     case Instruction::ZExt:
2454ef860a24SChandler Carruth     case Instruction::SExt:
2455ef860a24SChandler Carruth     case Instruction::Trunc:
2456ef860a24SChandler Carruth       return true;
2457ef860a24SChandler Carruth     case Instruction::BitCast:
2458ef860a24SChandler Carruth       return getOperand(0)->getType()->isIntegerTy() &&
2459ef860a24SChandler Carruth         getType()->isIntegerTy();
2460ef860a24SChandler Carruth   }
2461ef860a24SChandler Carruth }
2462ef860a24SChandler Carruth 
2463ef860a24SChandler Carruth bool CastInst::isLosslessCast() const {
2464ef860a24SChandler Carruth   // Only BitCast can be lossless, exit fast if we're not BitCast
2465ef860a24SChandler Carruth   if (getOpcode() != Instruction::BitCast)
2466ef860a24SChandler Carruth     return false;
2467ef860a24SChandler Carruth 
2468ef860a24SChandler Carruth   // Identity cast is always lossless
2469ef860a24SChandler Carruth   Type *SrcTy = getOperand(0)->getType();
2470ef860a24SChandler Carruth   Type *DstTy = getType();
2471ef860a24SChandler Carruth   if (SrcTy == DstTy)
2472ef860a24SChandler Carruth     return true;
2473ef860a24SChandler Carruth 
2474ef860a24SChandler Carruth   // Pointer to pointer is always lossless.
2475ef860a24SChandler Carruth   if (SrcTy->isPointerTy())
2476ef860a24SChandler Carruth     return DstTy->isPointerTy();
2477ef860a24SChandler Carruth   return false;  // Other types have no identity values
2478ef860a24SChandler Carruth }
2479ef860a24SChandler Carruth 
2480ef860a24SChandler Carruth /// This function determines if the CastInst does not require any bits to be
2481ef860a24SChandler Carruth /// changed in order to effect the cast. Essentially, it identifies cases where
2482ef860a24SChandler Carruth /// no code gen is necessary for the cast, hence the name no-op cast.  For
2483ef860a24SChandler Carruth /// example, the following are all no-op casts:
2484ef860a24SChandler Carruth /// # bitcast i32* %x to i8*
2485ef860a24SChandler Carruth /// # bitcast <2 x i32> %x to <4 x i16>
2486ef860a24SChandler Carruth /// # ptrtoint i32* %x to i32     ; on 32-bit plaforms only
24874dfcc4a7SAdrian Prantl /// Determine if the described cast is a no-op.
2488ef860a24SChandler Carruth bool CastInst::isNoopCast(Instruction::CastOps Opcode,
2489ef860a24SChandler Carruth                           Type *SrcTy,
2490ef860a24SChandler Carruth                           Type *DestTy,
24910ec1d25dSMikael Holmen                           const DataLayout &DL) {
2492ef860a24SChandler Carruth   switch (Opcode) {
2493ef860a24SChandler Carruth     default: llvm_unreachable("Invalid CastOp");
2494ef860a24SChandler Carruth     case Instruction::Trunc:
2495ef860a24SChandler Carruth     case Instruction::ZExt:
2496ef860a24SChandler Carruth     case Instruction::SExt:
2497ef860a24SChandler Carruth     case Instruction::FPTrunc:
2498ef860a24SChandler Carruth     case Instruction::FPExt:
2499ef860a24SChandler Carruth     case Instruction::UIToFP:
2500ef860a24SChandler Carruth     case Instruction::SIToFP:
2501ef860a24SChandler Carruth     case Instruction::FPToUI:
2502ef860a24SChandler Carruth     case Instruction::FPToSI:
2503b03bd4d9SMatt Arsenault     case Instruction::AddrSpaceCast:
2504b03bd4d9SMatt Arsenault       // TODO: Target informations may give a more accurate answer here.
2505b03bd4d9SMatt Arsenault       return false;
2506ef860a24SChandler Carruth     case Instruction::BitCast:
2507ef860a24SChandler Carruth       return true;  // BitCast never modifies bits.
2508ef860a24SChandler Carruth     case Instruction::PtrToInt:
25090ec1d25dSMikael Holmen       return DL.getIntPtrType(SrcTy)->getScalarSizeInBits() ==
2510ef860a24SChandler Carruth              DestTy->getScalarSizeInBits();
2511ef860a24SChandler Carruth     case Instruction::IntToPtr:
25120ec1d25dSMikael Holmen       return DL.getIntPtrType(DestTy)->getScalarSizeInBits() ==
2513ef860a24SChandler Carruth              SrcTy->getScalarSizeInBits();
2514ef860a24SChandler Carruth   }
2515ef860a24SChandler Carruth }
2516ef860a24SChandler Carruth 
2517a28d91d8SMehdi Amini bool CastInst::isNoopCast(const DataLayout &DL) const {
25186efe507eSMikael Holmen   return isNoopCast(getOpcode(), getOperand(0)->getType(), getType(), DL);
2519a236ea55SMatt Arsenault }
2520a236ea55SMatt Arsenault 
2521ef860a24SChandler Carruth /// This function determines if a pair of casts can be eliminated and what
2522ef860a24SChandler Carruth /// opcode should be used in the elimination. This assumes that there are two
2523ef860a24SChandler Carruth /// instructions like this:
2524ef860a24SChandler Carruth /// *  %F = firstOpcode SrcTy %x to MidTy
2525ef860a24SChandler Carruth /// *  %S = secondOpcode MidTy %F to DstTy
2526ef860a24SChandler Carruth /// The function returns a resultOpcode so these two casts can be replaced with:
2527ef860a24SChandler Carruth /// *  %Replacement = resultOpcode %SrcTy %x to DstTy
25284dad27e0SSanjay Patel /// If no such cast is permitted, the function returns 0.
2529ef860a24SChandler Carruth unsigned CastInst::isEliminableCastPair(
2530ef860a24SChandler Carruth   Instruction::CastOps firstOp, Instruction::CastOps secondOp,
2531ef860a24SChandler Carruth   Type *SrcTy, Type *MidTy, Type *DstTy, Type *SrcIntPtrTy, Type *MidIntPtrTy,
2532ef860a24SChandler Carruth   Type *DstIntPtrTy) {
2533ef860a24SChandler Carruth   // Define the 144 possibilities for these two cast instructions. The values
2534ef860a24SChandler Carruth   // in this matrix determine what to do in a given situation and select the
2535ef860a24SChandler Carruth   // case in the switch below.  The rows correspond to firstOp, the columns
2536ef860a24SChandler Carruth   // correspond to secondOp.  In looking at the table below, keep in mind
2537ef860a24SChandler Carruth   // the following cast properties:
2538ef860a24SChandler Carruth   //
2539ef860a24SChandler Carruth   //          Size Compare       Source               Destination
2540ef860a24SChandler Carruth   // Operator  Src ? Size   Type       Sign         Type       Sign
2541ef860a24SChandler Carruth   // -------- ------------ -------------------   ---------------------
2542ef860a24SChandler Carruth   // TRUNC         >       Integer      Any        Integral     Any
2543ef860a24SChandler Carruth   // ZEXT          <       Integral   Unsigned     Integer      Any
2544ef860a24SChandler Carruth   // SEXT          <       Integral    Signed      Integer      Any
2545ef860a24SChandler Carruth   // FPTOUI       n/a      FloatPt      n/a        Integral   Unsigned
2546ef860a24SChandler Carruth   // FPTOSI       n/a      FloatPt      n/a        Integral    Signed
2547ef860a24SChandler Carruth   // UITOFP       n/a      Integral   Unsigned     FloatPt      n/a
2548ef860a24SChandler Carruth   // SITOFP       n/a      Integral    Signed      FloatPt      n/a
2549ef860a24SChandler Carruth   // FPTRUNC       >       FloatPt      n/a        FloatPt      n/a
2550ef860a24SChandler Carruth   // FPEXT         <       FloatPt      n/a        FloatPt      n/a
2551ef860a24SChandler Carruth   // PTRTOINT     n/a      Pointer      n/a        Integral   Unsigned
2552ef860a24SChandler Carruth   // INTTOPTR     n/a      Integral   Unsigned     Pointer      n/a
2553ef860a24SChandler Carruth   // BITCAST       =       FirstClass   n/a       FirstClass    n/a
2554b03bd4d9SMatt Arsenault   // ADDRSPCST    n/a      Pointer      n/a        Pointer      n/a
2555ef860a24SChandler Carruth   //
2556ef860a24SChandler Carruth   // NOTE: some transforms are safe, but we consider them to be non-profitable.
2557ef860a24SChandler Carruth   // For example, we could merge "fptoui double to i32" + "zext i32 to i64",
2558ef860a24SChandler Carruth   // into "fptoui double to i64", but this loses information about the range
2559ef860a24SChandler Carruth   // of the produced value (we no longer know the top-part is all zeros).
2560ef860a24SChandler Carruth   // Further this conversion is often much more expensive for typical hardware,
2561ef860a24SChandler Carruth   // and causes issues when building libgcc.  We disallow fptosi+sext for the
2562ef860a24SChandler Carruth   // same reason.
2563ef860a24SChandler Carruth   const unsigned numCastOps =
2564ef860a24SChandler Carruth     Instruction::CastOpsEnd - Instruction::CastOpsBegin;
2565ef860a24SChandler Carruth   static const uint8_t CastResults[numCastOps][numCastOps] = {
2566b03bd4d9SMatt Arsenault     // T        F  F  U  S  F  F  P  I  B  A  -+
2567b03bd4d9SMatt Arsenault     // R  Z  S  P  P  I  I  T  P  2  N  T  S   |
2568b03bd4d9SMatt Arsenault     // U  E  E  2  2  2  2  R  E  I  T  C  C   +- secondOp
2569b03bd4d9SMatt Arsenault     // N  X  X  U  S  F  F  N  X  N  2  V  V   |
2570b03bd4d9SMatt Arsenault     // C  T  T  I  I  P  P  C  T  T  P  T  T  -+
2571b03bd4d9SMatt Arsenault     {  1, 0, 0,99,99, 0, 0,99,99,99, 0, 3, 0}, // Trunc         -+
25720d41db11SFiona Glaser     {  8, 1, 9,99,99, 2,17,99,99,99, 2, 3, 0}, // ZExt           |
2573b03bd4d9SMatt Arsenault     {  8, 0, 1,99,99, 0, 2,99,99,99, 0, 3, 0}, // SExt           |
2574b03bd4d9SMatt Arsenault     {  0, 0, 0,99,99, 0, 0,99,99,99, 0, 3, 0}, // FPToUI         |
2575b03bd4d9SMatt Arsenault     {  0, 0, 0,99,99, 0, 0,99,99,99, 0, 3, 0}, // FPToSI         |
2576b03bd4d9SMatt Arsenault     { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4, 0}, // UIToFP         +- firstOp
2577b03bd4d9SMatt Arsenault     { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4, 0}, // SIToFP         |
25780ea9d1e7SAhmed Bougacha     { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4, 0}, // FPTrunc        |
257918799f4cSCraig Topper     { 99,99,99, 2, 2,99,99, 8, 2,99,99, 4, 0}, // FPExt          |
2580b03bd4d9SMatt Arsenault     {  1, 0, 0,99,99, 0, 0,99,99,99, 7, 3, 0}, // PtrToInt       |
2581b03bd4d9SMatt Arsenault     { 99,99,99,99,99,99,99,99,99,11,99,15, 0}, // IntToPtr       |
2582b03bd4d9SMatt Arsenault     {  5, 5, 5, 6, 6, 5, 5, 6, 6,16, 5, 1,14}, // BitCast        |
2583b03bd4d9SMatt Arsenault     {  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,13,12}, // AddrSpaceCast -+
2584ef860a24SChandler Carruth   };
2585ef860a24SChandler Carruth 
258693f55dd3SSanjay Patel   // TODO: This logic could be encoded into the table above and handled in the
258793f55dd3SSanjay Patel   // switch below.
2588ef860a24SChandler Carruth   // If either of the casts are a bitcast from scalar to vector, disallow the
258993f55dd3SSanjay Patel   // merging. However, any pair of bitcasts are allowed.
259093f55dd3SSanjay Patel   bool IsFirstBitcast  = (firstOp == Instruction::BitCast);
259193f55dd3SSanjay Patel   bool IsSecondBitcast = (secondOp == Instruction::BitCast);
259293f55dd3SSanjay Patel   bool AreBothBitcasts = IsFirstBitcast && IsSecondBitcast;
2593ef860a24SChandler Carruth 
259493f55dd3SSanjay Patel   // Check if any of the casts convert scalars <-> vectors.
259593f55dd3SSanjay Patel   if ((IsFirstBitcast  && isa<VectorType>(SrcTy) != isa<VectorType>(MidTy)) ||
259693f55dd3SSanjay Patel       (IsSecondBitcast && isa<VectorType>(MidTy) != isa<VectorType>(DstTy)))
259793f55dd3SSanjay Patel     if (!AreBothBitcasts)
259893f55dd3SSanjay Patel       return 0;
2599ef860a24SChandler Carruth 
2600ef860a24SChandler Carruth   int ElimCase = CastResults[firstOp-Instruction::CastOpsBegin]
2601ef860a24SChandler Carruth                             [secondOp-Instruction::CastOpsBegin];
2602ef860a24SChandler Carruth   switch (ElimCase) {
2603ef860a24SChandler Carruth     case 0:
2604b03bd4d9SMatt Arsenault       // Categorically disallowed.
2605ef860a24SChandler Carruth       return 0;
2606ef860a24SChandler Carruth     case 1:
2607b03bd4d9SMatt Arsenault       // Allowed, use first cast's opcode.
2608ef860a24SChandler Carruth       return firstOp;
2609ef860a24SChandler Carruth     case 2:
2610b03bd4d9SMatt Arsenault       // Allowed, use second cast's opcode.
2611ef860a24SChandler Carruth       return secondOp;
2612ef860a24SChandler Carruth     case 3:
2613b03bd4d9SMatt Arsenault       // No-op cast in second op implies firstOp as long as the DestTy
2614ef860a24SChandler Carruth       // is integer and we are not converting between a vector and a
2615f907b891SAlp Toker       // non-vector type.
2616ef860a24SChandler Carruth       if (!SrcTy->isVectorTy() && DstTy->isIntegerTy())
2617ef860a24SChandler Carruth         return firstOp;
2618ef860a24SChandler Carruth       return 0;
2619ef860a24SChandler Carruth     case 4:
2620b03bd4d9SMatt Arsenault       // No-op cast in second op implies firstOp as long as the DestTy
2621ef860a24SChandler Carruth       // is floating point.
2622ef860a24SChandler Carruth       if (DstTy->isFloatingPointTy())
2623ef860a24SChandler Carruth         return firstOp;
2624ef860a24SChandler Carruth       return 0;
2625ef860a24SChandler Carruth     case 5:
2626b03bd4d9SMatt Arsenault       // No-op cast in first op implies secondOp as long as the SrcTy
2627ef860a24SChandler Carruth       // is an integer.
2628ef860a24SChandler Carruth       if (SrcTy->isIntegerTy())
2629ef860a24SChandler Carruth         return secondOp;
2630ef860a24SChandler Carruth       return 0;
2631ef860a24SChandler Carruth     case 6:
2632b03bd4d9SMatt Arsenault       // No-op cast in first op implies secondOp as long as the SrcTy
2633ef860a24SChandler Carruth       // is a floating point.
2634ef860a24SChandler Carruth       if (SrcTy->isFloatingPointTy())
2635ef860a24SChandler Carruth         return secondOp;
2636ef860a24SChandler Carruth       return 0;
2637ef860a24SChandler Carruth     case 7: {
2638b03bd4d9SMatt Arsenault       // Cannot simplify if address spaces are different!
2639b03bd4d9SMatt Arsenault       if (SrcTy->getPointerAddressSpace() != DstTy->getPointerAddressSpace())
2640b03bd4d9SMatt Arsenault         return 0;
2641b03bd4d9SMatt Arsenault 
2642130e0ef6SMatt Arsenault       unsigned MidSize = MidTy->getScalarSizeInBits();
2643b03bd4d9SMatt Arsenault       // We can still fold this without knowing the actual sizes as long we
2644b03bd4d9SMatt Arsenault       // know that the intermediate pointer is the largest possible
2645b03bd4d9SMatt Arsenault       // pointer size.
2646b03bd4d9SMatt Arsenault       // FIXME: Is this always true?
2647b03bd4d9SMatt Arsenault       if (MidSize == 64)
2648130e0ef6SMatt Arsenault         return Instruction::BitCast;
2649130e0ef6SMatt Arsenault 
2650130e0ef6SMatt Arsenault       // ptrtoint, inttoptr -> bitcast (ptr -> ptr) if int size is >= ptr size.
2651ef860a24SChandler Carruth       if (!SrcIntPtrTy || DstIntPtrTy != SrcIntPtrTy)
2652ef860a24SChandler Carruth         return 0;
2653ef860a24SChandler Carruth       unsigned PtrSize = SrcIntPtrTy->getScalarSizeInBits();
2654ef860a24SChandler Carruth       if (MidSize >= PtrSize)
2655ef860a24SChandler Carruth         return Instruction::BitCast;
2656ef860a24SChandler Carruth       return 0;
2657ef860a24SChandler Carruth     }
2658ef860a24SChandler Carruth     case 8: {
2659ef860a24SChandler Carruth       // ext, trunc -> bitcast,    if the SrcTy and DstTy are same size
2660ef860a24SChandler Carruth       // ext, trunc -> ext,        if sizeof(SrcTy) < sizeof(DstTy)
2661ef860a24SChandler Carruth       // ext, trunc -> trunc,      if sizeof(SrcTy) > sizeof(DstTy)
2662ef860a24SChandler Carruth       unsigned SrcSize = SrcTy->getScalarSizeInBits();
2663ef860a24SChandler Carruth       unsigned DstSize = DstTy->getScalarSizeInBits();
2664ef860a24SChandler Carruth       if (SrcSize == DstSize)
2665ef860a24SChandler Carruth         return Instruction::BitCast;
2666ef860a24SChandler Carruth       else if (SrcSize < DstSize)
2667ef860a24SChandler Carruth         return firstOp;
2668ef860a24SChandler Carruth       return secondOp;
2669ef860a24SChandler Carruth     }
2670b03bd4d9SMatt Arsenault     case 9:
2671b03bd4d9SMatt Arsenault       // zext, sext -> zext, because sext can't sign extend after zext
2672ef860a24SChandler Carruth       return Instruction::ZExt;
2673130e0ef6SMatt Arsenault     case 11: {
2674ef860a24SChandler Carruth       // inttoptr, ptrtoint -> bitcast if SrcSize<=PtrSize and SrcSize==DstSize
2675ef860a24SChandler Carruth       if (!MidIntPtrTy)
2676ef860a24SChandler Carruth         return 0;
2677ef860a24SChandler Carruth       unsigned PtrSize = MidIntPtrTy->getScalarSizeInBits();
2678ef860a24SChandler Carruth       unsigned SrcSize = SrcTy->getScalarSizeInBits();
2679ef860a24SChandler Carruth       unsigned DstSize = DstTy->getScalarSizeInBits();
2680ef860a24SChandler Carruth       if (SrcSize <= PtrSize && SrcSize == DstSize)
2681ef860a24SChandler Carruth         return Instruction::BitCast;
2682ef860a24SChandler Carruth       return 0;
2683ef860a24SChandler Carruth     }
2684d761e2c2SEugene Zelenko     case 12:
2685b03bd4d9SMatt Arsenault       // addrspacecast, addrspacecast -> bitcast,       if SrcAS == DstAS
2686b03bd4d9SMatt Arsenault       // addrspacecast, addrspacecast -> addrspacecast, if SrcAS != DstAS
2687b03bd4d9SMatt Arsenault       if (SrcTy->getPointerAddressSpace() != DstTy->getPointerAddressSpace())
2688b03bd4d9SMatt Arsenault         return Instruction::AddrSpaceCast;
2689b03bd4d9SMatt Arsenault       return Instruction::BitCast;
2690b03bd4d9SMatt Arsenault     case 13:
2691b03bd4d9SMatt Arsenault       // FIXME: this state can be merged with (1), but the following assert
2692b03bd4d9SMatt Arsenault       // is useful to check the correcteness of the sequence due to semantic
2693b03bd4d9SMatt Arsenault       // change of bitcast.
2694b03bd4d9SMatt Arsenault       assert(
2695b03bd4d9SMatt Arsenault         SrcTy->isPtrOrPtrVectorTy() &&
2696b03bd4d9SMatt Arsenault         MidTy->isPtrOrPtrVectorTy() &&
2697b03bd4d9SMatt Arsenault         DstTy->isPtrOrPtrVectorTy() &&
2698b03bd4d9SMatt Arsenault         SrcTy->getPointerAddressSpace() != MidTy->getPointerAddressSpace() &&
2699b03bd4d9SMatt Arsenault         MidTy->getPointerAddressSpace() == DstTy->getPointerAddressSpace() &&
2700b03bd4d9SMatt Arsenault         "Illegal addrspacecast, bitcast sequence!");
2701b03bd4d9SMatt Arsenault       // Allowed, use first cast's opcode
2702b03bd4d9SMatt Arsenault       return firstOp;
2703b03bd4d9SMatt Arsenault     case 14:
270477145d94SJingyue Wu       // bitcast, addrspacecast -> addrspacecast if the element type of
270577145d94SJingyue Wu       // bitcast's source is the same as that of addrspacecast's destination.
27069d5fd4dbSPeter Collingbourne       if (SrcTy->getScalarType()->getPointerElementType() ==
27079d5fd4dbSPeter Collingbourne           DstTy->getScalarType()->getPointerElementType())
270877145d94SJingyue Wu         return Instruction::AddrSpaceCast;
270977145d94SJingyue Wu       return 0;
2710b03bd4d9SMatt Arsenault     case 15:
2711b03bd4d9SMatt Arsenault       // FIXME: this state can be merged with (1), but the following assert
2712b03bd4d9SMatt Arsenault       // is useful to check the correcteness of the sequence due to semantic
2713b03bd4d9SMatt Arsenault       // change of bitcast.
2714b03bd4d9SMatt Arsenault       assert(
2715b03bd4d9SMatt Arsenault         SrcTy->isIntOrIntVectorTy() &&
2716b03bd4d9SMatt Arsenault         MidTy->isPtrOrPtrVectorTy() &&
2717b03bd4d9SMatt Arsenault         DstTy->isPtrOrPtrVectorTy() &&
2718b03bd4d9SMatt Arsenault         MidTy->getPointerAddressSpace() == DstTy->getPointerAddressSpace() &&
2719b03bd4d9SMatt Arsenault         "Illegal inttoptr, bitcast sequence!");
2720b03bd4d9SMatt Arsenault       // Allowed, use first cast's opcode
2721b03bd4d9SMatt Arsenault       return firstOp;
2722b03bd4d9SMatt Arsenault     case 16:
2723b03bd4d9SMatt Arsenault       // FIXME: this state can be merged with (2), but the following assert
2724b03bd4d9SMatt Arsenault       // is useful to check the correcteness of the sequence due to semantic
2725b03bd4d9SMatt Arsenault       // change of bitcast.
2726b03bd4d9SMatt Arsenault       assert(
2727b03bd4d9SMatt Arsenault         SrcTy->isPtrOrPtrVectorTy() &&
2728b03bd4d9SMatt Arsenault         MidTy->isPtrOrPtrVectorTy() &&
2729b03bd4d9SMatt Arsenault         DstTy->isIntOrIntVectorTy() &&
2730b03bd4d9SMatt Arsenault         SrcTy->getPointerAddressSpace() == MidTy->getPointerAddressSpace() &&
2731b03bd4d9SMatt Arsenault         "Illegal bitcast, ptrtoint sequence!");
2732b03bd4d9SMatt Arsenault       // Allowed, use second cast's opcode
2733b03bd4d9SMatt Arsenault       return secondOp;
27340d41db11SFiona Glaser     case 17:
27350d41db11SFiona Glaser       // (sitofp (zext x)) -> (uitofp x)
27360d41db11SFiona Glaser       return Instruction::UIToFP;
2737ef860a24SChandler Carruth     case 99:
2738b03bd4d9SMatt Arsenault       // Cast combination can't happen (error in input). This is for all cases
2739ef860a24SChandler Carruth       // where the MidTy is not the same for the two cast instructions.
2740ef860a24SChandler Carruth       llvm_unreachable("Invalid Cast Combination");
2741ef860a24SChandler Carruth     default:
2742ef860a24SChandler Carruth       llvm_unreachable("Error in CastResults table!!!");
2743ef860a24SChandler Carruth   }
2744ef860a24SChandler Carruth }
2745ef860a24SChandler Carruth 
2746ef860a24SChandler Carruth CastInst *CastInst::Create(Instruction::CastOps op, Value *S, Type *Ty,
2747ef860a24SChandler Carruth   const Twine &Name, Instruction *InsertBefore) {
2748ef860a24SChandler Carruth   assert(castIsValid(op, S, Ty) && "Invalid cast!");
2749ef860a24SChandler Carruth   // Construct and return the appropriate CastInst subclass
2750ef860a24SChandler Carruth   switch (op) {
2751ef860a24SChandler Carruth   case Trunc:         return new TruncInst         (S, Ty, Name, InsertBefore);
2752ef860a24SChandler Carruth   case ZExt:          return new ZExtInst          (S, Ty, Name, InsertBefore);
2753ef860a24SChandler Carruth   case SExt:          return new SExtInst          (S, Ty, Name, InsertBefore);
2754ef860a24SChandler Carruth   case FPTrunc:       return new FPTruncInst       (S, Ty, Name, InsertBefore);
2755ef860a24SChandler Carruth   case FPExt:         return new FPExtInst         (S, Ty, Name, InsertBefore);
2756ef860a24SChandler Carruth   case UIToFP:        return new UIToFPInst        (S, Ty, Name, InsertBefore);
2757ef860a24SChandler Carruth   case SIToFP:        return new SIToFPInst        (S, Ty, Name, InsertBefore);
2758ef860a24SChandler Carruth   case FPToUI:        return new FPToUIInst        (S, Ty, Name, InsertBefore);
2759ef860a24SChandler Carruth   case FPToSI:        return new FPToSIInst        (S, Ty, Name, InsertBefore);
2760ef860a24SChandler Carruth   case PtrToInt:      return new PtrToIntInst      (S, Ty, Name, InsertBefore);
2761ef860a24SChandler Carruth   case IntToPtr:      return new IntToPtrInst      (S, Ty, Name, InsertBefore);
2762ef860a24SChandler Carruth   case BitCast:       return new BitCastInst       (S, Ty, Name, InsertBefore);
2763b03bd4d9SMatt Arsenault   case AddrSpaceCast: return new AddrSpaceCastInst (S, Ty, Name, InsertBefore);
2764ef860a24SChandler Carruth   default: llvm_unreachable("Invalid opcode provided");
2765ef860a24SChandler Carruth   }
2766ef860a24SChandler Carruth }
2767ef860a24SChandler Carruth 
2768ef860a24SChandler Carruth CastInst *CastInst::Create(Instruction::CastOps op, Value *S, Type *Ty,
2769ef860a24SChandler Carruth   const Twine &Name, BasicBlock *InsertAtEnd) {
2770ef860a24SChandler Carruth   assert(castIsValid(op, S, Ty) && "Invalid cast!");
2771ef860a24SChandler Carruth   // Construct and return the appropriate CastInst subclass
2772ef860a24SChandler Carruth   switch (op) {
2773ef860a24SChandler Carruth   case Trunc:         return new TruncInst         (S, Ty, Name, InsertAtEnd);
2774ef860a24SChandler Carruth   case ZExt:          return new ZExtInst          (S, Ty, Name, InsertAtEnd);
2775ef860a24SChandler Carruth   case SExt:          return new SExtInst          (S, Ty, Name, InsertAtEnd);
2776ef860a24SChandler Carruth   case FPTrunc:       return new FPTruncInst       (S, Ty, Name, InsertAtEnd);
2777ef860a24SChandler Carruth   case FPExt:         return new FPExtInst         (S, Ty, Name, InsertAtEnd);
2778ef860a24SChandler Carruth   case UIToFP:        return new UIToFPInst        (S, Ty, Name, InsertAtEnd);
2779ef860a24SChandler Carruth   case SIToFP:        return new SIToFPInst        (S, Ty, Name, InsertAtEnd);
2780ef860a24SChandler Carruth   case FPToUI:        return new FPToUIInst        (S, Ty, Name, InsertAtEnd);
2781ef860a24SChandler Carruth   case FPToSI:        return new FPToSIInst        (S, Ty, Name, InsertAtEnd);
2782ef860a24SChandler Carruth   case PtrToInt:      return new PtrToIntInst      (S, Ty, Name, InsertAtEnd);
2783ef860a24SChandler Carruth   case IntToPtr:      return new IntToPtrInst      (S, Ty, Name, InsertAtEnd);
2784ef860a24SChandler Carruth   case BitCast:       return new BitCastInst       (S, Ty, Name, InsertAtEnd);
2785b03bd4d9SMatt Arsenault   case AddrSpaceCast: return new AddrSpaceCastInst (S, Ty, Name, InsertAtEnd);
2786ef860a24SChandler Carruth   default: llvm_unreachable("Invalid opcode provided");
2787ef860a24SChandler Carruth   }
2788ef860a24SChandler Carruth }
2789ef860a24SChandler Carruth 
2790ef860a24SChandler Carruth CastInst *CastInst::CreateZExtOrBitCast(Value *S, Type *Ty,
2791ef860a24SChandler Carruth                                         const Twine &Name,
2792ef860a24SChandler Carruth                                         Instruction *InsertBefore) {
2793ef860a24SChandler Carruth   if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2794ef860a24SChandler Carruth     return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2795ef860a24SChandler Carruth   return Create(Instruction::ZExt, S, Ty, Name, InsertBefore);
2796ef860a24SChandler Carruth }
2797ef860a24SChandler Carruth 
2798ef860a24SChandler Carruth CastInst *CastInst::CreateZExtOrBitCast(Value *S, Type *Ty,
2799ef860a24SChandler Carruth                                         const Twine &Name,
2800ef860a24SChandler Carruth                                         BasicBlock *InsertAtEnd) {
2801ef860a24SChandler Carruth   if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2802ef860a24SChandler Carruth     return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2803ef860a24SChandler Carruth   return Create(Instruction::ZExt, S, Ty, Name, InsertAtEnd);
2804ef860a24SChandler Carruth }
2805ef860a24SChandler Carruth 
2806ef860a24SChandler Carruth CastInst *CastInst::CreateSExtOrBitCast(Value *S, Type *Ty,
2807ef860a24SChandler Carruth                                         const Twine &Name,
2808ef860a24SChandler Carruth                                         Instruction *InsertBefore) {
2809ef860a24SChandler Carruth   if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2810ef860a24SChandler Carruth     return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2811ef860a24SChandler Carruth   return Create(Instruction::SExt, S, Ty, Name, InsertBefore);
2812ef860a24SChandler Carruth }
2813ef860a24SChandler Carruth 
2814ef860a24SChandler Carruth CastInst *CastInst::CreateSExtOrBitCast(Value *S, Type *Ty,
2815ef860a24SChandler Carruth                                         const Twine &Name,
2816ef860a24SChandler Carruth                                         BasicBlock *InsertAtEnd) {
2817ef860a24SChandler Carruth   if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2818ef860a24SChandler Carruth     return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2819ef860a24SChandler Carruth   return Create(Instruction::SExt, S, Ty, Name, InsertAtEnd);
2820ef860a24SChandler Carruth }
2821ef860a24SChandler Carruth 
2822ef860a24SChandler Carruth CastInst *CastInst::CreateTruncOrBitCast(Value *S, Type *Ty,
2823ef860a24SChandler Carruth                                          const Twine &Name,
2824ef860a24SChandler Carruth                                          Instruction *InsertBefore) {
2825ef860a24SChandler Carruth   if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2826ef860a24SChandler Carruth     return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2827ef860a24SChandler Carruth   return Create(Instruction::Trunc, S, Ty, Name, InsertBefore);
2828ef860a24SChandler Carruth }
2829ef860a24SChandler Carruth 
2830ef860a24SChandler Carruth CastInst *CastInst::CreateTruncOrBitCast(Value *S, Type *Ty,
2831ef860a24SChandler Carruth                                          const Twine &Name,
2832ef860a24SChandler Carruth                                          BasicBlock *InsertAtEnd) {
2833ef860a24SChandler Carruth   if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2834ef860a24SChandler Carruth     return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2835ef860a24SChandler Carruth   return Create(Instruction::Trunc, S, Ty, Name, InsertAtEnd);
2836ef860a24SChandler Carruth }
2837ef860a24SChandler Carruth 
2838ef860a24SChandler Carruth CastInst *CastInst::CreatePointerCast(Value *S, Type *Ty,
2839ef860a24SChandler Carruth                                       const Twine &Name,
2840ef860a24SChandler Carruth                                       BasicBlock *InsertAtEnd) {
2841065ced9bSMatt Arsenault   assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
2842065ced9bSMatt Arsenault   assert((Ty->isIntOrIntVectorTy() || Ty->isPtrOrPtrVectorTy()) &&
2843065ced9bSMatt Arsenault          "Invalid cast");
2844065ced9bSMatt Arsenault   assert(Ty->isVectorTy() == S->getType()->isVectorTy() && "Invalid cast");
28458dc43231SRichard Trieu   assert((!Ty->isVectorTy() ||
28468dc43231SRichard Trieu           Ty->getVectorNumElements() == S->getType()->getVectorNumElements()) &&
2847ef860a24SChandler Carruth          "Invalid cast");
2848ef860a24SChandler Carruth 
2849065ced9bSMatt Arsenault   if (Ty->isIntOrIntVectorTy())
2850ef860a24SChandler Carruth     return Create(Instruction::PtrToInt, S, Ty, Name, InsertAtEnd);
2851b03bd4d9SMatt Arsenault 
2852740980eeSMatt Arsenault   return CreatePointerBitCastOrAddrSpaceCast(S, Ty, Name, InsertAtEnd);
2853ef860a24SChandler Carruth }
2854ef860a24SChandler Carruth 
28554dfcc4a7SAdrian Prantl /// Create a BitCast or a PtrToInt cast instruction
2856ef860a24SChandler Carruth CastInst *CastInst::CreatePointerCast(Value *S, Type *Ty,
2857ef860a24SChandler Carruth                                       const Twine &Name,
2858ef860a24SChandler Carruth                                       Instruction *InsertBefore) {
2859c9bd35b1SEvgeniy Stepanov   assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
2860c9bd35b1SEvgeniy Stepanov   assert((Ty->isIntOrIntVectorTy() || Ty->isPtrOrPtrVectorTy()) &&
2861ef860a24SChandler Carruth          "Invalid cast");
2862065ced9bSMatt Arsenault   assert(Ty->isVectorTy() == S->getType()->isVectorTy() && "Invalid cast");
28638dc43231SRichard Trieu   assert((!Ty->isVectorTy() ||
28648dc43231SRichard Trieu           Ty->getVectorNumElements() == S->getType()->getVectorNumElements()) &&
2865065ced9bSMatt Arsenault          "Invalid cast");
2866ef860a24SChandler Carruth 
2867c9bd35b1SEvgeniy Stepanov   if (Ty->isIntOrIntVectorTy())
2868ef860a24SChandler Carruth     return Create(Instruction::PtrToInt, S, Ty, Name, InsertBefore);
2869b03bd4d9SMatt Arsenault 
2870740980eeSMatt Arsenault   return CreatePointerBitCastOrAddrSpaceCast(S, Ty, Name, InsertBefore);
2871740980eeSMatt Arsenault }
2872740980eeSMatt Arsenault 
2873740980eeSMatt Arsenault CastInst *CastInst::CreatePointerBitCastOrAddrSpaceCast(
2874740980eeSMatt Arsenault   Value *S, Type *Ty,
2875740980eeSMatt Arsenault   const Twine &Name,
2876740980eeSMatt Arsenault   BasicBlock *InsertAtEnd) {
2877740980eeSMatt Arsenault   assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
2878740980eeSMatt Arsenault   assert(Ty->isPtrOrPtrVectorTy() && "Invalid cast");
2879740980eeSMatt Arsenault 
2880740980eeSMatt Arsenault   if (S->getType()->getPointerAddressSpace() != Ty->getPointerAddressSpace())
2881740980eeSMatt Arsenault     return Create(Instruction::AddrSpaceCast, S, Ty, Name, InsertAtEnd);
2882740980eeSMatt Arsenault 
2883740980eeSMatt Arsenault   return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2884740980eeSMatt Arsenault }
2885740980eeSMatt Arsenault 
2886740980eeSMatt Arsenault CastInst *CastInst::CreatePointerBitCastOrAddrSpaceCast(
2887740980eeSMatt Arsenault   Value *S, Type *Ty,
2888740980eeSMatt Arsenault   const Twine &Name,
2889740980eeSMatt Arsenault   Instruction *InsertBefore) {
2890740980eeSMatt Arsenault   assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
2891740980eeSMatt Arsenault   assert(Ty->isPtrOrPtrVectorTy() && "Invalid cast");
2892740980eeSMatt Arsenault 
2893740980eeSMatt Arsenault   if (S->getType()->getPointerAddressSpace() != Ty->getPointerAddressSpace())
2894b03bd4d9SMatt Arsenault     return Create(Instruction::AddrSpaceCast, S, Ty, Name, InsertBefore);
2895b03bd4d9SMatt Arsenault 
2896ef860a24SChandler Carruth   return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2897ef860a24SChandler Carruth }
2898ef860a24SChandler Carruth 
28991a3c2c41SChandler Carruth CastInst *CastInst::CreateBitOrPointerCast(Value *S, Type *Ty,
29001a3c2c41SChandler Carruth                                            const Twine &Name,
29011a3c2c41SChandler Carruth                                            Instruction *InsertBefore) {
29021a3c2c41SChandler Carruth   if (S->getType()->isPointerTy() && Ty->isIntegerTy())
29031a3c2c41SChandler Carruth     return Create(Instruction::PtrToInt, S, Ty, Name, InsertBefore);
29041a3c2c41SChandler Carruth   if (S->getType()->isIntegerTy() && Ty->isPointerTy())
29051a3c2c41SChandler Carruth     return Create(Instruction::IntToPtr, S, Ty, Name, InsertBefore);
29061a3c2c41SChandler Carruth 
29071a3c2c41SChandler Carruth   return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
29081a3c2c41SChandler Carruth }
29091a3c2c41SChandler Carruth 
2910ef860a24SChandler Carruth CastInst *CastInst::CreateIntegerCast(Value *C, Type *Ty,
2911ef860a24SChandler Carruth                                       bool isSigned, const Twine &Name,
2912ef860a24SChandler Carruth                                       Instruction *InsertBefore) {
2913ef860a24SChandler Carruth   assert(C->getType()->isIntOrIntVectorTy() && Ty->isIntOrIntVectorTy() &&
2914ef860a24SChandler Carruth          "Invalid integer cast");
2915ef860a24SChandler Carruth   unsigned SrcBits = C->getType()->getScalarSizeInBits();
2916ef860a24SChandler Carruth   unsigned DstBits = Ty->getScalarSizeInBits();
2917ef860a24SChandler Carruth   Instruction::CastOps opcode =
2918ef860a24SChandler Carruth     (SrcBits == DstBits ? Instruction::BitCast :
2919ef860a24SChandler Carruth      (SrcBits > DstBits ? Instruction::Trunc :
2920ef860a24SChandler Carruth       (isSigned ? Instruction::SExt : Instruction::ZExt)));
2921ef860a24SChandler Carruth   return Create(opcode, C, Ty, Name, InsertBefore);
2922ef860a24SChandler Carruth }
2923ef860a24SChandler Carruth 
2924ef860a24SChandler Carruth CastInst *CastInst::CreateIntegerCast(Value *C, Type *Ty,
2925ef860a24SChandler Carruth                                       bool isSigned, const Twine &Name,
2926ef860a24SChandler Carruth                                       BasicBlock *InsertAtEnd) {
2927ef860a24SChandler Carruth   assert(C->getType()->isIntOrIntVectorTy() && Ty->isIntOrIntVectorTy() &&
2928ef860a24SChandler Carruth          "Invalid cast");
2929ef860a24SChandler Carruth   unsigned SrcBits = C->getType()->getScalarSizeInBits();
2930ef860a24SChandler Carruth   unsigned DstBits = Ty->getScalarSizeInBits();
2931ef860a24SChandler Carruth   Instruction::CastOps opcode =
2932ef860a24SChandler Carruth     (SrcBits == DstBits ? Instruction::BitCast :
2933ef860a24SChandler Carruth      (SrcBits > DstBits ? Instruction::Trunc :
2934ef860a24SChandler Carruth       (isSigned ? Instruction::SExt : Instruction::ZExt)));
2935ef860a24SChandler Carruth   return Create(opcode, C, Ty, Name, InsertAtEnd);
2936ef860a24SChandler Carruth }
2937ef860a24SChandler Carruth 
2938ef860a24SChandler Carruth CastInst *CastInst::CreateFPCast(Value *C, Type *Ty,
2939ef860a24SChandler Carruth                                  const Twine &Name,
2940ef860a24SChandler Carruth                                  Instruction *InsertBefore) {
2941ef860a24SChandler Carruth   assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
2942ef860a24SChandler Carruth          "Invalid cast");
2943ef860a24SChandler Carruth   unsigned SrcBits = C->getType()->getScalarSizeInBits();
2944ef860a24SChandler Carruth   unsigned DstBits = Ty->getScalarSizeInBits();
2945ef860a24SChandler Carruth   Instruction::CastOps opcode =
2946ef860a24SChandler Carruth     (SrcBits == DstBits ? Instruction::BitCast :
2947ef860a24SChandler Carruth      (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
2948ef860a24SChandler Carruth   return Create(opcode, C, Ty, Name, InsertBefore);
2949ef860a24SChandler Carruth }
2950ef860a24SChandler Carruth 
2951ef860a24SChandler Carruth CastInst *CastInst::CreateFPCast(Value *C, Type *Ty,
2952ef860a24SChandler Carruth                                  const Twine &Name,
2953ef860a24SChandler Carruth                                  BasicBlock *InsertAtEnd) {
2954ef860a24SChandler Carruth   assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
2955ef860a24SChandler Carruth          "Invalid cast");
2956ef860a24SChandler Carruth   unsigned SrcBits = C->getType()->getScalarSizeInBits();
2957ef860a24SChandler Carruth   unsigned DstBits = Ty->getScalarSizeInBits();
2958ef860a24SChandler Carruth   Instruction::CastOps opcode =
2959ef860a24SChandler Carruth     (SrcBits == DstBits ? Instruction::BitCast :
2960ef860a24SChandler Carruth      (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
2961ef860a24SChandler Carruth   return Create(opcode, C, Ty, Name, InsertAtEnd);
2962ef860a24SChandler Carruth }
2963ef860a24SChandler Carruth 
2964b4019ae1SMatt Arsenault // Check whether it is valid to call getCastOpcode for these types.
2965b4019ae1SMatt Arsenault // This routine must be kept in sync with getCastOpcode.
2966b4019ae1SMatt Arsenault bool CastInst::isCastable(Type *SrcTy, Type *DestTy) {
2967b4019ae1SMatt Arsenault   if (!SrcTy->isFirstClassType() || !DestTy->isFirstClassType())
2968b4019ae1SMatt Arsenault     return false;
2969b4019ae1SMatt Arsenault 
2970b4019ae1SMatt Arsenault   if (SrcTy == DestTy)
2971b4019ae1SMatt Arsenault     return true;
2972b4019ae1SMatt Arsenault 
2973b4019ae1SMatt Arsenault   if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy))
2974b4019ae1SMatt Arsenault     if (VectorType *DestVecTy = dyn_cast<VectorType>(DestTy))
2975b4019ae1SMatt Arsenault       if (SrcVecTy->getNumElements() == DestVecTy->getNumElements()) {
2976b4019ae1SMatt Arsenault         // An element by element cast.  Valid if casting the elements is valid.
2977b4019ae1SMatt Arsenault         SrcTy = SrcVecTy->getElementType();
2978b4019ae1SMatt Arsenault         DestTy = DestVecTy->getElementType();
2979b4019ae1SMatt Arsenault       }
2980b4019ae1SMatt Arsenault 
2981b4019ae1SMatt Arsenault   // Get the bit sizes, we'll need these
2982f998fa29SGraham Hunter   TypeSize SrcBits = SrcTy->getPrimitiveSizeInBits();   // 0 for ptr
2983f998fa29SGraham Hunter   TypeSize DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr
2984b4019ae1SMatt Arsenault 
2985b4019ae1SMatt Arsenault   // Run through the possibilities ...
2986b4019ae1SMatt Arsenault   if (DestTy->isIntegerTy()) {               // Casting to integral
29879965c5aeSDavid Blaikie     if (SrcTy->isIntegerTy())                // Casting from integral
2988b4019ae1SMatt Arsenault         return true;
29899965c5aeSDavid Blaikie     if (SrcTy->isFloatingPointTy())   // Casting from floating pt
2990b4019ae1SMatt Arsenault       return true;
29919965c5aeSDavid Blaikie     if (SrcTy->isVectorTy())          // Casting from vector
2992b4019ae1SMatt Arsenault       return DestBits == SrcBits;
29939965c5aeSDavid Blaikie                                       // Casting from something else
2994b4019ae1SMatt Arsenault     return SrcTy->isPointerTy();
2995b4019ae1SMatt Arsenault   }
29969965c5aeSDavid Blaikie   if (DestTy->isFloatingPointTy()) {  // Casting to floating pt
29979965c5aeSDavid Blaikie     if (SrcTy->isIntegerTy())                // Casting from integral
2998b4019ae1SMatt Arsenault       return true;
29999965c5aeSDavid Blaikie     if (SrcTy->isFloatingPointTy())   // Casting from floating pt
3000b4019ae1SMatt Arsenault       return true;
30019965c5aeSDavid Blaikie     if (SrcTy->isVectorTy())          // Casting from vector
3002b4019ae1SMatt Arsenault       return DestBits == SrcBits;
30039965c5aeSDavid Blaikie                                     // Casting from something else
3004b4019ae1SMatt Arsenault     return false;
3005b4019ae1SMatt Arsenault   }
30069965c5aeSDavid Blaikie   if (DestTy->isVectorTy())         // Casting to vector
3007b4019ae1SMatt Arsenault     return DestBits == SrcBits;
30089965c5aeSDavid Blaikie   if (DestTy->isPointerTy()) {        // Casting to pointer
30099965c5aeSDavid Blaikie     if (SrcTy->isPointerTy())                // Casting from pointer
3010b4019ae1SMatt Arsenault       return true;
30119965c5aeSDavid Blaikie     return SrcTy->isIntegerTy();             // Casting from integral
3012b4019ae1SMatt Arsenault   }
30139965c5aeSDavid Blaikie   if (DestTy->isX86_MMXTy()) {
30149965c5aeSDavid Blaikie     if (SrcTy->isVectorTy())
3015b4019ae1SMatt Arsenault       return DestBits == SrcBits;       // 64-bit vector to MMX
3016b4019ae1SMatt Arsenault     return false;
30179965c5aeSDavid Blaikie   }                                    // Casting to something else
3018b4019ae1SMatt Arsenault   return false;
3019b4019ae1SMatt Arsenault }
3020b4019ae1SMatt Arsenault 
3021cacbb237SMatt Arsenault bool CastInst::isBitCastable(Type *SrcTy, Type *DestTy) {
3022cacbb237SMatt Arsenault   if (!SrcTy->isFirstClassType() || !DestTy->isFirstClassType())
3023cacbb237SMatt Arsenault     return false;
3024cacbb237SMatt Arsenault 
3025cacbb237SMatt Arsenault   if (SrcTy == DestTy)
3026cacbb237SMatt Arsenault     return true;
3027cacbb237SMatt Arsenault 
3028cacbb237SMatt Arsenault   if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy)) {
3029cacbb237SMatt Arsenault     if (VectorType *DestVecTy = dyn_cast<VectorType>(DestTy)) {
3030b302561bSGraham Hunter       if (SrcVecTy->getElementCount() == DestVecTy->getElementCount()) {
3031cacbb237SMatt Arsenault         // An element by element cast. Valid if casting the elements is valid.
3032cacbb237SMatt Arsenault         SrcTy = SrcVecTy->getElementType();
3033cacbb237SMatt Arsenault         DestTy = DestVecTy->getElementType();
3034cacbb237SMatt Arsenault       }
3035cacbb237SMatt Arsenault     }
3036cacbb237SMatt Arsenault   }
3037cacbb237SMatt Arsenault 
3038cacbb237SMatt Arsenault   if (PointerType *DestPtrTy = dyn_cast<PointerType>(DestTy)) {
3039cacbb237SMatt Arsenault     if (PointerType *SrcPtrTy = dyn_cast<PointerType>(SrcTy)) {
3040cacbb237SMatt Arsenault       return SrcPtrTy->getAddressSpace() == DestPtrTy->getAddressSpace();
3041cacbb237SMatt Arsenault     }
3042cacbb237SMatt Arsenault   }
3043cacbb237SMatt Arsenault 
3044f998fa29SGraham Hunter   TypeSize SrcBits = SrcTy->getPrimitiveSizeInBits();   // 0 for ptr
3045f998fa29SGraham Hunter   TypeSize DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr
3046cacbb237SMatt Arsenault 
3047cacbb237SMatt Arsenault   // Could still have vectors of pointers if the number of elements doesn't
3048cacbb237SMatt Arsenault   // match
3049b302561bSGraham Hunter   if (SrcBits.getKnownMinSize() == 0 || DestBits.getKnownMinSize() == 0)
3050cacbb237SMatt Arsenault     return false;
3051cacbb237SMatt Arsenault 
3052cacbb237SMatt Arsenault   if (SrcBits != DestBits)
3053cacbb237SMatt Arsenault     return false;
3054cacbb237SMatt Arsenault 
3055cacbb237SMatt Arsenault   if (DestTy->isX86_MMXTy() || SrcTy->isX86_MMXTy())
3056cacbb237SMatt Arsenault     return false;
3057cacbb237SMatt Arsenault 
3058cacbb237SMatt Arsenault   return true;
3059cacbb237SMatt Arsenault }
3060cacbb237SMatt Arsenault 
30611a3c2c41SChandler Carruth bool CastInst::isBitOrNoopPointerCastable(Type *SrcTy, Type *DestTy,
3062a28d91d8SMehdi Amini                                           const DataLayout &DL) {
306392c11ee3SYichao Yu   // ptrtoint and inttoptr are not allowed on non-integral pointers
30641a3c2c41SChandler Carruth   if (auto *PtrTy = dyn_cast<PointerType>(SrcTy))
30651a3c2c41SChandler Carruth     if (auto *IntTy = dyn_cast<IntegerType>(DestTy))
306692c11ee3SYichao Yu       return (IntTy->getBitWidth() == DL.getPointerTypeSizeInBits(PtrTy) &&
306792c11ee3SYichao Yu               !DL.isNonIntegralPointerType(PtrTy));
30681a3c2c41SChandler Carruth   if (auto *PtrTy = dyn_cast<PointerType>(DestTy))
30691a3c2c41SChandler Carruth     if (auto *IntTy = dyn_cast<IntegerType>(SrcTy))
307092c11ee3SYichao Yu       return (IntTy->getBitWidth() == DL.getPointerTypeSizeInBits(PtrTy) &&
307192c11ee3SYichao Yu               !DL.isNonIntegralPointerType(PtrTy));
30721a3c2c41SChandler Carruth 
30731a3c2c41SChandler Carruth   return isBitCastable(SrcTy, DestTy);
30741a3c2c41SChandler Carruth }
30751a3c2c41SChandler Carruth 
3076ef860a24SChandler Carruth // Provide a way to get a "cast" where the cast opcode is inferred from the
3077ef860a24SChandler Carruth // types and size of the operand. This, basically, is a parallel of the
3078ef860a24SChandler Carruth // logic in the castIsValid function below.  This axiom should hold:
3079ef860a24SChandler Carruth //   castIsValid( getCastOpcode(Val, Ty), Val, Ty)
3080ef860a24SChandler Carruth // should not assert in castIsValid. In other words, this produces a "correct"
3081ef860a24SChandler Carruth // casting opcode for the arguments passed to it.
3082ef860a24SChandler Carruth // This routine must be kept in sync with isCastable.
3083ef860a24SChandler Carruth Instruction::CastOps
3084ef860a24SChandler Carruth CastInst::getCastOpcode(
3085ef860a24SChandler Carruth   const Value *Src, bool SrcIsSigned, Type *DestTy, bool DestIsSigned) {
3086ef860a24SChandler Carruth   Type *SrcTy = Src->getType();
3087ef860a24SChandler Carruth 
3088ef860a24SChandler Carruth   assert(SrcTy->isFirstClassType() && DestTy->isFirstClassType() &&
3089ef860a24SChandler Carruth          "Only first class types are castable!");
3090ef860a24SChandler Carruth 
3091ef860a24SChandler Carruth   if (SrcTy == DestTy)
3092ef860a24SChandler Carruth     return BitCast;
3093ef860a24SChandler Carruth 
3094cacbb237SMatt Arsenault   // FIXME: Check address space sizes here
3095ef860a24SChandler Carruth   if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy))
3096ef860a24SChandler Carruth     if (VectorType *DestVecTy = dyn_cast<VectorType>(DestTy))
3097ef860a24SChandler Carruth       if (SrcVecTy->getNumElements() == DestVecTy->getNumElements()) {
3098ef860a24SChandler Carruth         // An element by element cast.  Find the appropriate opcode based on the
3099ef860a24SChandler Carruth         // element types.
3100ef860a24SChandler Carruth         SrcTy = SrcVecTy->getElementType();
3101ef860a24SChandler Carruth         DestTy = DestVecTy->getElementType();
3102ef860a24SChandler Carruth       }
3103ef860a24SChandler Carruth 
3104ef860a24SChandler Carruth   // Get the bit sizes, we'll need these
3105ef860a24SChandler Carruth   unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();   // 0 for ptr
3106ef860a24SChandler Carruth   unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr
3107ef860a24SChandler Carruth 
3108ef860a24SChandler Carruth   // Run through the possibilities ...
3109ef860a24SChandler Carruth   if (DestTy->isIntegerTy()) {                      // Casting to integral
3110ef860a24SChandler Carruth     if (SrcTy->isIntegerTy()) {                     // Casting from integral
3111ef860a24SChandler Carruth       if (DestBits < SrcBits)
3112ef860a24SChandler Carruth         return Trunc;                               // int -> smaller int
3113ef860a24SChandler Carruth       else if (DestBits > SrcBits) {                // its an extension
3114ef860a24SChandler Carruth         if (SrcIsSigned)
3115ef860a24SChandler Carruth           return SExt;                              // signed -> SEXT
3116ef860a24SChandler Carruth         else
3117ef860a24SChandler Carruth           return ZExt;                              // unsigned -> ZEXT
3118ef860a24SChandler Carruth       } else {
3119ef860a24SChandler Carruth         return BitCast;                             // Same size, No-op cast
3120ef860a24SChandler Carruth       }
3121ef860a24SChandler Carruth     } else if (SrcTy->isFloatingPointTy()) {        // Casting from floating pt
3122ef860a24SChandler Carruth       if (DestIsSigned)
3123ef860a24SChandler Carruth         return FPToSI;                              // FP -> sint
3124ef860a24SChandler Carruth       else
3125ef860a24SChandler Carruth         return FPToUI;                              // FP -> uint
3126ef860a24SChandler Carruth     } else if (SrcTy->isVectorTy()) {
3127ef860a24SChandler Carruth       assert(DestBits == SrcBits &&
3128ef860a24SChandler Carruth              "Casting vector to integer of different width");
3129ef860a24SChandler Carruth       return BitCast;                             // Same size, no-op cast
3130ef860a24SChandler Carruth     } else {
3131ef860a24SChandler Carruth       assert(SrcTy->isPointerTy() &&
3132ef860a24SChandler Carruth              "Casting from a value that is not first-class type");
3133ef860a24SChandler Carruth       return PtrToInt;                              // ptr -> int
3134ef860a24SChandler Carruth     }
3135ef860a24SChandler Carruth   } else if (DestTy->isFloatingPointTy()) {         // Casting to floating pt
3136ef860a24SChandler Carruth     if (SrcTy->isIntegerTy()) {                     // Casting from integral
3137ef860a24SChandler Carruth       if (SrcIsSigned)
3138ef860a24SChandler Carruth         return SIToFP;                              // sint -> FP
3139ef860a24SChandler Carruth       else
3140ef860a24SChandler Carruth         return UIToFP;                              // uint -> FP
3141ef860a24SChandler Carruth     } else if (SrcTy->isFloatingPointTy()) {        // Casting from floating pt
3142ef860a24SChandler Carruth       if (DestBits < SrcBits) {
3143ef860a24SChandler Carruth         return FPTrunc;                             // FP -> smaller FP
3144ef860a24SChandler Carruth       } else if (DestBits > SrcBits) {
3145ef860a24SChandler Carruth         return FPExt;                               // FP -> larger FP
3146ef860a24SChandler Carruth       } else  {
3147ef860a24SChandler Carruth         return BitCast;                             // same size, no-op cast
3148ef860a24SChandler Carruth       }
3149ef860a24SChandler Carruth     } else if (SrcTy->isVectorTy()) {
3150ef860a24SChandler Carruth       assert(DestBits == SrcBits &&
3151ef860a24SChandler Carruth              "Casting vector to floating point of different width");
3152ef860a24SChandler Carruth       return BitCast;                             // same size, no-op cast
3153ef860a24SChandler Carruth     }
3154ef860a24SChandler Carruth     llvm_unreachable("Casting pointer or non-first class to float");
3155ef860a24SChandler Carruth   } else if (DestTy->isVectorTy()) {
3156ef860a24SChandler Carruth     assert(DestBits == SrcBits &&
3157ef860a24SChandler Carruth            "Illegal cast to vector (wrong type or size)");
3158ef860a24SChandler Carruth     return BitCast;
3159ef860a24SChandler Carruth   } else if (DestTy->isPointerTy()) {
3160ef860a24SChandler Carruth     if (SrcTy->isPointerTy()) {
3161b03bd4d9SMatt Arsenault       if (DestTy->getPointerAddressSpace() != SrcTy->getPointerAddressSpace())
3162b03bd4d9SMatt Arsenault         return AddrSpaceCast;
3163ef860a24SChandler Carruth       return BitCast;                               // ptr -> ptr
3164ef860a24SChandler Carruth     } else if (SrcTy->isIntegerTy()) {
3165ef860a24SChandler Carruth       return IntToPtr;                              // int -> ptr
3166ef860a24SChandler Carruth     }
3167ef860a24SChandler Carruth     llvm_unreachable("Casting pointer to other than pointer or int");
3168ef860a24SChandler Carruth   } else if (DestTy->isX86_MMXTy()) {
3169ef860a24SChandler Carruth     if (SrcTy->isVectorTy()) {
3170ef860a24SChandler Carruth       assert(DestBits == SrcBits && "Casting vector of wrong width to X86_MMX");
3171ef860a24SChandler Carruth       return BitCast;                               // 64-bit vector to MMX
3172ef860a24SChandler Carruth     }
3173ef860a24SChandler Carruth     llvm_unreachable("Illegal cast to X86_MMX");
3174ef860a24SChandler Carruth   }
3175ef860a24SChandler Carruth   llvm_unreachable("Casting to type that is not first-class");
3176ef860a24SChandler Carruth }
3177ef860a24SChandler Carruth 
3178ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
3179ef860a24SChandler Carruth //                    CastInst SubClass Constructors
3180ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
3181ef860a24SChandler Carruth 
3182ef860a24SChandler Carruth /// Check that the construction parameters for a CastInst are correct. This
3183ef860a24SChandler Carruth /// could be broken out into the separate constructors but it is useful to have
3184ef860a24SChandler Carruth /// it in one place and to eliminate the redundant code for getting the sizes
3185ef860a24SChandler Carruth /// of the types involved.
3186ef860a24SChandler Carruth bool
3187ef860a24SChandler Carruth CastInst::castIsValid(Instruction::CastOps op, Value *S, Type *DstTy) {
3188ef860a24SChandler Carruth   // Check for type sanity on the arguments
3189ef860a24SChandler Carruth   Type *SrcTy = S->getType();
3190098d7b76SEvan Cheng 
3191ef860a24SChandler Carruth   if (!SrcTy->isFirstClassType() || !DstTy->isFirstClassType() ||
3192ef860a24SChandler Carruth       SrcTy->isAggregateType() || DstTy->isAggregateType())
3193ef860a24SChandler Carruth     return false;
3194ef860a24SChandler Carruth 
3195ef860a24SChandler Carruth   // Get the size of the types in bits, we'll need this later
3196ef860a24SChandler Carruth   unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
3197ef860a24SChandler Carruth   unsigned DstBitSize = DstTy->getScalarSizeInBits();
3198ef860a24SChandler Carruth 
3199ef860a24SChandler Carruth   // If these are vector types, get the lengths of the vectors (using zero for
3200ef860a24SChandler Carruth   // scalar types means that checking that vector lengths match also checks that
3201ef860a24SChandler Carruth   // scalars are not being converted to vectors or vectors to scalars).
3202ef860a24SChandler Carruth   unsigned SrcLength = SrcTy->isVectorTy() ?
3203ef860a24SChandler Carruth     cast<VectorType>(SrcTy)->getNumElements() : 0;
3204ef860a24SChandler Carruth   unsigned DstLength = DstTy->isVectorTy() ?
3205ef860a24SChandler Carruth     cast<VectorType>(DstTy)->getNumElements() : 0;
3206ef860a24SChandler Carruth 
3207ef860a24SChandler Carruth   // Switch on the opcode provided
3208ef860a24SChandler Carruth   switch (op) {
3209ef860a24SChandler Carruth   default: return false; // This is an input error
3210ef860a24SChandler Carruth   case Instruction::Trunc:
3211ef860a24SChandler Carruth     return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() &&
3212ef860a24SChandler Carruth       SrcLength == DstLength && SrcBitSize > DstBitSize;
3213ef860a24SChandler Carruth   case Instruction::ZExt:
3214ef860a24SChandler Carruth     return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() &&
3215ef860a24SChandler Carruth       SrcLength == DstLength && SrcBitSize < DstBitSize;
3216ef860a24SChandler Carruth   case Instruction::SExt:
3217ef860a24SChandler Carruth     return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() &&
3218ef860a24SChandler Carruth       SrcLength == DstLength && SrcBitSize < DstBitSize;
3219ef860a24SChandler Carruth   case Instruction::FPTrunc:
3220ef860a24SChandler Carruth     return SrcTy->isFPOrFPVectorTy() && DstTy->isFPOrFPVectorTy() &&
3221ef860a24SChandler Carruth       SrcLength == DstLength && SrcBitSize > DstBitSize;
3222ef860a24SChandler Carruth   case Instruction::FPExt:
3223ef860a24SChandler Carruth     return SrcTy->isFPOrFPVectorTy() && DstTy->isFPOrFPVectorTy() &&
3224ef860a24SChandler Carruth       SrcLength == DstLength && SrcBitSize < DstBitSize;
3225ef860a24SChandler Carruth   case Instruction::UIToFP:
3226ef860a24SChandler Carruth   case Instruction::SIToFP:
3227ef860a24SChandler Carruth     return SrcTy->isIntOrIntVectorTy() && DstTy->isFPOrFPVectorTy() &&
3228ef860a24SChandler Carruth       SrcLength == DstLength;
3229ef860a24SChandler Carruth   case Instruction::FPToUI:
3230ef860a24SChandler Carruth   case Instruction::FPToSI:
3231ef860a24SChandler Carruth     return SrcTy->isFPOrFPVectorTy() && DstTy->isIntOrIntVectorTy() &&
3232ef860a24SChandler Carruth       SrcLength == DstLength;
3233ef860a24SChandler Carruth   case Instruction::PtrToInt:
3234ef860a24SChandler Carruth     if (isa<VectorType>(SrcTy) != isa<VectorType>(DstTy))
3235ef860a24SChandler Carruth       return false;
3236ef860a24SChandler Carruth     if (VectorType *VT = dyn_cast<VectorType>(SrcTy))
3237ef860a24SChandler Carruth       if (VT->getNumElements() != cast<VectorType>(DstTy)->getNumElements())
3238ef860a24SChandler Carruth         return false;
323995d2347aSCraig Topper     return SrcTy->isPtrOrPtrVectorTy() && DstTy->isIntOrIntVectorTy();
3240ef860a24SChandler Carruth   case Instruction::IntToPtr:
3241ef860a24SChandler Carruth     if (isa<VectorType>(SrcTy) != isa<VectorType>(DstTy))
3242ef860a24SChandler Carruth       return false;
3243ef860a24SChandler Carruth     if (VectorType *VT = dyn_cast<VectorType>(SrcTy))
3244ef860a24SChandler Carruth       if (VT->getNumElements() != cast<VectorType>(DstTy)->getNumElements())
3245ef860a24SChandler Carruth         return false;
324695d2347aSCraig Topper     return SrcTy->isIntOrIntVectorTy() && DstTy->isPtrOrPtrVectorTy();
3247fc3c91d0SMatt Arsenault   case Instruction::BitCast: {
3248fc3c91d0SMatt Arsenault     PointerType *SrcPtrTy = dyn_cast<PointerType>(SrcTy->getScalarType());
3249fc3c91d0SMatt Arsenault     PointerType *DstPtrTy = dyn_cast<PointerType>(DstTy->getScalarType());
3250fc3c91d0SMatt Arsenault 
3251ef860a24SChandler Carruth     // BitCast implies a no-op cast of type only. No bits change.
3252ef860a24SChandler Carruth     // However, you can't cast pointers to anything but pointers.
3253fc3c91d0SMatt Arsenault     if (!SrcPtrTy != !DstPtrTy)
3254ef860a24SChandler Carruth       return false;
3255ef860a24SChandler Carruth 
3256f907b891SAlp Toker     // For non-pointer cases, the cast is okay if the source and destination bit
3257b03bd4d9SMatt Arsenault     // widths are identical.
3258fc3c91d0SMatt Arsenault     if (!SrcPtrTy)
3259ef860a24SChandler Carruth       return SrcTy->getPrimitiveSizeInBits() == DstTy->getPrimitiveSizeInBits();
3260b03bd4d9SMatt Arsenault 
3261fc3c91d0SMatt Arsenault     // If both are pointers then the address spaces must match.
3262fc3c91d0SMatt Arsenault     if (SrcPtrTy->getAddressSpace() != DstPtrTy->getAddressSpace())
3263fc3c91d0SMatt Arsenault       return false;
3264b03bd4d9SMatt Arsenault 
3265fc3c91d0SMatt Arsenault     // A vector of pointers must have the same number of elements.
326609ab5067SSerguei Katkov     VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy);
326709ab5067SSerguei Katkov     VectorType *DstVecTy = dyn_cast<VectorType>(DstTy);
326809ab5067SSerguei Katkov     if (SrcVecTy && DstVecTy)
3269fc3c91d0SMatt Arsenault       return (SrcVecTy->getNumElements() == DstVecTy->getNumElements());
327009ab5067SSerguei Katkov     if (SrcVecTy)
327109ab5067SSerguei Katkov       return SrcVecTy->getNumElements() == 1;
327209ab5067SSerguei Katkov     if (DstVecTy)
327309ab5067SSerguei Katkov       return DstVecTy->getNumElements() == 1;
3274fc3c91d0SMatt Arsenault 
3275fc3c91d0SMatt Arsenault     return true;
3276fc3c91d0SMatt Arsenault   }
3277fc3c91d0SMatt Arsenault   case Instruction::AddrSpaceCast: {
3278fc3c91d0SMatt Arsenault     PointerType *SrcPtrTy = dyn_cast<PointerType>(SrcTy->getScalarType());
3279fc3c91d0SMatt Arsenault     if (!SrcPtrTy)
3280fc3c91d0SMatt Arsenault       return false;
3281fc3c91d0SMatt Arsenault 
3282fc3c91d0SMatt Arsenault     PointerType *DstPtrTy = dyn_cast<PointerType>(DstTy->getScalarType());
3283fc3c91d0SMatt Arsenault     if (!DstPtrTy)
3284fc3c91d0SMatt Arsenault       return false;
3285fc3c91d0SMatt Arsenault 
3286fc3c91d0SMatt Arsenault     if (SrcPtrTy->getAddressSpace() == DstPtrTy->getAddressSpace())
3287fc3c91d0SMatt Arsenault       return false;
3288fc3c91d0SMatt Arsenault 
3289fc3c91d0SMatt Arsenault     if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy)) {
3290fc3c91d0SMatt Arsenault       if (VectorType *DstVecTy = dyn_cast<VectorType>(DstTy))
3291fc3c91d0SMatt Arsenault         return (SrcVecTy->getNumElements() == DstVecTy->getNumElements());
3292fc3c91d0SMatt Arsenault 
3293fc3c91d0SMatt Arsenault       return false;
3294fc3c91d0SMatt Arsenault     }
3295fc3c91d0SMatt Arsenault 
3296fc3c91d0SMatt Arsenault     return true;
3297fc3c91d0SMatt Arsenault   }
3298ef860a24SChandler Carruth   }
3299ef860a24SChandler Carruth }
3300ef860a24SChandler Carruth 
3301ef860a24SChandler Carruth TruncInst::TruncInst(
3302ef860a24SChandler Carruth   Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3303ef860a24SChandler Carruth ) : CastInst(Ty, Trunc, S, Name, InsertBefore) {
3304ef860a24SChandler Carruth   assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
3305ef860a24SChandler Carruth }
3306ef860a24SChandler Carruth 
3307ef860a24SChandler Carruth TruncInst::TruncInst(
3308ef860a24SChandler Carruth   Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3309ef860a24SChandler Carruth ) : CastInst(Ty, Trunc, S, Name, InsertAtEnd) {
3310ef860a24SChandler Carruth   assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
3311ef860a24SChandler Carruth }
3312ef860a24SChandler Carruth 
3313ef860a24SChandler Carruth ZExtInst::ZExtInst(
3314ef860a24SChandler Carruth   Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3315ef860a24SChandler Carruth )  : CastInst(Ty, ZExt, S, Name, InsertBefore) {
3316ef860a24SChandler Carruth   assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
3317ef860a24SChandler Carruth }
3318ef860a24SChandler Carruth 
3319ef860a24SChandler Carruth ZExtInst::ZExtInst(
3320ef860a24SChandler Carruth   Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3321ef860a24SChandler Carruth )  : CastInst(Ty, ZExt, S, Name, InsertAtEnd) {
3322ef860a24SChandler Carruth   assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
3323ef860a24SChandler Carruth }
3324ef860a24SChandler Carruth SExtInst::SExtInst(
3325ef860a24SChandler Carruth   Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3326ef860a24SChandler Carruth ) : CastInst(Ty, SExt, S, Name, InsertBefore) {
3327ef860a24SChandler Carruth   assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
3328ef860a24SChandler Carruth }
3329ef860a24SChandler Carruth 
3330ef860a24SChandler Carruth SExtInst::SExtInst(
3331ef860a24SChandler Carruth   Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3332ef860a24SChandler Carruth )  : CastInst(Ty, SExt, S, Name, InsertAtEnd) {
3333ef860a24SChandler Carruth   assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
3334ef860a24SChandler Carruth }
3335ef860a24SChandler Carruth 
3336ef860a24SChandler Carruth FPTruncInst::FPTruncInst(
3337ef860a24SChandler Carruth   Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3338ef860a24SChandler Carruth ) : CastInst(Ty, FPTrunc, S, Name, InsertBefore) {
3339ef860a24SChandler Carruth   assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
3340ef860a24SChandler Carruth }
3341ef860a24SChandler Carruth 
3342ef860a24SChandler Carruth FPTruncInst::FPTruncInst(
3343ef860a24SChandler Carruth   Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3344ef860a24SChandler Carruth ) : CastInst(Ty, FPTrunc, S, Name, InsertAtEnd) {
3345ef860a24SChandler Carruth   assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
3346ef860a24SChandler Carruth }
3347ef860a24SChandler Carruth 
3348ef860a24SChandler Carruth FPExtInst::FPExtInst(
3349ef860a24SChandler Carruth   Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3350ef860a24SChandler Carruth ) : CastInst(Ty, FPExt, S, Name, InsertBefore) {
3351ef860a24SChandler Carruth   assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
3352ef860a24SChandler Carruth }
3353ef860a24SChandler Carruth 
3354ef860a24SChandler Carruth FPExtInst::FPExtInst(
3355ef860a24SChandler Carruth   Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3356ef860a24SChandler Carruth ) : CastInst(Ty, FPExt, S, Name, InsertAtEnd) {
3357ef860a24SChandler Carruth   assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
3358ef860a24SChandler Carruth }
3359ef860a24SChandler Carruth 
3360ef860a24SChandler Carruth UIToFPInst::UIToFPInst(
3361ef860a24SChandler Carruth   Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3362ef860a24SChandler Carruth ) : CastInst(Ty, UIToFP, S, Name, InsertBefore) {
3363ef860a24SChandler Carruth   assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
3364ef860a24SChandler Carruth }
3365ef860a24SChandler Carruth 
3366ef860a24SChandler Carruth UIToFPInst::UIToFPInst(
3367ef860a24SChandler Carruth   Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3368ef860a24SChandler Carruth ) : CastInst(Ty, UIToFP, S, Name, InsertAtEnd) {
3369ef860a24SChandler Carruth   assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
3370ef860a24SChandler Carruth }
3371ef860a24SChandler Carruth 
3372ef860a24SChandler Carruth SIToFPInst::SIToFPInst(
3373ef860a24SChandler Carruth   Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3374ef860a24SChandler Carruth ) : CastInst(Ty, SIToFP, S, Name, InsertBefore) {
3375ef860a24SChandler Carruth   assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
3376ef860a24SChandler Carruth }
3377ef860a24SChandler Carruth 
3378ef860a24SChandler Carruth SIToFPInst::SIToFPInst(
3379ef860a24SChandler Carruth   Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3380ef860a24SChandler Carruth ) : CastInst(Ty, SIToFP, S, Name, InsertAtEnd) {
3381ef860a24SChandler Carruth   assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
3382ef860a24SChandler Carruth }
3383ef860a24SChandler Carruth 
3384ef860a24SChandler Carruth FPToUIInst::FPToUIInst(
3385ef860a24SChandler Carruth   Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3386ef860a24SChandler Carruth ) : CastInst(Ty, FPToUI, S, Name, InsertBefore) {
3387ef860a24SChandler Carruth   assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
3388ef860a24SChandler Carruth }
3389ef860a24SChandler Carruth 
3390ef860a24SChandler Carruth FPToUIInst::FPToUIInst(
3391ef860a24SChandler Carruth   Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3392ef860a24SChandler Carruth ) : CastInst(Ty, FPToUI, S, Name, InsertAtEnd) {
3393ef860a24SChandler Carruth   assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
3394ef860a24SChandler Carruth }
3395ef860a24SChandler Carruth 
3396ef860a24SChandler Carruth FPToSIInst::FPToSIInst(
3397ef860a24SChandler Carruth   Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3398ef860a24SChandler Carruth ) : CastInst(Ty, FPToSI, S, Name, InsertBefore) {
3399ef860a24SChandler Carruth   assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
3400ef860a24SChandler Carruth }
3401ef860a24SChandler Carruth 
3402ef860a24SChandler Carruth FPToSIInst::FPToSIInst(
3403ef860a24SChandler Carruth   Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3404ef860a24SChandler Carruth ) : CastInst(Ty, FPToSI, S, Name, InsertAtEnd) {
3405ef860a24SChandler Carruth   assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
3406ef860a24SChandler Carruth }
3407ef860a24SChandler Carruth 
3408ef860a24SChandler Carruth PtrToIntInst::PtrToIntInst(
3409ef860a24SChandler Carruth   Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3410ef860a24SChandler Carruth ) : CastInst(Ty, PtrToInt, S, Name, InsertBefore) {
3411ef860a24SChandler Carruth   assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
3412ef860a24SChandler Carruth }
3413ef860a24SChandler Carruth 
3414ef860a24SChandler Carruth PtrToIntInst::PtrToIntInst(
3415ef860a24SChandler Carruth   Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3416ef860a24SChandler Carruth ) : CastInst(Ty, PtrToInt, S, Name, InsertAtEnd) {
3417ef860a24SChandler Carruth   assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
3418ef860a24SChandler Carruth }
3419ef860a24SChandler Carruth 
3420ef860a24SChandler Carruth IntToPtrInst::IntToPtrInst(
3421ef860a24SChandler Carruth   Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3422ef860a24SChandler Carruth ) : CastInst(Ty, IntToPtr, S, Name, InsertBefore) {
3423ef860a24SChandler Carruth   assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
3424ef860a24SChandler Carruth }
3425ef860a24SChandler Carruth 
3426ef860a24SChandler Carruth IntToPtrInst::IntToPtrInst(
3427ef860a24SChandler Carruth   Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3428ef860a24SChandler Carruth ) : CastInst(Ty, IntToPtr, S, Name, InsertAtEnd) {
3429ef860a24SChandler Carruth   assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
3430ef860a24SChandler Carruth }
3431ef860a24SChandler Carruth 
3432ef860a24SChandler Carruth BitCastInst::BitCastInst(
3433ef860a24SChandler Carruth   Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3434ef860a24SChandler Carruth ) : CastInst(Ty, BitCast, S, Name, InsertBefore) {
3435ef860a24SChandler Carruth   assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
3436ef860a24SChandler Carruth }
3437ef860a24SChandler Carruth 
3438ef860a24SChandler Carruth BitCastInst::BitCastInst(
3439ef860a24SChandler Carruth   Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3440ef860a24SChandler Carruth ) : CastInst(Ty, BitCast, S, Name, InsertAtEnd) {
3441ef860a24SChandler Carruth   assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
3442ef860a24SChandler Carruth }
3443ef860a24SChandler Carruth 
3444b03bd4d9SMatt Arsenault AddrSpaceCastInst::AddrSpaceCastInst(
3445b03bd4d9SMatt Arsenault   Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3446b03bd4d9SMatt Arsenault ) : CastInst(Ty, AddrSpaceCast, S, Name, InsertBefore) {
3447b03bd4d9SMatt Arsenault   assert(castIsValid(getOpcode(), S, Ty) && "Illegal AddrSpaceCast");
3448b03bd4d9SMatt Arsenault }
3449b03bd4d9SMatt Arsenault 
3450b03bd4d9SMatt Arsenault AddrSpaceCastInst::AddrSpaceCastInst(
3451b03bd4d9SMatt Arsenault   Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3452b03bd4d9SMatt Arsenault ) : CastInst(Ty, AddrSpaceCast, S, Name, InsertAtEnd) {
3453b03bd4d9SMatt Arsenault   assert(castIsValid(getOpcode(), S, Ty) && "Illegal AddrSpaceCast");
3454b03bd4d9SMatt Arsenault }
3455b03bd4d9SMatt Arsenault 
3456ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
3457ef860a24SChandler Carruth //                               CmpInst Classes
3458ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
3459ef860a24SChandler Carruth 
34601c3f2831SCraig Topper CmpInst::CmpInst(Type *ty, OtherOps op, Predicate predicate, Value *LHS,
3461d1172a0cSSanjay Patel                  Value *RHS, const Twine &Name, Instruction *InsertBefore,
3462d1172a0cSSanjay Patel                  Instruction *FlagsSource)
3463ef860a24SChandler Carruth   : Instruction(ty, op,
3464ef860a24SChandler Carruth                 OperandTraits<CmpInst>::op_begin(this),
3465ef860a24SChandler Carruth                 OperandTraits<CmpInst>::operands(this),
3466ef860a24SChandler Carruth                 InsertBefore) {
3467ef860a24SChandler Carruth   Op<0>() = LHS;
3468ef860a24SChandler Carruth   Op<1>() = RHS;
3469ef860a24SChandler Carruth   setPredicate((Predicate)predicate);
3470ef860a24SChandler Carruth   setName(Name);
3471d1172a0cSSanjay Patel   if (FlagsSource)
3472d1172a0cSSanjay Patel     copyIRFlags(FlagsSource);
3473ef860a24SChandler Carruth }
3474ef860a24SChandler Carruth 
34751c3f2831SCraig Topper CmpInst::CmpInst(Type *ty, OtherOps op, Predicate predicate, Value *LHS,
34761c3f2831SCraig Topper                  Value *RHS, const Twine &Name, BasicBlock *InsertAtEnd)
3477ef860a24SChandler Carruth   : Instruction(ty, op,
3478ef860a24SChandler Carruth                 OperandTraits<CmpInst>::op_begin(this),
3479ef860a24SChandler Carruth                 OperandTraits<CmpInst>::operands(this),
3480ef860a24SChandler Carruth                 InsertAtEnd) {
3481ef860a24SChandler Carruth   Op<0>() = LHS;
3482ef860a24SChandler Carruth   Op<1>() = RHS;
3483ef860a24SChandler Carruth   setPredicate((Predicate)predicate);
3484ef860a24SChandler Carruth   setName(Name);
3485ef860a24SChandler Carruth }
3486ef860a24SChandler Carruth 
3487ef860a24SChandler Carruth CmpInst *
34881c3f2831SCraig Topper CmpInst::Create(OtherOps Op, Predicate predicate, Value *S1, Value *S2,
3489ef860a24SChandler Carruth                 const Twine &Name, Instruction *InsertBefore) {
3490ef860a24SChandler Carruth   if (Op == Instruction::ICmp) {
3491ef860a24SChandler Carruth     if (InsertBefore)
3492ef860a24SChandler Carruth       return new ICmpInst(InsertBefore, CmpInst::Predicate(predicate),
3493ef860a24SChandler Carruth                           S1, S2, Name);
3494ef860a24SChandler Carruth     else
3495ef860a24SChandler Carruth       return new ICmpInst(CmpInst::Predicate(predicate),
3496ef860a24SChandler Carruth                           S1, S2, Name);
3497ef860a24SChandler Carruth   }
3498ef860a24SChandler Carruth 
3499ef860a24SChandler Carruth   if (InsertBefore)
3500ef860a24SChandler Carruth     return new FCmpInst(InsertBefore, CmpInst::Predicate(predicate),
3501ef860a24SChandler Carruth                         S1, S2, Name);
3502ef860a24SChandler Carruth   else
3503ef860a24SChandler Carruth     return new FCmpInst(CmpInst::Predicate(predicate),
3504ef860a24SChandler Carruth                         S1, S2, Name);
3505ef860a24SChandler Carruth }
3506ef860a24SChandler Carruth 
3507ef860a24SChandler Carruth CmpInst *
35081c3f2831SCraig Topper CmpInst::Create(OtherOps Op, Predicate predicate, Value *S1, Value *S2,
3509ef860a24SChandler Carruth                 const Twine &Name, BasicBlock *InsertAtEnd) {
3510ef860a24SChandler Carruth   if (Op == Instruction::ICmp) {
3511ef860a24SChandler Carruth     return new ICmpInst(*InsertAtEnd, CmpInst::Predicate(predicate),
3512ef860a24SChandler Carruth                         S1, S2, Name);
3513ef860a24SChandler Carruth   }
3514ef860a24SChandler Carruth   return new FCmpInst(*InsertAtEnd, CmpInst::Predicate(predicate),
3515ef860a24SChandler Carruth                       S1, S2, Name);
3516ef860a24SChandler Carruth }
3517ef860a24SChandler Carruth 
3518ef860a24SChandler Carruth void CmpInst::swapOperands() {
3519ef860a24SChandler Carruth   if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
3520ef860a24SChandler Carruth     IC->swapOperands();
3521ef860a24SChandler Carruth   else
3522ef860a24SChandler Carruth     cast<FCmpInst>(this)->swapOperands();
3523ef860a24SChandler Carruth }
3524ef860a24SChandler Carruth 
3525ef860a24SChandler Carruth bool CmpInst::isCommutative() const {
3526ef860a24SChandler Carruth   if (const ICmpInst *IC = dyn_cast<ICmpInst>(this))
3527ef860a24SChandler Carruth     return IC->isCommutative();
3528ef860a24SChandler Carruth   return cast<FCmpInst>(this)->isCommutative();
3529ef860a24SChandler Carruth }
3530ef860a24SChandler Carruth 
3531ef860a24SChandler Carruth bool CmpInst::isEquality() const {
3532ef860a24SChandler Carruth   if (const ICmpInst *IC = dyn_cast<ICmpInst>(this))
3533ef860a24SChandler Carruth     return IC->isEquality();
3534ef860a24SChandler Carruth   return cast<FCmpInst>(this)->isEquality();
3535ef860a24SChandler Carruth }
3536ef860a24SChandler Carruth 
3537ef860a24SChandler Carruth CmpInst::Predicate CmpInst::getInversePredicate(Predicate pred) {
3538ef860a24SChandler Carruth   switch (pred) {
3539ef860a24SChandler Carruth     default: llvm_unreachable("Unknown cmp predicate!");
3540ef860a24SChandler Carruth     case ICMP_EQ: return ICMP_NE;
3541ef860a24SChandler Carruth     case ICMP_NE: return ICMP_EQ;
3542ef860a24SChandler Carruth     case ICMP_UGT: return ICMP_ULE;
3543ef860a24SChandler Carruth     case ICMP_ULT: return ICMP_UGE;
3544ef860a24SChandler Carruth     case ICMP_UGE: return ICMP_ULT;
3545ef860a24SChandler Carruth     case ICMP_ULE: return ICMP_UGT;
3546ef860a24SChandler Carruth     case ICMP_SGT: return ICMP_SLE;
3547ef860a24SChandler Carruth     case ICMP_SLT: return ICMP_SGE;
3548ef860a24SChandler Carruth     case ICMP_SGE: return ICMP_SLT;
3549ef860a24SChandler Carruth     case ICMP_SLE: return ICMP_SGT;
3550ef860a24SChandler Carruth 
3551ef860a24SChandler Carruth     case FCMP_OEQ: return FCMP_UNE;
3552ef860a24SChandler Carruth     case FCMP_ONE: return FCMP_UEQ;
3553ef860a24SChandler Carruth     case FCMP_OGT: return FCMP_ULE;
3554ef860a24SChandler Carruth     case FCMP_OLT: return FCMP_UGE;
3555ef860a24SChandler Carruth     case FCMP_OGE: return FCMP_ULT;
3556ef860a24SChandler Carruth     case FCMP_OLE: return FCMP_UGT;
3557ef860a24SChandler Carruth     case FCMP_UEQ: return FCMP_ONE;
3558ef860a24SChandler Carruth     case FCMP_UNE: return FCMP_OEQ;
3559ef860a24SChandler Carruth     case FCMP_UGT: return FCMP_OLE;
3560ef860a24SChandler Carruth     case FCMP_ULT: return FCMP_OGE;
3561ef860a24SChandler Carruth     case FCMP_UGE: return FCMP_OLT;
3562ef860a24SChandler Carruth     case FCMP_ULE: return FCMP_OGT;
3563ef860a24SChandler Carruth     case FCMP_ORD: return FCMP_UNO;
3564ef860a24SChandler Carruth     case FCMP_UNO: return FCMP_ORD;
3565ef860a24SChandler Carruth     case FCMP_TRUE: return FCMP_FALSE;
3566ef860a24SChandler Carruth     case FCMP_FALSE: return FCMP_TRUE;
3567ef860a24SChandler Carruth   }
3568ef860a24SChandler Carruth }
3569ef860a24SChandler Carruth 
3570de3aea04STim Northover StringRef CmpInst::getPredicateName(Predicate Pred) {
3571de3aea04STim Northover   switch (Pred) {
3572de3aea04STim Northover   default:                   return "unknown";
3573de3aea04STim Northover   case FCmpInst::FCMP_FALSE: return "false";
3574de3aea04STim Northover   case FCmpInst::FCMP_OEQ:   return "oeq";
3575de3aea04STim Northover   case FCmpInst::FCMP_OGT:   return "ogt";
3576de3aea04STim Northover   case FCmpInst::FCMP_OGE:   return "oge";
3577de3aea04STim Northover   case FCmpInst::FCMP_OLT:   return "olt";
3578de3aea04STim Northover   case FCmpInst::FCMP_OLE:   return "ole";
3579de3aea04STim Northover   case FCmpInst::FCMP_ONE:   return "one";
3580de3aea04STim Northover   case FCmpInst::FCMP_ORD:   return "ord";
3581de3aea04STim Northover   case FCmpInst::FCMP_UNO:   return "uno";
3582de3aea04STim Northover   case FCmpInst::FCMP_UEQ:   return "ueq";
3583de3aea04STim Northover   case FCmpInst::FCMP_UGT:   return "ugt";
3584de3aea04STim Northover   case FCmpInst::FCMP_UGE:   return "uge";
3585de3aea04STim Northover   case FCmpInst::FCMP_ULT:   return "ult";
3586de3aea04STim Northover   case FCmpInst::FCMP_ULE:   return "ule";
3587de3aea04STim Northover   case FCmpInst::FCMP_UNE:   return "une";
3588de3aea04STim Northover   case FCmpInst::FCMP_TRUE:  return "true";
3589de3aea04STim Northover   case ICmpInst::ICMP_EQ:    return "eq";
3590de3aea04STim Northover   case ICmpInst::ICMP_NE:    return "ne";
3591de3aea04STim Northover   case ICmpInst::ICMP_SGT:   return "sgt";
3592de3aea04STim Northover   case ICmpInst::ICMP_SGE:   return "sge";
3593de3aea04STim Northover   case ICmpInst::ICMP_SLT:   return "slt";
3594de3aea04STim Northover   case ICmpInst::ICMP_SLE:   return "sle";
3595de3aea04STim Northover   case ICmpInst::ICMP_UGT:   return "ugt";
3596de3aea04STim Northover   case ICmpInst::ICMP_UGE:   return "uge";
3597de3aea04STim Northover   case ICmpInst::ICMP_ULT:   return "ult";
3598de3aea04STim Northover   case ICmpInst::ICMP_ULE:   return "ule";
3599de3aea04STim Northover   }
3600de3aea04STim Northover }
3601de3aea04STim Northover 
3602ef860a24SChandler Carruth ICmpInst::Predicate ICmpInst::getSignedPredicate(Predicate pred) {
3603ef860a24SChandler Carruth   switch (pred) {
3604ef860a24SChandler Carruth     default: llvm_unreachable("Unknown icmp predicate!");
3605ef860a24SChandler Carruth     case ICMP_EQ: case ICMP_NE:
3606ef860a24SChandler Carruth     case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE:
3607ef860a24SChandler Carruth        return pred;
3608ef860a24SChandler Carruth     case ICMP_UGT: return ICMP_SGT;
3609ef860a24SChandler Carruth     case ICMP_ULT: return ICMP_SLT;
3610ef860a24SChandler Carruth     case ICMP_UGE: return ICMP_SGE;
3611ef860a24SChandler Carruth     case ICMP_ULE: return ICMP_SLE;
3612ef860a24SChandler Carruth   }
3613ef860a24SChandler Carruth }
3614ef860a24SChandler Carruth 
3615ef860a24SChandler Carruth ICmpInst::Predicate ICmpInst::getUnsignedPredicate(Predicate pred) {
3616ef860a24SChandler Carruth   switch (pred) {
3617ef860a24SChandler Carruth     default: llvm_unreachable("Unknown icmp predicate!");
3618ef860a24SChandler Carruth     case ICMP_EQ: case ICMP_NE:
3619ef860a24SChandler Carruth     case ICMP_UGT: case ICMP_ULT: case ICMP_UGE: case ICMP_ULE:
3620ef860a24SChandler Carruth        return pred;
3621ef860a24SChandler Carruth     case ICMP_SGT: return ICMP_UGT;
3622ef860a24SChandler Carruth     case ICMP_SLT: return ICMP_ULT;
3623ef860a24SChandler Carruth     case ICMP_SGE: return ICMP_UGE;
3624ef860a24SChandler Carruth     case ICMP_SLE: return ICMP_ULE;
3625ef860a24SChandler Carruth   }
3626ef860a24SChandler Carruth }
3627ef860a24SChandler Carruth 
36283cb4c34aSSerguei Katkov CmpInst::Predicate CmpInst::getFlippedStrictnessPredicate(Predicate pred) {
36293cb4c34aSSerguei Katkov   switch (pred) {
36303cb4c34aSSerguei Katkov     default: llvm_unreachable("Unknown or unsupported cmp predicate!");
36313cb4c34aSSerguei Katkov     case ICMP_SGT: return ICMP_SGE;
36323cb4c34aSSerguei Katkov     case ICMP_SLT: return ICMP_SLE;
36333cb4c34aSSerguei Katkov     case ICMP_SGE: return ICMP_SGT;
36343cb4c34aSSerguei Katkov     case ICMP_SLE: return ICMP_SLT;
36353cb4c34aSSerguei Katkov     case ICMP_UGT: return ICMP_UGE;
36363cb4c34aSSerguei Katkov     case ICMP_ULT: return ICMP_ULE;
36373cb4c34aSSerguei Katkov     case ICMP_UGE: return ICMP_UGT;
36383cb4c34aSSerguei Katkov     case ICMP_ULE: return ICMP_ULT;
36393cb4c34aSSerguei Katkov 
36403cb4c34aSSerguei Katkov     case FCMP_OGT: return FCMP_OGE;
36413cb4c34aSSerguei Katkov     case FCMP_OLT: return FCMP_OLE;
36423cb4c34aSSerguei Katkov     case FCMP_OGE: return FCMP_OGT;
36433cb4c34aSSerguei Katkov     case FCMP_OLE: return FCMP_OLT;
36443cb4c34aSSerguei Katkov     case FCMP_UGT: return FCMP_UGE;
36453cb4c34aSSerguei Katkov     case FCMP_ULT: return FCMP_ULE;
36463cb4c34aSSerguei Katkov     case FCMP_UGE: return FCMP_UGT;
36473cb4c34aSSerguei Katkov     case FCMP_ULE: return FCMP_ULT;
36483cb4c34aSSerguei Katkov   }
36493cb4c34aSSerguei Katkov }
36503cb4c34aSSerguei Katkov 
3651ef860a24SChandler Carruth CmpInst::Predicate CmpInst::getSwappedPredicate(Predicate pred) {
3652ef860a24SChandler Carruth   switch (pred) {
3653ef860a24SChandler Carruth     default: llvm_unreachable("Unknown cmp predicate!");
3654ef860a24SChandler Carruth     case ICMP_EQ: case ICMP_NE:
3655ef860a24SChandler Carruth       return pred;
3656ef860a24SChandler Carruth     case ICMP_SGT: return ICMP_SLT;
3657ef860a24SChandler Carruth     case ICMP_SLT: return ICMP_SGT;
3658ef860a24SChandler Carruth     case ICMP_SGE: return ICMP_SLE;
3659ef860a24SChandler Carruth     case ICMP_SLE: return ICMP_SGE;
3660ef860a24SChandler Carruth     case ICMP_UGT: return ICMP_ULT;
3661ef860a24SChandler Carruth     case ICMP_ULT: return ICMP_UGT;
3662ef860a24SChandler Carruth     case ICMP_UGE: return ICMP_ULE;
3663ef860a24SChandler Carruth     case ICMP_ULE: return ICMP_UGE;
3664ef860a24SChandler Carruth 
3665ef860a24SChandler Carruth     case FCMP_FALSE: case FCMP_TRUE:
3666ef860a24SChandler Carruth     case FCMP_OEQ: case FCMP_ONE:
3667ef860a24SChandler Carruth     case FCMP_UEQ: case FCMP_UNE:
3668ef860a24SChandler Carruth     case FCMP_ORD: case FCMP_UNO:
3669ef860a24SChandler Carruth       return pred;
3670ef860a24SChandler Carruth     case FCMP_OGT: return FCMP_OLT;
3671ef860a24SChandler Carruth     case FCMP_OLT: return FCMP_OGT;
3672ef860a24SChandler Carruth     case FCMP_OGE: return FCMP_OLE;
3673ef860a24SChandler Carruth     case FCMP_OLE: return FCMP_OGE;
3674ef860a24SChandler Carruth     case FCMP_UGT: return FCMP_ULT;
3675ef860a24SChandler Carruth     case FCMP_ULT: return FCMP_UGT;
3676ef860a24SChandler Carruth     case FCMP_UGE: return FCMP_ULE;
3677ef860a24SChandler Carruth     case FCMP_ULE: return FCMP_UGE;
3678ef860a24SChandler Carruth   }
3679ef860a24SChandler Carruth }
3680ef860a24SChandler Carruth 
3681b299ade2SMax Kazantsev CmpInst::Predicate CmpInst::getNonStrictPredicate(Predicate pred) {
3682b299ade2SMax Kazantsev   switch (pred) {
3683b299ade2SMax Kazantsev   case ICMP_SGT: return ICMP_SGE;
3684b299ade2SMax Kazantsev   case ICMP_SLT: return ICMP_SLE;
3685b299ade2SMax Kazantsev   case ICMP_UGT: return ICMP_UGE;
3686b299ade2SMax Kazantsev   case ICMP_ULT: return ICMP_ULE;
3687b299ade2SMax Kazantsev   case FCMP_OGT: return FCMP_OGE;
3688b299ade2SMax Kazantsev   case FCMP_OLT: return FCMP_OLE;
3689b299ade2SMax Kazantsev   case FCMP_UGT: return FCMP_UGE;
3690b299ade2SMax Kazantsev   case FCMP_ULT: return FCMP_ULE;
3691b299ade2SMax Kazantsev   default: return pred;
3692b299ade2SMax Kazantsev   }
3693b299ade2SMax Kazantsev }
3694b299ade2SMax Kazantsev 
36956e78b17bSSanjoy Das CmpInst::Predicate CmpInst::getSignedPredicate(Predicate pred) {
36966e78b17bSSanjoy Das   assert(CmpInst::isUnsigned(pred) && "Call only with signed predicates!");
36976e78b17bSSanjoy Das 
36986e78b17bSSanjoy Das   switch (pred) {
36996e78b17bSSanjoy Das   default:
37006e78b17bSSanjoy Das     llvm_unreachable("Unknown predicate!");
37016e78b17bSSanjoy Das   case CmpInst::ICMP_ULT:
37026e78b17bSSanjoy Das     return CmpInst::ICMP_SLT;
37036e78b17bSSanjoy Das   case CmpInst::ICMP_ULE:
37046e78b17bSSanjoy Das     return CmpInst::ICMP_SLE;
37056e78b17bSSanjoy Das   case CmpInst::ICMP_UGT:
37066e78b17bSSanjoy Das     return CmpInst::ICMP_SGT;
37076e78b17bSSanjoy Das   case CmpInst::ICMP_UGE:
37086e78b17bSSanjoy Das     return CmpInst::ICMP_SGE;
37096e78b17bSSanjoy Das   }
37106e78b17bSSanjoy Das }
37116e78b17bSSanjoy Das 
37121c3f2831SCraig Topper bool CmpInst::isUnsigned(Predicate predicate) {
3713ef860a24SChandler Carruth   switch (predicate) {
3714ef860a24SChandler Carruth     default: return false;
3715ef860a24SChandler Carruth     case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE: case ICmpInst::ICMP_UGT:
3716ef860a24SChandler Carruth     case ICmpInst::ICMP_UGE: return true;
3717ef860a24SChandler Carruth   }
3718ef860a24SChandler Carruth }
3719ef860a24SChandler Carruth 
37201c3f2831SCraig Topper bool CmpInst::isSigned(Predicate predicate) {
3721ef860a24SChandler Carruth   switch (predicate) {
3722ef860a24SChandler Carruth     default: return false;
3723ef860a24SChandler Carruth     case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_SLE: case ICmpInst::ICMP_SGT:
3724ef860a24SChandler Carruth     case ICmpInst::ICMP_SGE: return true;
3725ef860a24SChandler Carruth   }
3726ef860a24SChandler Carruth }
3727ef860a24SChandler Carruth 
37281c3f2831SCraig Topper bool CmpInst::isOrdered(Predicate predicate) {
3729ef860a24SChandler Carruth   switch (predicate) {
3730ef860a24SChandler Carruth     default: return false;
3731ef860a24SChandler Carruth     case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_OGT:
3732ef860a24SChandler Carruth     case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLE:
3733ef860a24SChandler Carruth     case FCmpInst::FCMP_ORD: return true;
3734ef860a24SChandler Carruth   }
3735ef860a24SChandler Carruth }
3736ef860a24SChandler Carruth 
37371c3f2831SCraig Topper bool CmpInst::isUnordered(Predicate predicate) {
3738ef860a24SChandler Carruth   switch (predicate) {
3739ef860a24SChandler Carruth     default: return false;
3740ef860a24SChandler Carruth     case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UNE: case FCmpInst::FCMP_UGT:
3741ef860a24SChandler Carruth     case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_UGE: case FCmpInst::FCMP_ULE:
3742ef860a24SChandler Carruth     case FCmpInst::FCMP_UNO: return true;
3743ef860a24SChandler Carruth   }
3744ef860a24SChandler Carruth }
3745ef860a24SChandler Carruth 
37461c3f2831SCraig Topper bool CmpInst::isTrueWhenEqual(Predicate predicate) {
3747ef860a24SChandler Carruth   switch(predicate) {
3748ef860a24SChandler Carruth     default: return false;
3749ef860a24SChandler Carruth     case ICMP_EQ:   case ICMP_UGE: case ICMP_ULE: case ICMP_SGE: case ICMP_SLE:
3750ef860a24SChandler Carruth     case FCMP_TRUE: case FCMP_UEQ: case FCMP_UGE: case FCMP_ULE: return true;
3751ef860a24SChandler Carruth   }
3752ef860a24SChandler Carruth }
3753ef860a24SChandler Carruth 
37541c3f2831SCraig Topper bool CmpInst::isFalseWhenEqual(Predicate predicate) {
3755ef860a24SChandler Carruth   switch(predicate) {
3756ef860a24SChandler Carruth   case ICMP_NE:    case ICMP_UGT: case ICMP_ULT: case ICMP_SGT: case ICMP_SLT:
3757ef860a24SChandler Carruth   case FCMP_FALSE: case FCMP_ONE: case FCMP_OGT: case FCMP_OLT: return true;
3758ef860a24SChandler Carruth   default: return false;
3759ef860a24SChandler Carruth   }
3760ef860a24SChandler Carruth }
3761ef860a24SChandler Carruth 
376299bc480bSChad Rosier bool CmpInst::isImpliedTrueByMatchingCmp(Predicate Pred1, Predicate Pred2) {
3763af83e40dSChad Rosier   // If the predicates match, then we know the first condition implies the
3764af83e40dSChad Rosier   // second is true.
3765af83e40dSChad Rosier   if (Pred1 == Pred2)
3766af83e40dSChad Rosier     return true;
3767af83e40dSChad Rosier 
3768af83e40dSChad Rosier   switch (Pred1) {
3769af83e40dSChad Rosier   default:
3770af83e40dSChad Rosier     break;
37711a601590SChad Rosier   case ICMP_EQ:
37723d75f8ceSChad Rosier     // A == B implies A >=u B, A <=u B, A >=s B, and A <=s B are true.
37731a601590SChad Rosier     return Pred2 == ICMP_UGE || Pred2 == ICMP_ULE || Pred2 == ICMP_SGE ||
37741a601590SChad Rosier            Pred2 == ICMP_SLE;
37753456cb56SChad Rosier   case ICMP_UGT: // A >u B implies A != B and A >=u B are true.
37763456cb56SChad Rosier     return Pred2 == ICMP_NE || Pred2 == ICMP_UGE;
37773456cb56SChad Rosier   case ICMP_ULT: // A <u B implies A != B and A <=u B are true.
37783456cb56SChad Rosier     return Pred2 == ICMP_NE || Pred2 == ICMP_ULE;
37793456cb56SChad Rosier   case ICMP_SGT: // A >s B implies A != B and A >=s B are true.
37803456cb56SChad Rosier     return Pred2 == ICMP_NE || Pred2 == ICMP_SGE;
37813456cb56SChad Rosier   case ICMP_SLT: // A <s B implies A != B and A <=s B are true.
37823456cb56SChad Rosier     return Pred2 == ICMP_NE || Pred2 == ICMP_SLE;
3783af83e40dSChad Rosier   }
3784af83e40dSChad Rosier   return false;
3785af83e40dSChad Rosier }
3786af83e40dSChad Rosier 
378799bc480bSChad Rosier bool CmpInst::isImpliedFalseByMatchingCmp(Predicate Pred1, Predicate Pred2) {
37881a601590SChad Rosier   return isImpliedTrueByMatchingCmp(Pred1, getInversePredicate(Pred2));
3789af83e40dSChad Rosier }
3790ef860a24SChandler Carruth 
3791ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
3792ef860a24SChandler Carruth //                        SwitchInst Implementation
3793ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
3794ef860a24SChandler Carruth 
3795ef860a24SChandler Carruth void SwitchInst::init(Value *Value, BasicBlock *Default, unsigned NumReserved) {
3796ef860a24SChandler Carruth   assert(Value && Default && NumReserved);
3797ef860a24SChandler Carruth   ReservedSpace = NumReserved;
3798b4eede2cSPete Cooper   setNumHungOffUseOperands(2);
37993fc30408SPete Cooper   allocHungoffUses(ReservedSpace);
3800ef860a24SChandler Carruth 
3801eb31b68cSPete Cooper   Op<0>() = Value;
3802eb31b68cSPete Cooper   Op<1>() = Default;
3803ef860a24SChandler Carruth }
3804ef860a24SChandler Carruth 
3805ef860a24SChandler Carruth /// SwitchInst ctor - Create a new switch instruction, specifying a value to
3806ef860a24SChandler Carruth /// switch on and a default destination.  The number of additional cases can
3807ef860a24SChandler Carruth /// be specified here to make memory allocation more efficient.  This
3808ef860a24SChandler Carruth /// constructor can also autoinsert before another instruction.
3809ef860a24SChandler Carruth SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
3810ef860a24SChandler Carruth                        Instruction *InsertBefore)
3811509e20e0SChandler Carruth     : Instruction(Type::getVoidTy(Value->getContext()), Instruction::Switch,
3812c620761cSCraig Topper                   nullptr, 0, InsertBefore) {
3813ef860a24SChandler Carruth   init(Value, Default, 2+NumCases*2);
3814ef860a24SChandler Carruth }
3815ef860a24SChandler Carruth 
3816ef860a24SChandler Carruth /// SwitchInst ctor - Create a new switch instruction, specifying a value to
3817ef860a24SChandler Carruth /// switch on and a default destination.  The number of additional cases can
3818ef860a24SChandler Carruth /// be specified here to make memory allocation more efficient.  This
3819ef860a24SChandler Carruth /// constructor also autoinserts at the end of the specified BasicBlock.
3820ef860a24SChandler Carruth SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
3821ef860a24SChandler Carruth                        BasicBlock *InsertAtEnd)
3822509e20e0SChandler Carruth     : Instruction(Type::getVoidTy(Value->getContext()), Instruction::Switch,
3823c620761cSCraig Topper                   nullptr, 0, InsertAtEnd) {
3824ef860a24SChandler Carruth   init(Value, Default, 2+NumCases*2);
3825ef860a24SChandler Carruth }
3826ef860a24SChandler Carruth 
3827ef860a24SChandler Carruth SwitchInst::SwitchInst(const SwitchInst &SI)
3828509e20e0SChandler Carruth     : Instruction(SI.getType(), Instruction::Switch, nullptr, 0) {
3829ef860a24SChandler Carruth   init(SI.getCondition(), SI.getDefaultDest(), SI.getNumOperands());
3830b4eede2cSPete Cooper   setNumHungOffUseOperands(SI.getNumOperands());
383174510a40SPete Cooper   Use *OL = getOperandList();
383274510a40SPete Cooper   const Use *InOL = SI.getOperandList();
3833ef860a24SChandler Carruth   for (unsigned i = 2, E = SI.getNumOperands(); i != E; i += 2) {
3834ef860a24SChandler Carruth     OL[i] = InOL[i];
3835ef860a24SChandler Carruth     OL[i+1] = InOL[i+1];
3836ef860a24SChandler Carruth   }
3837ef860a24SChandler Carruth   SubclassOptionalData = SI.SubclassOptionalData;
3838ef860a24SChandler Carruth }
3839ef860a24SChandler Carruth 
3840ef860a24SChandler Carruth /// addCase - Add an entry to the switch instruction...
3841ef860a24SChandler Carruth ///
3842ef860a24SChandler Carruth void SwitchInst::addCase(ConstantInt *OnVal, BasicBlock *Dest) {
3843ef860a24SChandler Carruth   unsigned NewCaseIdx = getNumCases();
3844b4eede2cSPete Cooper   unsigned OpNo = getNumOperands();
3845ef860a24SChandler Carruth   if (OpNo+2 > ReservedSpace)
3846ef860a24SChandler Carruth     growOperands();  // Get more space!
3847ef860a24SChandler Carruth   // Initialize some new operands.
3848ef860a24SChandler Carruth   assert(OpNo+1 < ReservedSpace && "Growing didn't work!");
3849b4eede2cSPete Cooper   setNumHungOffUseOperands(OpNo+2);
3850927d8e61SChandler Carruth   CaseHandle Case(this, NewCaseIdx);
3851e407736aSBob Wilson   Case.setValue(OnVal);
3852ef860a24SChandler Carruth   Case.setSuccessor(Dest);
3853ef860a24SChandler Carruth }
3854ef860a24SChandler Carruth 
3855ef860a24SChandler Carruth /// removeCase - This method removes the specified case and its successor
3856ef860a24SChandler Carruth /// from the switch instruction.
3857927d8e61SChandler Carruth SwitchInst::CaseIt SwitchInst::removeCase(CaseIt I) {
3858927d8e61SChandler Carruth   unsigned idx = I->getCaseIndex();
3859ef860a24SChandler Carruth 
3860ef860a24SChandler Carruth   assert(2 + idx*2 < getNumOperands() && "Case index out of range!!!");
3861ef860a24SChandler Carruth 
3862ef860a24SChandler Carruth   unsigned NumOps = getNumOperands();
386374510a40SPete Cooper   Use *OL = getOperandList();
3864ef860a24SChandler Carruth 
3865ef860a24SChandler Carruth   // Overwrite this case with the end of the list.
3866ef860a24SChandler Carruth   if (2 + (idx + 1) * 2 != NumOps) {
3867ef860a24SChandler Carruth     OL[2 + idx * 2] = OL[NumOps - 2];
3868ef860a24SChandler Carruth     OL[2 + idx * 2 + 1] = OL[NumOps - 1];
3869ef860a24SChandler Carruth   }
3870ef860a24SChandler Carruth 
3871ef860a24SChandler Carruth   // Nuke the last value.
3872c620761cSCraig Topper   OL[NumOps-2].set(nullptr);
3873c620761cSCraig Topper   OL[NumOps-2+1].set(nullptr);
3874b4eede2cSPete Cooper   setNumHungOffUseOperands(NumOps-2);
38750d256c0fSChandler Carruth 
38760d256c0fSChandler Carruth   return CaseIt(this, idx);
3877ef860a24SChandler Carruth }
3878ef860a24SChandler Carruth 
3879ef860a24SChandler Carruth /// growOperands - grow operands - This grows the operand list in response
3880ef860a24SChandler Carruth /// to a push_back style of operation.  This grows the number of ops by 3 times.
3881ef860a24SChandler Carruth ///
3882ef860a24SChandler Carruth void SwitchInst::growOperands() {
3883ef860a24SChandler Carruth   unsigned e = getNumOperands();
3884ef860a24SChandler Carruth   unsigned NumOps = e*3;
3885ef860a24SChandler Carruth 
3886ef860a24SChandler Carruth   ReservedSpace = NumOps;
388793f9ff57SPete Cooper   growHungoffUses(ReservedSpace);
3888ef860a24SChandler Carruth }
3889ef860a24SChandler Carruth 
3890c652b345SYevgeny Rouban MDNode *
3891c652b345SYevgeny Rouban SwitchInstProfUpdateWrapper::getProfBranchWeightsMD(const SwitchInst &SI) {
3892c652b345SYevgeny Rouban   if (MDNode *ProfileData = SI.getMetadata(LLVMContext::MD_prof))
3893c652b345SYevgeny Rouban     if (auto *MDName = dyn_cast<MDString>(ProfileData->getOperand(0)))
3894c652b345SYevgeny Rouban       if (MDName->getString() == "branch_weights")
3895c652b345SYevgeny Rouban         return ProfileData;
3896c652b345SYevgeny Rouban   return nullptr;
3897c652b345SYevgeny Rouban }
3898c652b345SYevgeny Rouban 
3899c652b345SYevgeny Rouban MDNode *SwitchInstProfUpdateWrapper::buildProfBranchWeightsMD() {
3900bdfe84adSYevgeny Rouban   assert(Changed && "called only if metadata has changed");
3901c652b345SYevgeny Rouban 
3902c652b345SYevgeny Rouban   if (!Weights)
3903c652b345SYevgeny Rouban     return nullptr;
3904c652b345SYevgeny Rouban 
3905c652b345SYevgeny Rouban   assert(SI.getNumSuccessors() == Weights->size() &&
3906c652b345SYevgeny Rouban          "num of prof branch_weights must accord with num of successors");
3907c652b345SYevgeny Rouban 
3908c652b345SYevgeny Rouban   bool AllZeroes =
3909c652b345SYevgeny Rouban       all_of(Weights.getValue(), [](uint32_t W) { return W == 0; });
3910c652b345SYevgeny Rouban 
3911c652b345SYevgeny Rouban   if (AllZeroes || Weights.getValue().size() < 2)
3912c652b345SYevgeny Rouban     return nullptr;
3913c652b345SYevgeny Rouban 
3914c652b345SYevgeny Rouban   return MDBuilder(SI.getParent()->getContext()).createBranchWeights(*Weights);
3915c652b345SYevgeny Rouban }
3916c652b345SYevgeny Rouban 
39174f9e6814SYevgeny Rouban void SwitchInstProfUpdateWrapper::init() {
3918c652b345SYevgeny Rouban   MDNode *ProfileData = getProfBranchWeightsMD(SI);
3919bdfe84adSYevgeny Rouban   if (!ProfileData)
39204f9e6814SYevgeny Rouban     return;
39214f9e6814SYevgeny Rouban 
39224f9e6814SYevgeny Rouban   if (ProfileData->getNumOperands() != SI.getNumSuccessors() + 1) {
3923592f44a7SYevgeny Rouban     llvm_unreachable("number of prof branch_weights metadata operands does "
3924592f44a7SYevgeny Rouban                      "not correspond to number of succesors");
39254f9e6814SYevgeny Rouban   }
3926c652b345SYevgeny Rouban 
3927c652b345SYevgeny Rouban   SmallVector<uint32_t, 8> Weights;
3928c652b345SYevgeny Rouban   for (unsigned CI = 1, CE = SI.getNumSuccessors(); CI <= CE; ++CI) {
3929c652b345SYevgeny Rouban     ConstantInt *C = mdconst::extract<ConstantInt>(ProfileData->getOperand(CI));
3930c652b345SYevgeny Rouban     uint32_t CW = C->getValue().getZExtValue();
3931c652b345SYevgeny Rouban     Weights.push_back(CW);
3932c652b345SYevgeny Rouban   }
39334f9e6814SYevgeny Rouban   this->Weights = std::move(Weights);
3934c652b345SYevgeny Rouban }
3935c652b345SYevgeny Rouban 
3936c652b345SYevgeny Rouban SwitchInst::CaseIt
3937c652b345SYevgeny Rouban SwitchInstProfUpdateWrapper::removeCase(SwitchInst::CaseIt I) {
3938c652b345SYevgeny Rouban   if (Weights) {
3939c652b345SYevgeny Rouban     assert(SI.getNumSuccessors() == Weights->size() &&
3940c652b345SYevgeny Rouban            "num of prof branch_weights must accord with num of successors");
3941bdfe84adSYevgeny Rouban     Changed = true;
3942c652b345SYevgeny Rouban     // Copy the last case to the place of the removed one and shrink.
3943c652b345SYevgeny Rouban     // This is tightly coupled with the way SwitchInst::removeCase() removes
3944c652b345SYevgeny Rouban     // the cases in SwitchInst::removeCase(CaseIt).
3945c652b345SYevgeny Rouban     Weights.getValue()[I->getCaseIndex() + 1] = Weights.getValue().back();
3946c652b345SYevgeny Rouban     Weights.getValue().pop_back();
3947c652b345SYevgeny Rouban   }
3948c652b345SYevgeny Rouban   return SI.removeCase(I);
3949c652b345SYevgeny Rouban }
3950c652b345SYevgeny Rouban 
3951c652b345SYevgeny Rouban void SwitchInstProfUpdateWrapper::addCase(
3952c652b345SYevgeny Rouban     ConstantInt *OnVal, BasicBlock *Dest,
3953c652b345SYevgeny Rouban     SwitchInstProfUpdateWrapper::CaseWeightOpt W) {
3954c652b345SYevgeny Rouban   SI.addCase(OnVal, Dest);
3955c652b345SYevgeny Rouban 
3956c652b345SYevgeny Rouban   if (!Weights && W && *W) {
3957bdfe84adSYevgeny Rouban     Changed = true;
3958c652b345SYevgeny Rouban     Weights = SmallVector<uint32_t, 8>(SI.getNumSuccessors(), 0);
3959c652b345SYevgeny Rouban     Weights.getValue()[SI.getNumSuccessors() - 1] = *W;
3960c652b345SYevgeny Rouban   } else if (Weights) {
3961bdfe84adSYevgeny Rouban     Changed = true;
3962c652b345SYevgeny Rouban     Weights.getValue().push_back(W ? *W : 0);
3963c652b345SYevgeny Rouban   }
3964c652b345SYevgeny Rouban   if (Weights)
3965c652b345SYevgeny Rouban     assert(SI.getNumSuccessors() == Weights->size() &&
3966c652b345SYevgeny Rouban            "num of prof branch_weights must accord with num of successors");
3967c652b345SYevgeny Rouban }
3968c652b345SYevgeny Rouban 
3969c652b345SYevgeny Rouban SymbolTableList<Instruction>::iterator
3970c652b345SYevgeny Rouban SwitchInstProfUpdateWrapper::eraseFromParent() {
3971c652b345SYevgeny Rouban   // Instruction is erased. Mark as unchanged to not touch it in the destructor.
3972bdfe84adSYevgeny Rouban   Changed = false;
3973c652b345SYevgeny Rouban   if (Weights)
3974c652b345SYevgeny Rouban     Weights->resize(0);
3975c652b345SYevgeny Rouban   return SI.eraseFromParent();
3976c652b345SYevgeny Rouban }
3977c652b345SYevgeny Rouban 
3978c652b345SYevgeny Rouban SwitchInstProfUpdateWrapper::CaseWeightOpt
3979c652b345SYevgeny Rouban SwitchInstProfUpdateWrapper::getSuccessorWeight(unsigned idx) {
3980c652b345SYevgeny Rouban   if (!Weights)
3981c652b345SYevgeny Rouban     return None;
3982c652b345SYevgeny Rouban   return Weights.getValue()[idx];
3983c652b345SYevgeny Rouban }
3984c652b345SYevgeny Rouban 
3985c652b345SYevgeny Rouban void SwitchInstProfUpdateWrapper::setSuccessorWeight(
3986c652b345SYevgeny Rouban     unsigned idx, SwitchInstProfUpdateWrapper::CaseWeightOpt W) {
3987bdfe84adSYevgeny Rouban   if (!W)
3988c652b345SYevgeny Rouban     return;
3989c652b345SYevgeny Rouban 
3990c652b345SYevgeny Rouban   if (!Weights && *W)
3991c652b345SYevgeny Rouban     Weights = SmallVector<uint32_t, 8>(SI.getNumSuccessors(), 0);
3992c652b345SYevgeny Rouban 
3993c652b345SYevgeny Rouban   if (Weights) {
3994c652b345SYevgeny Rouban     auto &OldW = Weights.getValue()[idx];
3995c652b345SYevgeny Rouban     if (*W != OldW) {
3996bdfe84adSYevgeny Rouban       Changed = true;
3997c652b345SYevgeny Rouban       OldW = *W;
3998c652b345SYevgeny Rouban     }
3999c652b345SYevgeny Rouban   }
4000c652b345SYevgeny Rouban }
4001c652b345SYevgeny Rouban 
4002c652b345SYevgeny Rouban SwitchInstProfUpdateWrapper::CaseWeightOpt
4003c652b345SYevgeny Rouban SwitchInstProfUpdateWrapper::getSuccessorWeight(const SwitchInst &SI,
4004c652b345SYevgeny Rouban                                                 unsigned idx) {
4005c652b345SYevgeny Rouban   if (MDNode *ProfileData = getProfBranchWeightsMD(SI))
40064f9e6814SYevgeny Rouban     if (ProfileData->getNumOperands() == SI.getNumSuccessors() + 1)
4007c652b345SYevgeny Rouban       return mdconst::extract<ConstantInt>(ProfileData->getOperand(idx + 1))
4008c652b345SYevgeny Rouban           ->getValue()
4009c652b345SYevgeny Rouban           .getZExtValue();
4010c652b345SYevgeny Rouban 
4011c652b345SYevgeny Rouban   return None;
4012c652b345SYevgeny Rouban }
4013c652b345SYevgeny Rouban 
4014ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
4015ef860a24SChandler Carruth //                        IndirectBrInst Implementation
4016ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
4017ef860a24SChandler Carruth 
4018ef860a24SChandler Carruth void IndirectBrInst::init(Value *Address, unsigned NumDests) {
4019ef860a24SChandler Carruth   assert(Address && Address->getType()->isPointerTy() &&
4020ef860a24SChandler Carruth          "Address of indirectbr must be a pointer");
4021ef860a24SChandler Carruth   ReservedSpace = 1+NumDests;
4022b4eede2cSPete Cooper   setNumHungOffUseOperands(1);
40233fc30408SPete Cooper   allocHungoffUses(ReservedSpace);
4024ef860a24SChandler Carruth 
4025eb31b68cSPete Cooper   Op<0>() = Address;
4026ef860a24SChandler Carruth }
4027ef860a24SChandler Carruth 
4028ef860a24SChandler Carruth 
4029ef860a24SChandler Carruth /// growOperands - grow operands - This grows the operand list in response
4030ef860a24SChandler Carruth /// to a push_back style of operation.  This grows the number of ops by 2 times.
4031ef860a24SChandler Carruth ///
4032ef860a24SChandler Carruth void IndirectBrInst::growOperands() {
4033ef860a24SChandler Carruth   unsigned e = getNumOperands();
4034ef860a24SChandler Carruth   unsigned NumOps = e*2;
4035ef860a24SChandler Carruth 
4036ef860a24SChandler Carruth   ReservedSpace = NumOps;
403793f9ff57SPete Cooper   growHungoffUses(ReservedSpace);
4038ef860a24SChandler Carruth }
4039ef860a24SChandler Carruth 
4040ef860a24SChandler Carruth IndirectBrInst::IndirectBrInst(Value *Address, unsigned NumCases,
4041ef860a24SChandler Carruth                                Instruction *InsertBefore)
4042509e20e0SChandler Carruth     : Instruction(Type::getVoidTy(Address->getContext()),
4043509e20e0SChandler Carruth                   Instruction::IndirectBr, nullptr, 0, InsertBefore) {
4044ef860a24SChandler Carruth   init(Address, NumCases);
4045ef860a24SChandler Carruth }
4046ef860a24SChandler Carruth 
4047ef860a24SChandler Carruth IndirectBrInst::IndirectBrInst(Value *Address, unsigned NumCases,
4048ef860a24SChandler Carruth                                BasicBlock *InsertAtEnd)
4049509e20e0SChandler Carruth     : Instruction(Type::getVoidTy(Address->getContext()),
4050509e20e0SChandler Carruth                   Instruction::IndirectBr, nullptr, 0, InsertAtEnd) {
4051ef860a24SChandler Carruth   init(Address, NumCases);
4052ef860a24SChandler Carruth }
4053ef860a24SChandler Carruth 
4054ef860a24SChandler Carruth IndirectBrInst::IndirectBrInst(const IndirectBrInst &IBI)
4055509e20e0SChandler Carruth     : Instruction(Type::getVoidTy(IBI.getContext()), Instruction::IndirectBr,
40563fc30408SPete Cooper                   nullptr, IBI.getNumOperands()) {
40573fc30408SPete Cooper   allocHungoffUses(IBI.getNumOperands());
405874510a40SPete Cooper   Use *OL = getOperandList();
405974510a40SPete Cooper   const Use *InOL = IBI.getOperandList();
4060ef860a24SChandler Carruth   for (unsigned i = 0, E = IBI.getNumOperands(); i != E; ++i)
4061ef860a24SChandler Carruth     OL[i] = InOL[i];
4062ef860a24SChandler Carruth   SubclassOptionalData = IBI.SubclassOptionalData;
4063ef860a24SChandler Carruth }
4064ef860a24SChandler Carruth 
4065ef860a24SChandler Carruth /// addDestination - Add a destination.
4066ef860a24SChandler Carruth ///
4067ef860a24SChandler Carruth void IndirectBrInst::addDestination(BasicBlock *DestBB) {
4068b4eede2cSPete Cooper   unsigned OpNo = getNumOperands();
4069ef860a24SChandler Carruth   if (OpNo+1 > ReservedSpace)
4070ef860a24SChandler Carruth     growOperands();  // Get more space!
4071ef860a24SChandler Carruth   // Initialize some new operands.
4072ef860a24SChandler Carruth   assert(OpNo < ReservedSpace && "Growing didn't work!");
4073b4eede2cSPete Cooper   setNumHungOffUseOperands(OpNo+1);
407474510a40SPete Cooper   getOperandList()[OpNo] = DestBB;
4075ef860a24SChandler Carruth }
4076ef860a24SChandler Carruth 
4077ef860a24SChandler Carruth /// removeDestination - This method removes the specified successor from the
4078ef860a24SChandler Carruth /// indirectbr instruction.
4079ef860a24SChandler Carruth void IndirectBrInst::removeDestination(unsigned idx) {
4080ef860a24SChandler Carruth   assert(idx < getNumOperands()-1 && "Successor index out of range!");
4081ef860a24SChandler Carruth 
4082ef860a24SChandler Carruth   unsigned NumOps = getNumOperands();
408374510a40SPete Cooper   Use *OL = getOperandList();
4084ef860a24SChandler Carruth 
4085ef860a24SChandler Carruth   // Replace this value with the last one.
4086ef860a24SChandler Carruth   OL[idx+1] = OL[NumOps-1];
4087ef860a24SChandler Carruth 
4088ef860a24SChandler Carruth   // Nuke the last value.
4089c620761cSCraig Topper   OL[NumOps-1].set(nullptr);
4090b4eede2cSPete Cooper   setNumHungOffUseOperands(NumOps-1);
4091ef860a24SChandler Carruth }
4092ef860a24SChandler Carruth 
4093ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
409475403d77SPete Cooper //                           cloneImpl() implementations
4095ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
4096ef860a24SChandler Carruth 
4097ef860a24SChandler Carruth // Define these methods here so vtables don't get emitted into every translation
4098ef860a24SChandler Carruth // unit that uses these classes.
4099ef860a24SChandler Carruth 
410075403d77SPete Cooper GetElementPtrInst *GetElementPtrInst::cloneImpl() const {
4101ef860a24SChandler Carruth   return new (getNumOperands()) GetElementPtrInst(*this);
4102ef860a24SChandler Carruth }
4103ef860a24SChandler Carruth 
4104cbde0d9cSCameron McInally UnaryOperator *UnaryOperator::cloneImpl() const {
4105cbde0d9cSCameron McInally   return Create(getOpcode(), Op<0>());
4106cbde0d9cSCameron McInally }
4107cbde0d9cSCameron McInally 
410875403d77SPete Cooper BinaryOperator *BinaryOperator::cloneImpl() const {
4109ef860a24SChandler Carruth   return Create(getOpcode(), Op<0>(), Op<1>());
4110ef860a24SChandler Carruth }
4111ef860a24SChandler Carruth 
411275403d77SPete Cooper FCmpInst *FCmpInst::cloneImpl() const {
4113ef860a24SChandler Carruth   return new FCmpInst(getPredicate(), Op<0>(), Op<1>());
4114ef860a24SChandler Carruth }
4115ef860a24SChandler Carruth 
411675403d77SPete Cooper ICmpInst *ICmpInst::cloneImpl() const {
4117ef860a24SChandler Carruth   return new ICmpInst(getPredicate(), Op<0>(), Op<1>());
4118ef860a24SChandler Carruth }
4119ef860a24SChandler Carruth 
412075403d77SPete Cooper ExtractValueInst *ExtractValueInst::cloneImpl() const {
4121ef860a24SChandler Carruth   return new ExtractValueInst(*this);
4122ef860a24SChandler Carruth }
4123ef860a24SChandler Carruth 
412475403d77SPete Cooper InsertValueInst *InsertValueInst::cloneImpl() const {
4125ef860a24SChandler Carruth   return new InsertValueInst(*this);
4126ef860a24SChandler Carruth }
4127ef860a24SChandler Carruth 
412875403d77SPete Cooper AllocaInst *AllocaInst::cloneImpl() const {
41296b3244c4SDavid Majnemer   AllocaInst *Result = new AllocaInst(getAllocatedType(),
41303c1fc768SMatt Arsenault                                       getType()->getAddressSpace(),
41316b3244c4SDavid Majnemer                                       (Value *)getOperand(0), getAlignment());
41326b3244c4SDavid Majnemer   Result->setUsedWithInAlloca(isUsedWithInAlloca());
41339bfd0d03SManman Ren   Result->setSwiftError(isSwiftError());
41346b3244c4SDavid Majnemer   return Result;
4135ef860a24SChandler Carruth }
4136ef860a24SChandler Carruth 
413775403d77SPete Cooper LoadInst *LoadInst::cloneImpl() const {
413884c1dbdeSJames Y Knight   return new LoadInst(getType(), getOperand(0), Twine(), isVolatile(),
4139734c74baSGuillaume Chatelet                       MaybeAlign(getAlignment()), getOrdering(),
4140734c74baSGuillaume Chatelet                       getSyncScopeID());
4141ef860a24SChandler Carruth }
4142ef860a24SChandler Carruth 
414375403d77SPete Cooper StoreInst *StoreInst::cloneImpl() const {
4144ef860a24SChandler Carruth   return new StoreInst(getOperand(0), getOperand(1), isVolatile(),
4145*5b99c189SGuillaume Chatelet                        MaybeAlign(getAlignment()), getOrdering(),
4146*5b99c189SGuillaume Chatelet                        getSyncScopeID());
4147ef860a24SChandler Carruth }
4148ef860a24SChandler Carruth 
414975403d77SPete Cooper AtomicCmpXchgInst *AtomicCmpXchgInst::cloneImpl() const {
4150ef860a24SChandler Carruth   AtomicCmpXchgInst *Result =
4151ef860a24SChandler Carruth     new AtomicCmpXchgInst(getOperand(0), getOperand(1), getOperand(2),
4152e94a518aSTim Northover                           getSuccessOrdering(), getFailureOrdering(),
4153bb80d3e1SKonstantin Zhuravlyov                           getSyncScopeID());
4154ef860a24SChandler Carruth   Result->setVolatile(isVolatile());
4155420a2168STim Northover   Result->setWeak(isWeak());
4156ef860a24SChandler Carruth   return Result;
4157ef860a24SChandler Carruth }
4158ef860a24SChandler Carruth 
415975403d77SPete Cooper AtomicRMWInst *AtomicRMWInst::cloneImpl() const {
4160ef860a24SChandler Carruth   AtomicRMWInst *Result =
4161ef860a24SChandler Carruth     new AtomicRMWInst(getOperation(), getOperand(0), getOperand(1),
4162bb80d3e1SKonstantin Zhuravlyov                       getOrdering(), getSyncScopeID());
4163ef860a24SChandler Carruth   Result->setVolatile(isVolatile());
4164ef860a24SChandler Carruth   return Result;
4165ef860a24SChandler Carruth }
4166ef860a24SChandler Carruth 
416775403d77SPete Cooper FenceInst *FenceInst::cloneImpl() const {
4168bb80d3e1SKonstantin Zhuravlyov   return new FenceInst(getContext(), getOrdering(), getSyncScopeID());
4169ef860a24SChandler Carruth }
4170ef860a24SChandler Carruth 
417175403d77SPete Cooper TruncInst *TruncInst::cloneImpl() const {
4172ef860a24SChandler Carruth   return new TruncInst(getOperand(0), getType());
4173ef860a24SChandler Carruth }
4174ef860a24SChandler Carruth 
417575403d77SPete Cooper ZExtInst *ZExtInst::cloneImpl() const {
4176ef860a24SChandler Carruth   return new ZExtInst(getOperand(0), getType());
4177ef860a24SChandler Carruth }
4178ef860a24SChandler Carruth 
417975403d77SPete Cooper SExtInst *SExtInst::cloneImpl() const {
4180ef860a24SChandler Carruth   return new SExtInst(getOperand(0), getType());
4181ef860a24SChandler Carruth }
4182ef860a24SChandler Carruth 
418375403d77SPete Cooper FPTruncInst *FPTruncInst::cloneImpl() const {
4184ef860a24SChandler Carruth   return new FPTruncInst(getOperand(0), getType());
4185ef860a24SChandler Carruth }
4186ef860a24SChandler Carruth 
418775403d77SPete Cooper FPExtInst *FPExtInst::cloneImpl() const {
4188ef860a24SChandler Carruth   return new FPExtInst(getOperand(0), getType());
4189ef860a24SChandler Carruth }
4190ef860a24SChandler Carruth 
419175403d77SPete Cooper UIToFPInst *UIToFPInst::cloneImpl() const {
4192ef860a24SChandler Carruth   return new UIToFPInst(getOperand(0), getType());
4193ef860a24SChandler Carruth }
4194ef860a24SChandler Carruth 
419575403d77SPete Cooper SIToFPInst *SIToFPInst::cloneImpl() const {
4196ef860a24SChandler Carruth   return new SIToFPInst(getOperand(0), getType());
4197ef860a24SChandler Carruth }
4198ef860a24SChandler Carruth 
419975403d77SPete Cooper FPToUIInst *FPToUIInst::cloneImpl() const {
4200ef860a24SChandler Carruth   return new FPToUIInst(getOperand(0), getType());
4201ef860a24SChandler Carruth }
4202ef860a24SChandler Carruth 
420375403d77SPete Cooper FPToSIInst *FPToSIInst::cloneImpl() const {
4204ef860a24SChandler Carruth   return new FPToSIInst(getOperand(0), getType());
4205ef860a24SChandler Carruth }
4206ef860a24SChandler Carruth 
420775403d77SPete Cooper PtrToIntInst *PtrToIntInst::cloneImpl() const {
4208ef860a24SChandler Carruth   return new PtrToIntInst(getOperand(0), getType());
4209ef860a24SChandler Carruth }
4210ef860a24SChandler Carruth 
421175403d77SPete Cooper IntToPtrInst *IntToPtrInst::cloneImpl() const {
4212ef860a24SChandler Carruth   return new IntToPtrInst(getOperand(0), getType());
4213ef860a24SChandler Carruth }
4214ef860a24SChandler Carruth 
421575403d77SPete Cooper BitCastInst *BitCastInst::cloneImpl() const {
4216ef860a24SChandler Carruth   return new BitCastInst(getOperand(0), getType());
4217ef860a24SChandler Carruth }
4218ef860a24SChandler Carruth 
421975403d77SPete Cooper AddrSpaceCastInst *AddrSpaceCastInst::cloneImpl() const {
4220b03bd4d9SMatt Arsenault   return new AddrSpaceCastInst(getOperand(0), getType());
4221b03bd4d9SMatt Arsenault }
4222b03bd4d9SMatt Arsenault 
422375403d77SPete Cooper CallInst *CallInst::cloneImpl() const {
4224bd1c1bfbSSanjoy Das   if (hasOperandBundles()) {
4225bd1c1bfbSSanjoy Das     unsigned DescriptorBytes = getNumOperandBundles() * sizeof(BundleOpInfo);
4226bd1c1bfbSSanjoy Das     return new(getNumOperands(), DescriptorBytes) CallInst(*this);
4227bd1c1bfbSSanjoy Das   }
4228ef860a24SChandler Carruth   return  new(getNumOperands()) CallInst(*this);
4229ef860a24SChandler Carruth }
4230ef860a24SChandler Carruth 
423175403d77SPete Cooper SelectInst *SelectInst::cloneImpl() const {
4232ef860a24SChandler Carruth   return SelectInst::Create(getOperand(0), getOperand(1), getOperand(2));
4233ef860a24SChandler Carruth }
4234ef860a24SChandler Carruth 
423575403d77SPete Cooper VAArgInst *VAArgInst::cloneImpl() const {
4236ef860a24SChandler Carruth   return new VAArgInst(getOperand(0), getType());
4237ef860a24SChandler Carruth }
4238ef860a24SChandler Carruth 
423975403d77SPete Cooper ExtractElementInst *ExtractElementInst::cloneImpl() const {
4240ef860a24SChandler Carruth   return ExtractElementInst::Create(getOperand(0), getOperand(1));
4241ef860a24SChandler Carruth }
4242ef860a24SChandler Carruth 
424375403d77SPete Cooper InsertElementInst *InsertElementInst::cloneImpl() const {
4244ef860a24SChandler Carruth   return InsertElementInst::Create(getOperand(0), getOperand(1), getOperand(2));
4245ef860a24SChandler Carruth }
4246ef860a24SChandler Carruth 
424775403d77SPete Cooper ShuffleVectorInst *ShuffleVectorInst::cloneImpl() const {
4248ef860a24SChandler Carruth   return new ShuffleVectorInst(getOperand(0), getOperand(1), getOperand(2));
4249ef860a24SChandler Carruth }
4250ef860a24SChandler Carruth 
425175403d77SPete Cooper PHINode *PHINode::cloneImpl() const { return new PHINode(*this); }
4252ef860a24SChandler Carruth 
425375403d77SPete Cooper LandingPadInst *LandingPadInst::cloneImpl() const {
4254ef860a24SChandler Carruth   return new LandingPadInst(*this);
4255ef860a24SChandler Carruth }
4256ef860a24SChandler Carruth 
425775403d77SPete Cooper ReturnInst *ReturnInst::cloneImpl() const {
4258ef860a24SChandler Carruth   return new(getNumOperands()) ReturnInst(*this);
4259ef860a24SChandler Carruth }
4260ef860a24SChandler Carruth 
426175403d77SPete Cooper BranchInst *BranchInst::cloneImpl() const {
4262ef860a24SChandler Carruth   return new(getNumOperands()) BranchInst(*this);
4263ef860a24SChandler Carruth }
4264ef860a24SChandler Carruth 
426575403d77SPete Cooper SwitchInst *SwitchInst::cloneImpl() const { return new SwitchInst(*this); }
4266ef860a24SChandler Carruth 
426775403d77SPete Cooper IndirectBrInst *IndirectBrInst::cloneImpl() const {
4268ef860a24SChandler Carruth   return new IndirectBrInst(*this);
4269ef860a24SChandler Carruth }
4270ef860a24SChandler Carruth 
427175403d77SPete Cooper InvokeInst *InvokeInst::cloneImpl() const {
4272bd1c1bfbSSanjoy Das   if (hasOperandBundles()) {
4273bd1c1bfbSSanjoy Das     unsigned DescriptorBytes = getNumOperandBundles() * sizeof(BundleOpInfo);
4274bd1c1bfbSSanjoy Das     return new(getNumOperands(), DescriptorBytes) InvokeInst(*this);
4275bd1c1bfbSSanjoy Das   }
4276ef860a24SChandler Carruth   return new(getNumOperands()) InvokeInst(*this);
4277ef860a24SChandler Carruth }
4278ef860a24SChandler Carruth 
4279784929d0SCraig Topper CallBrInst *CallBrInst::cloneImpl() const {
4280784929d0SCraig Topper   if (hasOperandBundles()) {
4281784929d0SCraig Topper     unsigned DescriptorBytes = getNumOperandBundles() * sizeof(BundleOpInfo);
4282784929d0SCraig Topper     return new (getNumOperands(), DescriptorBytes) CallBrInst(*this);
4283784929d0SCraig Topper   }
4284784929d0SCraig Topper   return new (getNumOperands()) CallBrInst(*this);
4285784929d0SCraig Topper }
4286784929d0SCraig Topper 
428775403d77SPete Cooper ResumeInst *ResumeInst::cloneImpl() const { return new (1) ResumeInst(*this); }
4288ef860a24SChandler Carruth 
4289654e130bSDavid Majnemer CleanupReturnInst *CleanupReturnInst::cloneImpl() const {
4290654e130bSDavid Majnemer   return new (getNumOperands()) CleanupReturnInst(*this);
4291654e130bSDavid Majnemer }
4292654e130bSDavid Majnemer 
4293654e130bSDavid Majnemer CatchReturnInst *CatchReturnInst::cloneImpl() const {
42940bc0eef7SDavid Majnemer   return new (getNumOperands()) CatchReturnInst(*this);
4295654e130bSDavid Majnemer }
4296654e130bSDavid Majnemer 
42978a1c45d6SDavid Majnemer CatchSwitchInst *CatchSwitchInst::cloneImpl() const {
42988a1c45d6SDavid Majnemer   return new CatchSwitchInst(*this);
42998a1c45d6SDavid Majnemer }
43008a1c45d6SDavid Majnemer 
43018a1c45d6SDavid Majnemer FuncletPadInst *FuncletPadInst::cloneImpl() const {
43028a1c45d6SDavid Majnemer   return new (getNumOperands()) FuncletPadInst(*this);
4303654e130bSDavid Majnemer }
4304654e130bSDavid Majnemer 
430575403d77SPete Cooper UnreachableInst *UnreachableInst::cloneImpl() const {
4306ef860a24SChandler Carruth   LLVMContext &Context = getContext();
4307ef860a24SChandler Carruth   return new UnreachableInst(Context);
4308ef860a24SChandler Carruth }
4309