[IR] Add bounds checking to paramHasAttr
[oota-llvm.git] / lib / IR / Instructions.cpp
1 //===-- Instructions.cpp - Implement the LLVM instructions ----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements all of the non-inline methods for the LLVM instruction
11 // classes.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "llvm/IR/Instructions.h"
16 #include "LLVMContextImpl.h"
17 #include "llvm/IR/CallSite.h"
18 #include "llvm/IR/ConstantRange.h"
19 #include "llvm/IR/Constants.h"
20 #include "llvm/IR/DataLayout.h"
21 #include "llvm/IR/DerivedTypes.h"
22 #include "llvm/IR/Function.h"
23 #include "llvm/IR/Module.h"
24 #include "llvm/IR/Operator.h"
25 #include "llvm/Support/ErrorHandling.h"
26 #include "llvm/Support/MathExtras.h"
27 using namespace llvm;
28
29 //===----------------------------------------------------------------------===//
30 //                            CallSite Class
31 //===----------------------------------------------------------------------===//
32
33 User::op_iterator CallSite::getCallee() const {
34   Instruction *II(getInstruction());
35   return isCall()
36     ? cast<CallInst>(II)->op_end() - 1 // Skip Callee
37     : cast<InvokeInst>(II)->op_end() - 3; // Skip BB, BB, Callee
38 }
39
40 //===----------------------------------------------------------------------===//
41 //                            TerminatorInst Class
42 //===----------------------------------------------------------------------===//
43
44 // Out of line virtual method, so the vtable, etc has a home.
45 TerminatorInst::~TerminatorInst() {
46 }
47
48 //===----------------------------------------------------------------------===//
49 //                           UnaryInstruction Class
50 //===----------------------------------------------------------------------===//
51
52 // Out of line virtual method, so the vtable, etc has a home.
53 UnaryInstruction::~UnaryInstruction() {
54 }
55
56 //===----------------------------------------------------------------------===//
57 //                              SelectInst Class
58 //===----------------------------------------------------------------------===//
59
60 /// areInvalidOperands - Return a string if the specified operands are invalid
61 /// for a select operation, otherwise return null.
62 const char *SelectInst::areInvalidOperands(Value *Op0, Value *Op1, Value *Op2) {
63   if (Op1->getType() != Op2->getType())
64     return "both values to select must have same type";
65
66   if (Op1->getType()->isTokenTy())
67     return "select values cannot have token type";
68
69   if (VectorType *VT = dyn_cast<VectorType>(Op0->getType())) {
70     // Vector select.
71     if (VT->getElementType() != Type::getInt1Ty(Op0->getContext()))
72       return "vector select condition element type must be i1";
73     VectorType *ET = dyn_cast<VectorType>(Op1->getType());
74     if (!ET)
75       return "selected values for vector select must be vectors";
76     if (ET->getNumElements() != VT->getNumElements())
77       return "vector select requires selected vectors to have "
78                    "the same vector length as select condition";
79   } else if (Op0->getType() != Type::getInt1Ty(Op0->getContext())) {
80     return "select condition must be i1 or <n x i1>";
81   }
82   return nullptr;
83 }
84
85
86 //===----------------------------------------------------------------------===//
87 //                               PHINode Class
88 //===----------------------------------------------------------------------===//
89
90 PHINode::PHINode(const PHINode &PN)
91     : Instruction(PN.getType(), Instruction::PHI, nullptr, PN.getNumOperands()),
92       ReservedSpace(PN.getNumOperands()) {
93   allocHungoffUses(PN.getNumOperands());
94   std::copy(PN.op_begin(), PN.op_end(), op_begin());
95   std::copy(PN.block_begin(), PN.block_end(), block_begin());
96   SubclassOptionalData = PN.SubclassOptionalData;
97 }
98
99 // removeIncomingValue - Remove an incoming value.  This is useful if a
100 // predecessor basic block is deleted.
101 Value *PHINode::removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty) {
102   Value *Removed = getIncomingValue(Idx);
103
104   // Move everything after this operand down.
105   //
106   // FIXME: we could just swap with the end of the list, then erase.  However,
107   // clients might not expect this to happen.  The code as it is thrashes the
108   // use/def lists, which is kinda lame.
109   std::copy(op_begin() + Idx + 1, op_end(), op_begin() + Idx);
110   std::copy(block_begin() + Idx + 1, block_end(), block_begin() + Idx);
111
112   // Nuke the last value.
113   Op<-1>().set(nullptr);
114   setNumHungOffUseOperands(getNumOperands() - 1);
115
116   // If the PHI node is dead, because it has zero entries, nuke it now.
117   if (getNumOperands() == 0 && DeletePHIIfEmpty) {
118     // If anyone is using this PHI, make them use a dummy value instead...
119     replaceAllUsesWith(UndefValue::get(getType()));
120     eraseFromParent();
121   }
122   return Removed;
123 }
124
125 /// growOperands - grow operands - This grows the operand list in response
126 /// to a push_back style of operation.  This grows the number of ops by 1.5
127 /// times.
128 ///
129 void PHINode::growOperands() {
130   unsigned e = getNumOperands();
131   unsigned NumOps = e + e / 2;
132   if (NumOps < 2) NumOps = 2;      // 2 op PHI nodes are VERY common.
133
134   ReservedSpace = NumOps;
135   growHungoffUses(ReservedSpace, /* IsPhi */ true);
136 }
137
138 /// hasConstantValue - If the specified PHI node always merges together the same
139 /// value, return the value, otherwise return null.
140 Value *PHINode::hasConstantValue() const {
141   // Exploit the fact that phi nodes always have at least one entry.
142   Value *ConstantValue = getIncomingValue(0);
143   for (unsigned i = 1, e = getNumIncomingValues(); i != e; ++i)
144     if (getIncomingValue(i) != ConstantValue && getIncomingValue(i) != this) {
145       if (ConstantValue != this)
146         return nullptr; // Incoming values not all the same.
147        // The case where the first value is this PHI.
148       ConstantValue = getIncomingValue(i);
149     }
150   if (ConstantValue == this)
151     return UndefValue::get(getType());
152   return ConstantValue;
153 }
154
155 //===----------------------------------------------------------------------===//
156 //                       LandingPadInst Implementation
157 //===----------------------------------------------------------------------===//
158
159 LandingPadInst::LandingPadInst(Type *RetTy, unsigned NumReservedValues,
160                                const Twine &NameStr, Instruction *InsertBefore)
161     : Instruction(RetTy, Instruction::LandingPad, nullptr, 0, InsertBefore) {
162   init(NumReservedValues, NameStr);
163 }
164
165 LandingPadInst::LandingPadInst(Type *RetTy, unsigned NumReservedValues,
166                                const Twine &NameStr, BasicBlock *InsertAtEnd)
167     : Instruction(RetTy, Instruction::LandingPad, nullptr, 0, InsertAtEnd) {
168   init(NumReservedValues, NameStr);
169 }
170
171 LandingPadInst::LandingPadInst(const LandingPadInst &LP)
172     : Instruction(LP.getType(), Instruction::LandingPad, nullptr,
173                   LP.getNumOperands()),
174       ReservedSpace(LP.getNumOperands()) {
175   allocHungoffUses(LP.getNumOperands());
176   Use *OL = getOperandList();
177   const Use *InOL = LP.getOperandList();
178   for (unsigned I = 0, E = ReservedSpace; I != E; ++I)
179     OL[I] = InOL[I];
180
181   setCleanup(LP.isCleanup());
182 }
183
184 LandingPadInst *LandingPadInst::Create(Type *RetTy, unsigned NumReservedClauses,
185                                        const Twine &NameStr,
186                                        Instruction *InsertBefore) {
187   return new LandingPadInst(RetTy, NumReservedClauses, NameStr, InsertBefore);
188 }
189
190 LandingPadInst *LandingPadInst::Create(Type *RetTy, unsigned NumReservedClauses,
191                                        const Twine &NameStr,
192                                        BasicBlock *InsertAtEnd) {
193   return new LandingPadInst(RetTy, NumReservedClauses, NameStr, InsertAtEnd);
194 }
195
196 void LandingPadInst::init(unsigned NumReservedValues, const Twine &NameStr) {
197   ReservedSpace = NumReservedValues;
198   setNumHungOffUseOperands(0);
199   allocHungoffUses(ReservedSpace);
200   setName(NameStr);
201   setCleanup(false);
202 }
203
204 /// growOperands - grow operands - This grows the operand list in response to a
205 /// push_back style of operation. This grows the number of ops by 2 times.
206 void LandingPadInst::growOperands(unsigned Size) {
207   unsigned e = getNumOperands();
208   if (ReservedSpace >= e + Size) return;
209   ReservedSpace = (std::max(e, 1U) + Size / 2) * 2;
210   growHungoffUses(ReservedSpace);
211 }
212
213 void LandingPadInst::addClause(Constant *Val) {
214   unsigned OpNo = getNumOperands();
215   growOperands(1);
216   assert(OpNo < ReservedSpace && "Growing didn't work!");
217   setNumHungOffUseOperands(getNumOperands() + 1);
218   getOperandList()[OpNo] = Val;
219 }
220
221 //===----------------------------------------------------------------------===//
222 //                        CallInst Implementation
223 //===----------------------------------------------------------------------===//
224
225 CallInst::~CallInst() {
226 }
227
228 void CallInst::init(FunctionType *FTy, Value *Func, ArrayRef<Value *> Args,
229                     ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr) {
230   this->FTy = FTy;
231   assert(getNumOperands() == Args.size() + CountBundleInputs(Bundles) + 1 &&
232          "NumOperands not set up?");
233   Op<-1>() = Func;
234
235 #ifndef NDEBUG
236   assert((Args.size() == FTy->getNumParams() ||
237           (FTy->isVarArg() && Args.size() > FTy->getNumParams())) &&
238          "Calling a function with bad signature!");
239
240   for (unsigned i = 0; i != Args.size(); ++i)
241     assert((i >= FTy->getNumParams() || 
242             FTy->getParamType(i) == Args[i]->getType()) &&
243            "Calling a function with a bad signature!");
244 #endif
245
246   std::copy(Args.begin(), Args.end(), op_begin());
247
248   auto It = populateBundleOperandInfos(Bundles, Args.size());
249   (void)It;
250   assert(It + 1 == op_end() && "Should add up!");
251
252   setName(NameStr);
253 }
254
255 void CallInst::init(Value *Func, const Twine &NameStr) {
256   FTy =
257       cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
258   assert(getNumOperands() == 1 && "NumOperands not set up?");
259   Op<-1>() = Func;
260
261   assert(FTy->getNumParams() == 0 && "Calling a function with bad signature");
262
263   setName(NameStr);
264 }
265
266 CallInst::CallInst(Value *Func, const Twine &Name,
267                    Instruction *InsertBefore)
268   : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
269                                    ->getElementType())->getReturnType(),
270                 Instruction::Call,
271                 OperandTraits<CallInst>::op_end(this) - 1,
272                 1, InsertBefore) {
273   init(Func, Name);
274 }
275
276 CallInst::CallInst(Value *Func, const Twine &Name,
277                    BasicBlock *InsertAtEnd)
278   : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
279                                    ->getElementType())->getReturnType(),
280                 Instruction::Call,
281                 OperandTraits<CallInst>::op_end(this) - 1,
282                 1, InsertAtEnd) {
283   init(Func, Name);
284 }
285
286 CallInst::CallInst(const CallInst &CI)
287     : Instruction(CI.getType(), Instruction::Call,
288                   OperandTraits<CallInst>::op_end(this) - CI.getNumOperands(),
289                   CI.getNumOperands()),
290       AttributeList(CI.AttributeList), FTy(CI.FTy) {
291   setTailCallKind(CI.getTailCallKind());
292   setCallingConv(CI.getCallingConv());
293
294   std::copy(CI.op_begin(), CI.op_end(), op_begin());
295   std::copy(CI.bundle_op_info_begin(), CI.bundle_op_info_end(),
296             bundle_op_info_begin());
297   SubclassOptionalData = CI.SubclassOptionalData;
298 }
299
300 void CallInst::addAttribute(unsigned i, Attribute::AttrKind attr) {
301   AttributeSet PAL = getAttributes();
302   PAL = PAL.addAttribute(getContext(), i, attr);
303   setAttributes(PAL);
304 }
305
306 void CallInst::addAttribute(unsigned i, StringRef Kind, StringRef Value) {
307   AttributeSet PAL = getAttributes();
308   PAL = PAL.addAttribute(getContext(), i, Kind, Value);
309   setAttributes(PAL);
310 }
311
312 void CallInst::removeAttribute(unsigned i, Attribute attr) {
313   AttributeSet PAL = getAttributes();
314   AttrBuilder B(attr);
315   LLVMContext &Context = getContext();
316   PAL = PAL.removeAttributes(Context, i,
317                              AttributeSet::get(Context, i, B));
318   setAttributes(PAL);
319 }
320
321 void CallInst::addDereferenceableAttr(unsigned i, uint64_t Bytes) {
322   AttributeSet PAL = getAttributes();
323   PAL = PAL.addDereferenceableAttr(getContext(), i, Bytes);
324   setAttributes(PAL);
325 }
326
327 void CallInst::addDereferenceableOrNullAttr(unsigned i, uint64_t Bytes) {
328   AttributeSet PAL = getAttributes();
329   PAL = PAL.addDereferenceableOrNullAttr(getContext(), i, Bytes);
330   setAttributes(PAL);
331 }
332
333 bool CallInst::paramHasAttr(unsigned i, Attribute::AttrKind A) const {
334   assert(i < (getNumArgOperands() + 1) && "Param index out of bounds!");
335
336   if (AttributeList.hasAttribute(i, A))
337     return true;
338   if (const Function *F = getCalledFunction())
339     return F->getAttributes().hasAttribute(i, A);
340   return false;
341 }
342
343 /// IsConstantOne - Return true only if val is constant int 1
344 static bool IsConstantOne(Value *val) {
345   assert(val && "IsConstantOne does not work with nullptr val");
346   const ConstantInt *CVal = dyn_cast<ConstantInt>(val);
347   return CVal && CVal->isOne();
348 }
349
350 static Instruction *createMalloc(Instruction *InsertBefore,
351                                  BasicBlock *InsertAtEnd, Type *IntPtrTy,
352                                  Type *AllocTy, Value *AllocSize, 
353                                  Value *ArraySize, Function *MallocF,
354                                  const Twine &Name) {
355   assert(((!InsertBefore && InsertAtEnd) || (InsertBefore && !InsertAtEnd)) &&
356          "createMalloc needs either InsertBefore or InsertAtEnd");
357
358   // malloc(type) becomes: 
359   //       bitcast (i8* malloc(typeSize)) to type*
360   // malloc(type, arraySize) becomes:
361   //       bitcast (i8 *malloc(typeSize*arraySize)) to type*
362   if (!ArraySize)
363     ArraySize = ConstantInt::get(IntPtrTy, 1);
364   else if (ArraySize->getType() != IntPtrTy) {
365     if (InsertBefore)
366       ArraySize = CastInst::CreateIntegerCast(ArraySize, IntPtrTy, false,
367                                               "", InsertBefore);
368     else
369       ArraySize = CastInst::CreateIntegerCast(ArraySize, IntPtrTy, false,
370                                               "", InsertAtEnd);
371   }
372
373   if (!IsConstantOne(ArraySize)) {
374     if (IsConstantOne(AllocSize)) {
375       AllocSize = ArraySize;         // Operand * 1 = Operand
376     } else if (Constant *CO = dyn_cast<Constant>(ArraySize)) {
377       Constant *Scale = ConstantExpr::getIntegerCast(CO, IntPtrTy,
378                                                      false /*ZExt*/);
379       // Malloc arg is constant product of type size and array size
380       AllocSize = ConstantExpr::getMul(Scale, cast<Constant>(AllocSize));
381     } else {
382       // Multiply type size by the array size...
383       if (InsertBefore)
384         AllocSize = BinaryOperator::CreateMul(ArraySize, AllocSize,
385                                               "mallocsize", InsertBefore);
386       else
387         AllocSize = BinaryOperator::CreateMul(ArraySize, AllocSize,
388                                               "mallocsize", InsertAtEnd);
389     }
390   }
391
392   assert(AllocSize->getType() == IntPtrTy && "malloc arg is wrong size");
393   // Create the call to Malloc.
394   BasicBlock* BB = InsertBefore ? InsertBefore->getParent() : InsertAtEnd;
395   Module* M = BB->getParent()->getParent();
396   Type *BPTy = Type::getInt8PtrTy(BB->getContext());
397   Value *MallocFunc = MallocF;
398   if (!MallocFunc)
399     // prototype malloc as "void *malloc(size_t)"
400     MallocFunc = M->getOrInsertFunction("malloc", BPTy, IntPtrTy, nullptr);
401   PointerType *AllocPtrType = PointerType::getUnqual(AllocTy);
402   CallInst *MCall = nullptr;
403   Instruction *Result = nullptr;
404   if (InsertBefore) {
405     MCall = CallInst::Create(MallocFunc, AllocSize, "malloccall", InsertBefore);
406     Result = MCall;
407     if (Result->getType() != AllocPtrType)
408       // Create a cast instruction to convert to the right type...
409       Result = new BitCastInst(MCall, AllocPtrType, Name, InsertBefore);
410   } else {
411     MCall = CallInst::Create(MallocFunc, AllocSize, "malloccall");
412     Result = MCall;
413     if (Result->getType() != AllocPtrType) {
414       InsertAtEnd->getInstList().push_back(MCall);
415       // Create a cast instruction to convert to the right type...
416       Result = new BitCastInst(MCall, AllocPtrType, Name);
417     }
418   }
419   MCall->setTailCall();
420   if (Function *F = dyn_cast<Function>(MallocFunc)) {
421     MCall->setCallingConv(F->getCallingConv());
422     if (!F->doesNotAlias(0)) F->setDoesNotAlias(0);
423   }
424   assert(!MCall->getType()->isVoidTy() && "Malloc has void return type");
425
426   return Result;
427 }
428
429 /// CreateMalloc - Generate the IR for a call to malloc:
430 /// 1. Compute the malloc call's argument as the specified type's size,
431 ///    possibly multiplied by the array size if the array size is not
432 ///    constant 1.
433 /// 2. Call malloc with that argument.
434 /// 3. Bitcast the result of the malloc call to the specified type.
435 Instruction *CallInst::CreateMalloc(Instruction *InsertBefore,
436                                     Type *IntPtrTy, Type *AllocTy,
437                                     Value *AllocSize, Value *ArraySize,
438                                     Function * MallocF,
439                                     const Twine &Name) {
440   return createMalloc(InsertBefore, nullptr, IntPtrTy, AllocTy, AllocSize,
441                       ArraySize, MallocF, Name);
442 }
443
444 /// CreateMalloc - Generate the IR for a call to malloc:
445 /// 1. Compute the malloc call's argument as the specified type's size,
446 ///    possibly multiplied by the array size if the array size is not
447 ///    constant 1.
448 /// 2. Call malloc with that argument.
449 /// 3. Bitcast the result of the malloc call to the specified type.
450 /// Note: This function does not add the bitcast to the basic block, that is the
451 /// responsibility of the caller.
452 Instruction *CallInst::CreateMalloc(BasicBlock *InsertAtEnd,
453                                     Type *IntPtrTy, Type *AllocTy,
454                                     Value *AllocSize, Value *ArraySize, 
455                                     Function *MallocF, const Twine &Name) {
456   return createMalloc(nullptr, InsertAtEnd, IntPtrTy, AllocTy, AllocSize,
457                       ArraySize, MallocF, Name);
458 }
459
460 static Instruction* createFree(Value* Source, Instruction *InsertBefore,
461                                BasicBlock *InsertAtEnd) {
462   assert(((!InsertBefore && InsertAtEnd) || (InsertBefore && !InsertAtEnd)) &&
463          "createFree needs either InsertBefore or InsertAtEnd");
464   assert(Source->getType()->isPointerTy() &&
465          "Can not free something of nonpointer type!");
466
467   BasicBlock* BB = InsertBefore ? InsertBefore->getParent() : InsertAtEnd;
468   Module* M = BB->getParent()->getParent();
469
470   Type *VoidTy = Type::getVoidTy(M->getContext());
471   Type *IntPtrTy = Type::getInt8PtrTy(M->getContext());
472   // prototype free as "void free(void*)"
473   Value *FreeFunc = M->getOrInsertFunction("free", VoidTy, IntPtrTy, nullptr);
474   CallInst* Result = nullptr;
475   Value *PtrCast = Source;
476   if (InsertBefore) {
477     if (Source->getType() != IntPtrTy)
478       PtrCast = new BitCastInst(Source, IntPtrTy, "", InsertBefore);
479     Result = CallInst::Create(FreeFunc, PtrCast, "", InsertBefore);
480   } else {
481     if (Source->getType() != IntPtrTy)
482       PtrCast = new BitCastInst(Source, IntPtrTy, "", InsertAtEnd);
483     Result = CallInst::Create(FreeFunc, PtrCast, "");
484   }
485   Result->setTailCall();
486   if (Function *F = dyn_cast<Function>(FreeFunc))
487     Result->setCallingConv(F->getCallingConv());
488
489   return Result;
490 }
491
492 /// CreateFree - Generate the IR for a call to the builtin free function.
493 Instruction * CallInst::CreateFree(Value* Source, Instruction *InsertBefore) {
494   return createFree(Source, InsertBefore, nullptr);
495 }
496
497 /// CreateFree - Generate the IR for a call to the builtin free function.
498 /// Note: This function does not add the call to the basic block, that is the
499 /// responsibility of the caller.
500 Instruction* CallInst::CreateFree(Value* Source, BasicBlock *InsertAtEnd) {
501   Instruction* FreeCall = createFree(Source, nullptr, InsertAtEnd);
502   assert(FreeCall && "CreateFree did not create a CallInst");
503   return FreeCall;
504 }
505
506 //===----------------------------------------------------------------------===//
507 //                        InvokeInst Implementation
508 //===----------------------------------------------------------------------===//
509
510 void InvokeInst::init(FunctionType *FTy, Value *Fn, BasicBlock *IfNormal,
511                       BasicBlock *IfException, ArrayRef<Value *> Args,
512                       ArrayRef<OperandBundleDef> Bundles,
513                       const Twine &NameStr) {
514   this->FTy = FTy;
515
516   assert(getNumOperands() == 3 + Args.size() + CountBundleInputs(Bundles) &&
517          "NumOperands not set up?");
518   Op<-3>() = Fn;
519   Op<-2>() = IfNormal;
520   Op<-1>() = IfException;
521
522 #ifndef NDEBUG
523   assert(((Args.size() == FTy->getNumParams()) ||
524           (FTy->isVarArg() && Args.size() > FTy->getNumParams())) &&
525          "Invoking a function with bad signature");
526
527   for (unsigned i = 0, e = Args.size(); i != e; i++)
528     assert((i >= FTy->getNumParams() || 
529             FTy->getParamType(i) == Args[i]->getType()) &&
530            "Invoking a function with a bad signature!");
531 #endif
532
533   std::copy(Args.begin(), Args.end(), op_begin());
534
535   auto It = populateBundleOperandInfos(Bundles, Args.size());
536   (void)It;
537   assert(It + 3 == op_end() && "Should add up!");
538
539   setName(NameStr);
540 }
541
542 InvokeInst::InvokeInst(const InvokeInst &II)
543     : TerminatorInst(II.getType(), Instruction::Invoke,
544                      OperandTraits<InvokeInst>::op_end(this) -
545                          II.getNumOperands(),
546                      II.getNumOperands()),
547       AttributeList(II.AttributeList), FTy(II.FTy) {
548   setCallingConv(II.getCallingConv());
549   std::copy(II.op_begin(), II.op_end(), op_begin());
550   std::copy(II.bundle_op_info_begin(), II.bundle_op_info_end(),
551             bundle_op_info_begin());
552   SubclassOptionalData = II.SubclassOptionalData;
553 }
554
555 BasicBlock *InvokeInst::getSuccessorV(unsigned idx) const {
556   return getSuccessor(idx);
557 }
558 unsigned InvokeInst::getNumSuccessorsV() const {
559   return getNumSuccessors();
560 }
561 void InvokeInst::setSuccessorV(unsigned idx, BasicBlock *B) {
562   return setSuccessor(idx, B);
563 }
564
565 bool InvokeInst::hasFnAttrImpl(Attribute::AttrKind A) const {
566   if (AttributeList.hasAttribute(AttributeSet::FunctionIndex, A))
567     return true;
568
569   // Operand bundles override attributes on the called function, but don't
570   // override attributes directly present on the invoke instruction.
571   if (isFnAttrDisallowedByOpBundle(A))
572     return false;
573
574   if (const Function *F = getCalledFunction())
575     return F->getAttributes().hasAttribute(AttributeSet::FunctionIndex, A);
576   return false;
577 }
578
579 bool InvokeInst::paramHasAttr(unsigned i, Attribute::AttrKind A) const {
580   assert(i < (getNumArgOperands() + 1) && "Param index out of bounds!");
581
582   if (AttributeList.hasAttribute(i, A))
583     return true;
584   if (const Function *F = getCalledFunction())
585     return F->getAttributes().hasAttribute(i, A);
586   return false;
587 }
588
589 void InvokeInst::addAttribute(unsigned i, Attribute::AttrKind attr) {
590   AttributeSet PAL = getAttributes();
591   PAL = PAL.addAttribute(getContext(), i, attr);
592   setAttributes(PAL);
593 }
594
595 void InvokeInst::removeAttribute(unsigned i, Attribute attr) {
596   AttributeSet PAL = getAttributes();
597   AttrBuilder B(attr);
598   PAL = PAL.removeAttributes(getContext(), i,
599                              AttributeSet::get(getContext(), i, B));
600   setAttributes(PAL);
601 }
602
603 void InvokeInst::addDereferenceableAttr(unsigned i, uint64_t Bytes) {
604   AttributeSet PAL = getAttributes();
605   PAL = PAL.addDereferenceableAttr(getContext(), i, Bytes);
606   setAttributes(PAL);
607 }
608
609 void InvokeInst::addDereferenceableOrNullAttr(unsigned i, uint64_t Bytes) {
610   AttributeSet PAL = getAttributes();
611   PAL = PAL.addDereferenceableOrNullAttr(getContext(), i, Bytes);
612   setAttributes(PAL);
613 }
614
615 LandingPadInst *InvokeInst::getLandingPadInst() const {
616   return cast<LandingPadInst>(getUnwindDest()->getFirstNonPHI());
617 }
618
619 //===----------------------------------------------------------------------===//
620 //                        ReturnInst Implementation
621 //===----------------------------------------------------------------------===//
622
623 ReturnInst::ReturnInst(const ReturnInst &RI)
624   : TerminatorInst(Type::getVoidTy(RI.getContext()), Instruction::Ret,
625                    OperandTraits<ReturnInst>::op_end(this) -
626                      RI.getNumOperands(),
627                    RI.getNumOperands()) {
628   if (RI.getNumOperands())
629     Op<0>() = RI.Op<0>();
630   SubclassOptionalData = RI.SubclassOptionalData;
631 }
632
633 ReturnInst::ReturnInst(LLVMContext &C, Value *retVal, Instruction *InsertBefore)
634   : TerminatorInst(Type::getVoidTy(C), Instruction::Ret,
635                    OperandTraits<ReturnInst>::op_end(this) - !!retVal, !!retVal,
636                    InsertBefore) {
637   if (retVal)
638     Op<0>() = retVal;
639 }
640 ReturnInst::ReturnInst(LLVMContext &C, Value *retVal, BasicBlock *InsertAtEnd)
641   : TerminatorInst(Type::getVoidTy(C), Instruction::Ret,
642                    OperandTraits<ReturnInst>::op_end(this) - !!retVal, !!retVal,
643                    InsertAtEnd) {
644   if (retVal)
645     Op<0>() = retVal;
646 }
647 ReturnInst::ReturnInst(LLVMContext &Context, BasicBlock *InsertAtEnd)
648   : TerminatorInst(Type::getVoidTy(Context), Instruction::Ret,
649                    OperandTraits<ReturnInst>::op_end(this), 0, InsertAtEnd) {
650 }
651
652 unsigned ReturnInst::getNumSuccessorsV() const {
653   return getNumSuccessors();
654 }
655
656 /// Out-of-line ReturnInst method, put here so the C++ compiler can choose to
657 /// emit the vtable for the class in this translation unit.
658 void ReturnInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
659   llvm_unreachable("ReturnInst has no successors!");
660 }
661
662 BasicBlock *ReturnInst::getSuccessorV(unsigned idx) const {
663   llvm_unreachable("ReturnInst has no successors!");
664 }
665
666 ReturnInst::~ReturnInst() {
667 }
668
669 //===----------------------------------------------------------------------===//
670 //                        ResumeInst Implementation
671 //===----------------------------------------------------------------------===//
672
673 ResumeInst::ResumeInst(const ResumeInst &RI)
674   : TerminatorInst(Type::getVoidTy(RI.getContext()), Instruction::Resume,
675                    OperandTraits<ResumeInst>::op_begin(this), 1) {
676   Op<0>() = RI.Op<0>();
677 }
678
679 ResumeInst::ResumeInst(Value *Exn, Instruction *InsertBefore)
680   : TerminatorInst(Type::getVoidTy(Exn->getContext()), Instruction::Resume,
681                    OperandTraits<ResumeInst>::op_begin(this), 1, InsertBefore) {
682   Op<0>() = Exn;
683 }
684
685 ResumeInst::ResumeInst(Value *Exn, BasicBlock *InsertAtEnd)
686   : TerminatorInst(Type::getVoidTy(Exn->getContext()), Instruction::Resume,
687                    OperandTraits<ResumeInst>::op_begin(this), 1, InsertAtEnd) {
688   Op<0>() = Exn;
689 }
690
691 unsigned ResumeInst::getNumSuccessorsV() const {
692   return getNumSuccessors();
693 }
694
695 void ResumeInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
696   llvm_unreachable("ResumeInst has no successors!");
697 }
698
699 BasicBlock *ResumeInst::getSuccessorV(unsigned idx) const {
700   llvm_unreachable("ResumeInst has no successors!");
701 }
702
703 //===----------------------------------------------------------------------===//
704 //                        CleanupEndPadInst Implementation
705 //===----------------------------------------------------------------------===//
706
707 CleanupEndPadInst::CleanupEndPadInst(const CleanupEndPadInst &CEPI)
708     : TerminatorInst(CEPI.getType(), Instruction::CleanupEndPad,
709                      OperandTraits<CleanupEndPadInst>::op_end(this) -
710                          CEPI.getNumOperands(),
711                      CEPI.getNumOperands()) {
712   setInstructionSubclassData(CEPI.getSubclassDataFromInstruction());
713   setCleanupPad(CEPI.getCleanupPad());
714   if (BasicBlock *UnwindDest = CEPI.getUnwindDest())
715     setUnwindDest(UnwindDest);
716 }
717
718 void CleanupEndPadInst::init(CleanupPadInst *CleanupPad, BasicBlock *UnwindBB) {
719   setCleanupPad(CleanupPad);
720   if (UnwindBB) {
721     setInstructionSubclassData(getSubclassDataFromInstruction() | 1);
722     setUnwindDest(UnwindBB);
723   }
724 }
725
726 CleanupEndPadInst::CleanupEndPadInst(CleanupPadInst *CleanupPad,
727                                      BasicBlock *UnwindBB, unsigned Values,
728                                      Instruction *InsertBefore)
729     : TerminatorInst(Type::getVoidTy(CleanupPad->getContext()),
730                      Instruction::CleanupEndPad,
731                      OperandTraits<CleanupEndPadInst>::op_end(this) - Values,
732                      Values, InsertBefore) {
733   init(CleanupPad, UnwindBB);
734 }
735
736 CleanupEndPadInst::CleanupEndPadInst(CleanupPadInst *CleanupPad,
737                                      BasicBlock *UnwindBB, unsigned Values,
738                                      BasicBlock *InsertAtEnd)
739     : TerminatorInst(Type::getVoidTy(CleanupPad->getContext()),
740                      Instruction::CleanupEndPad,
741                      OperandTraits<CleanupEndPadInst>::op_end(this) - Values,
742                      Values, InsertAtEnd) {
743   init(CleanupPad, UnwindBB);
744 }
745
746 BasicBlock *CleanupEndPadInst::getSuccessorV(unsigned Idx) const {
747   assert(Idx == 0);
748   return getUnwindDest();
749 }
750 unsigned CleanupEndPadInst::getNumSuccessorsV() const {
751   return getNumSuccessors();
752 }
753 void CleanupEndPadInst::setSuccessorV(unsigned Idx, BasicBlock *B) {
754   assert(Idx == 0);
755   setUnwindDest(B);
756 }
757
758 //===----------------------------------------------------------------------===//
759 //                        CleanupReturnInst Implementation
760 //===----------------------------------------------------------------------===//
761
762 CleanupReturnInst::CleanupReturnInst(const CleanupReturnInst &CRI)
763     : TerminatorInst(CRI.getType(), Instruction::CleanupRet,
764                      OperandTraits<CleanupReturnInst>::op_end(this) -
765                          CRI.getNumOperands(),
766                      CRI.getNumOperands()) {
767   setInstructionSubclassData(CRI.getSubclassDataFromInstruction());
768   Op<-1>() = CRI.Op<-1>();
769   if (CRI.hasUnwindDest())
770     Op<-2>() = CRI.Op<-2>();
771 }
772
773 void CleanupReturnInst::init(CleanupPadInst *CleanupPad, BasicBlock *UnwindBB) {
774   if (UnwindBB)
775     setInstructionSubclassData(getSubclassDataFromInstruction() | 1);
776
777   Op<-1>() = CleanupPad;
778   if (UnwindBB)
779     Op<-2>() = UnwindBB;
780 }
781
782 CleanupReturnInst::CleanupReturnInst(CleanupPadInst *CleanupPad,
783                                      BasicBlock *UnwindBB, unsigned Values,
784                                      Instruction *InsertBefore)
785     : TerminatorInst(Type::getVoidTy(CleanupPad->getContext()),
786                      Instruction::CleanupRet,
787                      OperandTraits<CleanupReturnInst>::op_end(this) - Values,
788                      Values, InsertBefore) {
789   init(CleanupPad, UnwindBB);
790 }
791
792 CleanupReturnInst::CleanupReturnInst(CleanupPadInst *CleanupPad,
793                                      BasicBlock *UnwindBB, unsigned Values,
794                                      BasicBlock *InsertAtEnd)
795     : TerminatorInst(Type::getVoidTy(CleanupPad->getContext()),
796                      Instruction::CleanupRet,
797                      OperandTraits<CleanupReturnInst>::op_end(this) - Values,
798                      Values, InsertAtEnd) {
799   init(CleanupPad, UnwindBB);
800 }
801
802 BasicBlock *CleanupReturnInst::getSuccessorV(unsigned Idx) const {
803   assert(Idx == 0);
804   return getUnwindDest();
805 }
806 unsigned CleanupReturnInst::getNumSuccessorsV() const {
807   return getNumSuccessors();
808 }
809 void CleanupReturnInst::setSuccessorV(unsigned Idx, BasicBlock *B) {
810   assert(Idx == 0);
811   setUnwindDest(B);
812 }
813
814 //===----------------------------------------------------------------------===//
815 //                        CatchEndPadInst Implementation
816 //===----------------------------------------------------------------------===//
817
818 CatchEndPadInst::CatchEndPadInst(const CatchEndPadInst &CRI)
819     : TerminatorInst(CRI.getType(), Instruction::CatchEndPad,
820                      OperandTraits<CatchEndPadInst>::op_end(this) -
821                          CRI.getNumOperands(),
822                      CRI.getNumOperands()) {
823   setInstructionSubclassData(CRI.getSubclassDataFromInstruction());
824   if (BasicBlock *UnwindDest = CRI.getUnwindDest())
825     setUnwindDest(UnwindDest);
826 }
827
828 void CatchEndPadInst::init(BasicBlock *UnwindBB) {
829   if (UnwindBB) {
830     setInstructionSubclassData(getSubclassDataFromInstruction() | 1);
831     setUnwindDest(UnwindBB);
832   }
833 }
834
835 CatchEndPadInst::CatchEndPadInst(LLVMContext &C, BasicBlock *UnwindBB,
836                                  unsigned Values, Instruction *InsertBefore)
837     : TerminatorInst(Type::getVoidTy(C), Instruction::CatchEndPad,
838                      OperandTraits<CatchEndPadInst>::op_end(this) - Values,
839                      Values, InsertBefore) {
840   init(UnwindBB);
841 }
842
843 CatchEndPadInst::CatchEndPadInst(LLVMContext &C, BasicBlock *UnwindBB,
844                                  unsigned Values, BasicBlock *InsertAtEnd)
845     : TerminatorInst(Type::getVoidTy(C), Instruction::CatchEndPad,
846                      OperandTraits<CatchEndPadInst>::op_end(this) - Values,
847                      Values, InsertAtEnd) {
848   init(UnwindBB);
849 }
850
851 BasicBlock *CatchEndPadInst::getSuccessorV(unsigned Idx) const {
852   assert(Idx == 0);
853   return getUnwindDest();
854 }
855 unsigned CatchEndPadInst::getNumSuccessorsV() const {
856   return getNumSuccessors();
857 }
858 void CatchEndPadInst::setSuccessorV(unsigned Idx, BasicBlock *B) {
859   assert(Idx == 0);
860   setUnwindDest(B);
861 }
862
863 //===----------------------------------------------------------------------===//
864 //                        CatchReturnInst Implementation
865 //===----------------------------------------------------------------------===//
866 void CatchReturnInst::init(CatchPadInst *CatchPad, BasicBlock *BB) {
867   Op<0>() = CatchPad;
868   Op<1>() = BB;
869 }
870
871 CatchReturnInst::CatchReturnInst(const CatchReturnInst &CRI)
872     : TerminatorInst(Type::getVoidTy(CRI.getContext()), Instruction::CatchRet,
873                      OperandTraits<CatchReturnInst>::op_begin(this), 2) {
874   Op<0>() = CRI.Op<0>();
875   Op<1>() = CRI.Op<1>();
876 }
877
878 CatchReturnInst::CatchReturnInst(CatchPadInst *CatchPad, BasicBlock *BB,
879                                  Instruction *InsertBefore)
880     : TerminatorInst(Type::getVoidTy(BB->getContext()), Instruction::CatchRet,
881                      OperandTraits<CatchReturnInst>::op_begin(this), 2,
882                      InsertBefore) {
883   init(CatchPad, BB);
884 }
885
886 CatchReturnInst::CatchReturnInst(CatchPadInst *CatchPad, BasicBlock *BB,
887                                  BasicBlock *InsertAtEnd)
888     : TerminatorInst(Type::getVoidTy(BB->getContext()), Instruction::CatchRet,
889                      OperandTraits<CatchReturnInst>::op_begin(this), 2,
890                      InsertAtEnd) {
891   init(CatchPad, BB);
892 }
893
894 BasicBlock *CatchReturnInst::getSuccessorV(unsigned Idx) const {
895   assert(Idx < getNumSuccessors() && "Successor # out of range for catchret!");
896   return getSuccessor();
897 }
898 unsigned CatchReturnInst::getNumSuccessorsV() const {
899   return getNumSuccessors();
900 }
901 void CatchReturnInst::setSuccessorV(unsigned Idx, BasicBlock *B) {
902   assert(Idx < getNumSuccessors() && "Successor # out of range for catchret!");
903   setSuccessor(B);
904 }
905
906 //===----------------------------------------------------------------------===//
907 //                        CatchPadInst Implementation
908 //===----------------------------------------------------------------------===//
909 void CatchPadInst::init(BasicBlock *IfNormal, BasicBlock *IfException,
910                         ArrayRef<Value *> Args, const Twine &NameStr) {
911   assert(getNumOperands() == 2 + Args.size() && "NumOperands not set up?");
912   Op<-2>() = IfNormal;
913   Op<-1>() = IfException;
914   std::copy(Args.begin(), Args.end(), op_begin());
915   setName(NameStr);
916 }
917
918 CatchPadInst::CatchPadInst(const CatchPadInst &CPI)
919     : TerminatorInst(CPI.getType(), Instruction::CatchPad,
920                      OperandTraits<CatchPadInst>::op_end(this) -
921                          CPI.getNumOperands(),
922                      CPI.getNumOperands()) {
923   std::copy(CPI.op_begin(), CPI.op_end(), op_begin());
924 }
925
926 CatchPadInst::CatchPadInst(BasicBlock *IfNormal, BasicBlock *IfException,
927                            ArrayRef<Value *> Args, unsigned Values,
928                            const Twine &NameStr, Instruction *InsertBefore)
929     : TerminatorInst(Type::getTokenTy(IfNormal->getContext()),
930                      Instruction::CatchPad,
931                      OperandTraits<CatchPadInst>::op_end(this) - Values, Values,
932                      InsertBefore) {
933   init(IfNormal, IfException, Args, NameStr);
934 }
935
936 CatchPadInst::CatchPadInst(BasicBlock *IfNormal, BasicBlock *IfException,
937                            ArrayRef<Value *> Args, unsigned Values,
938                            const Twine &NameStr, BasicBlock *InsertAtEnd)
939     : TerminatorInst(Type::getTokenTy(IfNormal->getContext()),
940                      Instruction::CatchPad,
941                      OperandTraits<CatchPadInst>::op_end(this) - Values, Values,
942                      InsertAtEnd) {
943   init(IfNormal, IfException, Args, NameStr);
944 }
945
946 BasicBlock *CatchPadInst::getSuccessorV(unsigned Idx) const {
947   return getSuccessor(Idx);
948 }
949 unsigned CatchPadInst::getNumSuccessorsV() const {
950   return getNumSuccessors();
951 }
952 void CatchPadInst::setSuccessorV(unsigned Idx, BasicBlock *B) {
953   return setSuccessor(Idx, B);
954 }
955
956 //===----------------------------------------------------------------------===//
957 //                        TerminatePadInst Implementation
958 //===----------------------------------------------------------------------===//
959 void TerminatePadInst::init(BasicBlock *BB, ArrayRef<Value *> Args) {
960   if (BB)
961     setInstructionSubclassData(getSubclassDataFromInstruction() | 1);
962   if (BB)
963     Op<-1>() = BB;
964   std::copy(Args.begin(), Args.end(), op_begin());
965 }
966
967 TerminatePadInst::TerminatePadInst(const TerminatePadInst &TPI)
968     : TerminatorInst(TPI.getType(), Instruction::TerminatePad,
969                      OperandTraits<TerminatePadInst>::op_end(this) -
970                          TPI.getNumOperands(),
971                      TPI.getNumOperands()) {
972   setInstructionSubclassData(TPI.getSubclassDataFromInstruction());
973   std::copy(TPI.op_begin(), TPI.op_end(), op_begin());
974 }
975
976 TerminatePadInst::TerminatePadInst(LLVMContext &C, BasicBlock *BB,
977                                    ArrayRef<Value *> Args, unsigned Values,
978                                    Instruction *InsertBefore)
979     : TerminatorInst(Type::getVoidTy(C), Instruction::TerminatePad,
980                      OperandTraits<TerminatePadInst>::op_end(this) - Values,
981                      Values, InsertBefore) {
982   init(BB, Args);
983 }
984
985 TerminatePadInst::TerminatePadInst(LLVMContext &C, BasicBlock *BB,
986                                    ArrayRef<Value *> Args, unsigned Values,
987                                    BasicBlock *InsertAtEnd)
988     : TerminatorInst(Type::getVoidTy(C), Instruction::TerminatePad,
989                      OperandTraits<TerminatePadInst>::op_end(this) - Values,
990                      Values, InsertAtEnd) {
991   init(BB, Args);
992 }
993
994 BasicBlock *TerminatePadInst::getSuccessorV(unsigned Idx) const {
995   assert(Idx == 0);
996   return getUnwindDest();
997 }
998 unsigned TerminatePadInst::getNumSuccessorsV() const {
999   return getNumSuccessors();
1000 }
1001 void TerminatePadInst::setSuccessorV(unsigned Idx, BasicBlock *B) {
1002   assert(Idx == 0);
1003   return setUnwindDest(B);
1004 }
1005
1006 //===----------------------------------------------------------------------===//
1007 //                        CleanupPadInst Implementation
1008 //===----------------------------------------------------------------------===//
1009 void CleanupPadInst::init(ArrayRef<Value *> Args, const Twine &NameStr) {
1010   assert(getNumOperands() == Args.size() && "NumOperands not set up?");
1011   std::copy(Args.begin(), Args.end(), op_begin());
1012   setName(NameStr);
1013 }
1014
1015 CleanupPadInst::CleanupPadInst(const CleanupPadInst &CPI)
1016     : Instruction(CPI.getType(), Instruction::CleanupPad,
1017                   OperandTraits<CleanupPadInst>::op_end(this) -
1018                       CPI.getNumOperands(),
1019                   CPI.getNumOperands()) {
1020   std::copy(CPI.op_begin(), CPI.op_end(), op_begin());
1021 }
1022
1023 CleanupPadInst::CleanupPadInst(LLVMContext &C, ArrayRef<Value *> Args,
1024                                const Twine &NameStr, Instruction *InsertBefore)
1025     : Instruction(Type::getTokenTy(C), Instruction::CleanupPad,
1026                   OperandTraits<CleanupPadInst>::op_end(this) - Args.size(),
1027                   Args.size(), InsertBefore) {
1028   init(Args, NameStr);
1029 }
1030
1031 CleanupPadInst::CleanupPadInst(LLVMContext &C, ArrayRef<Value *> Args,
1032                                const Twine &NameStr, BasicBlock *InsertAtEnd)
1033     : Instruction(Type::getTokenTy(C), Instruction::CleanupPad,
1034                   OperandTraits<CleanupPadInst>::op_end(this) - Args.size(),
1035                   Args.size(), InsertAtEnd) {
1036   init(Args, NameStr);
1037 }
1038
1039 //===----------------------------------------------------------------------===//
1040 //                      UnreachableInst Implementation
1041 //===----------------------------------------------------------------------===//
1042
1043 UnreachableInst::UnreachableInst(LLVMContext &Context, 
1044                                  Instruction *InsertBefore)
1045   : TerminatorInst(Type::getVoidTy(Context), Instruction::Unreachable,
1046                    nullptr, 0, InsertBefore) {
1047 }
1048 UnreachableInst::UnreachableInst(LLVMContext &Context, BasicBlock *InsertAtEnd)
1049   : TerminatorInst(Type::getVoidTy(Context), Instruction::Unreachable,
1050                    nullptr, 0, InsertAtEnd) {
1051 }
1052
1053 unsigned UnreachableInst::getNumSuccessorsV() const {
1054   return getNumSuccessors();
1055 }
1056
1057 void UnreachableInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
1058   llvm_unreachable("UnreachableInst has no successors!");
1059 }
1060
1061 BasicBlock *UnreachableInst::getSuccessorV(unsigned idx) const {
1062   llvm_unreachable("UnreachableInst has no successors!");
1063 }
1064
1065 //===----------------------------------------------------------------------===//
1066 //                        BranchInst Implementation
1067 //===----------------------------------------------------------------------===//
1068
1069 void BranchInst::AssertOK() {
1070   if (isConditional())
1071     assert(getCondition()->getType()->isIntegerTy(1) &&
1072            "May only branch on boolean predicates!");
1073 }
1074
1075 BranchInst::BranchInst(BasicBlock *IfTrue, Instruction *InsertBefore)
1076   : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
1077                    OperandTraits<BranchInst>::op_end(this) - 1,
1078                    1, InsertBefore) {
1079   assert(IfTrue && "Branch destination may not be null!");
1080   Op<-1>() = IfTrue;
1081 }
1082 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
1083                        Instruction *InsertBefore)
1084   : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
1085                    OperandTraits<BranchInst>::op_end(this) - 3,
1086                    3, InsertBefore) {
1087   Op<-1>() = IfTrue;
1088   Op<-2>() = IfFalse;
1089   Op<-3>() = Cond;
1090 #ifndef NDEBUG
1091   AssertOK();
1092 #endif
1093 }
1094
1095 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *InsertAtEnd)
1096   : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
1097                    OperandTraits<BranchInst>::op_end(this) - 1,
1098                    1, InsertAtEnd) {
1099   assert(IfTrue && "Branch destination may not be null!");
1100   Op<-1>() = IfTrue;
1101 }
1102
1103 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
1104            BasicBlock *InsertAtEnd)
1105   : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
1106                    OperandTraits<BranchInst>::op_end(this) - 3,
1107                    3, InsertAtEnd) {
1108   Op<-1>() = IfTrue;
1109   Op<-2>() = IfFalse;
1110   Op<-3>() = Cond;
1111 #ifndef NDEBUG
1112   AssertOK();
1113 #endif
1114 }
1115
1116
1117 BranchInst::BranchInst(const BranchInst &BI) :
1118   TerminatorInst(Type::getVoidTy(BI.getContext()), Instruction::Br,
1119                  OperandTraits<BranchInst>::op_end(this) - BI.getNumOperands(),
1120                  BI.getNumOperands()) {
1121   Op<-1>() = BI.Op<-1>();
1122   if (BI.getNumOperands() != 1) {
1123     assert(BI.getNumOperands() == 3 && "BR can have 1 or 3 operands!");
1124     Op<-3>() = BI.Op<-3>();
1125     Op<-2>() = BI.Op<-2>();
1126   }
1127   SubclassOptionalData = BI.SubclassOptionalData;
1128 }
1129
1130 void BranchInst::swapSuccessors() {
1131   assert(isConditional() &&
1132          "Cannot swap successors of an unconditional branch");
1133   Op<-1>().swap(Op<-2>());
1134
1135   // Update profile metadata if present and it matches our structural
1136   // expectations.
1137   MDNode *ProfileData = getMetadata(LLVMContext::MD_prof);
1138   if (!ProfileData || ProfileData->getNumOperands() != 3)
1139     return;
1140
1141   // The first operand is the name. Fetch them backwards and build a new one.
1142   Metadata *Ops[] = {ProfileData->getOperand(0), ProfileData->getOperand(2),
1143                      ProfileData->getOperand(1)};
1144   setMetadata(LLVMContext::MD_prof,
1145               MDNode::get(ProfileData->getContext(), Ops));
1146 }
1147
1148 BasicBlock *BranchInst::getSuccessorV(unsigned idx) const {
1149   return getSuccessor(idx);
1150 }
1151 unsigned BranchInst::getNumSuccessorsV() const {
1152   return getNumSuccessors();
1153 }
1154 void BranchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
1155   setSuccessor(idx, B);
1156 }
1157
1158
1159 //===----------------------------------------------------------------------===//
1160 //                        AllocaInst Implementation
1161 //===----------------------------------------------------------------------===//
1162
1163 static Value *getAISize(LLVMContext &Context, Value *Amt) {
1164   if (!Amt)
1165     Amt = ConstantInt::get(Type::getInt32Ty(Context), 1);
1166   else {
1167     assert(!isa<BasicBlock>(Amt) &&
1168            "Passed basic block into allocation size parameter! Use other ctor");
1169     assert(Amt->getType()->isIntegerTy() &&
1170            "Allocation array size is not an integer!");
1171   }
1172   return Amt;
1173 }
1174
1175 AllocaInst::AllocaInst(Type *Ty, const Twine &Name, Instruction *InsertBefore)
1176     : AllocaInst(Ty, /*ArraySize=*/nullptr, Name, InsertBefore) {}
1177
1178 AllocaInst::AllocaInst(Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd)
1179     : AllocaInst(Ty, /*ArraySize=*/nullptr, Name, InsertAtEnd) {}
1180
1181 AllocaInst::AllocaInst(Type *Ty, Value *ArraySize, const Twine &Name,
1182                        Instruction *InsertBefore)
1183     : AllocaInst(Ty, ArraySize, /*Align=*/0, Name, InsertBefore) {}
1184
1185 AllocaInst::AllocaInst(Type *Ty, Value *ArraySize, const Twine &Name,
1186                        BasicBlock *InsertAtEnd)
1187     : AllocaInst(Ty, ArraySize, /*Align=*/0, Name, InsertAtEnd) {}
1188
1189 AllocaInst::AllocaInst(Type *Ty, Value *ArraySize, unsigned Align,
1190                        const Twine &Name, Instruction *InsertBefore)
1191     : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
1192                        getAISize(Ty->getContext(), ArraySize), InsertBefore),
1193       AllocatedType(Ty) {
1194   setAlignment(Align);
1195   assert(!Ty->isVoidTy() && "Cannot allocate void!");
1196   setName(Name);
1197 }
1198
1199 AllocaInst::AllocaInst(Type *Ty, Value *ArraySize, unsigned Align,
1200                        const Twine &Name, BasicBlock *InsertAtEnd)
1201     : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
1202                        getAISize(Ty->getContext(), ArraySize), InsertAtEnd),
1203       AllocatedType(Ty) {
1204   setAlignment(Align);
1205   assert(!Ty->isVoidTy() && "Cannot allocate void!");
1206   setName(Name);
1207 }
1208
1209 // Out of line virtual method, so the vtable, etc has a home.
1210 AllocaInst::~AllocaInst() {
1211 }
1212
1213 void AllocaInst::setAlignment(unsigned Align) {
1214   assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
1215   assert(Align <= MaximumAlignment &&
1216          "Alignment is greater than MaximumAlignment!");
1217   setInstructionSubclassData((getSubclassDataFromInstruction() & ~31) |
1218                              (Log2_32(Align) + 1));
1219   assert(getAlignment() == Align && "Alignment representation error!");
1220 }
1221
1222 bool AllocaInst::isArrayAllocation() const {
1223   if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(0)))
1224     return !CI->isOne();
1225   return true;
1226 }
1227
1228 /// isStaticAlloca - Return true if this alloca is in the entry block of the
1229 /// function and is a constant size.  If so, the code generator will fold it
1230 /// into the prolog/epilog code, so it is basically free.
1231 bool AllocaInst::isStaticAlloca() const {
1232   // Must be constant size.
1233   if (!isa<ConstantInt>(getArraySize())) return false;
1234   
1235   // Must be in the entry block.
1236   const BasicBlock *Parent = getParent();
1237   return Parent == &Parent->getParent()->front() && !isUsedWithInAlloca();
1238 }
1239
1240 //===----------------------------------------------------------------------===//
1241 //                           LoadInst Implementation
1242 //===----------------------------------------------------------------------===//
1243
1244 void LoadInst::AssertOK() {
1245   assert(getOperand(0)->getType()->isPointerTy() &&
1246          "Ptr must have pointer type.");
1247   assert(!(isAtomic() && getAlignment() == 0) &&
1248          "Alignment required for atomic load");
1249 }
1250
1251 LoadInst::LoadInst(Value *Ptr, const Twine &Name, Instruction *InsertBef)
1252     : LoadInst(Ptr, Name, /*isVolatile=*/false, InsertBef) {}
1253
1254 LoadInst::LoadInst(Value *Ptr, const Twine &Name, BasicBlock *InsertAE)
1255     : LoadInst(Ptr, Name, /*isVolatile=*/false, InsertAE) {}
1256
1257 LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile,
1258                    Instruction *InsertBef)
1259     : LoadInst(Ty, Ptr, Name, isVolatile, /*Align=*/0, InsertBef) {}
1260
1261 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
1262                    BasicBlock *InsertAE)
1263     : LoadInst(Ptr, Name, isVolatile, /*Align=*/0, InsertAE) {}
1264
1265 LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile,
1266                    unsigned Align, Instruction *InsertBef)
1267     : LoadInst(Ty, Ptr, Name, isVolatile, Align, NotAtomic, CrossThread,
1268                InsertBef) {}
1269
1270 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
1271                    unsigned Align, BasicBlock *InsertAE)
1272     : LoadInst(Ptr, Name, isVolatile, Align, NotAtomic, CrossThread, InsertAE) {
1273 }
1274
1275 LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile,
1276                    unsigned Align, AtomicOrdering Order,
1277                    SynchronizationScope SynchScope, Instruction *InsertBef)
1278     : UnaryInstruction(Ty, Load, Ptr, InsertBef) {
1279   assert(Ty == cast<PointerType>(Ptr->getType())->getElementType());
1280   setVolatile(isVolatile);
1281   setAlignment(Align);
1282   setAtomic(Order, SynchScope);
1283   AssertOK();
1284   setName(Name);
1285 }
1286
1287 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile, 
1288                    unsigned Align, AtomicOrdering Order,
1289                    SynchronizationScope SynchScope,
1290                    BasicBlock *InsertAE)
1291   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1292                      Load, Ptr, InsertAE) {
1293   setVolatile(isVolatile);
1294   setAlignment(Align);
1295   setAtomic(Order, SynchScope);
1296   AssertOK();
1297   setName(Name);
1298 }
1299
1300 LoadInst::LoadInst(Value *Ptr, const char *Name, Instruction *InsertBef)
1301   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1302                      Load, Ptr, InsertBef) {
1303   setVolatile(false);
1304   setAlignment(0);
1305   setAtomic(NotAtomic);
1306   AssertOK();
1307   if (Name && Name[0]) setName(Name);
1308 }
1309
1310 LoadInst::LoadInst(Value *Ptr, const char *Name, BasicBlock *InsertAE)
1311   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1312                      Load, Ptr, InsertAE) {
1313   setVolatile(false);
1314   setAlignment(0);
1315   setAtomic(NotAtomic);
1316   AssertOK();
1317   if (Name && Name[0]) setName(Name);
1318 }
1319
1320 LoadInst::LoadInst(Type *Ty, Value *Ptr, const char *Name, bool isVolatile,
1321                    Instruction *InsertBef)
1322     : UnaryInstruction(Ty, Load, Ptr, InsertBef) {
1323   assert(Ty == cast<PointerType>(Ptr->getType())->getElementType());
1324   setVolatile(isVolatile);
1325   setAlignment(0);
1326   setAtomic(NotAtomic);
1327   AssertOK();
1328   if (Name && Name[0]) setName(Name);
1329 }
1330
1331 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
1332                    BasicBlock *InsertAE)
1333   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1334                      Load, Ptr, InsertAE) {
1335   setVolatile(isVolatile);
1336   setAlignment(0);
1337   setAtomic(NotAtomic);
1338   AssertOK();
1339   if (Name && Name[0]) setName(Name);
1340 }
1341
1342 void LoadInst::setAlignment(unsigned Align) {
1343   assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
1344   assert(Align <= MaximumAlignment &&
1345          "Alignment is greater than MaximumAlignment!");
1346   setInstructionSubclassData((getSubclassDataFromInstruction() & ~(31 << 1)) |
1347                              ((Log2_32(Align)+1)<<1));
1348   assert(getAlignment() == Align && "Alignment representation error!");
1349 }
1350
1351 //===----------------------------------------------------------------------===//
1352 //                           StoreInst Implementation
1353 //===----------------------------------------------------------------------===//
1354
1355 void StoreInst::AssertOK() {
1356   assert(getOperand(0) && getOperand(1) && "Both operands must be non-null!");
1357   assert(getOperand(1)->getType()->isPointerTy() &&
1358          "Ptr must have pointer type!");
1359   assert(getOperand(0)->getType() ==
1360                  cast<PointerType>(getOperand(1)->getType())->getElementType()
1361          && "Ptr must be a pointer to Val type!");
1362   assert(!(isAtomic() && getAlignment() == 0) &&
1363          "Alignment required for atomic store");
1364 }
1365
1366 StoreInst::StoreInst(Value *val, Value *addr, Instruction *InsertBefore)
1367     : StoreInst(val, addr, /*isVolatile=*/false, InsertBefore) {}
1368
1369 StoreInst::StoreInst(Value *val, Value *addr, BasicBlock *InsertAtEnd)
1370     : StoreInst(val, addr, /*isVolatile=*/false, InsertAtEnd) {}
1371
1372 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1373                      Instruction *InsertBefore)
1374     : StoreInst(val, addr, isVolatile, /*Align=*/0, InsertBefore) {}
1375
1376 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1377                      BasicBlock *InsertAtEnd)
1378     : StoreInst(val, addr, isVolatile, /*Align=*/0, InsertAtEnd) {}
1379
1380 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile, unsigned Align,
1381                      Instruction *InsertBefore)
1382     : StoreInst(val, addr, isVolatile, Align, NotAtomic, CrossThread,
1383                 InsertBefore) {}
1384
1385 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile, unsigned Align,
1386                      BasicBlock *InsertAtEnd)
1387     : StoreInst(val, addr, isVolatile, Align, NotAtomic, CrossThread,
1388                 InsertAtEnd) {}
1389
1390 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1391                      unsigned Align, AtomicOrdering Order,
1392                      SynchronizationScope SynchScope,
1393                      Instruction *InsertBefore)
1394   : Instruction(Type::getVoidTy(val->getContext()), Store,
1395                 OperandTraits<StoreInst>::op_begin(this),
1396                 OperandTraits<StoreInst>::operands(this),
1397                 InsertBefore) {
1398   Op<0>() = val;
1399   Op<1>() = addr;
1400   setVolatile(isVolatile);
1401   setAlignment(Align);
1402   setAtomic(Order, SynchScope);
1403   AssertOK();
1404 }
1405
1406 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1407                      unsigned Align, AtomicOrdering Order,
1408                      SynchronizationScope SynchScope,
1409                      BasicBlock *InsertAtEnd)
1410   : Instruction(Type::getVoidTy(val->getContext()), Store,
1411                 OperandTraits<StoreInst>::op_begin(this),
1412                 OperandTraits<StoreInst>::operands(this),
1413                 InsertAtEnd) {
1414   Op<0>() = val;
1415   Op<1>() = addr;
1416   setVolatile(isVolatile);
1417   setAlignment(Align);
1418   setAtomic(Order, SynchScope);
1419   AssertOK();
1420 }
1421
1422 void StoreInst::setAlignment(unsigned Align) {
1423   assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
1424   assert(Align <= MaximumAlignment &&
1425          "Alignment is greater than MaximumAlignment!");
1426   setInstructionSubclassData((getSubclassDataFromInstruction() & ~(31 << 1)) |
1427                              ((Log2_32(Align)+1) << 1));
1428   assert(getAlignment() == Align && "Alignment representation error!");
1429 }
1430
1431 //===----------------------------------------------------------------------===//
1432 //                       AtomicCmpXchgInst Implementation
1433 //===----------------------------------------------------------------------===//
1434
1435 void AtomicCmpXchgInst::Init(Value *Ptr, Value *Cmp, Value *NewVal,
1436                              AtomicOrdering SuccessOrdering,
1437                              AtomicOrdering FailureOrdering,
1438                              SynchronizationScope SynchScope) {
1439   Op<0>() = Ptr;
1440   Op<1>() = Cmp;
1441   Op<2>() = NewVal;
1442   setSuccessOrdering(SuccessOrdering);
1443   setFailureOrdering(FailureOrdering);
1444   setSynchScope(SynchScope);
1445
1446   assert(getOperand(0) && getOperand(1) && getOperand(2) &&
1447          "All operands must be non-null!");
1448   assert(getOperand(0)->getType()->isPointerTy() &&
1449          "Ptr must have pointer type!");
1450   assert(getOperand(1)->getType() ==
1451                  cast<PointerType>(getOperand(0)->getType())->getElementType()
1452          && "Ptr must be a pointer to Cmp type!");
1453   assert(getOperand(2)->getType() ==
1454                  cast<PointerType>(getOperand(0)->getType())->getElementType()
1455          && "Ptr must be a pointer to NewVal type!");
1456   assert(SuccessOrdering != NotAtomic &&
1457          "AtomicCmpXchg instructions must be atomic!");
1458   assert(FailureOrdering != NotAtomic &&
1459          "AtomicCmpXchg instructions must be atomic!");
1460   assert(SuccessOrdering >= FailureOrdering &&
1461          "AtomicCmpXchg success ordering must be at least as strong as fail");
1462   assert(FailureOrdering != Release && FailureOrdering != AcquireRelease &&
1463          "AtomicCmpXchg failure ordering cannot include release semantics");
1464 }
1465
1466 AtomicCmpXchgInst::AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal,
1467                                      AtomicOrdering SuccessOrdering,
1468                                      AtomicOrdering FailureOrdering,
1469                                      SynchronizationScope SynchScope,
1470                                      Instruction *InsertBefore)
1471     : Instruction(
1472           StructType::get(Cmp->getType(), Type::getInt1Ty(Cmp->getContext()),
1473                           nullptr),
1474           AtomicCmpXchg, OperandTraits<AtomicCmpXchgInst>::op_begin(this),
1475           OperandTraits<AtomicCmpXchgInst>::operands(this), InsertBefore) {
1476   Init(Ptr, Cmp, NewVal, SuccessOrdering, FailureOrdering, SynchScope);
1477 }
1478
1479 AtomicCmpXchgInst::AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal,
1480                                      AtomicOrdering SuccessOrdering,
1481                                      AtomicOrdering FailureOrdering,
1482                                      SynchronizationScope SynchScope,
1483                                      BasicBlock *InsertAtEnd)
1484     : Instruction(
1485           StructType::get(Cmp->getType(), Type::getInt1Ty(Cmp->getContext()),
1486                           nullptr),
1487           AtomicCmpXchg, OperandTraits<AtomicCmpXchgInst>::op_begin(this),
1488           OperandTraits<AtomicCmpXchgInst>::operands(this), InsertAtEnd) {
1489   Init(Ptr, Cmp, NewVal, SuccessOrdering, FailureOrdering, SynchScope);
1490 }
1491
1492 //===----------------------------------------------------------------------===//
1493 //                       AtomicRMWInst Implementation
1494 //===----------------------------------------------------------------------===//
1495
1496 void AtomicRMWInst::Init(BinOp Operation, Value *Ptr, Value *Val,
1497                          AtomicOrdering Ordering,
1498                          SynchronizationScope SynchScope) {
1499   Op<0>() = Ptr;
1500   Op<1>() = Val;
1501   setOperation(Operation);
1502   setOrdering(Ordering);
1503   setSynchScope(SynchScope);
1504
1505   assert(getOperand(0) && getOperand(1) &&
1506          "All operands must be non-null!");
1507   assert(getOperand(0)->getType()->isPointerTy() &&
1508          "Ptr must have pointer type!");
1509   assert(getOperand(1)->getType() ==
1510          cast<PointerType>(getOperand(0)->getType())->getElementType()
1511          && "Ptr must be a pointer to Val type!");
1512   assert(Ordering != NotAtomic &&
1513          "AtomicRMW instructions must be atomic!");
1514 }
1515
1516 AtomicRMWInst::AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val,
1517                              AtomicOrdering Ordering,
1518                              SynchronizationScope SynchScope,
1519                              Instruction *InsertBefore)
1520   : Instruction(Val->getType(), AtomicRMW,
1521                 OperandTraits<AtomicRMWInst>::op_begin(this),
1522                 OperandTraits<AtomicRMWInst>::operands(this),
1523                 InsertBefore) {
1524   Init(Operation, Ptr, Val, Ordering, SynchScope);
1525 }
1526
1527 AtomicRMWInst::AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val,
1528                              AtomicOrdering Ordering,
1529                              SynchronizationScope SynchScope,
1530                              BasicBlock *InsertAtEnd)
1531   : Instruction(Val->getType(), AtomicRMW,
1532                 OperandTraits<AtomicRMWInst>::op_begin(this),
1533                 OperandTraits<AtomicRMWInst>::operands(this),
1534                 InsertAtEnd) {
1535   Init(Operation, Ptr, Val, Ordering, SynchScope);
1536 }
1537
1538 //===----------------------------------------------------------------------===//
1539 //                       FenceInst Implementation
1540 //===----------------------------------------------------------------------===//
1541
1542 FenceInst::FenceInst(LLVMContext &C, AtomicOrdering Ordering, 
1543                      SynchronizationScope SynchScope,
1544                      Instruction *InsertBefore)
1545   : Instruction(Type::getVoidTy(C), Fence, nullptr, 0, InsertBefore) {
1546   setOrdering(Ordering);
1547   setSynchScope(SynchScope);
1548 }
1549
1550 FenceInst::FenceInst(LLVMContext &C, AtomicOrdering Ordering, 
1551                      SynchronizationScope SynchScope,
1552                      BasicBlock *InsertAtEnd)
1553   : Instruction(Type::getVoidTy(C), Fence, nullptr, 0, InsertAtEnd) {
1554   setOrdering(Ordering);
1555   setSynchScope(SynchScope);
1556 }
1557
1558 //===----------------------------------------------------------------------===//
1559 //                       GetElementPtrInst Implementation
1560 //===----------------------------------------------------------------------===//
1561
1562 void GetElementPtrInst::init(Value *Ptr, ArrayRef<Value *> IdxList,
1563                              const Twine &Name) {
1564   assert(getNumOperands() == 1 + IdxList.size() &&
1565          "NumOperands not initialized?");
1566   Op<0>() = Ptr;
1567   std::copy(IdxList.begin(), IdxList.end(), op_begin() + 1);
1568   setName(Name);
1569 }
1570
1571 GetElementPtrInst::GetElementPtrInst(const GetElementPtrInst &GEPI)
1572     : Instruction(GEPI.getType(), GetElementPtr,
1573                   OperandTraits<GetElementPtrInst>::op_end(this) -
1574                       GEPI.getNumOperands(),
1575                   GEPI.getNumOperands()),
1576       SourceElementType(GEPI.SourceElementType),
1577       ResultElementType(GEPI.ResultElementType) {
1578   std::copy(GEPI.op_begin(), GEPI.op_end(), op_begin());
1579   SubclassOptionalData = GEPI.SubclassOptionalData;
1580 }
1581
1582 /// getIndexedType - Returns the type of the element that would be accessed with
1583 /// a gep instruction with the specified parameters.
1584 ///
1585 /// The Idxs pointer should point to a continuous piece of memory containing the
1586 /// indices, either as Value* or uint64_t.
1587 ///
1588 /// A null type is returned if the indices are invalid for the specified
1589 /// pointer type.
1590 ///
1591 template <typename IndexTy>
1592 static Type *getIndexedTypeInternal(Type *Agg, ArrayRef<IndexTy> IdxList) {
1593   // Handle the special case of the empty set index set, which is always valid.
1594   if (IdxList.empty())
1595     return Agg;
1596
1597   // If there is at least one index, the top level type must be sized, otherwise
1598   // it cannot be 'stepped over'.
1599   if (!Agg->isSized())
1600     return nullptr;
1601
1602   unsigned CurIdx = 1;
1603   for (; CurIdx != IdxList.size(); ++CurIdx) {
1604     CompositeType *CT = dyn_cast<CompositeType>(Agg);
1605     if (!CT || CT->isPointerTy()) return nullptr;
1606     IndexTy Index = IdxList[CurIdx];
1607     if (!CT->indexValid(Index)) return nullptr;
1608     Agg = CT->getTypeAtIndex(Index);
1609   }
1610   return CurIdx == IdxList.size() ? Agg : nullptr;
1611 }
1612
1613 Type *GetElementPtrInst::getIndexedType(Type *Ty, ArrayRef<Value *> IdxList) {
1614   return getIndexedTypeInternal(Ty, IdxList);
1615 }
1616
1617 Type *GetElementPtrInst::getIndexedType(Type *Ty,
1618                                         ArrayRef<Constant *> IdxList) {
1619   return getIndexedTypeInternal(Ty, IdxList);
1620 }
1621
1622 Type *GetElementPtrInst::getIndexedType(Type *Ty, ArrayRef<uint64_t> IdxList) {
1623   return getIndexedTypeInternal(Ty, IdxList);
1624 }
1625
1626 /// hasAllZeroIndices - Return true if all of the indices of this GEP are
1627 /// zeros.  If so, the result pointer and the first operand have the same
1628 /// value, just potentially different types.
1629 bool GetElementPtrInst::hasAllZeroIndices() const {
1630   for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1631     if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(i))) {
1632       if (!CI->isZero()) return false;
1633     } else {
1634       return false;
1635     }
1636   }
1637   return true;
1638 }
1639
1640 /// hasAllConstantIndices - Return true if all of the indices of this GEP are
1641 /// constant integers.  If so, the result pointer and the first operand have
1642 /// a constant offset between them.
1643 bool GetElementPtrInst::hasAllConstantIndices() const {
1644   for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1645     if (!isa<ConstantInt>(getOperand(i)))
1646       return false;
1647   }
1648   return true;
1649 }
1650
1651 void GetElementPtrInst::setIsInBounds(bool B) {
1652   cast<GEPOperator>(this)->setIsInBounds(B);
1653 }
1654
1655 bool GetElementPtrInst::isInBounds() const {
1656   return cast<GEPOperator>(this)->isInBounds();
1657 }
1658
1659 bool GetElementPtrInst::accumulateConstantOffset(const DataLayout &DL,
1660                                                  APInt &Offset) const {
1661   // Delegate to the generic GEPOperator implementation.
1662   return cast<GEPOperator>(this)->accumulateConstantOffset(DL, Offset);
1663 }
1664
1665 //===----------------------------------------------------------------------===//
1666 //                           ExtractElementInst Implementation
1667 //===----------------------------------------------------------------------===//
1668
1669 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1670                                        const Twine &Name,
1671                                        Instruction *InsertBef)
1672   : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1673                 ExtractElement,
1674                 OperandTraits<ExtractElementInst>::op_begin(this),
1675                 2, InsertBef) {
1676   assert(isValidOperands(Val, Index) &&
1677          "Invalid extractelement instruction operands!");
1678   Op<0>() = Val;
1679   Op<1>() = Index;
1680   setName(Name);
1681 }
1682
1683 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1684                                        const Twine &Name,
1685                                        BasicBlock *InsertAE)
1686   : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1687                 ExtractElement,
1688                 OperandTraits<ExtractElementInst>::op_begin(this),
1689                 2, InsertAE) {
1690   assert(isValidOperands(Val, Index) &&
1691          "Invalid extractelement instruction operands!");
1692
1693   Op<0>() = Val;
1694   Op<1>() = Index;
1695   setName(Name);
1696 }
1697
1698
1699 bool ExtractElementInst::isValidOperands(const Value *Val, const Value *Index) {
1700   if (!Val->getType()->isVectorTy() || !Index->getType()->isIntegerTy())
1701     return false;
1702   return true;
1703 }
1704
1705
1706 //===----------------------------------------------------------------------===//
1707 //                           InsertElementInst Implementation
1708 //===----------------------------------------------------------------------===//
1709
1710 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1711                                      const Twine &Name,
1712                                      Instruction *InsertBef)
1713   : Instruction(Vec->getType(), InsertElement,
1714                 OperandTraits<InsertElementInst>::op_begin(this),
1715                 3, InsertBef) {
1716   assert(isValidOperands(Vec, Elt, Index) &&
1717          "Invalid insertelement instruction operands!");
1718   Op<0>() = Vec;
1719   Op<1>() = Elt;
1720   Op<2>() = Index;
1721   setName(Name);
1722 }
1723
1724 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1725                                      const Twine &Name,
1726                                      BasicBlock *InsertAE)
1727   : Instruction(Vec->getType(), InsertElement,
1728                 OperandTraits<InsertElementInst>::op_begin(this),
1729                 3, InsertAE) {
1730   assert(isValidOperands(Vec, Elt, Index) &&
1731          "Invalid insertelement instruction operands!");
1732
1733   Op<0>() = Vec;
1734   Op<1>() = Elt;
1735   Op<2>() = Index;
1736   setName(Name);
1737 }
1738
1739 bool InsertElementInst::isValidOperands(const Value *Vec, const Value *Elt, 
1740                                         const Value *Index) {
1741   if (!Vec->getType()->isVectorTy())
1742     return false;   // First operand of insertelement must be vector type.
1743   
1744   if (Elt->getType() != cast<VectorType>(Vec->getType())->getElementType())
1745     return false;// Second operand of insertelement must be vector element type.
1746     
1747   if (!Index->getType()->isIntegerTy())
1748     return false;  // Third operand of insertelement must be i32.
1749   return true;
1750 }
1751
1752
1753 //===----------------------------------------------------------------------===//
1754 //                      ShuffleVectorInst Implementation
1755 //===----------------------------------------------------------------------===//
1756
1757 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1758                                      const Twine &Name,
1759                                      Instruction *InsertBefore)
1760 : Instruction(VectorType::get(cast<VectorType>(V1->getType())->getElementType(),
1761                 cast<VectorType>(Mask->getType())->getNumElements()),
1762               ShuffleVector,
1763               OperandTraits<ShuffleVectorInst>::op_begin(this),
1764               OperandTraits<ShuffleVectorInst>::operands(this),
1765               InsertBefore) {
1766   assert(isValidOperands(V1, V2, Mask) &&
1767          "Invalid shuffle vector instruction operands!");
1768   Op<0>() = V1;
1769   Op<1>() = V2;
1770   Op<2>() = Mask;
1771   setName(Name);
1772 }
1773
1774 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1775                                      const Twine &Name,
1776                                      BasicBlock *InsertAtEnd)
1777 : Instruction(VectorType::get(cast<VectorType>(V1->getType())->getElementType(),
1778                 cast<VectorType>(Mask->getType())->getNumElements()),
1779               ShuffleVector,
1780               OperandTraits<ShuffleVectorInst>::op_begin(this),
1781               OperandTraits<ShuffleVectorInst>::operands(this),
1782               InsertAtEnd) {
1783   assert(isValidOperands(V1, V2, Mask) &&
1784          "Invalid shuffle vector instruction operands!");
1785
1786   Op<0>() = V1;
1787   Op<1>() = V2;
1788   Op<2>() = Mask;
1789   setName(Name);
1790 }
1791
1792 bool ShuffleVectorInst::isValidOperands(const Value *V1, const Value *V2,
1793                                         const Value *Mask) {
1794   // V1 and V2 must be vectors of the same type.
1795   if (!V1->getType()->isVectorTy() || V1->getType() != V2->getType())
1796     return false;
1797   
1798   // Mask must be vector of i32.
1799   VectorType *MaskTy = dyn_cast<VectorType>(Mask->getType());
1800   if (!MaskTy || !MaskTy->getElementType()->isIntegerTy(32))
1801     return false;
1802
1803   // Check to see if Mask is valid.
1804   if (isa<UndefValue>(Mask) || isa<ConstantAggregateZero>(Mask))
1805     return true;
1806
1807   if (const ConstantVector *MV = dyn_cast<ConstantVector>(Mask)) {
1808     unsigned V1Size = cast<VectorType>(V1->getType())->getNumElements();
1809     for (Value *Op : MV->operands()) {
1810       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
1811         if (CI->uge(V1Size*2))
1812           return false;
1813       } else if (!isa<UndefValue>(Op)) {
1814         return false;
1815       }
1816     }
1817     return true;
1818   }
1819   
1820   if (const ConstantDataSequential *CDS =
1821         dyn_cast<ConstantDataSequential>(Mask)) {
1822     unsigned V1Size = cast<VectorType>(V1->getType())->getNumElements();
1823     for (unsigned i = 0, e = MaskTy->getNumElements(); i != e; ++i)
1824       if (CDS->getElementAsInteger(i) >= V1Size*2)
1825         return false;
1826     return true;
1827   }
1828   
1829   // The bitcode reader can create a place holder for a forward reference
1830   // used as the shuffle mask. When this occurs, the shuffle mask will
1831   // fall into this case and fail. To avoid this error, do this bit of
1832   // ugliness to allow such a mask pass.
1833   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(Mask))
1834     if (CE->getOpcode() == Instruction::UserOp1)
1835       return true;
1836
1837   return false;
1838 }
1839
1840 /// getMaskValue - Return the index from the shuffle mask for the specified
1841 /// output result.  This is either -1 if the element is undef or a number less
1842 /// than 2*numelements.
1843 int ShuffleVectorInst::getMaskValue(Constant *Mask, unsigned i) {
1844   assert(i < Mask->getType()->getVectorNumElements() && "Index out of range");
1845   if (ConstantDataSequential *CDS =dyn_cast<ConstantDataSequential>(Mask))
1846     return CDS->getElementAsInteger(i);
1847   Constant *C = Mask->getAggregateElement(i);
1848   if (isa<UndefValue>(C))
1849     return -1;
1850   return cast<ConstantInt>(C)->getZExtValue();
1851 }
1852
1853 /// getShuffleMask - Return the full mask for this instruction, where each
1854 /// element is the element number and undef's are returned as -1.
1855 void ShuffleVectorInst::getShuffleMask(Constant *Mask,
1856                                        SmallVectorImpl<int> &Result) {
1857   unsigned NumElts = Mask->getType()->getVectorNumElements();
1858   
1859   if (ConstantDataSequential *CDS=dyn_cast<ConstantDataSequential>(Mask)) {
1860     for (unsigned i = 0; i != NumElts; ++i)
1861       Result.push_back(CDS->getElementAsInteger(i));
1862     return;
1863   }    
1864   for (unsigned i = 0; i != NumElts; ++i) {
1865     Constant *C = Mask->getAggregateElement(i);
1866     Result.push_back(isa<UndefValue>(C) ? -1 :
1867                      cast<ConstantInt>(C)->getZExtValue());
1868   }
1869 }
1870
1871
1872 //===----------------------------------------------------------------------===//
1873 //                             InsertValueInst Class
1874 //===----------------------------------------------------------------------===//
1875
1876 void InsertValueInst::init(Value *Agg, Value *Val, ArrayRef<unsigned> Idxs, 
1877                            const Twine &Name) {
1878   assert(getNumOperands() == 2 && "NumOperands not initialized?");
1879
1880   // There's no fundamental reason why we require at least one index
1881   // (other than weirdness with &*IdxBegin being invalid; see
1882   // getelementptr's init routine for example). But there's no
1883   // present need to support it.
1884   assert(Idxs.size() > 0 && "InsertValueInst must have at least one index");
1885
1886   assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs) ==
1887          Val->getType() && "Inserted value must match indexed type!");
1888   Op<0>() = Agg;
1889   Op<1>() = Val;
1890
1891   Indices.append(Idxs.begin(), Idxs.end());
1892   setName(Name);
1893 }
1894
1895 InsertValueInst::InsertValueInst(const InsertValueInst &IVI)
1896   : Instruction(IVI.getType(), InsertValue,
1897                 OperandTraits<InsertValueInst>::op_begin(this), 2),
1898     Indices(IVI.Indices) {
1899   Op<0>() = IVI.getOperand(0);
1900   Op<1>() = IVI.getOperand(1);
1901   SubclassOptionalData = IVI.SubclassOptionalData;
1902 }
1903
1904 //===----------------------------------------------------------------------===//
1905 //                             ExtractValueInst Class
1906 //===----------------------------------------------------------------------===//
1907
1908 void ExtractValueInst::init(ArrayRef<unsigned> Idxs, const Twine &Name) {
1909   assert(getNumOperands() == 1 && "NumOperands not initialized?");
1910
1911   // There's no fundamental reason why we require at least one index.
1912   // But there's no present need to support it.
1913   assert(Idxs.size() > 0 && "ExtractValueInst must have at least one index");
1914
1915   Indices.append(Idxs.begin(), Idxs.end());
1916   setName(Name);
1917 }
1918
1919 ExtractValueInst::ExtractValueInst(const ExtractValueInst &EVI)
1920   : UnaryInstruction(EVI.getType(), ExtractValue, EVI.getOperand(0)),
1921     Indices(EVI.Indices) {
1922   SubclassOptionalData = EVI.SubclassOptionalData;
1923 }
1924
1925 // getIndexedType - Returns the type of the element that would be extracted
1926 // with an extractvalue instruction with the specified parameters.
1927 //
1928 // A null type is returned if the indices are invalid for the specified
1929 // pointer type.
1930 //
1931 Type *ExtractValueInst::getIndexedType(Type *Agg,
1932                                        ArrayRef<unsigned> Idxs) {
1933   for (unsigned Index : Idxs) {
1934     // We can't use CompositeType::indexValid(Index) here.
1935     // indexValid() always returns true for arrays because getelementptr allows
1936     // out-of-bounds indices. Since we don't allow those for extractvalue and
1937     // insertvalue we need to check array indexing manually.
1938     // Since the only other types we can index into are struct types it's just
1939     // as easy to check those manually as well.
1940     if (ArrayType *AT = dyn_cast<ArrayType>(Agg)) {
1941       if (Index >= AT->getNumElements())
1942         return nullptr;
1943     } else if (StructType *ST = dyn_cast<StructType>(Agg)) {
1944       if (Index >= ST->getNumElements())
1945         return nullptr;
1946     } else {
1947       // Not a valid type to index into.
1948       return nullptr;
1949     }
1950
1951     Agg = cast<CompositeType>(Agg)->getTypeAtIndex(Index);
1952   }
1953   return const_cast<Type*>(Agg);
1954 }
1955
1956 //===----------------------------------------------------------------------===//
1957 //                             BinaryOperator Class
1958 //===----------------------------------------------------------------------===//
1959
1960 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
1961                                Type *Ty, const Twine &Name,
1962                                Instruction *InsertBefore)
1963   : Instruction(Ty, iType,
1964                 OperandTraits<BinaryOperator>::op_begin(this),
1965                 OperandTraits<BinaryOperator>::operands(this),
1966                 InsertBefore) {
1967   Op<0>() = S1;
1968   Op<1>() = S2;
1969   init(iType);
1970   setName(Name);
1971 }
1972
1973 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2, 
1974                                Type *Ty, const Twine &Name,
1975                                BasicBlock *InsertAtEnd)
1976   : Instruction(Ty, iType,
1977                 OperandTraits<BinaryOperator>::op_begin(this),
1978                 OperandTraits<BinaryOperator>::operands(this),
1979                 InsertAtEnd) {
1980   Op<0>() = S1;
1981   Op<1>() = S2;
1982   init(iType);
1983   setName(Name);
1984 }
1985
1986
1987 void BinaryOperator::init(BinaryOps iType) {
1988   Value *LHS = getOperand(0), *RHS = getOperand(1);
1989   (void)LHS; (void)RHS; // Silence warnings.
1990   assert(LHS->getType() == RHS->getType() &&
1991          "Binary operator operand types must match!");
1992 #ifndef NDEBUG
1993   switch (iType) {
1994   case Add: case Sub:
1995   case Mul:
1996     assert(getType() == LHS->getType() &&
1997            "Arithmetic operation should return same type as operands!");
1998     assert(getType()->isIntOrIntVectorTy() &&
1999            "Tried to create an integer operation on a non-integer type!");
2000     break;
2001   case FAdd: case FSub:
2002   case FMul:
2003     assert(getType() == LHS->getType() &&
2004            "Arithmetic operation should return same type as operands!");
2005     assert(getType()->isFPOrFPVectorTy() &&
2006            "Tried to create a floating-point operation on a "
2007            "non-floating-point type!");
2008     break;
2009   case UDiv: 
2010   case SDiv: 
2011     assert(getType() == LHS->getType() &&
2012            "Arithmetic operation should return same type as operands!");
2013     assert((getType()->isIntegerTy() || (getType()->isVectorTy() && 
2014             cast<VectorType>(getType())->getElementType()->isIntegerTy())) &&
2015            "Incorrect operand type (not integer) for S/UDIV");
2016     break;
2017   case FDiv:
2018     assert(getType() == LHS->getType() &&
2019            "Arithmetic operation should return same type as operands!");
2020     assert(getType()->isFPOrFPVectorTy() &&
2021            "Incorrect operand type (not floating point) for FDIV");
2022     break;
2023   case URem: 
2024   case SRem: 
2025     assert(getType() == LHS->getType() &&
2026            "Arithmetic operation should return same type as operands!");
2027     assert((getType()->isIntegerTy() || (getType()->isVectorTy() && 
2028             cast<VectorType>(getType())->getElementType()->isIntegerTy())) &&
2029            "Incorrect operand type (not integer) for S/UREM");
2030     break;
2031   case FRem:
2032     assert(getType() == LHS->getType() &&
2033            "Arithmetic operation should return same type as operands!");
2034     assert(getType()->isFPOrFPVectorTy() &&
2035            "Incorrect operand type (not floating point) for FREM");
2036     break;
2037   case Shl:
2038   case LShr:
2039   case AShr:
2040     assert(getType() == LHS->getType() &&
2041            "Shift operation should return same type as operands!");
2042     assert((getType()->isIntegerTy() ||
2043             (getType()->isVectorTy() && 
2044              cast<VectorType>(getType())->getElementType()->isIntegerTy())) &&
2045            "Tried to create a shift operation on a non-integral type!");
2046     break;
2047   case And: case Or:
2048   case Xor:
2049     assert(getType() == LHS->getType() &&
2050            "Logical operation should return same type as operands!");
2051     assert((getType()->isIntegerTy() ||
2052             (getType()->isVectorTy() && 
2053              cast<VectorType>(getType())->getElementType()->isIntegerTy())) &&
2054            "Tried to create a logical operation on a non-integral type!");
2055     break;
2056   default:
2057     break;
2058   }
2059 #endif
2060 }
2061
2062 BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2,
2063                                        const Twine &Name,
2064                                        Instruction *InsertBefore) {
2065   assert(S1->getType() == S2->getType() &&
2066          "Cannot create binary operator with two operands of differing type!");
2067   return new BinaryOperator(Op, S1, S2, S1->getType(), Name, InsertBefore);
2068 }
2069
2070 BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2,
2071                                        const Twine &Name,
2072                                        BasicBlock *InsertAtEnd) {
2073   BinaryOperator *Res = Create(Op, S1, S2, Name);
2074   InsertAtEnd->getInstList().push_back(Res);
2075   return Res;
2076 }
2077
2078 BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const Twine &Name,
2079                                           Instruction *InsertBefore) {
2080   Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
2081   return new BinaryOperator(Instruction::Sub,
2082                             zero, Op,
2083                             Op->getType(), Name, InsertBefore);
2084 }
2085
2086 BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const Twine &Name,
2087                                           BasicBlock *InsertAtEnd) {
2088   Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
2089   return new BinaryOperator(Instruction::Sub,
2090                             zero, Op,
2091                             Op->getType(), Name, InsertAtEnd);
2092 }
2093
2094 BinaryOperator *BinaryOperator::CreateNSWNeg(Value *Op, const Twine &Name,
2095                                              Instruction *InsertBefore) {
2096   Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
2097   return BinaryOperator::CreateNSWSub(zero, Op, Name, InsertBefore);
2098 }
2099
2100 BinaryOperator *BinaryOperator::CreateNSWNeg(Value *Op, const Twine &Name,
2101                                              BasicBlock *InsertAtEnd) {
2102   Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
2103   return BinaryOperator::CreateNSWSub(zero, Op, Name, InsertAtEnd);
2104 }
2105
2106 BinaryOperator *BinaryOperator::CreateNUWNeg(Value *Op, const Twine &Name,
2107                                              Instruction *InsertBefore) {
2108   Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
2109   return BinaryOperator::CreateNUWSub(zero, Op, Name, InsertBefore);
2110 }
2111
2112 BinaryOperator *BinaryOperator::CreateNUWNeg(Value *Op, const Twine &Name,
2113                                              BasicBlock *InsertAtEnd) {
2114   Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
2115   return BinaryOperator::CreateNUWSub(zero, Op, Name, InsertAtEnd);
2116 }
2117
2118 BinaryOperator *BinaryOperator::CreateFNeg(Value *Op, const Twine &Name,
2119                                            Instruction *InsertBefore) {
2120   Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
2121   return new BinaryOperator(Instruction::FSub, zero, Op,
2122                             Op->getType(), Name, InsertBefore);
2123 }
2124
2125 BinaryOperator *BinaryOperator::CreateFNeg(Value *Op, const Twine &Name,
2126                                            BasicBlock *InsertAtEnd) {
2127   Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
2128   return new BinaryOperator(Instruction::FSub, zero, Op,
2129                             Op->getType(), Name, InsertAtEnd);
2130 }
2131
2132 BinaryOperator *BinaryOperator::CreateNot(Value *Op, const Twine &Name,
2133                                           Instruction *InsertBefore) {
2134   Constant *C = Constant::getAllOnesValue(Op->getType());
2135   return new BinaryOperator(Instruction::Xor, Op, C,
2136                             Op->getType(), Name, InsertBefore);
2137 }
2138
2139 BinaryOperator *BinaryOperator::CreateNot(Value *Op, const Twine &Name,
2140                                           BasicBlock *InsertAtEnd) {
2141   Constant *AllOnes = Constant::getAllOnesValue(Op->getType());
2142   return new BinaryOperator(Instruction::Xor, Op, AllOnes,
2143                             Op->getType(), Name, InsertAtEnd);
2144 }
2145
2146
2147 // isConstantAllOnes - Helper function for several functions below
2148 static inline bool isConstantAllOnes(const Value *V) {
2149   if (const Constant *C = dyn_cast<Constant>(V))
2150     return C->isAllOnesValue();
2151   return false;
2152 }
2153
2154 bool BinaryOperator::isNeg(const Value *V) {
2155   if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
2156     if (Bop->getOpcode() == Instruction::Sub)
2157       if (Constant* C = dyn_cast<Constant>(Bop->getOperand(0)))
2158         return C->isNegativeZeroValue();
2159   return false;
2160 }
2161
2162 bool BinaryOperator::isFNeg(const Value *V, bool IgnoreZeroSign) {
2163   if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
2164     if (Bop->getOpcode() == Instruction::FSub)
2165       if (Constant* C = dyn_cast<Constant>(Bop->getOperand(0))) {
2166         if (!IgnoreZeroSign)
2167           IgnoreZeroSign = cast<Instruction>(V)->hasNoSignedZeros();
2168         return !IgnoreZeroSign ? C->isNegativeZeroValue() : C->isZeroValue();
2169       }
2170   return false;
2171 }
2172
2173 bool BinaryOperator::isNot(const Value *V) {
2174   if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
2175     return (Bop->getOpcode() == Instruction::Xor &&
2176             (isConstantAllOnes(Bop->getOperand(1)) ||
2177              isConstantAllOnes(Bop->getOperand(0))));
2178   return false;
2179 }
2180
2181 Value *BinaryOperator::getNegArgument(Value *BinOp) {
2182   return cast<BinaryOperator>(BinOp)->getOperand(1);
2183 }
2184
2185 const Value *BinaryOperator::getNegArgument(const Value *BinOp) {
2186   return getNegArgument(const_cast<Value*>(BinOp));
2187 }
2188
2189 Value *BinaryOperator::getFNegArgument(Value *BinOp) {
2190   return cast<BinaryOperator>(BinOp)->getOperand(1);
2191 }
2192
2193 const Value *BinaryOperator::getFNegArgument(const Value *BinOp) {
2194   return getFNegArgument(const_cast<Value*>(BinOp));
2195 }
2196
2197 Value *BinaryOperator::getNotArgument(Value *BinOp) {
2198   assert(isNot(BinOp) && "getNotArgument on non-'not' instruction!");
2199   BinaryOperator *BO = cast<BinaryOperator>(BinOp);
2200   Value *Op0 = BO->getOperand(0);
2201   Value *Op1 = BO->getOperand(1);
2202   if (isConstantAllOnes(Op0)) return Op1;
2203
2204   assert(isConstantAllOnes(Op1));
2205   return Op0;
2206 }
2207
2208 const Value *BinaryOperator::getNotArgument(const Value *BinOp) {
2209   return getNotArgument(const_cast<Value*>(BinOp));
2210 }
2211
2212
2213 // swapOperands - Exchange the two operands to this instruction.  This
2214 // instruction is safe to use on any binary instruction and does not
2215 // modify the semantics of the instruction.  If the instruction is
2216 // order dependent (SetLT f.e.) the opcode is changed.
2217 //
2218 bool BinaryOperator::swapOperands() {
2219   if (!isCommutative())
2220     return true; // Can't commute operands
2221   Op<0>().swap(Op<1>());
2222   return false;
2223 }
2224
2225 void BinaryOperator::setHasNoUnsignedWrap(bool b) {
2226   cast<OverflowingBinaryOperator>(this)->setHasNoUnsignedWrap(b);
2227 }
2228
2229 void BinaryOperator::setHasNoSignedWrap(bool b) {
2230   cast<OverflowingBinaryOperator>(this)->setHasNoSignedWrap(b);
2231 }
2232
2233 void BinaryOperator::setIsExact(bool b) {
2234   cast<PossiblyExactOperator>(this)->setIsExact(b);
2235 }
2236
2237 bool BinaryOperator::hasNoUnsignedWrap() const {
2238   return cast<OverflowingBinaryOperator>(this)->hasNoUnsignedWrap();
2239 }
2240
2241 bool BinaryOperator::hasNoSignedWrap() const {
2242   return cast<OverflowingBinaryOperator>(this)->hasNoSignedWrap();
2243 }
2244
2245 bool BinaryOperator::isExact() const {
2246   return cast<PossiblyExactOperator>(this)->isExact();
2247 }
2248
2249 void BinaryOperator::copyIRFlags(const Value *V) {
2250   // Copy the wrapping flags.
2251   if (auto *OB = dyn_cast<OverflowingBinaryOperator>(V)) {
2252     setHasNoSignedWrap(OB->hasNoSignedWrap());
2253     setHasNoUnsignedWrap(OB->hasNoUnsignedWrap());
2254   }
2255
2256   // Copy the exact flag.
2257   if (auto *PE = dyn_cast<PossiblyExactOperator>(V))
2258     setIsExact(PE->isExact());
2259   
2260   // Copy the fast-math flags.
2261   if (auto *FP = dyn_cast<FPMathOperator>(V))
2262     copyFastMathFlags(FP->getFastMathFlags());
2263 }
2264
2265 void BinaryOperator::andIRFlags(const Value *V) {
2266   if (auto *OB = dyn_cast<OverflowingBinaryOperator>(V)) {
2267     setHasNoSignedWrap(hasNoSignedWrap() & OB->hasNoSignedWrap());
2268     setHasNoUnsignedWrap(hasNoUnsignedWrap() & OB->hasNoUnsignedWrap());
2269   }
2270   
2271   if (auto *PE = dyn_cast<PossiblyExactOperator>(V))
2272     setIsExact(isExact() & PE->isExact());
2273   
2274   if (auto *FP = dyn_cast<FPMathOperator>(V)) {
2275     FastMathFlags FM = getFastMathFlags();
2276     FM &= FP->getFastMathFlags();
2277     copyFastMathFlags(FM);
2278   }
2279 }
2280
2281
2282 //===----------------------------------------------------------------------===//
2283 //                             FPMathOperator Class
2284 //===----------------------------------------------------------------------===//
2285
2286 /// getFPAccuracy - Get the maximum error permitted by this operation in ULPs.
2287 /// An accuracy of 0.0 means that the operation should be performed with the
2288 /// default precision.
2289 float FPMathOperator::getFPAccuracy() const {
2290   const MDNode *MD =
2291       cast<Instruction>(this)->getMetadata(LLVMContext::MD_fpmath);
2292   if (!MD)
2293     return 0.0;
2294   ConstantFP *Accuracy = mdconst::extract<ConstantFP>(MD->getOperand(0));
2295   return Accuracy->getValueAPF().convertToFloat();
2296 }
2297
2298
2299 //===----------------------------------------------------------------------===//
2300 //                                CastInst Class
2301 //===----------------------------------------------------------------------===//
2302
2303 void CastInst::anchor() {}
2304
2305 // Just determine if this cast only deals with integral->integral conversion.
2306 bool CastInst::isIntegerCast() const {
2307   switch (getOpcode()) {
2308     default: return false;
2309     case Instruction::ZExt:
2310     case Instruction::SExt:
2311     case Instruction::Trunc:
2312       return true;
2313     case Instruction::BitCast:
2314       return getOperand(0)->getType()->isIntegerTy() &&
2315         getType()->isIntegerTy();
2316   }
2317 }
2318
2319 bool CastInst::isLosslessCast() const {
2320   // Only BitCast can be lossless, exit fast if we're not BitCast
2321   if (getOpcode() != Instruction::BitCast)
2322     return false;
2323
2324   // Identity cast is always lossless
2325   Type* SrcTy = getOperand(0)->getType();
2326   Type* DstTy = getType();
2327   if (SrcTy == DstTy)
2328     return true;
2329   
2330   // Pointer to pointer is always lossless.
2331   if (SrcTy->isPointerTy())
2332     return DstTy->isPointerTy();
2333   return false;  // Other types have no identity values
2334 }
2335
2336 /// This function determines if the CastInst does not require any bits to be
2337 /// changed in order to effect the cast. Essentially, it identifies cases where
2338 /// no code gen is necessary for the cast, hence the name no-op cast.  For 
2339 /// example, the following are all no-op casts:
2340 /// # bitcast i32* %x to i8*
2341 /// # bitcast <2 x i32> %x to <4 x i16> 
2342 /// # ptrtoint i32* %x to i32     ; on 32-bit plaforms only
2343 /// @brief Determine if the described cast is a no-op.
2344 bool CastInst::isNoopCast(Instruction::CastOps Opcode,
2345                           Type *SrcTy,
2346                           Type *DestTy,
2347                           Type *IntPtrTy) {
2348   switch (Opcode) {
2349     default: llvm_unreachable("Invalid CastOp");
2350     case Instruction::Trunc:
2351     case Instruction::ZExt:
2352     case Instruction::SExt: 
2353     case Instruction::FPTrunc:
2354     case Instruction::FPExt:
2355     case Instruction::UIToFP:
2356     case Instruction::SIToFP:
2357     case Instruction::FPToUI:
2358     case Instruction::FPToSI:
2359     case Instruction::AddrSpaceCast:
2360       // TODO: Target informations may give a more accurate answer here.
2361       return false;
2362     case Instruction::BitCast:
2363       return true;  // BitCast never modifies bits.
2364     case Instruction::PtrToInt:
2365       return IntPtrTy->getScalarSizeInBits() ==
2366              DestTy->getScalarSizeInBits();
2367     case Instruction::IntToPtr:
2368       return IntPtrTy->getScalarSizeInBits() ==
2369              SrcTy->getScalarSizeInBits();
2370   }
2371 }
2372
2373 /// @brief Determine if a cast is a no-op.
2374 bool CastInst::isNoopCast(Type *IntPtrTy) const {
2375   return isNoopCast(getOpcode(), getOperand(0)->getType(), getType(), IntPtrTy);
2376 }
2377
2378 bool CastInst::isNoopCast(const DataLayout &DL) const {
2379   Type *PtrOpTy = nullptr;
2380   if (getOpcode() == Instruction::PtrToInt)
2381     PtrOpTy = getOperand(0)->getType();
2382   else if (getOpcode() == Instruction::IntToPtr)
2383     PtrOpTy = getType();
2384
2385   Type *IntPtrTy =
2386       PtrOpTy ? DL.getIntPtrType(PtrOpTy) : DL.getIntPtrType(getContext(), 0);
2387
2388   return isNoopCast(getOpcode(), getOperand(0)->getType(), getType(), IntPtrTy);
2389 }
2390
2391 /// This function determines if a pair of casts can be eliminated and what
2392 /// opcode should be used in the elimination. This assumes that there are two
2393 /// instructions like this:
2394 /// *  %F = firstOpcode SrcTy %x to MidTy
2395 /// *  %S = secondOpcode MidTy %F to DstTy
2396 /// The function returns a resultOpcode so these two casts can be replaced with:
2397 /// *  %Replacement = resultOpcode %SrcTy %x to DstTy
2398 /// If no such cast is permited, the function returns 0.
2399 unsigned CastInst::isEliminableCastPair(
2400   Instruction::CastOps firstOp, Instruction::CastOps secondOp,
2401   Type *SrcTy, Type *MidTy, Type *DstTy, Type *SrcIntPtrTy, Type *MidIntPtrTy,
2402   Type *DstIntPtrTy) {
2403   // Define the 144 possibilities for these two cast instructions. The values
2404   // in this matrix determine what to do in a given situation and select the
2405   // case in the switch below.  The rows correspond to firstOp, the columns 
2406   // correspond to secondOp.  In looking at the table below, keep in  mind
2407   // the following cast properties:
2408   //
2409   //          Size Compare       Source               Destination
2410   // Operator  Src ? Size   Type       Sign         Type       Sign
2411   // -------- ------------ -------------------   ---------------------
2412   // TRUNC         >       Integer      Any        Integral     Any
2413   // ZEXT          <       Integral   Unsigned     Integer      Any
2414   // SEXT          <       Integral    Signed      Integer      Any
2415   // FPTOUI       n/a      FloatPt      n/a        Integral   Unsigned
2416   // FPTOSI       n/a      FloatPt      n/a        Integral    Signed
2417   // UITOFP       n/a      Integral   Unsigned     FloatPt      n/a
2418   // SITOFP       n/a      Integral    Signed      FloatPt      n/a
2419   // FPTRUNC       >       FloatPt      n/a        FloatPt      n/a
2420   // FPEXT         <       FloatPt      n/a        FloatPt      n/a
2421   // PTRTOINT     n/a      Pointer      n/a        Integral   Unsigned
2422   // INTTOPTR     n/a      Integral   Unsigned     Pointer      n/a
2423   // BITCAST       =       FirstClass   n/a       FirstClass    n/a
2424   // ADDRSPCST    n/a      Pointer      n/a        Pointer      n/a
2425   //
2426   // NOTE: some transforms are safe, but we consider them to be non-profitable.
2427   // For example, we could merge "fptoui double to i32" + "zext i32 to i64",
2428   // into "fptoui double to i64", but this loses information about the range
2429   // of the produced value (we no longer know the top-part is all zeros).
2430   // Further this conversion is often much more expensive for typical hardware,
2431   // and causes issues when building libgcc.  We disallow fptosi+sext for the
2432   // same reason.
2433   const unsigned numCastOps =
2434     Instruction::CastOpsEnd - Instruction::CastOpsBegin;
2435   static const uint8_t CastResults[numCastOps][numCastOps] = {
2436     // T        F  F  U  S  F  F  P  I  B  A  -+
2437     // R  Z  S  P  P  I  I  T  P  2  N  T  S   |
2438     // U  E  E  2  2  2  2  R  E  I  T  C  C   +- secondOp
2439     // N  X  X  U  S  F  F  N  X  N  2  V  V   |
2440     // C  T  T  I  I  P  P  C  T  T  P  T  T  -+
2441     {  1, 0, 0,99,99, 0, 0,99,99,99, 0, 3, 0}, // Trunc         -+
2442     {  8, 1, 9,99,99, 2,17,99,99,99, 2, 3, 0}, // ZExt           |
2443     {  8, 0, 1,99,99, 0, 2,99,99,99, 0, 3, 0}, // SExt           |
2444     {  0, 0, 0,99,99, 0, 0,99,99,99, 0, 3, 0}, // FPToUI         |
2445     {  0, 0, 0,99,99, 0, 0,99,99,99, 0, 3, 0}, // FPToSI         |
2446     { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4, 0}, // UIToFP         +- firstOp
2447     { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4, 0}, // SIToFP         |
2448     { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4, 0}, // FPTrunc        |
2449     { 99,99,99, 2, 2,99,99,10, 2,99,99, 4, 0}, // FPExt          |
2450     {  1, 0, 0,99,99, 0, 0,99,99,99, 7, 3, 0}, // PtrToInt       |
2451     { 99,99,99,99,99,99,99,99,99,11,99,15, 0}, // IntToPtr       |
2452     {  5, 5, 5, 6, 6, 5, 5, 6, 6,16, 5, 1,14}, // BitCast        |
2453     {  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,13,12}, // AddrSpaceCast -+
2454   };
2455
2456   // If either of the casts are a bitcast from scalar to vector, disallow the
2457   // merging. However, bitcast of A->B->A are allowed.
2458   bool isFirstBitcast  = (firstOp == Instruction::BitCast);
2459   bool isSecondBitcast = (secondOp == Instruction::BitCast);
2460   bool chainedBitcast  = (SrcTy == DstTy && isFirstBitcast && isSecondBitcast);
2461
2462   // Check if any of the bitcasts convert scalars<->vectors.
2463   if ((isFirstBitcast  && isa<VectorType>(SrcTy) != isa<VectorType>(MidTy)) ||
2464       (isSecondBitcast && isa<VectorType>(MidTy) != isa<VectorType>(DstTy)))
2465     // Unless we are bitcasing to the original type, disallow optimizations.
2466     if (!chainedBitcast) return 0;
2467
2468   int ElimCase = CastResults[firstOp-Instruction::CastOpsBegin]
2469                             [secondOp-Instruction::CastOpsBegin];
2470   switch (ElimCase) {
2471     case 0: 
2472       // Categorically disallowed.
2473       return 0;
2474     case 1: 
2475       // Allowed, use first cast's opcode.
2476       return firstOp;
2477     case 2: 
2478       // Allowed, use second cast's opcode.
2479       return secondOp;
2480     case 3: 
2481       // No-op cast in second op implies firstOp as long as the DestTy
2482       // is integer and we are not converting between a vector and a
2483       // non-vector type.
2484       if (!SrcTy->isVectorTy() && DstTy->isIntegerTy())
2485         return firstOp;
2486       return 0;
2487     case 4:
2488       // No-op cast in second op implies firstOp as long as the DestTy
2489       // is floating point.
2490       if (DstTy->isFloatingPointTy())
2491         return firstOp;
2492       return 0;
2493     case 5: 
2494       // No-op cast in first op implies secondOp as long as the SrcTy
2495       // is an integer.
2496       if (SrcTy->isIntegerTy())
2497         return secondOp;
2498       return 0;
2499     case 6:
2500       // No-op cast in first op implies secondOp as long as the SrcTy
2501       // is a floating point.
2502       if (SrcTy->isFloatingPointTy())
2503         return secondOp;
2504       return 0;
2505     case 7: {
2506       // Cannot simplify if address spaces are different!
2507       if (SrcTy->getPointerAddressSpace() != DstTy->getPointerAddressSpace())
2508         return 0;
2509
2510       unsigned MidSize = MidTy->getScalarSizeInBits();
2511       // We can still fold this without knowing the actual sizes as long we
2512       // know that the intermediate pointer is the largest possible
2513       // pointer size.
2514       // FIXME: Is this always true?
2515       if (MidSize == 64)
2516         return Instruction::BitCast;
2517
2518       // ptrtoint, inttoptr -> bitcast (ptr -> ptr) if int size is >= ptr size.
2519       if (!SrcIntPtrTy || DstIntPtrTy != SrcIntPtrTy)
2520         return 0;
2521       unsigned PtrSize = SrcIntPtrTy->getScalarSizeInBits();
2522       if (MidSize >= PtrSize)
2523         return Instruction::BitCast;
2524       return 0;
2525     }
2526     case 8: {
2527       // ext, trunc -> bitcast,    if the SrcTy and DstTy are same size
2528       // ext, trunc -> ext,        if sizeof(SrcTy) < sizeof(DstTy)
2529       // ext, trunc -> trunc,      if sizeof(SrcTy) > sizeof(DstTy)
2530       unsigned SrcSize = SrcTy->getScalarSizeInBits();
2531       unsigned DstSize = DstTy->getScalarSizeInBits();
2532       if (SrcSize == DstSize)
2533         return Instruction::BitCast;
2534       else if (SrcSize < DstSize)
2535         return firstOp;
2536       return secondOp;
2537     }
2538     case 9:
2539       // zext, sext -> zext, because sext can't sign extend after zext
2540       return Instruction::ZExt;
2541     case 10:
2542       // fpext followed by ftrunc is allowed if the bit size returned to is
2543       // the same as the original, in which case its just a bitcast
2544       if (SrcTy == DstTy)
2545         return Instruction::BitCast;
2546       return 0; // If the types are not the same we can't eliminate it.
2547     case 11: {
2548       // inttoptr, ptrtoint -> bitcast if SrcSize<=PtrSize and SrcSize==DstSize
2549       if (!MidIntPtrTy)
2550         return 0;
2551       unsigned PtrSize = MidIntPtrTy->getScalarSizeInBits();
2552       unsigned SrcSize = SrcTy->getScalarSizeInBits();
2553       unsigned DstSize = DstTy->getScalarSizeInBits();
2554       if (SrcSize <= PtrSize && SrcSize == DstSize)
2555         return Instruction::BitCast;
2556       return 0;
2557     }
2558     case 12: {
2559       // addrspacecast, addrspacecast -> bitcast,       if SrcAS == DstAS
2560       // addrspacecast, addrspacecast -> addrspacecast, if SrcAS != DstAS
2561       if (SrcTy->getPointerAddressSpace() != DstTy->getPointerAddressSpace())
2562         return Instruction::AddrSpaceCast;
2563       return Instruction::BitCast;
2564     }
2565     case 13:
2566       // FIXME: this state can be merged with (1), but the following assert
2567       // is useful to check the correcteness of the sequence due to semantic
2568       // change of bitcast.
2569       assert(
2570         SrcTy->isPtrOrPtrVectorTy() &&
2571         MidTy->isPtrOrPtrVectorTy() &&
2572         DstTy->isPtrOrPtrVectorTy() &&
2573         SrcTy->getPointerAddressSpace() != MidTy->getPointerAddressSpace() &&
2574         MidTy->getPointerAddressSpace() == DstTy->getPointerAddressSpace() &&
2575         "Illegal addrspacecast, bitcast sequence!");
2576       // Allowed, use first cast's opcode
2577       return firstOp;
2578     case 14:
2579       // bitcast, addrspacecast -> addrspacecast if the element type of
2580       // bitcast's source is the same as that of addrspacecast's destination.
2581       if (SrcTy->getPointerElementType() == DstTy->getPointerElementType())
2582         return Instruction::AddrSpaceCast;
2583       return 0;
2584
2585     case 15:
2586       // FIXME: this state can be merged with (1), but the following assert
2587       // is useful to check the correcteness of the sequence due to semantic
2588       // change of bitcast.
2589       assert(
2590         SrcTy->isIntOrIntVectorTy() &&
2591         MidTy->isPtrOrPtrVectorTy() &&
2592         DstTy->isPtrOrPtrVectorTy() &&
2593         MidTy->getPointerAddressSpace() == DstTy->getPointerAddressSpace() &&
2594         "Illegal inttoptr, bitcast sequence!");
2595       // Allowed, use first cast's opcode
2596       return firstOp;
2597     case 16:
2598       // FIXME: this state can be merged with (2), but the following assert
2599       // is useful to check the correcteness of the sequence due to semantic
2600       // change of bitcast.
2601       assert(
2602         SrcTy->isPtrOrPtrVectorTy() &&
2603         MidTy->isPtrOrPtrVectorTy() &&
2604         DstTy->isIntOrIntVectorTy() &&
2605         SrcTy->getPointerAddressSpace() == MidTy->getPointerAddressSpace() &&
2606         "Illegal bitcast, ptrtoint sequence!");
2607       // Allowed, use second cast's opcode
2608       return secondOp;
2609     case 17:
2610       // (sitofp (zext x)) -> (uitofp x)
2611       return Instruction::UIToFP;
2612     case 99: 
2613       // Cast combination can't happen (error in input). This is for all cases
2614       // where the MidTy is not the same for the two cast instructions.
2615       llvm_unreachable("Invalid Cast Combination");
2616     default:
2617       llvm_unreachable("Error in CastResults table!!!");
2618   }
2619 }
2620
2621 CastInst *CastInst::Create(Instruction::CastOps op, Value *S, Type *Ty, 
2622   const Twine &Name, Instruction *InsertBefore) {
2623   assert(castIsValid(op, S, Ty) && "Invalid cast!");
2624   // Construct and return the appropriate CastInst subclass
2625   switch (op) {
2626   case Trunc:         return new TruncInst         (S, Ty, Name, InsertBefore);
2627   case ZExt:          return new ZExtInst          (S, Ty, Name, InsertBefore);
2628   case SExt:          return new SExtInst          (S, Ty, Name, InsertBefore);
2629   case FPTrunc:       return new FPTruncInst       (S, Ty, Name, InsertBefore);
2630   case FPExt:         return new FPExtInst         (S, Ty, Name, InsertBefore);
2631   case UIToFP:        return new UIToFPInst        (S, Ty, Name, InsertBefore);
2632   case SIToFP:        return new SIToFPInst        (S, Ty, Name, InsertBefore);
2633   case FPToUI:        return new FPToUIInst        (S, Ty, Name, InsertBefore);
2634   case FPToSI:        return new FPToSIInst        (S, Ty, Name, InsertBefore);
2635   case PtrToInt:      return new PtrToIntInst      (S, Ty, Name, InsertBefore);
2636   case IntToPtr:      return new IntToPtrInst      (S, Ty, Name, InsertBefore);
2637   case BitCast:       return new BitCastInst       (S, Ty, Name, InsertBefore);
2638   case AddrSpaceCast: return new AddrSpaceCastInst (S, Ty, Name, InsertBefore);
2639   default: llvm_unreachable("Invalid opcode provided");
2640   }
2641 }
2642
2643 CastInst *CastInst::Create(Instruction::CastOps op, Value *S, Type *Ty,
2644   const Twine &Name, BasicBlock *InsertAtEnd) {
2645   assert(castIsValid(op, S, Ty) && "Invalid cast!");
2646   // Construct and return the appropriate CastInst subclass
2647   switch (op) {
2648   case Trunc:         return new TruncInst         (S, Ty, Name, InsertAtEnd);
2649   case ZExt:          return new ZExtInst          (S, Ty, Name, InsertAtEnd);
2650   case SExt:          return new SExtInst          (S, Ty, Name, InsertAtEnd);
2651   case FPTrunc:       return new FPTruncInst       (S, Ty, Name, InsertAtEnd);
2652   case FPExt:         return new FPExtInst         (S, Ty, Name, InsertAtEnd);
2653   case UIToFP:        return new UIToFPInst        (S, Ty, Name, InsertAtEnd);
2654   case SIToFP:        return new SIToFPInst        (S, Ty, Name, InsertAtEnd);
2655   case FPToUI:        return new FPToUIInst        (S, Ty, Name, InsertAtEnd);
2656   case FPToSI:        return new FPToSIInst        (S, Ty, Name, InsertAtEnd);
2657   case PtrToInt:      return new PtrToIntInst      (S, Ty, Name, InsertAtEnd);
2658   case IntToPtr:      return new IntToPtrInst      (S, Ty, Name, InsertAtEnd);
2659   case BitCast:       return new BitCastInst       (S, Ty, Name, InsertAtEnd);
2660   case AddrSpaceCast: return new AddrSpaceCastInst (S, Ty, Name, InsertAtEnd);
2661   default: llvm_unreachable("Invalid opcode provided");
2662   }
2663 }
2664
2665 CastInst *CastInst::CreateZExtOrBitCast(Value *S, Type *Ty, 
2666                                         const Twine &Name,
2667                                         Instruction *InsertBefore) {
2668   if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2669     return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2670   return Create(Instruction::ZExt, S, Ty, Name, InsertBefore);
2671 }
2672
2673 CastInst *CastInst::CreateZExtOrBitCast(Value *S, Type *Ty, 
2674                                         const Twine &Name,
2675                                         BasicBlock *InsertAtEnd) {
2676   if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2677     return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2678   return Create(Instruction::ZExt, S, Ty, Name, InsertAtEnd);
2679 }
2680
2681 CastInst *CastInst::CreateSExtOrBitCast(Value *S, Type *Ty, 
2682                                         const Twine &Name,
2683                                         Instruction *InsertBefore) {
2684   if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2685     return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2686   return Create(Instruction::SExt, S, Ty, Name, InsertBefore);
2687 }
2688
2689 CastInst *CastInst::CreateSExtOrBitCast(Value *S, Type *Ty, 
2690                                         const Twine &Name,
2691                                         BasicBlock *InsertAtEnd) {
2692   if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2693     return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2694   return Create(Instruction::SExt, S, Ty, Name, InsertAtEnd);
2695 }
2696
2697 CastInst *CastInst::CreateTruncOrBitCast(Value *S, Type *Ty,
2698                                          const Twine &Name,
2699                                          Instruction *InsertBefore) {
2700   if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2701     return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2702   return Create(Instruction::Trunc, S, Ty, Name, InsertBefore);
2703 }
2704
2705 CastInst *CastInst::CreateTruncOrBitCast(Value *S, Type *Ty,
2706                                          const Twine &Name, 
2707                                          BasicBlock *InsertAtEnd) {
2708   if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2709     return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2710   return Create(Instruction::Trunc, S, Ty, Name, InsertAtEnd);
2711 }
2712
2713 CastInst *CastInst::CreatePointerCast(Value *S, Type *Ty,
2714                                       const Twine &Name,
2715                                       BasicBlock *InsertAtEnd) {
2716   assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
2717   assert((Ty->isIntOrIntVectorTy() || Ty->isPtrOrPtrVectorTy()) &&
2718          "Invalid cast");
2719   assert(Ty->isVectorTy() == S->getType()->isVectorTy() && "Invalid cast");
2720   assert((!Ty->isVectorTy() ||
2721           Ty->getVectorNumElements() == S->getType()->getVectorNumElements()) &&
2722          "Invalid cast");
2723
2724   if (Ty->isIntOrIntVectorTy())
2725     return Create(Instruction::PtrToInt, S, Ty, Name, InsertAtEnd);
2726
2727   return CreatePointerBitCastOrAddrSpaceCast(S, Ty, Name, InsertAtEnd);
2728 }
2729
2730 /// @brief Create a BitCast or a PtrToInt cast instruction
2731 CastInst *CastInst::CreatePointerCast(Value *S, Type *Ty,
2732                                       const Twine &Name,
2733                                       Instruction *InsertBefore) {
2734   assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
2735   assert((Ty->isIntOrIntVectorTy() || Ty->isPtrOrPtrVectorTy()) &&
2736          "Invalid cast");
2737   assert(Ty->isVectorTy() == S->getType()->isVectorTy() && "Invalid cast");
2738   assert((!Ty->isVectorTy() ||
2739           Ty->getVectorNumElements() == S->getType()->getVectorNumElements()) &&
2740          "Invalid cast");
2741
2742   if (Ty->isIntOrIntVectorTy())
2743     return Create(Instruction::PtrToInt, S, Ty, Name, InsertBefore);
2744
2745   return CreatePointerBitCastOrAddrSpaceCast(S, Ty, Name, InsertBefore);
2746 }
2747
2748 CastInst *CastInst::CreatePointerBitCastOrAddrSpaceCast(
2749   Value *S, Type *Ty,
2750   const Twine &Name,
2751   BasicBlock *InsertAtEnd) {
2752   assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
2753   assert(Ty->isPtrOrPtrVectorTy() && "Invalid cast");
2754
2755   if (S->getType()->getPointerAddressSpace() != Ty->getPointerAddressSpace())
2756     return Create(Instruction::AddrSpaceCast, S, Ty, Name, InsertAtEnd);
2757
2758   return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2759 }
2760
2761 CastInst *CastInst::CreatePointerBitCastOrAddrSpaceCast(
2762   Value *S, Type *Ty,
2763   const Twine &Name,
2764   Instruction *InsertBefore) {
2765   assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
2766   assert(Ty->isPtrOrPtrVectorTy() && "Invalid cast");
2767
2768   if (S->getType()->getPointerAddressSpace() != Ty->getPointerAddressSpace())
2769     return Create(Instruction::AddrSpaceCast, S, Ty, Name, InsertBefore);
2770
2771   return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2772 }
2773
2774 CastInst *CastInst::CreateBitOrPointerCast(Value *S, Type *Ty,
2775                                            const Twine &Name,
2776                                            Instruction *InsertBefore) {
2777   if (S->getType()->isPointerTy() && Ty->isIntegerTy())
2778     return Create(Instruction::PtrToInt, S, Ty, Name, InsertBefore);
2779   if (S->getType()->isIntegerTy() && Ty->isPointerTy())
2780     return Create(Instruction::IntToPtr, S, Ty, Name, InsertBefore);
2781
2782   return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2783 }
2784
2785 CastInst *CastInst::CreateIntegerCast(Value *C, Type *Ty,
2786                                       bool isSigned, const Twine &Name,
2787                                       Instruction *InsertBefore) {
2788   assert(C->getType()->isIntOrIntVectorTy() && Ty->isIntOrIntVectorTy() &&
2789          "Invalid integer cast");
2790   unsigned SrcBits = C->getType()->getScalarSizeInBits();
2791   unsigned DstBits = Ty->getScalarSizeInBits();
2792   Instruction::CastOps opcode =
2793     (SrcBits == DstBits ? Instruction::BitCast :
2794      (SrcBits > DstBits ? Instruction::Trunc :
2795       (isSigned ? Instruction::SExt : Instruction::ZExt)));
2796   return Create(opcode, C, Ty, Name, InsertBefore);
2797 }
2798
2799 CastInst *CastInst::CreateIntegerCast(Value *C, Type *Ty, 
2800                                       bool isSigned, const Twine &Name,
2801                                       BasicBlock *InsertAtEnd) {
2802   assert(C->getType()->isIntOrIntVectorTy() && Ty->isIntOrIntVectorTy() &&
2803          "Invalid cast");
2804   unsigned SrcBits = C->getType()->getScalarSizeInBits();
2805   unsigned DstBits = Ty->getScalarSizeInBits();
2806   Instruction::CastOps opcode =
2807     (SrcBits == DstBits ? Instruction::BitCast :
2808      (SrcBits > DstBits ? Instruction::Trunc :
2809       (isSigned ? Instruction::SExt : Instruction::ZExt)));
2810   return Create(opcode, C, Ty, Name, InsertAtEnd);
2811 }
2812
2813 CastInst *CastInst::CreateFPCast(Value *C, Type *Ty, 
2814                                  const Twine &Name, 
2815                                  Instruction *InsertBefore) {
2816   assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
2817          "Invalid cast");
2818   unsigned SrcBits = C->getType()->getScalarSizeInBits();
2819   unsigned DstBits = Ty->getScalarSizeInBits();
2820   Instruction::CastOps opcode =
2821     (SrcBits == DstBits ? Instruction::BitCast :
2822      (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
2823   return Create(opcode, C, Ty, Name, InsertBefore);
2824 }
2825
2826 CastInst *CastInst::CreateFPCast(Value *C, Type *Ty, 
2827                                  const Twine &Name, 
2828                                  BasicBlock *InsertAtEnd) {
2829   assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
2830          "Invalid cast");
2831   unsigned SrcBits = C->getType()->getScalarSizeInBits();
2832   unsigned DstBits = Ty->getScalarSizeInBits();
2833   Instruction::CastOps opcode =
2834     (SrcBits == DstBits ? Instruction::BitCast :
2835      (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
2836   return Create(opcode, C, Ty, Name, InsertAtEnd);
2837 }
2838
2839 // Check whether it is valid to call getCastOpcode for these types.
2840 // This routine must be kept in sync with getCastOpcode.
2841 bool CastInst::isCastable(Type *SrcTy, Type *DestTy) {
2842   if (!SrcTy->isFirstClassType() || !DestTy->isFirstClassType())
2843     return false;
2844
2845   if (SrcTy == DestTy)
2846     return true;
2847
2848   if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy))
2849     if (VectorType *DestVecTy = dyn_cast<VectorType>(DestTy))
2850       if (SrcVecTy->getNumElements() == DestVecTy->getNumElements()) {
2851         // An element by element cast.  Valid if casting the elements is valid.
2852         SrcTy = SrcVecTy->getElementType();
2853         DestTy = DestVecTy->getElementType();
2854       }
2855
2856   // Get the bit sizes, we'll need these
2857   unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();   // 0 for ptr
2858   unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr
2859
2860   // Run through the possibilities ...
2861   if (DestTy->isIntegerTy()) {               // Casting to integral
2862     if (SrcTy->isIntegerTy())                // Casting from integral
2863         return true;
2864     if (SrcTy->isFloatingPointTy())   // Casting from floating pt
2865       return true;
2866     if (SrcTy->isVectorTy())          // Casting from vector
2867       return DestBits == SrcBits;
2868                                       // Casting from something else
2869     return SrcTy->isPointerTy();
2870   } 
2871   if (DestTy->isFloatingPointTy()) {  // Casting to floating pt
2872     if (SrcTy->isIntegerTy())                // Casting from integral
2873       return true;
2874     if (SrcTy->isFloatingPointTy())   // Casting from floating pt
2875       return true;
2876     if (SrcTy->isVectorTy())          // Casting from vector
2877       return DestBits == SrcBits;
2878                                     // Casting from something else
2879     return false;
2880   }
2881   if (DestTy->isVectorTy())         // Casting to vector
2882     return DestBits == SrcBits;
2883   if (DestTy->isPointerTy()) {        // Casting to pointer
2884     if (SrcTy->isPointerTy())                // Casting from pointer
2885       return true;
2886     return SrcTy->isIntegerTy();             // Casting from integral
2887   } 
2888   if (DestTy->isX86_MMXTy()) {
2889     if (SrcTy->isVectorTy())
2890       return DestBits == SrcBits;       // 64-bit vector to MMX
2891     return false;
2892   }                                    // Casting to something else
2893   return false;
2894 }
2895
2896 bool CastInst::isBitCastable(Type *SrcTy, Type *DestTy) {
2897   if (!SrcTy->isFirstClassType() || !DestTy->isFirstClassType())
2898     return false;
2899
2900   if (SrcTy == DestTy)
2901     return true;
2902
2903   if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy)) {
2904     if (VectorType *DestVecTy = dyn_cast<VectorType>(DestTy)) {
2905       if (SrcVecTy->getNumElements() == DestVecTy->getNumElements()) {
2906         // An element by element cast. Valid if casting the elements is valid.
2907         SrcTy = SrcVecTy->getElementType();
2908         DestTy = DestVecTy->getElementType();
2909       }
2910     }
2911   }
2912
2913   if (PointerType *DestPtrTy = dyn_cast<PointerType>(DestTy)) {
2914     if (PointerType *SrcPtrTy = dyn_cast<PointerType>(SrcTy)) {
2915       return SrcPtrTy->getAddressSpace() == DestPtrTy->getAddressSpace();
2916     }
2917   }
2918
2919   unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();   // 0 for ptr
2920   unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr
2921
2922   // Could still have vectors of pointers if the number of elements doesn't
2923   // match
2924   if (SrcBits == 0 || DestBits == 0)
2925     return false;
2926
2927   if (SrcBits != DestBits)
2928     return false;
2929
2930   if (DestTy->isX86_MMXTy() || SrcTy->isX86_MMXTy())
2931     return false;
2932
2933   return true;
2934 }
2935
2936 bool CastInst::isBitOrNoopPointerCastable(Type *SrcTy, Type *DestTy,
2937                                           const DataLayout &DL) {
2938   if (auto *PtrTy = dyn_cast<PointerType>(SrcTy))
2939     if (auto *IntTy = dyn_cast<IntegerType>(DestTy))
2940       return IntTy->getBitWidth() == DL.getPointerTypeSizeInBits(PtrTy);
2941   if (auto *PtrTy = dyn_cast<PointerType>(DestTy))
2942     if (auto *IntTy = dyn_cast<IntegerType>(SrcTy))
2943       return IntTy->getBitWidth() == DL.getPointerTypeSizeInBits(PtrTy);
2944
2945   return isBitCastable(SrcTy, DestTy);
2946 }
2947
2948 // Provide a way to get a "cast" where the cast opcode is inferred from the
2949 // types and size of the operand. This, basically, is a parallel of the
2950 // logic in the castIsValid function below.  This axiom should hold:
2951 //   castIsValid( getCastOpcode(Val, Ty), Val, Ty)
2952 // should not assert in castIsValid. In other words, this produces a "correct"
2953 // casting opcode for the arguments passed to it.
2954 // This routine must be kept in sync with isCastable.
2955 Instruction::CastOps
2956 CastInst::getCastOpcode(
2957   const Value *Src, bool SrcIsSigned, Type *DestTy, bool DestIsSigned) {
2958   Type *SrcTy = Src->getType();
2959
2960   assert(SrcTy->isFirstClassType() && DestTy->isFirstClassType() &&
2961          "Only first class types are castable!");
2962
2963   if (SrcTy == DestTy)
2964     return BitCast;
2965
2966   // FIXME: Check address space sizes here
2967   if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy))
2968     if (VectorType *DestVecTy = dyn_cast<VectorType>(DestTy))
2969       if (SrcVecTy->getNumElements() == DestVecTy->getNumElements()) {
2970         // An element by element cast.  Find the appropriate opcode based on the
2971         // element types.
2972         SrcTy = SrcVecTy->getElementType();
2973         DestTy = DestVecTy->getElementType();
2974       }
2975
2976   // Get the bit sizes, we'll need these
2977   unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();   // 0 for ptr
2978   unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr
2979
2980   // Run through the possibilities ...
2981   if (DestTy->isIntegerTy()) {                      // Casting to integral
2982     if (SrcTy->isIntegerTy()) {                     // Casting from integral
2983       if (DestBits < SrcBits)
2984         return Trunc;                               // int -> smaller int
2985       else if (DestBits > SrcBits) {                // its an extension
2986         if (SrcIsSigned)
2987           return SExt;                              // signed -> SEXT
2988         else
2989           return ZExt;                              // unsigned -> ZEXT
2990       } else {
2991         return BitCast;                             // Same size, No-op cast
2992       }
2993     } else if (SrcTy->isFloatingPointTy()) {        // Casting from floating pt
2994       if (DestIsSigned) 
2995         return FPToSI;                              // FP -> sint
2996       else
2997         return FPToUI;                              // FP -> uint 
2998     } else if (SrcTy->isVectorTy()) {
2999       assert(DestBits == SrcBits &&
3000              "Casting vector to integer of different width");
3001       return BitCast;                             // Same size, no-op cast
3002     } else {
3003       assert(SrcTy->isPointerTy() &&
3004              "Casting from a value that is not first-class type");
3005       return PtrToInt;                              // ptr -> int
3006     }
3007   } else if (DestTy->isFloatingPointTy()) {         // Casting to floating pt
3008     if (SrcTy->isIntegerTy()) {                     // Casting from integral
3009       if (SrcIsSigned)
3010         return SIToFP;                              // sint -> FP
3011       else
3012         return UIToFP;                              // uint -> FP
3013     } else if (SrcTy->isFloatingPointTy()) {        // Casting from floating pt
3014       if (DestBits < SrcBits) {
3015         return FPTrunc;                             // FP -> smaller FP
3016       } else if (DestBits > SrcBits) {
3017         return FPExt;                               // FP -> larger FP
3018       } else  {
3019         return BitCast;                             // same size, no-op cast
3020       }
3021     } else if (SrcTy->isVectorTy()) {
3022       assert(DestBits == SrcBits &&
3023              "Casting vector to floating point of different width");
3024       return BitCast;                             // same size, no-op cast
3025     }
3026     llvm_unreachable("Casting pointer or non-first class to float");
3027   } else if (DestTy->isVectorTy()) {
3028     assert(DestBits == SrcBits &&
3029            "Illegal cast to vector (wrong type or size)");
3030     return BitCast;
3031   } else if (DestTy->isPointerTy()) {
3032     if (SrcTy->isPointerTy()) {
3033       if (DestTy->getPointerAddressSpace() != SrcTy->getPointerAddressSpace())
3034         return AddrSpaceCast;
3035       return BitCast;                               // ptr -> ptr
3036     } else if (SrcTy->isIntegerTy()) {
3037       return IntToPtr;                              // int -> ptr
3038     }
3039     llvm_unreachable("Casting pointer to other than pointer or int");
3040   } else if (DestTy->isX86_MMXTy()) {
3041     if (SrcTy->isVectorTy()) {
3042       assert(DestBits == SrcBits && "Casting vector of wrong width to X86_MMX");
3043       return BitCast;                               // 64-bit vector to MMX
3044     }
3045     llvm_unreachable("Illegal cast to X86_MMX");
3046   }
3047   llvm_unreachable("Casting to type that is not first-class");
3048 }
3049
3050 //===----------------------------------------------------------------------===//
3051 //                    CastInst SubClass Constructors
3052 //===----------------------------------------------------------------------===//
3053
3054 /// Check that the construction parameters for a CastInst are correct. This
3055 /// could be broken out into the separate constructors but it is useful to have
3056 /// it in one place and to eliminate the redundant code for getting the sizes
3057 /// of the types involved.
3058 bool 
3059 CastInst::castIsValid(Instruction::CastOps op, Value *S, Type *DstTy) {
3060
3061   // Check for type sanity on the arguments
3062   Type *SrcTy = S->getType();
3063
3064   if (!SrcTy->isFirstClassType() || !DstTy->isFirstClassType() ||
3065       SrcTy->isAggregateType() || DstTy->isAggregateType())
3066     return false;
3067
3068   // Get the size of the types in bits, we'll need this later
3069   unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
3070   unsigned DstBitSize = DstTy->getScalarSizeInBits();
3071
3072   // If these are vector types, get the lengths of the vectors (using zero for
3073   // scalar types means that checking that vector lengths match also checks that
3074   // scalars are not being converted to vectors or vectors to scalars).
3075   unsigned SrcLength = SrcTy->isVectorTy() ?
3076     cast<VectorType>(SrcTy)->getNumElements() : 0;
3077   unsigned DstLength = DstTy->isVectorTy() ?
3078     cast<VectorType>(DstTy)->getNumElements() : 0;
3079
3080   // Switch on the opcode provided
3081   switch (op) {
3082   default: return false; // This is an input error
3083   case Instruction::Trunc:
3084     return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() &&
3085       SrcLength == DstLength && SrcBitSize > DstBitSize;
3086   case Instruction::ZExt:
3087     return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() &&
3088       SrcLength == DstLength && SrcBitSize < DstBitSize;
3089   case Instruction::SExt: 
3090     return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() &&
3091       SrcLength == DstLength && SrcBitSize < DstBitSize;
3092   case Instruction::FPTrunc:
3093     return SrcTy->isFPOrFPVectorTy() && DstTy->isFPOrFPVectorTy() &&
3094       SrcLength == DstLength && SrcBitSize > DstBitSize;
3095   case Instruction::FPExt:
3096     return SrcTy->isFPOrFPVectorTy() && DstTy->isFPOrFPVectorTy() &&
3097       SrcLength == DstLength && SrcBitSize < DstBitSize;
3098   case Instruction::UIToFP:
3099   case Instruction::SIToFP:
3100     return SrcTy->isIntOrIntVectorTy() && DstTy->isFPOrFPVectorTy() &&
3101       SrcLength == DstLength;
3102   case Instruction::FPToUI:
3103   case Instruction::FPToSI:
3104     return SrcTy->isFPOrFPVectorTy() && DstTy->isIntOrIntVectorTy() &&
3105       SrcLength == DstLength;
3106   case Instruction::PtrToInt:
3107     if (isa<VectorType>(SrcTy) != isa<VectorType>(DstTy))
3108       return false;
3109     if (VectorType *VT = dyn_cast<VectorType>(SrcTy))
3110       if (VT->getNumElements() != cast<VectorType>(DstTy)->getNumElements())
3111         return false;
3112     return SrcTy->getScalarType()->isPointerTy() &&
3113            DstTy->getScalarType()->isIntegerTy();
3114   case Instruction::IntToPtr:
3115     if (isa<VectorType>(SrcTy) != isa<VectorType>(DstTy))
3116       return false;
3117     if (VectorType *VT = dyn_cast<VectorType>(SrcTy))
3118       if (VT->getNumElements() != cast<VectorType>(DstTy)->getNumElements())
3119         return false;
3120     return SrcTy->getScalarType()->isIntegerTy() &&
3121            DstTy->getScalarType()->isPointerTy();
3122   case Instruction::BitCast: {
3123     PointerType *SrcPtrTy = dyn_cast<PointerType>(SrcTy->getScalarType());
3124     PointerType *DstPtrTy = dyn_cast<PointerType>(DstTy->getScalarType());
3125
3126     // BitCast implies a no-op cast of type only. No bits change.
3127     // However, you can't cast pointers to anything but pointers.
3128     if (!SrcPtrTy != !DstPtrTy)
3129       return false;
3130
3131     // For non-pointer cases, the cast is okay if the source and destination bit
3132     // widths are identical.
3133     if (!SrcPtrTy)
3134       return SrcTy->getPrimitiveSizeInBits() == DstTy->getPrimitiveSizeInBits();
3135
3136     // If both are pointers then the address spaces must match.
3137     if (SrcPtrTy->getAddressSpace() != DstPtrTy->getAddressSpace())
3138       return false;
3139
3140     // A vector of pointers must have the same number of elements.
3141     if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy)) {
3142       if (VectorType *DstVecTy = dyn_cast<VectorType>(DstTy))
3143         return (SrcVecTy->getNumElements() == DstVecTy->getNumElements());
3144
3145       return false;
3146     }
3147
3148     return true;
3149   }
3150   case Instruction::AddrSpaceCast: {
3151     PointerType *SrcPtrTy = dyn_cast<PointerType>(SrcTy->getScalarType());
3152     if (!SrcPtrTy)
3153       return false;
3154
3155     PointerType *DstPtrTy = dyn_cast<PointerType>(DstTy->getScalarType());
3156     if (!DstPtrTy)
3157       return false;
3158
3159     if (SrcPtrTy->getAddressSpace() == DstPtrTy->getAddressSpace())
3160       return false;
3161
3162     if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy)) {
3163       if (VectorType *DstVecTy = dyn_cast<VectorType>(DstTy))
3164         return (SrcVecTy->getNumElements() == DstVecTy->getNumElements());
3165
3166       return false;
3167     }
3168
3169     return true;
3170   }
3171   }
3172 }
3173
3174 TruncInst::TruncInst(
3175   Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3176 ) : CastInst(Ty, Trunc, S, Name, InsertBefore) {
3177   assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
3178 }
3179
3180 TruncInst::TruncInst(
3181   Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3182 ) : CastInst(Ty, Trunc, S, Name, InsertAtEnd) { 
3183   assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
3184 }
3185
3186 ZExtInst::ZExtInst(
3187   Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3188 )  : CastInst(Ty, ZExt, S, Name, InsertBefore) { 
3189   assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
3190 }
3191
3192 ZExtInst::ZExtInst(
3193   Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3194 )  : CastInst(Ty, ZExt, S, Name, InsertAtEnd) { 
3195   assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
3196 }
3197 SExtInst::SExtInst(
3198   Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3199 ) : CastInst(Ty, SExt, S, Name, InsertBefore) { 
3200   assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
3201 }
3202
3203 SExtInst::SExtInst(
3204   Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3205 )  : CastInst(Ty, SExt, S, Name, InsertAtEnd) { 
3206   assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
3207 }
3208
3209 FPTruncInst::FPTruncInst(
3210   Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3211 ) : CastInst(Ty, FPTrunc, S, Name, InsertBefore) { 
3212   assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
3213 }
3214
3215 FPTruncInst::FPTruncInst(
3216   Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3217 ) : CastInst(Ty, FPTrunc, S, Name, InsertAtEnd) { 
3218   assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
3219 }
3220
3221 FPExtInst::FPExtInst(
3222   Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3223 ) : CastInst(Ty, FPExt, S, Name, InsertBefore) { 
3224   assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
3225 }
3226
3227 FPExtInst::FPExtInst(
3228   Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3229 ) : CastInst(Ty, FPExt, S, Name, InsertAtEnd) { 
3230   assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
3231 }
3232
3233 UIToFPInst::UIToFPInst(
3234   Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3235 ) : CastInst(Ty, UIToFP, S, Name, InsertBefore) { 
3236   assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
3237 }
3238
3239 UIToFPInst::UIToFPInst(
3240   Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3241 ) : CastInst(Ty, UIToFP, S, Name, InsertAtEnd) { 
3242   assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
3243 }
3244
3245 SIToFPInst::SIToFPInst(
3246   Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3247 ) : CastInst(Ty, SIToFP, S, Name, InsertBefore) { 
3248   assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
3249 }
3250
3251 SIToFPInst::SIToFPInst(
3252   Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3253 ) : CastInst(Ty, SIToFP, S, Name, InsertAtEnd) { 
3254   assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
3255 }
3256
3257 FPToUIInst::FPToUIInst(
3258   Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3259 ) : CastInst(Ty, FPToUI, S, Name, InsertBefore) { 
3260   assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
3261 }
3262
3263 FPToUIInst::FPToUIInst(
3264   Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3265 ) : CastInst(Ty, FPToUI, S, Name, InsertAtEnd) { 
3266   assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
3267 }
3268
3269 FPToSIInst::FPToSIInst(
3270   Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3271 ) : CastInst(Ty, FPToSI, S, Name, InsertBefore) { 
3272   assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
3273 }
3274
3275 FPToSIInst::FPToSIInst(
3276   Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3277 ) : CastInst(Ty, FPToSI, S, Name, InsertAtEnd) { 
3278   assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
3279 }
3280
3281 PtrToIntInst::PtrToIntInst(
3282   Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3283 ) : CastInst(Ty, PtrToInt, S, Name, InsertBefore) { 
3284   assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
3285 }
3286
3287 PtrToIntInst::PtrToIntInst(
3288   Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3289 ) : CastInst(Ty, PtrToInt, S, Name, InsertAtEnd) { 
3290   assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
3291 }
3292
3293 IntToPtrInst::IntToPtrInst(
3294   Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3295 ) : CastInst(Ty, IntToPtr, S, Name, InsertBefore) { 
3296   assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
3297 }
3298
3299 IntToPtrInst::IntToPtrInst(
3300   Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3301 ) : CastInst(Ty, IntToPtr, S, Name, InsertAtEnd) { 
3302   assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
3303 }
3304
3305 BitCastInst::BitCastInst(
3306   Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3307 ) : CastInst(Ty, BitCast, S, Name, InsertBefore) { 
3308   assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
3309 }
3310
3311 BitCastInst::BitCastInst(
3312   Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3313 ) : CastInst(Ty, BitCast, S, Name, InsertAtEnd) { 
3314   assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
3315 }
3316
3317 AddrSpaceCastInst::AddrSpaceCastInst(
3318   Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3319 ) : CastInst(Ty, AddrSpaceCast, S, Name, InsertBefore) {
3320   assert(castIsValid(getOpcode(), S, Ty) && "Illegal AddrSpaceCast");
3321 }
3322
3323 AddrSpaceCastInst::AddrSpaceCastInst(
3324   Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3325 ) : CastInst(Ty, AddrSpaceCast, S, Name, InsertAtEnd) {
3326   assert(castIsValid(getOpcode(), S, Ty) && "Illegal AddrSpaceCast");
3327 }
3328
3329 //===----------------------------------------------------------------------===//
3330 //                               CmpInst Classes
3331 //===----------------------------------------------------------------------===//
3332
3333 void CmpInst::anchor() {}
3334
3335 CmpInst::CmpInst(Type *ty, OtherOps op, unsigned short predicate,
3336                  Value *LHS, Value *RHS, const Twine &Name,
3337                  Instruction *InsertBefore)
3338   : Instruction(ty, op,
3339                 OperandTraits<CmpInst>::op_begin(this),
3340                 OperandTraits<CmpInst>::operands(this),
3341                 InsertBefore) {
3342     Op<0>() = LHS;
3343     Op<1>() = RHS;
3344   setPredicate((Predicate)predicate);
3345   setName(Name);
3346 }
3347
3348 CmpInst::CmpInst(Type *ty, OtherOps op, unsigned short predicate,
3349                  Value *LHS, Value *RHS, const Twine &Name,
3350                  BasicBlock *InsertAtEnd)
3351   : Instruction(ty, op,
3352                 OperandTraits<CmpInst>::op_begin(this),
3353                 OperandTraits<CmpInst>::operands(this),
3354                 InsertAtEnd) {
3355   Op<0>() = LHS;
3356   Op<1>() = RHS;
3357   setPredicate((Predicate)predicate);
3358   setName(Name);
3359 }
3360
3361 CmpInst *
3362 CmpInst::Create(OtherOps Op, unsigned short predicate,
3363                 Value *S1, Value *S2, 
3364                 const Twine &Name, Instruction *InsertBefore) {
3365   if (Op == Instruction::ICmp) {
3366     if (InsertBefore)
3367       return new ICmpInst(InsertBefore, CmpInst::Predicate(predicate),
3368                           S1, S2, Name);
3369     else
3370       return new ICmpInst(CmpInst::Predicate(predicate),
3371                           S1, S2, Name);
3372   }
3373   
3374   if (InsertBefore)
3375     return new FCmpInst(InsertBefore, CmpInst::Predicate(predicate),
3376                         S1, S2, Name);
3377   else
3378     return new FCmpInst(CmpInst::Predicate(predicate),
3379                         S1, S2, Name);
3380 }
3381
3382 CmpInst *
3383 CmpInst::Create(OtherOps Op, unsigned short predicate, Value *S1, Value *S2, 
3384                 const Twine &Name, BasicBlock *InsertAtEnd) {
3385   if (Op == Instruction::ICmp) {
3386     return new ICmpInst(*InsertAtEnd, CmpInst::Predicate(predicate),
3387                         S1, S2, Name);
3388   }
3389   return new FCmpInst(*InsertAtEnd, CmpInst::Predicate(predicate),
3390                       S1, S2, Name);
3391 }
3392
3393 void CmpInst::swapOperands() {
3394   if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
3395     IC->swapOperands();
3396   else
3397     cast<FCmpInst>(this)->swapOperands();
3398 }
3399
3400 bool CmpInst::isCommutative() const {
3401   if (const ICmpInst *IC = dyn_cast<ICmpInst>(this))
3402     return IC->isCommutative();
3403   return cast<FCmpInst>(this)->isCommutative();
3404 }
3405
3406 bool CmpInst::isEquality() const {
3407   if (const ICmpInst *IC = dyn_cast<ICmpInst>(this))
3408     return IC->isEquality();
3409   return cast<FCmpInst>(this)->isEquality();
3410 }
3411
3412
3413 CmpInst::Predicate CmpInst::getInversePredicate(Predicate pred) {
3414   switch (pred) {
3415     default: llvm_unreachable("Unknown cmp predicate!");
3416     case ICMP_EQ: return ICMP_NE;
3417     case ICMP_NE: return ICMP_EQ;
3418     case ICMP_UGT: return ICMP_ULE;
3419     case ICMP_ULT: return ICMP_UGE;
3420     case ICMP_UGE: return ICMP_ULT;
3421     case ICMP_ULE: return ICMP_UGT;
3422     case ICMP_SGT: return ICMP_SLE;
3423     case ICMP_SLT: return ICMP_SGE;
3424     case ICMP_SGE: return ICMP_SLT;
3425     case ICMP_SLE: return ICMP_SGT;
3426
3427     case FCMP_OEQ: return FCMP_UNE;
3428     case FCMP_ONE: return FCMP_UEQ;
3429     case FCMP_OGT: return FCMP_ULE;
3430     case FCMP_OLT: return FCMP_UGE;
3431     case FCMP_OGE: return FCMP_ULT;
3432     case FCMP_OLE: return FCMP_UGT;
3433     case FCMP_UEQ: return FCMP_ONE;
3434     case FCMP_UNE: return FCMP_OEQ;
3435     case FCMP_UGT: return FCMP_OLE;
3436     case FCMP_ULT: return FCMP_OGE;
3437     case FCMP_UGE: return FCMP_OLT;
3438     case FCMP_ULE: return FCMP_OGT;
3439     case FCMP_ORD: return FCMP_UNO;
3440     case FCMP_UNO: return FCMP_ORD;
3441     case FCMP_TRUE: return FCMP_FALSE;
3442     case FCMP_FALSE: return FCMP_TRUE;
3443   }
3444 }
3445
3446 ICmpInst::Predicate ICmpInst::getSignedPredicate(Predicate pred) {
3447   switch (pred) {
3448     default: llvm_unreachable("Unknown icmp predicate!");
3449     case ICMP_EQ: case ICMP_NE: 
3450     case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE: 
3451        return pred;
3452     case ICMP_UGT: return ICMP_SGT;
3453     case ICMP_ULT: return ICMP_SLT;
3454     case ICMP_UGE: return ICMP_SGE;
3455     case ICMP_ULE: return ICMP_SLE;
3456   }
3457 }
3458
3459 ICmpInst::Predicate ICmpInst::getUnsignedPredicate(Predicate pred) {
3460   switch (pred) {
3461     default: llvm_unreachable("Unknown icmp predicate!");
3462     case ICMP_EQ: case ICMP_NE: 
3463     case ICMP_UGT: case ICMP_ULT: case ICMP_UGE: case ICMP_ULE: 
3464        return pred;
3465     case ICMP_SGT: return ICMP_UGT;
3466     case ICMP_SLT: return ICMP_ULT;
3467     case ICMP_SGE: return ICMP_UGE;
3468     case ICMP_SLE: return ICMP_ULE;
3469   }
3470 }
3471
3472 /// Initialize a set of values that all satisfy the condition with C.
3473 ///
3474 ConstantRange 
3475 ICmpInst::makeConstantRange(Predicate pred, const APInt &C) {
3476   APInt Lower(C);
3477   APInt Upper(C);
3478   uint32_t BitWidth = C.getBitWidth();
3479   switch (pred) {
3480   default: llvm_unreachable("Invalid ICmp opcode to ConstantRange ctor!");
3481   case ICmpInst::ICMP_EQ: ++Upper; break;
3482   case ICmpInst::ICMP_NE: ++Lower; break;
3483   case ICmpInst::ICMP_ULT:
3484     Lower = APInt::getMinValue(BitWidth);
3485     // Check for an empty-set condition.
3486     if (Lower == Upper)
3487       return ConstantRange(BitWidth, /*isFullSet=*/false);
3488     break;
3489   case ICmpInst::ICMP_SLT:
3490     Lower = APInt::getSignedMinValue(BitWidth);
3491     // Check for an empty-set condition.
3492     if (Lower == Upper)
3493       return ConstantRange(BitWidth, /*isFullSet=*/false);
3494     break;
3495   case ICmpInst::ICMP_UGT: 
3496     ++Lower; Upper = APInt::getMinValue(BitWidth);        // Min = Next(Max)
3497     // Check for an empty-set condition.
3498     if (Lower == Upper)
3499       return ConstantRange(BitWidth, /*isFullSet=*/false);
3500     break;
3501   case ICmpInst::ICMP_SGT:
3502     ++Lower; Upper = APInt::getSignedMinValue(BitWidth);  // Min = Next(Max)
3503     // Check for an empty-set condition.
3504     if (Lower == Upper)
3505       return ConstantRange(BitWidth, /*isFullSet=*/false);
3506     break;
3507   case ICmpInst::ICMP_ULE: 
3508     Lower = APInt::getMinValue(BitWidth); ++Upper; 
3509     // Check for a full-set condition.
3510     if (Lower == Upper)
3511       return ConstantRange(BitWidth, /*isFullSet=*/true);
3512     break;
3513   case ICmpInst::ICMP_SLE: 
3514     Lower = APInt::getSignedMinValue(BitWidth); ++Upper; 
3515     // Check for a full-set condition.
3516     if (Lower == Upper)
3517       return ConstantRange(BitWidth, /*isFullSet=*/true);
3518     break;
3519   case ICmpInst::ICMP_UGE:
3520     Upper = APInt::getMinValue(BitWidth);        // Min = Next(Max)
3521     // Check for a full-set condition.
3522     if (Lower == Upper)
3523       return ConstantRange(BitWidth, /*isFullSet=*/true);
3524     break;
3525   case ICmpInst::ICMP_SGE:
3526     Upper = APInt::getSignedMinValue(BitWidth);  // Min = Next(Max)
3527     // Check for a full-set condition.
3528     if (Lower == Upper)
3529       return ConstantRange(BitWidth, /*isFullSet=*/true);
3530     break;
3531   }
3532   return ConstantRange(Lower, Upper);
3533 }
3534
3535 CmpInst::Predicate CmpInst::getSwappedPredicate(Predicate pred) {
3536   switch (pred) {
3537     default: llvm_unreachable("Unknown cmp predicate!");
3538     case ICMP_EQ: case ICMP_NE:
3539       return pred;
3540     case ICMP_SGT: return ICMP_SLT;
3541     case ICMP_SLT: return ICMP_SGT;
3542     case ICMP_SGE: return ICMP_SLE;
3543     case ICMP_SLE: return ICMP_SGE;
3544     case ICMP_UGT: return ICMP_ULT;
3545     case ICMP_ULT: return ICMP_UGT;
3546     case ICMP_UGE: return ICMP_ULE;
3547     case ICMP_ULE: return ICMP_UGE;
3548   
3549     case FCMP_FALSE: case FCMP_TRUE:
3550     case FCMP_OEQ: case FCMP_ONE:
3551     case FCMP_UEQ: case FCMP_UNE:
3552     case FCMP_ORD: case FCMP_UNO:
3553       return pred;
3554     case FCMP_OGT: return FCMP_OLT;
3555     case FCMP_OLT: return FCMP_OGT;
3556     case FCMP_OGE: return FCMP_OLE;
3557     case FCMP_OLE: return FCMP_OGE;
3558     case FCMP_UGT: return FCMP_ULT;
3559     case FCMP_ULT: return FCMP_UGT;
3560     case FCMP_UGE: return FCMP_ULE;
3561     case FCMP_ULE: return FCMP_UGE;
3562   }
3563 }
3564
3565 CmpInst::Predicate CmpInst::getSignedPredicate(Predicate pred) {
3566   assert(CmpInst::isUnsigned(pred) && "Call only with signed predicates!");
3567
3568   switch (pred) {
3569   default:
3570     llvm_unreachable("Unknown predicate!");
3571   case CmpInst::ICMP_ULT:
3572     return CmpInst::ICMP_SLT;
3573   case CmpInst::ICMP_ULE:
3574     return CmpInst::ICMP_SLE;
3575   case CmpInst::ICMP_UGT:
3576     return CmpInst::ICMP_SGT;
3577   case CmpInst::ICMP_UGE:
3578     return CmpInst::ICMP_SGE;
3579   }
3580 }
3581
3582 bool CmpInst::isUnsigned(unsigned short predicate) {
3583   switch (predicate) {
3584     default: return false;
3585     case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE: case ICmpInst::ICMP_UGT: 
3586     case ICmpInst::ICMP_UGE: return true;
3587   }
3588 }
3589
3590 bool CmpInst::isSigned(unsigned short predicate) {
3591   switch (predicate) {
3592     default: return false;
3593     case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_SLE: case ICmpInst::ICMP_SGT: 
3594     case ICmpInst::ICMP_SGE: return true;
3595   }
3596 }
3597
3598 bool CmpInst::isOrdered(unsigned short predicate) {
3599   switch (predicate) {
3600     default: return false;
3601     case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_OGT: 
3602     case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLE: 
3603     case FCmpInst::FCMP_ORD: return true;
3604   }
3605 }
3606       
3607 bool CmpInst::isUnordered(unsigned short predicate) {
3608   switch (predicate) {
3609     default: return false;
3610     case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UNE: case FCmpInst::FCMP_UGT: 
3611     case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_UGE: case FCmpInst::FCMP_ULE: 
3612     case FCmpInst::FCMP_UNO: return true;
3613   }
3614 }
3615
3616 bool CmpInst::isTrueWhenEqual(unsigned short predicate) {
3617   switch(predicate) {
3618     default: return false;
3619     case ICMP_EQ:   case ICMP_UGE: case ICMP_ULE: case ICMP_SGE: case ICMP_SLE:
3620     case FCMP_TRUE: case FCMP_UEQ: case FCMP_UGE: case FCMP_ULE: return true;
3621   }
3622 }
3623
3624 bool CmpInst::isFalseWhenEqual(unsigned short predicate) {
3625   switch(predicate) {
3626   case ICMP_NE:    case ICMP_UGT: case ICMP_ULT: case ICMP_SGT: case ICMP_SLT:
3627   case FCMP_FALSE: case FCMP_ONE: case FCMP_OGT: case FCMP_OLT: return true;
3628   default: return false;
3629   }
3630 }
3631
3632
3633 //===----------------------------------------------------------------------===//
3634 //                        SwitchInst Implementation
3635 //===----------------------------------------------------------------------===//
3636
3637 void SwitchInst::init(Value *Value, BasicBlock *Default, unsigned NumReserved) {
3638   assert(Value && Default && NumReserved);
3639   ReservedSpace = NumReserved;
3640   setNumHungOffUseOperands(2);
3641   allocHungoffUses(ReservedSpace);
3642
3643   Op<0>() = Value;
3644   Op<1>() = Default;
3645 }
3646
3647 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
3648 /// switch on and a default destination.  The number of additional cases can
3649 /// be specified here to make memory allocation more efficient.  This
3650 /// constructor can also autoinsert before another instruction.
3651 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
3652                        Instruction *InsertBefore)
3653   : TerminatorInst(Type::getVoidTy(Value->getContext()), Instruction::Switch,
3654                    nullptr, 0, InsertBefore) {
3655   init(Value, Default, 2+NumCases*2);
3656 }
3657
3658 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
3659 /// switch on and a default destination.  The number of additional cases can
3660 /// be specified here to make memory allocation more efficient.  This
3661 /// constructor also autoinserts at the end of the specified BasicBlock.
3662 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
3663                        BasicBlock *InsertAtEnd)
3664   : TerminatorInst(Type::getVoidTy(Value->getContext()), Instruction::Switch,
3665                    nullptr, 0, InsertAtEnd) {
3666   init(Value, Default, 2+NumCases*2);
3667 }
3668
3669 SwitchInst::SwitchInst(const SwitchInst &SI)
3670   : TerminatorInst(SI.getType(), Instruction::Switch, nullptr, 0) {
3671   init(SI.getCondition(), SI.getDefaultDest(), SI.getNumOperands());
3672   setNumHungOffUseOperands(SI.getNumOperands());
3673   Use *OL = getOperandList();
3674   const Use *InOL = SI.getOperandList();
3675   for (unsigned i = 2, E = SI.getNumOperands(); i != E; i += 2) {
3676     OL[i] = InOL[i];
3677     OL[i+1] = InOL[i+1];
3678   }
3679   SubclassOptionalData = SI.SubclassOptionalData;
3680 }
3681
3682
3683 /// addCase - Add an entry to the switch instruction...
3684 ///
3685 void SwitchInst::addCase(ConstantInt *OnVal, BasicBlock *Dest) {
3686   unsigned NewCaseIdx = getNumCases();
3687   unsigned OpNo = getNumOperands();
3688   if (OpNo+2 > ReservedSpace)
3689     growOperands();  // Get more space!
3690   // Initialize some new operands.
3691   assert(OpNo+1 < ReservedSpace && "Growing didn't work!");
3692   setNumHungOffUseOperands(OpNo+2);
3693   CaseIt Case(this, NewCaseIdx);
3694   Case.setValue(OnVal);
3695   Case.setSuccessor(Dest);
3696 }
3697
3698 /// removeCase - This method removes the specified case and its successor
3699 /// from the switch instruction.
3700 void SwitchInst::removeCase(CaseIt i) {
3701   unsigned idx = i.getCaseIndex();
3702   
3703   assert(2 + idx*2 < getNumOperands() && "Case index out of range!!!");
3704
3705   unsigned NumOps = getNumOperands();
3706   Use *OL = getOperandList();
3707
3708   // Overwrite this case with the end of the list.
3709   if (2 + (idx + 1) * 2 != NumOps) {
3710     OL[2 + idx * 2] = OL[NumOps - 2];
3711     OL[2 + idx * 2 + 1] = OL[NumOps - 1];
3712   }
3713
3714   // Nuke the last value.
3715   OL[NumOps-2].set(nullptr);
3716   OL[NumOps-2+1].set(nullptr);
3717   setNumHungOffUseOperands(NumOps-2);
3718 }
3719
3720 /// growOperands - grow operands - This grows the operand list in response
3721 /// to a push_back style of operation.  This grows the number of ops by 3 times.
3722 ///
3723 void SwitchInst::growOperands() {
3724   unsigned e = getNumOperands();
3725   unsigned NumOps = e*3;
3726
3727   ReservedSpace = NumOps;
3728   growHungoffUses(ReservedSpace);
3729 }
3730
3731
3732 BasicBlock *SwitchInst::getSuccessorV(unsigned idx) const {
3733   return getSuccessor(idx);
3734 }
3735 unsigned SwitchInst::getNumSuccessorsV() const {
3736   return getNumSuccessors();
3737 }
3738 void SwitchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
3739   setSuccessor(idx, B);
3740 }
3741
3742 //===----------------------------------------------------------------------===//
3743 //                        IndirectBrInst Implementation
3744 //===----------------------------------------------------------------------===//
3745
3746 void IndirectBrInst::init(Value *Address, unsigned NumDests) {
3747   assert(Address && Address->getType()->isPointerTy() &&
3748          "Address of indirectbr must be a pointer");
3749   ReservedSpace = 1+NumDests;
3750   setNumHungOffUseOperands(1);
3751   allocHungoffUses(ReservedSpace);
3752
3753   Op<0>() = Address;
3754 }
3755
3756
3757 /// growOperands - grow operands - This grows the operand list in response
3758 /// to a push_back style of operation.  This grows the number of ops by 2 times.
3759 ///
3760 void IndirectBrInst::growOperands() {
3761   unsigned e = getNumOperands();
3762   unsigned NumOps = e*2;
3763   
3764   ReservedSpace = NumOps;
3765   growHungoffUses(ReservedSpace);
3766 }
3767
3768 IndirectBrInst::IndirectBrInst(Value *Address, unsigned NumCases,
3769                                Instruction *InsertBefore)
3770 : TerminatorInst(Type::getVoidTy(Address->getContext()),Instruction::IndirectBr,
3771                  nullptr, 0, InsertBefore) {
3772   init(Address, NumCases);
3773 }
3774
3775 IndirectBrInst::IndirectBrInst(Value *Address, unsigned NumCases,
3776                                BasicBlock *InsertAtEnd)
3777 : TerminatorInst(Type::getVoidTy(Address->getContext()),Instruction::IndirectBr,
3778                  nullptr, 0, InsertAtEnd) {
3779   init(Address, NumCases);
3780 }
3781
3782 IndirectBrInst::IndirectBrInst(const IndirectBrInst &IBI)
3783     : TerminatorInst(Type::getVoidTy(IBI.getContext()), Instruction::IndirectBr,
3784                      nullptr, IBI.getNumOperands()) {
3785   allocHungoffUses(IBI.getNumOperands());
3786   Use *OL = getOperandList();
3787   const Use *InOL = IBI.getOperandList();
3788   for (unsigned i = 0, E = IBI.getNumOperands(); i != E; ++i)
3789     OL[i] = InOL[i];
3790   SubclassOptionalData = IBI.SubclassOptionalData;
3791 }
3792
3793 /// addDestination - Add a destination.
3794 ///
3795 void IndirectBrInst::addDestination(BasicBlock *DestBB) {
3796   unsigned OpNo = getNumOperands();
3797   if (OpNo+1 > ReservedSpace)
3798     growOperands();  // Get more space!
3799   // Initialize some new operands.
3800   assert(OpNo < ReservedSpace && "Growing didn't work!");
3801   setNumHungOffUseOperands(OpNo+1);
3802   getOperandList()[OpNo] = DestBB;
3803 }
3804
3805 /// removeDestination - This method removes the specified successor from the
3806 /// indirectbr instruction.
3807 void IndirectBrInst::removeDestination(unsigned idx) {
3808   assert(idx < getNumOperands()-1 && "Successor index out of range!");
3809   
3810   unsigned NumOps = getNumOperands();
3811   Use *OL = getOperandList();
3812
3813   // Replace this value with the last one.
3814   OL[idx+1] = OL[NumOps-1];
3815   
3816   // Nuke the last value.
3817   OL[NumOps-1].set(nullptr);
3818   setNumHungOffUseOperands(NumOps-1);
3819 }
3820
3821 BasicBlock *IndirectBrInst::getSuccessorV(unsigned idx) const {
3822   return getSuccessor(idx);
3823 }
3824 unsigned IndirectBrInst::getNumSuccessorsV() const {
3825   return getNumSuccessors();
3826 }
3827 void IndirectBrInst::setSuccessorV(unsigned idx, BasicBlock *B) {
3828   setSuccessor(idx, B);
3829 }
3830
3831 //===----------------------------------------------------------------------===//
3832 //                           cloneImpl() implementations
3833 //===----------------------------------------------------------------------===//
3834
3835 // Define these methods here so vtables don't get emitted into every translation
3836 // unit that uses these classes.
3837
3838 GetElementPtrInst *GetElementPtrInst::cloneImpl() const {
3839   return new (getNumOperands()) GetElementPtrInst(*this);
3840 }
3841
3842 BinaryOperator *BinaryOperator::cloneImpl() const {
3843   return Create(getOpcode(), Op<0>(), Op<1>());
3844 }
3845
3846 FCmpInst *FCmpInst::cloneImpl() const {
3847   return new FCmpInst(getPredicate(), Op<0>(), Op<1>());
3848 }
3849
3850 ICmpInst *ICmpInst::cloneImpl() const {
3851   return new ICmpInst(getPredicate(), Op<0>(), Op<1>());
3852 }
3853
3854 ExtractValueInst *ExtractValueInst::cloneImpl() const {
3855   return new ExtractValueInst(*this);
3856 }
3857
3858 InsertValueInst *InsertValueInst::cloneImpl() const {
3859   return new InsertValueInst(*this);
3860 }
3861
3862 AllocaInst *AllocaInst::cloneImpl() const {
3863   AllocaInst *Result = new AllocaInst(getAllocatedType(),
3864                                       (Value *)getOperand(0), getAlignment());
3865   Result->setUsedWithInAlloca(isUsedWithInAlloca());
3866   return Result;
3867 }
3868
3869 LoadInst *LoadInst::cloneImpl() const {
3870   return new LoadInst(getOperand(0), Twine(), isVolatile(),
3871                       getAlignment(), getOrdering(), getSynchScope());
3872 }
3873
3874 StoreInst *StoreInst::cloneImpl() const {
3875   return new StoreInst(getOperand(0), getOperand(1), isVolatile(),
3876                        getAlignment(), getOrdering(), getSynchScope());
3877   
3878 }
3879
3880 AtomicCmpXchgInst *AtomicCmpXchgInst::cloneImpl() const {
3881   AtomicCmpXchgInst *Result =
3882     new AtomicCmpXchgInst(getOperand(0), getOperand(1), getOperand(2),
3883                           getSuccessOrdering(), getFailureOrdering(),
3884                           getSynchScope());
3885   Result->setVolatile(isVolatile());
3886   Result->setWeak(isWeak());
3887   return Result;
3888 }
3889
3890 AtomicRMWInst *AtomicRMWInst::cloneImpl() const {
3891   AtomicRMWInst *Result =
3892     new AtomicRMWInst(getOperation(),getOperand(0), getOperand(1),
3893                       getOrdering(), getSynchScope());
3894   Result->setVolatile(isVolatile());
3895   return Result;
3896 }
3897
3898 FenceInst *FenceInst::cloneImpl() const {
3899   return new FenceInst(getContext(), getOrdering(), getSynchScope());
3900 }
3901
3902 TruncInst *TruncInst::cloneImpl() const {
3903   return new TruncInst(getOperand(0), getType());
3904 }
3905
3906 ZExtInst *ZExtInst::cloneImpl() const {
3907   return new ZExtInst(getOperand(0), getType());
3908 }
3909
3910 SExtInst *SExtInst::cloneImpl() const {
3911   return new SExtInst(getOperand(0), getType());
3912 }
3913
3914 FPTruncInst *FPTruncInst::cloneImpl() const {
3915   return new FPTruncInst(getOperand(0), getType());
3916 }
3917
3918 FPExtInst *FPExtInst::cloneImpl() const {
3919   return new FPExtInst(getOperand(0), getType());
3920 }
3921
3922 UIToFPInst *UIToFPInst::cloneImpl() const {
3923   return new UIToFPInst(getOperand(0), getType());
3924 }
3925
3926 SIToFPInst *SIToFPInst::cloneImpl() const {
3927   return new SIToFPInst(getOperand(0), getType());
3928 }
3929
3930 FPToUIInst *FPToUIInst::cloneImpl() const {
3931   return new FPToUIInst(getOperand(0), getType());
3932 }
3933
3934 FPToSIInst *FPToSIInst::cloneImpl() const {
3935   return new FPToSIInst(getOperand(0), getType());
3936 }
3937
3938 PtrToIntInst *PtrToIntInst::cloneImpl() const {
3939   return new PtrToIntInst(getOperand(0), getType());
3940 }
3941
3942 IntToPtrInst *IntToPtrInst::cloneImpl() const {
3943   return new IntToPtrInst(getOperand(0), getType());
3944 }
3945
3946 BitCastInst *BitCastInst::cloneImpl() const {
3947   return new BitCastInst(getOperand(0), getType());
3948 }
3949
3950 AddrSpaceCastInst *AddrSpaceCastInst::cloneImpl() const {
3951   return new AddrSpaceCastInst(getOperand(0), getType());
3952 }
3953
3954 CallInst *CallInst::cloneImpl() const {
3955   return  new(getNumOperands()) CallInst(*this);
3956 }
3957
3958 SelectInst *SelectInst::cloneImpl() const {
3959   return SelectInst::Create(getOperand(0), getOperand(1), getOperand(2));
3960 }
3961
3962 VAArgInst *VAArgInst::cloneImpl() const {
3963   return new VAArgInst(getOperand(0), getType());
3964 }
3965
3966 ExtractElementInst *ExtractElementInst::cloneImpl() const {
3967   return ExtractElementInst::Create(getOperand(0), getOperand(1));
3968 }
3969
3970 InsertElementInst *InsertElementInst::cloneImpl() const {
3971   return InsertElementInst::Create(getOperand(0), getOperand(1), getOperand(2));
3972 }
3973
3974 ShuffleVectorInst *ShuffleVectorInst::cloneImpl() const {
3975   return new ShuffleVectorInst(getOperand(0), getOperand(1), getOperand(2));
3976 }
3977
3978 PHINode *PHINode::cloneImpl() const { return new PHINode(*this); }
3979
3980 LandingPadInst *LandingPadInst::cloneImpl() const {
3981   return new LandingPadInst(*this);
3982 }
3983
3984 ReturnInst *ReturnInst::cloneImpl() const {
3985   return new(getNumOperands()) ReturnInst(*this);
3986 }
3987
3988 BranchInst *BranchInst::cloneImpl() const {
3989   return new(getNumOperands()) BranchInst(*this);
3990 }
3991
3992 SwitchInst *SwitchInst::cloneImpl() const { return new SwitchInst(*this); }
3993
3994 IndirectBrInst *IndirectBrInst::cloneImpl() const {
3995   return new IndirectBrInst(*this);
3996 }
3997
3998 InvokeInst *InvokeInst::cloneImpl() const {
3999   return new(getNumOperands()) InvokeInst(*this);
4000 }
4001
4002 ResumeInst *ResumeInst::cloneImpl() const { return new (1) ResumeInst(*this); }
4003
4004 CleanupEndPadInst *CleanupEndPadInst::cloneImpl() const {
4005   return new (getNumOperands()) CleanupEndPadInst(*this);
4006 }
4007
4008 CleanupReturnInst *CleanupReturnInst::cloneImpl() const {
4009   return new (getNumOperands()) CleanupReturnInst(*this);
4010 }
4011
4012 CatchEndPadInst *CatchEndPadInst::cloneImpl() const {
4013   return new (getNumOperands()) CatchEndPadInst(*this);
4014 }
4015
4016 CatchReturnInst *CatchReturnInst::cloneImpl() const {
4017   return new (getNumOperands()) CatchReturnInst(*this);
4018 }
4019
4020 CatchPadInst *CatchPadInst::cloneImpl() const {
4021   return new (getNumOperands()) CatchPadInst(*this);
4022 }
4023
4024 TerminatePadInst *TerminatePadInst::cloneImpl() const {
4025   return new (getNumOperands()) TerminatePadInst(*this);
4026 }
4027
4028 CleanupPadInst *CleanupPadInst::cloneImpl() const {
4029   return new (getNumOperands()) CleanupPadInst(*this);
4030 }
4031
4032 UnreachableInst *UnreachableInst::cloneImpl() const {
4033   LLVMContext &Context = getContext();
4034   return new UnreachableInst(Context);
4035 }