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