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