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