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