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