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