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