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