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