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