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