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