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