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