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