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