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