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