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