1 //===-- TargetLowering.cpp - Implement the TargetLowering class -----------===//
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 implements the TargetLowering class.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm/CodeGen/TargetLowering.h"
14 #include "llvm/ADT/STLExtras.h"
15 #include "llvm/CodeGen/CallingConvLower.h"
16 #include "llvm/CodeGen/CodeGenCommonISel.h"
17 #include "llvm/CodeGen/MachineFrameInfo.h"
18 #include "llvm/CodeGen/MachineFunction.h"
19 #include "llvm/CodeGen/MachineJumpTableInfo.h"
20 #include "llvm/CodeGen/MachineRegisterInfo.h"
21 #include "llvm/CodeGen/SelectionDAG.h"
22 #include "llvm/CodeGen/TargetRegisterInfo.h"
23 #include "llvm/IR/DataLayout.h"
24 #include "llvm/IR/DerivedTypes.h"
25 #include "llvm/IR/GlobalVariable.h"
26 #include "llvm/IR/LLVMContext.h"
27 #include "llvm/MC/MCAsmInfo.h"
28 #include "llvm/MC/MCExpr.h"
29 #include "llvm/Support/DivisionByConstantInfo.h"
30 #include "llvm/Support/ErrorHandling.h"
31 #include "llvm/Support/KnownBits.h"
32 #include "llvm/Support/MathExtras.h"
33 #include "llvm/Target/TargetMachine.h"
34 #include <cctype>
35 using namespace llvm;
36 
37 /// NOTE: The TargetMachine owns TLOF.
38 TargetLowering::TargetLowering(const TargetMachine &tm)
39     : TargetLoweringBase(tm) {}
40 
41 const char *TargetLowering::getTargetNodeName(unsigned Opcode) const {
42   return nullptr;
43 }
44 
45 bool TargetLowering::isPositionIndependent() const {
46   return getTargetMachine().isPositionIndependent();
47 }
48 
49 /// Check whether a given call node is in tail position within its function. If
50 /// so, it sets Chain to the input chain of the tail call.
51 bool TargetLowering::isInTailCallPosition(SelectionDAG &DAG, SDNode *Node,
52                                           SDValue &Chain) const {
53   const Function &F = DAG.getMachineFunction().getFunction();
54 
55   // First, check if tail calls have been disabled in this function.
56   if (F.getFnAttribute("disable-tail-calls").getValueAsBool())
57     return false;
58 
59   // Conservatively require the attributes of the call to match those of
60   // the return. Ignore following attributes because they don't affect the
61   // call sequence.
62   AttrBuilder CallerAttrs(F.getContext(), F.getAttributes().getRetAttrs());
63   for (const auto &Attr : {Attribute::Alignment, Attribute::Dereferenceable,
64                            Attribute::DereferenceableOrNull, Attribute::NoAlias,
65                            Attribute::NonNull, Attribute::NoUndef})
66     CallerAttrs.removeAttribute(Attr);
67 
68   if (CallerAttrs.hasAttributes())
69     return false;
70 
71   // It's not safe to eliminate the sign / zero extension of the return value.
72   if (CallerAttrs.contains(Attribute::ZExt) ||
73       CallerAttrs.contains(Attribute::SExt))
74     return false;
75 
76   // Check if the only use is a function return node.
77   return isUsedByReturnOnly(Node, Chain);
78 }
79 
80 bool TargetLowering::parametersInCSRMatch(const MachineRegisterInfo &MRI,
81     const uint32_t *CallerPreservedMask,
82     const SmallVectorImpl<CCValAssign> &ArgLocs,
83     const SmallVectorImpl<SDValue> &OutVals) const {
84   for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
85     const CCValAssign &ArgLoc = ArgLocs[I];
86     if (!ArgLoc.isRegLoc())
87       continue;
88     MCRegister Reg = ArgLoc.getLocReg();
89     // Only look at callee saved registers.
90     if (MachineOperand::clobbersPhysReg(CallerPreservedMask, Reg))
91       continue;
92     // Check that we pass the value used for the caller.
93     // (We look for a CopyFromReg reading a virtual register that is used
94     //  for the function live-in value of register Reg)
95     SDValue Value = OutVals[I];
96     if (Value->getOpcode() == ISD::AssertZext)
97       Value = Value.getOperand(0);
98     if (Value->getOpcode() != ISD::CopyFromReg)
99       return false;
100     Register ArgReg = cast<RegisterSDNode>(Value->getOperand(1))->getReg();
101     if (MRI.getLiveInPhysReg(ArgReg) != Reg)
102       return false;
103   }
104   return true;
105 }
106 
107 /// Set CallLoweringInfo attribute flags based on a call instruction
108 /// and called function attributes.
109 void TargetLoweringBase::ArgListEntry::setAttributes(const CallBase *Call,
110                                                      unsigned ArgIdx) {
111   IsSExt = Call->paramHasAttr(ArgIdx, Attribute::SExt);
112   IsZExt = Call->paramHasAttr(ArgIdx, Attribute::ZExt);
113   IsInReg = Call->paramHasAttr(ArgIdx, Attribute::InReg);
114   IsSRet = Call->paramHasAttr(ArgIdx, Attribute::StructRet);
115   IsNest = Call->paramHasAttr(ArgIdx, Attribute::Nest);
116   IsByVal = Call->paramHasAttr(ArgIdx, Attribute::ByVal);
117   IsPreallocated = Call->paramHasAttr(ArgIdx, Attribute::Preallocated);
118   IsInAlloca = Call->paramHasAttr(ArgIdx, Attribute::InAlloca);
119   IsReturned = Call->paramHasAttr(ArgIdx, Attribute::Returned);
120   IsSwiftSelf = Call->paramHasAttr(ArgIdx, Attribute::SwiftSelf);
121   IsSwiftAsync = Call->paramHasAttr(ArgIdx, Attribute::SwiftAsync);
122   IsSwiftError = Call->paramHasAttr(ArgIdx, Attribute::SwiftError);
123   Alignment = Call->getParamStackAlign(ArgIdx);
124   IndirectType = nullptr;
125   assert(IsByVal + IsPreallocated + IsInAlloca + IsSRet <= 1 &&
126          "multiple ABI attributes?");
127   if (IsByVal) {
128     IndirectType = Call->getParamByValType(ArgIdx);
129     if (!Alignment)
130       Alignment = Call->getParamAlign(ArgIdx);
131   }
132   if (IsPreallocated)
133     IndirectType = Call->getParamPreallocatedType(ArgIdx);
134   if (IsInAlloca)
135     IndirectType = Call->getParamInAllocaType(ArgIdx);
136   if (IsSRet)
137     IndirectType = Call->getParamStructRetType(ArgIdx);
138 }
139 
140 /// Generate a libcall taking the given operands as arguments and returning a
141 /// result of type RetVT.
142 std::pair<SDValue, SDValue>
143 TargetLowering::makeLibCall(SelectionDAG &DAG, RTLIB::Libcall LC, EVT RetVT,
144                             ArrayRef<SDValue> Ops,
145                             MakeLibCallOptions CallOptions,
146                             const SDLoc &dl,
147                             SDValue InChain) const {
148   if (!InChain)
149     InChain = DAG.getEntryNode();
150 
151   TargetLowering::ArgListTy Args;
152   Args.reserve(Ops.size());
153 
154   TargetLowering::ArgListEntry Entry;
155   for (unsigned i = 0; i < Ops.size(); ++i) {
156     SDValue NewOp = Ops[i];
157     Entry.Node = NewOp;
158     Entry.Ty = Entry.Node.getValueType().getTypeForEVT(*DAG.getContext());
159     Entry.IsSExt = shouldSignExtendTypeInLibCall(NewOp.getValueType(),
160                                                  CallOptions.IsSExt);
161     Entry.IsZExt = !Entry.IsSExt;
162 
163     if (CallOptions.IsSoften &&
164         !shouldExtendTypeInLibCall(CallOptions.OpsVTBeforeSoften[i])) {
165       Entry.IsSExt = Entry.IsZExt = false;
166     }
167     Args.push_back(Entry);
168   }
169 
170   if (LC == RTLIB::UNKNOWN_LIBCALL)
171     report_fatal_error("Unsupported library call operation!");
172   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
173                                          getPointerTy(DAG.getDataLayout()));
174 
175   Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext());
176   TargetLowering::CallLoweringInfo CLI(DAG);
177   bool signExtend = shouldSignExtendTypeInLibCall(RetVT, CallOptions.IsSExt);
178   bool zeroExtend = !signExtend;
179 
180   if (CallOptions.IsSoften &&
181       !shouldExtendTypeInLibCall(CallOptions.RetVTBeforeSoften)) {
182     signExtend = zeroExtend = false;
183   }
184 
185   CLI.setDebugLoc(dl)
186       .setChain(InChain)
187       .setLibCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args))
188       .setNoReturn(CallOptions.DoesNotReturn)
189       .setDiscardResult(!CallOptions.IsReturnValueUsed)
190       .setIsPostTypeLegalization(CallOptions.IsPostTypeLegalization)
191       .setSExtResult(signExtend)
192       .setZExtResult(zeroExtend);
193   return LowerCallTo(CLI);
194 }
195 
196 bool TargetLowering::findOptimalMemOpLowering(
197     std::vector<EVT> &MemOps, unsigned Limit, const MemOp &Op, unsigned DstAS,
198     unsigned SrcAS, const AttributeList &FuncAttributes) const {
199   if (Limit != ~unsigned(0) && Op.isMemcpyWithFixedDstAlign() &&
200       Op.getSrcAlign() < Op.getDstAlign())
201     return false;
202 
203   EVT VT = getOptimalMemOpType(Op, FuncAttributes);
204 
205   if (VT == MVT::Other) {
206     // Use the largest integer type whose alignment constraints are satisfied.
207     // We only need to check DstAlign here as SrcAlign is always greater or
208     // equal to DstAlign (or zero).
209     VT = MVT::i64;
210     if (Op.isFixedDstAlign())
211       while (Op.getDstAlign() < (VT.getSizeInBits() / 8) &&
212              !allowsMisalignedMemoryAccesses(VT, DstAS, Op.getDstAlign()))
213         VT = (MVT::SimpleValueType)(VT.getSimpleVT().SimpleTy - 1);
214     assert(VT.isInteger());
215 
216     // Find the largest legal integer type.
217     MVT LVT = MVT::i64;
218     while (!isTypeLegal(LVT))
219       LVT = (MVT::SimpleValueType)(LVT.SimpleTy - 1);
220     assert(LVT.isInteger());
221 
222     // If the type we've chosen is larger than the largest legal integer type
223     // then use that instead.
224     if (VT.bitsGT(LVT))
225       VT = LVT;
226   }
227 
228   unsigned NumMemOps = 0;
229   uint64_t Size = Op.size();
230   while (Size) {
231     unsigned VTSize = VT.getSizeInBits() / 8;
232     while (VTSize > Size) {
233       // For now, only use non-vector load / store's for the left-over pieces.
234       EVT NewVT = VT;
235       unsigned NewVTSize;
236 
237       bool Found = false;
238       if (VT.isVector() || VT.isFloatingPoint()) {
239         NewVT = (VT.getSizeInBits() > 64) ? MVT::i64 : MVT::i32;
240         if (isOperationLegalOrCustom(ISD::STORE, NewVT) &&
241             isSafeMemOpType(NewVT.getSimpleVT()))
242           Found = true;
243         else if (NewVT == MVT::i64 &&
244                  isOperationLegalOrCustom(ISD::STORE, MVT::f64) &&
245                  isSafeMemOpType(MVT::f64)) {
246           // i64 is usually not legal on 32-bit targets, but f64 may be.
247           NewVT = MVT::f64;
248           Found = true;
249         }
250       }
251 
252       if (!Found) {
253         do {
254           NewVT = (MVT::SimpleValueType)(NewVT.getSimpleVT().SimpleTy - 1);
255           if (NewVT == MVT::i8)
256             break;
257         } while (!isSafeMemOpType(NewVT.getSimpleVT()));
258       }
259       NewVTSize = NewVT.getSizeInBits() / 8;
260 
261       // If the new VT cannot cover all of the remaining bits, then consider
262       // issuing a (or a pair of) unaligned and overlapping load / store.
263       bool Fast;
264       if (NumMemOps && Op.allowOverlap() && NewVTSize < Size &&
265           allowsMisalignedMemoryAccesses(
266               VT, DstAS, Op.isFixedDstAlign() ? Op.getDstAlign() : Align(1),
267               MachineMemOperand::MONone, &Fast) &&
268           Fast)
269         VTSize = Size;
270       else {
271         VT = NewVT;
272         VTSize = NewVTSize;
273       }
274     }
275 
276     if (++NumMemOps > Limit)
277       return false;
278 
279     MemOps.push_back(VT);
280     Size -= VTSize;
281   }
282 
283   return true;
284 }
285 
286 /// Soften the operands of a comparison. This code is shared among BR_CC,
287 /// SELECT_CC, and SETCC handlers.
288 void TargetLowering::softenSetCCOperands(SelectionDAG &DAG, EVT VT,
289                                          SDValue &NewLHS, SDValue &NewRHS,
290                                          ISD::CondCode &CCCode,
291                                          const SDLoc &dl, const SDValue OldLHS,
292                                          const SDValue OldRHS) const {
293   SDValue Chain;
294   return softenSetCCOperands(DAG, VT, NewLHS, NewRHS, CCCode, dl, OldLHS,
295                              OldRHS, Chain);
296 }
297 
298 void TargetLowering::softenSetCCOperands(SelectionDAG &DAG, EVT VT,
299                                          SDValue &NewLHS, SDValue &NewRHS,
300                                          ISD::CondCode &CCCode,
301                                          const SDLoc &dl, const SDValue OldLHS,
302                                          const SDValue OldRHS,
303                                          SDValue &Chain,
304                                          bool IsSignaling) const {
305   // FIXME: Currently we cannot really respect all IEEE predicates due to libgcc
306   // not supporting it. We can update this code when libgcc provides such
307   // functions.
308 
309   assert((VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128 || VT == MVT::ppcf128)
310          && "Unsupported setcc type!");
311 
312   // Expand into one or more soft-fp libcall(s).
313   RTLIB::Libcall LC1 = RTLIB::UNKNOWN_LIBCALL, LC2 = RTLIB::UNKNOWN_LIBCALL;
314   bool ShouldInvertCC = false;
315   switch (CCCode) {
316   case ISD::SETEQ:
317   case ISD::SETOEQ:
318     LC1 = (VT == MVT::f32) ? RTLIB::OEQ_F32 :
319           (VT == MVT::f64) ? RTLIB::OEQ_F64 :
320           (VT == MVT::f128) ? RTLIB::OEQ_F128 : RTLIB::OEQ_PPCF128;
321     break;
322   case ISD::SETNE:
323   case ISD::SETUNE:
324     LC1 = (VT == MVT::f32) ? RTLIB::UNE_F32 :
325           (VT == MVT::f64) ? RTLIB::UNE_F64 :
326           (VT == MVT::f128) ? RTLIB::UNE_F128 : RTLIB::UNE_PPCF128;
327     break;
328   case ISD::SETGE:
329   case ISD::SETOGE:
330     LC1 = (VT == MVT::f32) ? RTLIB::OGE_F32 :
331           (VT == MVT::f64) ? RTLIB::OGE_F64 :
332           (VT == MVT::f128) ? RTLIB::OGE_F128 : RTLIB::OGE_PPCF128;
333     break;
334   case ISD::SETLT:
335   case ISD::SETOLT:
336     LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 :
337           (VT == MVT::f64) ? RTLIB::OLT_F64 :
338           (VT == MVT::f128) ? RTLIB::OLT_F128 : RTLIB::OLT_PPCF128;
339     break;
340   case ISD::SETLE:
341   case ISD::SETOLE:
342     LC1 = (VT == MVT::f32) ? RTLIB::OLE_F32 :
343           (VT == MVT::f64) ? RTLIB::OLE_F64 :
344           (VT == MVT::f128) ? RTLIB::OLE_F128 : RTLIB::OLE_PPCF128;
345     break;
346   case ISD::SETGT:
347   case ISD::SETOGT:
348     LC1 = (VT == MVT::f32) ? RTLIB::OGT_F32 :
349           (VT == MVT::f64) ? RTLIB::OGT_F64 :
350           (VT == MVT::f128) ? RTLIB::OGT_F128 : RTLIB::OGT_PPCF128;
351     break;
352   case ISD::SETO:
353     ShouldInvertCC = true;
354     LLVM_FALLTHROUGH;
355   case ISD::SETUO:
356     LC1 = (VT == MVT::f32) ? RTLIB::UO_F32 :
357           (VT == MVT::f64) ? RTLIB::UO_F64 :
358           (VT == MVT::f128) ? RTLIB::UO_F128 : RTLIB::UO_PPCF128;
359     break;
360   case ISD::SETONE:
361     // SETONE = O && UNE
362     ShouldInvertCC = true;
363     LLVM_FALLTHROUGH;
364   case ISD::SETUEQ:
365     LC1 = (VT == MVT::f32) ? RTLIB::UO_F32 :
366           (VT == MVT::f64) ? RTLIB::UO_F64 :
367           (VT == MVT::f128) ? RTLIB::UO_F128 : RTLIB::UO_PPCF128;
368     LC2 = (VT == MVT::f32) ? RTLIB::OEQ_F32 :
369           (VT == MVT::f64) ? RTLIB::OEQ_F64 :
370           (VT == MVT::f128) ? RTLIB::OEQ_F128 : RTLIB::OEQ_PPCF128;
371     break;
372   default:
373     // Invert CC for unordered comparisons
374     ShouldInvertCC = true;
375     switch (CCCode) {
376     case ISD::SETULT:
377       LC1 = (VT == MVT::f32) ? RTLIB::OGE_F32 :
378             (VT == MVT::f64) ? RTLIB::OGE_F64 :
379             (VT == MVT::f128) ? RTLIB::OGE_F128 : RTLIB::OGE_PPCF128;
380       break;
381     case ISD::SETULE:
382       LC1 = (VT == MVT::f32) ? RTLIB::OGT_F32 :
383             (VT == MVT::f64) ? RTLIB::OGT_F64 :
384             (VT == MVT::f128) ? RTLIB::OGT_F128 : RTLIB::OGT_PPCF128;
385       break;
386     case ISD::SETUGT:
387       LC1 = (VT == MVT::f32) ? RTLIB::OLE_F32 :
388             (VT == MVT::f64) ? RTLIB::OLE_F64 :
389             (VT == MVT::f128) ? RTLIB::OLE_F128 : RTLIB::OLE_PPCF128;
390       break;
391     case ISD::SETUGE:
392       LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 :
393             (VT == MVT::f64) ? RTLIB::OLT_F64 :
394             (VT == MVT::f128) ? RTLIB::OLT_F128 : RTLIB::OLT_PPCF128;
395       break;
396     default: llvm_unreachable("Do not know how to soften this setcc!");
397     }
398   }
399 
400   // Use the target specific return value for comparions lib calls.
401   EVT RetVT = getCmpLibcallReturnType();
402   SDValue Ops[2] = {NewLHS, NewRHS};
403   TargetLowering::MakeLibCallOptions CallOptions;
404   EVT OpsVT[2] = { OldLHS.getValueType(),
405                    OldRHS.getValueType() };
406   CallOptions.setTypeListBeforeSoften(OpsVT, RetVT, true);
407   auto Call = makeLibCall(DAG, LC1, RetVT, Ops, CallOptions, dl, Chain);
408   NewLHS = Call.first;
409   NewRHS = DAG.getConstant(0, dl, RetVT);
410 
411   CCCode = getCmpLibcallCC(LC1);
412   if (ShouldInvertCC) {
413     assert(RetVT.isInteger());
414     CCCode = getSetCCInverse(CCCode, RetVT);
415   }
416 
417   if (LC2 == RTLIB::UNKNOWN_LIBCALL) {
418     // Update Chain.
419     Chain = Call.second;
420   } else {
421     EVT SetCCVT =
422         getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), RetVT);
423     SDValue Tmp = DAG.getSetCC(dl, SetCCVT, NewLHS, NewRHS, CCCode);
424     auto Call2 = makeLibCall(DAG, LC2, RetVT, Ops, CallOptions, dl, Chain);
425     CCCode = getCmpLibcallCC(LC2);
426     if (ShouldInvertCC)
427       CCCode = getSetCCInverse(CCCode, RetVT);
428     NewLHS = DAG.getSetCC(dl, SetCCVT, Call2.first, NewRHS, CCCode);
429     if (Chain)
430       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Call.second,
431                           Call2.second);
432     NewLHS = DAG.getNode(ShouldInvertCC ? ISD::AND : ISD::OR, dl,
433                          Tmp.getValueType(), Tmp, NewLHS);
434     NewRHS = SDValue();
435   }
436 }
437 
438 /// Return the entry encoding for a jump table in the current function. The
439 /// returned value is a member of the MachineJumpTableInfo::JTEntryKind enum.
440 unsigned TargetLowering::getJumpTableEncoding() const {
441   // In non-pic modes, just use the address of a block.
442   if (!isPositionIndependent())
443     return MachineJumpTableInfo::EK_BlockAddress;
444 
445   // In PIC mode, if the target supports a GPRel32 directive, use it.
446   if (getTargetMachine().getMCAsmInfo()->getGPRel32Directive() != nullptr)
447     return MachineJumpTableInfo::EK_GPRel32BlockAddress;
448 
449   // Otherwise, use a label difference.
450   return MachineJumpTableInfo::EK_LabelDifference32;
451 }
452 
453 SDValue TargetLowering::getPICJumpTableRelocBase(SDValue Table,
454                                                  SelectionDAG &DAG) const {
455   // If our PIC model is GP relative, use the global offset table as the base.
456   unsigned JTEncoding = getJumpTableEncoding();
457 
458   if ((JTEncoding == MachineJumpTableInfo::EK_GPRel64BlockAddress) ||
459       (JTEncoding == MachineJumpTableInfo::EK_GPRel32BlockAddress))
460     return DAG.getGLOBAL_OFFSET_TABLE(getPointerTy(DAG.getDataLayout()));
461 
462   return Table;
463 }
464 
465 /// This returns the relocation base for the given PIC jumptable, the same as
466 /// getPICJumpTableRelocBase, but as an MCExpr.
467 const MCExpr *
468 TargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
469                                              unsigned JTI,MCContext &Ctx) const{
470   // The normal PIC reloc base is the label at the start of the jump table.
471   return MCSymbolRefExpr::create(MF->getJTISymbol(JTI, Ctx), Ctx);
472 }
473 
474 bool
475 TargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
476   const TargetMachine &TM = getTargetMachine();
477   const GlobalValue *GV = GA->getGlobal();
478 
479   // If the address is not even local to this DSO we will have to load it from
480   // a got and then add the offset.
481   if (!TM.shouldAssumeDSOLocal(*GV->getParent(), GV))
482     return false;
483 
484   // If the code is position independent we will have to add a base register.
485   if (isPositionIndependent())
486     return false;
487 
488   // Otherwise we can do it.
489   return true;
490 }
491 
492 //===----------------------------------------------------------------------===//
493 //  Optimization Methods
494 //===----------------------------------------------------------------------===//
495 
496 /// If the specified instruction has a constant integer operand and there are
497 /// bits set in that constant that are not demanded, then clear those bits and
498 /// return true.
499 bool TargetLowering::ShrinkDemandedConstant(SDValue Op,
500                                             const APInt &DemandedBits,
501                                             const APInt &DemandedElts,
502                                             TargetLoweringOpt &TLO) const {
503   SDLoc DL(Op);
504   unsigned Opcode = Op.getOpcode();
505 
506   // Do target-specific constant optimization.
507   if (targetShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO))
508     return TLO.New.getNode();
509 
510   // FIXME: ISD::SELECT, ISD::SELECT_CC
511   switch (Opcode) {
512   default:
513     break;
514   case ISD::XOR:
515   case ISD::AND:
516   case ISD::OR: {
517     auto *Op1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
518     if (!Op1C || Op1C->isOpaque())
519       return false;
520 
521     // If this is a 'not' op, don't touch it because that's a canonical form.
522     const APInt &C = Op1C->getAPIntValue();
523     if (Opcode == ISD::XOR && DemandedBits.isSubsetOf(C))
524       return false;
525 
526     if (!C.isSubsetOf(DemandedBits)) {
527       EVT VT = Op.getValueType();
528       SDValue NewC = TLO.DAG.getConstant(DemandedBits & C, DL, VT);
529       SDValue NewOp = TLO.DAG.getNode(Opcode, DL, VT, Op.getOperand(0), NewC);
530       return TLO.CombineTo(Op, NewOp);
531     }
532 
533     break;
534   }
535   }
536 
537   return false;
538 }
539 
540 bool TargetLowering::ShrinkDemandedConstant(SDValue Op,
541                                             const APInt &DemandedBits,
542                                             TargetLoweringOpt &TLO) const {
543   EVT VT = Op.getValueType();
544   APInt DemandedElts = VT.isVector()
545                            ? APInt::getAllOnes(VT.getVectorNumElements())
546                            : APInt(1, 1);
547   return ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO);
548 }
549 
550 /// Convert x+y to (VT)((SmallVT)x+(SmallVT)y) if the casts are free.
551 /// This uses isZExtFree and ZERO_EXTEND for the widening cast, but it could be
552 /// generalized for targets with other types of implicit widening casts.
553 bool TargetLowering::ShrinkDemandedOp(SDValue Op, unsigned BitWidth,
554                                       const APInt &Demanded,
555                                       TargetLoweringOpt &TLO) const {
556   assert(Op.getNumOperands() == 2 &&
557          "ShrinkDemandedOp only supports binary operators!");
558   assert(Op.getNode()->getNumValues() == 1 &&
559          "ShrinkDemandedOp only supports nodes with one result!");
560 
561   SelectionDAG &DAG = TLO.DAG;
562   SDLoc dl(Op);
563 
564   // Early return, as this function cannot handle vector types.
565   if (Op.getValueType().isVector())
566     return false;
567 
568   // Don't do this if the node has another user, which may require the
569   // full value.
570   if (!Op.getNode()->hasOneUse())
571     return false;
572 
573   // Search for the smallest integer type with free casts to and from
574   // Op's type. For expedience, just check power-of-2 integer types.
575   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
576   unsigned DemandedSize = Demanded.getActiveBits();
577   unsigned SmallVTBits = DemandedSize;
578   if (!isPowerOf2_32(SmallVTBits))
579     SmallVTBits = NextPowerOf2(SmallVTBits);
580   for (; SmallVTBits < BitWidth; SmallVTBits = NextPowerOf2(SmallVTBits)) {
581     EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), SmallVTBits);
582     if (TLI.isTruncateFree(Op.getValueType(), SmallVT) &&
583         TLI.isZExtFree(SmallVT, Op.getValueType())) {
584       // We found a type with free casts.
585       SDValue X = DAG.getNode(
586           Op.getOpcode(), dl, SmallVT,
587           DAG.getNode(ISD::TRUNCATE, dl, SmallVT, Op.getOperand(0)),
588           DAG.getNode(ISD::TRUNCATE, dl, SmallVT, Op.getOperand(1)));
589       assert(DemandedSize <= SmallVTBits && "Narrowed below demanded bits?");
590       SDValue Z = DAG.getNode(ISD::ANY_EXTEND, dl, Op.getValueType(), X);
591       return TLO.CombineTo(Op, Z);
592     }
593   }
594   return false;
595 }
596 
597 bool TargetLowering::SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits,
598                                           DAGCombinerInfo &DCI) const {
599   SelectionDAG &DAG = DCI.DAG;
600   TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
601                         !DCI.isBeforeLegalizeOps());
602   KnownBits Known;
603 
604   bool Simplified = SimplifyDemandedBits(Op, DemandedBits, Known, TLO);
605   if (Simplified) {
606     DCI.AddToWorklist(Op.getNode());
607     DCI.CommitTargetLoweringOpt(TLO);
608   }
609   return Simplified;
610 }
611 
612 bool TargetLowering::SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits,
613                                           const APInt &DemandedElts,
614                                           DAGCombinerInfo &DCI) const {
615   SelectionDAG &DAG = DCI.DAG;
616   TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
617                         !DCI.isBeforeLegalizeOps());
618   KnownBits Known;
619 
620   bool Simplified =
621       SimplifyDemandedBits(Op, DemandedBits, DemandedElts, Known, TLO);
622   if (Simplified) {
623     DCI.AddToWorklist(Op.getNode());
624     DCI.CommitTargetLoweringOpt(TLO);
625   }
626   return Simplified;
627 }
628 
629 bool TargetLowering::SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits,
630                                           KnownBits &Known,
631                                           TargetLoweringOpt &TLO,
632                                           unsigned Depth,
633                                           bool AssumeSingleUse) const {
634   EVT VT = Op.getValueType();
635 
636   // TODO: We can probably do more work on calculating the known bits and
637   // simplifying the operations for scalable vectors, but for now we just
638   // bail out.
639   if (VT.isScalableVector()) {
640     // Pretend we don't know anything for now.
641     Known = KnownBits(DemandedBits.getBitWidth());
642     return false;
643   }
644 
645   APInt DemandedElts = VT.isVector()
646                            ? APInt::getAllOnes(VT.getVectorNumElements())
647                            : APInt(1, 1);
648   return SimplifyDemandedBits(Op, DemandedBits, DemandedElts, Known, TLO, Depth,
649                               AssumeSingleUse);
650 }
651 
652 // TODO: Can we merge SelectionDAG::GetDemandedBits into this?
653 // TODO: Under what circumstances can we create nodes? Constant folding?
654 SDValue TargetLowering::SimplifyMultipleUseDemandedBits(
655     SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
656     SelectionDAG &DAG, unsigned Depth) const {
657   // Limit search depth.
658   if (Depth >= SelectionDAG::MaxRecursionDepth)
659     return SDValue();
660 
661   // Ignore UNDEFs.
662   if (Op.isUndef())
663     return SDValue();
664 
665   // Not demanding any bits/elts from Op.
666   if (DemandedBits == 0 || DemandedElts == 0)
667     return DAG.getUNDEF(Op.getValueType());
668 
669   bool IsLE = DAG.getDataLayout().isLittleEndian();
670   unsigned NumElts = DemandedElts.getBitWidth();
671   unsigned BitWidth = DemandedBits.getBitWidth();
672   KnownBits LHSKnown, RHSKnown;
673   switch (Op.getOpcode()) {
674   case ISD::BITCAST: {
675     SDValue Src = peekThroughBitcasts(Op.getOperand(0));
676     EVT SrcVT = Src.getValueType();
677     EVT DstVT = Op.getValueType();
678     if (SrcVT == DstVT)
679       return Src;
680 
681     unsigned NumSrcEltBits = SrcVT.getScalarSizeInBits();
682     unsigned NumDstEltBits = DstVT.getScalarSizeInBits();
683     if (NumSrcEltBits == NumDstEltBits)
684       if (SDValue V = SimplifyMultipleUseDemandedBits(
685               Src, DemandedBits, DemandedElts, DAG, Depth + 1))
686         return DAG.getBitcast(DstVT, V);
687 
688     if (SrcVT.isVector() && (NumDstEltBits % NumSrcEltBits) == 0) {
689       unsigned Scale = NumDstEltBits / NumSrcEltBits;
690       unsigned NumSrcElts = SrcVT.getVectorNumElements();
691       APInt DemandedSrcBits = APInt::getZero(NumSrcEltBits);
692       APInt DemandedSrcElts = APInt::getZero(NumSrcElts);
693       for (unsigned i = 0; i != Scale; ++i) {
694         unsigned EltOffset = IsLE ? i : (Scale - 1 - i);
695         unsigned BitOffset = EltOffset * NumSrcEltBits;
696         APInt Sub = DemandedBits.extractBits(NumSrcEltBits, BitOffset);
697         if (!Sub.isZero()) {
698           DemandedSrcBits |= Sub;
699           for (unsigned j = 0; j != NumElts; ++j)
700             if (DemandedElts[j])
701               DemandedSrcElts.setBit((j * Scale) + i);
702         }
703       }
704 
705       if (SDValue V = SimplifyMultipleUseDemandedBits(
706               Src, DemandedSrcBits, DemandedSrcElts, DAG, Depth + 1))
707         return DAG.getBitcast(DstVT, V);
708     }
709 
710     // TODO - bigendian once we have test coverage.
711     if (IsLE && (NumSrcEltBits % NumDstEltBits) == 0) {
712       unsigned Scale = NumSrcEltBits / NumDstEltBits;
713       unsigned NumSrcElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1;
714       APInt DemandedSrcBits = APInt::getZero(NumSrcEltBits);
715       APInt DemandedSrcElts = APInt::getZero(NumSrcElts);
716       for (unsigned i = 0; i != NumElts; ++i)
717         if (DemandedElts[i]) {
718           unsigned Offset = (i % Scale) * NumDstEltBits;
719           DemandedSrcBits.insertBits(DemandedBits, Offset);
720           DemandedSrcElts.setBit(i / Scale);
721         }
722 
723       if (SDValue V = SimplifyMultipleUseDemandedBits(
724               Src, DemandedSrcBits, DemandedSrcElts, DAG, Depth + 1))
725         return DAG.getBitcast(DstVT, V);
726     }
727 
728     break;
729   }
730   case ISD::AND: {
731     LHSKnown = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
732     RHSKnown = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
733 
734     // If all of the demanded bits are known 1 on one side, return the other.
735     // These bits cannot contribute to the result of the 'and' in this
736     // context.
737     if (DemandedBits.isSubsetOf(LHSKnown.Zero | RHSKnown.One))
738       return Op.getOperand(0);
739     if (DemandedBits.isSubsetOf(RHSKnown.Zero | LHSKnown.One))
740       return Op.getOperand(1);
741     break;
742   }
743   case ISD::OR: {
744     LHSKnown = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
745     RHSKnown = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
746 
747     // If all of the demanded bits are known zero on one side, return the
748     // other.  These bits cannot contribute to the result of the 'or' in this
749     // context.
750     if (DemandedBits.isSubsetOf(LHSKnown.One | RHSKnown.Zero))
751       return Op.getOperand(0);
752     if (DemandedBits.isSubsetOf(RHSKnown.One | LHSKnown.Zero))
753       return Op.getOperand(1);
754     break;
755   }
756   case ISD::XOR: {
757     LHSKnown = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
758     RHSKnown = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
759 
760     // If all of the demanded bits are known zero on one side, return the
761     // other.
762     if (DemandedBits.isSubsetOf(RHSKnown.Zero))
763       return Op.getOperand(0);
764     if (DemandedBits.isSubsetOf(LHSKnown.Zero))
765       return Op.getOperand(1);
766     break;
767   }
768   case ISD::SHL: {
769     // If we are only demanding sign bits then we can use the shift source
770     // directly.
771     if (const APInt *MaxSA =
772             DAG.getValidMaximumShiftAmountConstant(Op, DemandedElts)) {
773       SDValue Op0 = Op.getOperand(0);
774       unsigned ShAmt = MaxSA->getZExtValue();
775       unsigned NumSignBits =
776           DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1);
777       unsigned UpperDemandedBits = BitWidth - DemandedBits.countTrailingZeros();
778       if (NumSignBits > ShAmt && (NumSignBits - ShAmt) >= (UpperDemandedBits))
779         return Op0;
780     }
781     break;
782   }
783   case ISD::SETCC: {
784     SDValue Op0 = Op.getOperand(0);
785     SDValue Op1 = Op.getOperand(1);
786     ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
787     // If (1) we only need the sign-bit, (2) the setcc operands are the same
788     // width as the setcc result, and (3) the result of a setcc conforms to 0 or
789     // -1, we may be able to bypass the setcc.
790     if (DemandedBits.isSignMask() &&
791         Op0.getScalarValueSizeInBits() == BitWidth &&
792         getBooleanContents(Op0.getValueType()) ==
793             BooleanContent::ZeroOrNegativeOneBooleanContent) {
794       // If we're testing X < 0, then this compare isn't needed - just use X!
795       // FIXME: We're limiting to integer types here, but this should also work
796       // if we don't care about FP signed-zero. The use of SETLT with FP means
797       // that we don't care about NaNs.
798       if (CC == ISD::SETLT && Op1.getValueType().isInteger() &&
799           (isNullConstant(Op1) || ISD::isBuildVectorAllZeros(Op1.getNode())))
800         return Op0;
801     }
802     break;
803   }
804   case ISD::SIGN_EXTEND_INREG: {
805     // If none of the extended bits are demanded, eliminate the sextinreg.
806     SDValue Op0 = Op.getOperand(0);
807     EVT ExVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
808     unsigned ExBits = ExVT.getScalarSizeInBits();
809     if (DemandedBits.getActiveBits() <= ExBits)
810       return Op0;
811     // If the input is already sign extended, just drop the extension.
812     unsigned NumSignBits = DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1);
813     if (NumSignBits >= (BitWidth - ExBits + 1))
814       return Op0;
815     break;
816   }
817   case ISD::ANY_EXTEND_VECTOR_INREG:
818   case ISD::SIGN_EXTEND_VECTOR_INREG:
819   case ISD::ZERO_EXTEND_VECTOR_INREG: {
820     // If we only want the lowest element and none of extended bits, then we can
821     // return the bitcasted source vector.
822     SDValue Src = Op.getOperand(0);
823     EVT SrcVT = Src.getValueType();
824     EVT DstVT = Op.getValueType();
825     if (IsLE && DemandedElts == 1 &&
826         DstVT.getSizeInBits() == SrcVT.getSizeInBits() &&
827         DemandedBits.getActiveBits() <= SrcVT.getScalarSizeInBits()) {
828       return DAG.getBitcast(DstVT, Src);
829     }
830     break;
831   }
832   case ISD::INSERT_VECTOR_ELT: {
833     // If we don't demand the inserted element, return the base vector.
834     SDValue Vec = Op.getOperand(0);
835     auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2));
836     EVT VecVT = Vec.getValueType();
837     if (CIdx && CIdx->getAPIntValue().ult(VecVT.getVectorNumElements()) &&
838         !DemandedElts[CIdx->getZExtValue()])
839       return Vec;
840     break;
841   }
842   case ISD::INSERT_SUBVECTOR: {
843     SDValue Vec = Op.getOperand(0);
844     SDValue Sub = Op.getOperand(1);
845     uint64_t Idx = Op.getConstantOperandVal(2);
846     unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
847     APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
848     // If we don't demand the inserted subvector, return the base vector.
849     if (DemandedSubElts == 0)
850       return Vec;
851     // If this simply widens the lowest subvector, see if we can do it earlier.
852     if (Idx == 0 && Vec.isUndef()) {
853       if (SDValue NewSub = SimplifyMultipleUseDemandedBits(
854               Sub, DemandedBits, DemandedSubElts, DAG, Depth + 1))
855         return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
856                            Op.getOperand(0), NewSub, Op.getOperand(2));
857     }
858     break;
859   }
860   case ISD::VECTOR_SHUFFLE: {
861     ArrayRef<int> ShuffleMask = cast<ShuffleVectorSDNode>(Op)->getMask();
862 
863     // If all the demanded elts are from one operand and are inline,
864     // then we can use the operand directly.
865     bool AllUndef = true, IdentityLHS = true, IdentityRHS = true;
866     for (unsigned i = 0; i != NumElts; ++i) {
867       int M = ShuffleMask[i];
868       if (M < 0 || !DemandedElts[i])
869         continue;
870       AllUndef = false;
871       IdentityLHS &= (M == (int)i);
872       IdentityRHS &= ((M - NumElts) == i);
873     }
874 
875     if (AllUndef)
876       return DAG.getUNDEF(Op.getValueType());
877     if (IdentityLHS)
878       return Op.getOperand(0);
879     if (IdentityRHS)
880       return Op.getOperand(1);
881     break;
882   }
883   default:
884     if (Op.getOpcode() >= ISD::BUILTIN_OP_END)
885       if (SDValue V = SimplifyMultipleUseDemandedBitsForTargetNode(
886               Op, DemandedBits, DemandedElts, DAG, Depth))
887         return V;
888     break;
889   }
890   return SDValue();
891 }
892 
893 SDValue TargetLowering::SimplifyMultipleUseDemandedBits(
894     SDValue Op, const APInt &DemandedBits, SelectionDAG &DAG,
895     unsigned Depth) const {
896   EVT VT = Op.getValueType();
897   APInt DemandedElts = VT.isVector()
898                            ? APInt::getAllOnes(VT.getVectorNumElements())
899                            : APInt(1, 1);
900   return SimplifyMultipleUseDemandedBits(Op, DemandedBits, DemandedElts, DAG,
901                                          Depth);
902 }
903 
904 SDValue TargetLowering::SimplifyMultipleUseDemandedVectorElts(
905     SDValue Op, const APInt &DemandedElts, SelectionDAG &DAG,
906     unsigned Depth) const {
907   APInt DemandedBits = APInt::getAllOnes(Op.getScalarValueSizeInBits());
908   return SimplifyMultipleUseDemandedBits(Op, DemandedBits, DemandedElts, DAG,
909                                          Depth);
910 }
911 
912 // Attempt to form ext(avgfloor(A, B)) from shr(add(ext(A), ext(B)), 1).
913 //      or to form ext(avgceil(A, B)) from shr(add(ext(A), ext(B), 1), 1).
914 static SDValue combineShiftToAVG(SDValue Op, SelectionDAG &DAG,
915                                  const TargetLowering &TLI,
916                                  const APInt &DemandedBits,
917                                  const APInt &DemandedElts,
918                                  unsigned Depth) {
919   assert((Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SRA) &&
920          "SRL or SRA node is required here!");
921   // Is the right shift using an immediate value of 1?
922   ConstantSDNode *N1C = isConstOrConstSplat(Op.getOperand(1), DemandedElts);
923   if (!N1C || !N1C->isOne())
924     return SDValue();
925 
926   // We are looking for an avgfloor
927   // add(ext, ext)
928   // or one of these as a avgceil
929   // add(add(ext, ext), 1)
930   // add(add(ext, 1), ext)
931   // add(ext, add(ext, 1))
932   SDValue Add = Op.getOperand(0);
933   if (Add.getOpcode() != ISD::ADD)
934     return SDValue();
935 
936   SDValue ExtOpA = Add.getOperand(0);
937   SDValue ExtOpB = Add.getOperand(1);
938   auto MatchOperands = [&](SDValue Op1, SDValue Op2, SDValue Op3) {
939     ConstantSDNode *ConstOp;
940     if ((ConstOp = isConstOrConstSplat(Op1, DemandedElts)) &&
941         ConstOp->isOne()) {
942       ExtOpA = Op2;
943       ExtOpB = Op3;
944       return true;
945     }
946     if ((ConstOp = isConstOrConstSplat(Op2, DemandedElts)) &&
947         ConstOp->isOne()) {
948       ExtOpA = Op1;
949       ExtOpB = Op3;
950       return true;
951     }
952     if ((ConstOp = isConstOrConstSplat(Op3, DemandedElts)) &&
953         ConstOp->isOne()) {
954       ExtOpA = Op1;
955       ExtOpB = Op2;
956       return true;
957     }
958     return false;
959   };
960   bool IsCeil =
961       (ExtOpA.getOpcode() == ISD::ADD &&
962        MatchOperands(ExtOpA.getOperand(0), ExtOpA.getOperand(1), ExtOpB)) ||
963       (ExtOpB.getOpcode() == ISD::ADD &&
964        MatchOperands(ExtOpB.getOperand(0), ExtOpB.getOperand(1), ExtOpA));
965 
966   // If the shift is signed (sra):
967   //  - Needs >= 2 sign bit for both operands.
968   //  - Needs >= 2 zero bits.
969   // If the shift is unsigned (srl):
970   //  - Needs >= 1 zero bit for both operands.
971   //  - Needs 1 demanded bit zero and >= 2 sign bits.
972   unsigned ShiftOpc = Op.getOpcode();
973   bool IsSigned = false;
974   unsigned KnownBits;
975   unsigned NumSignedA = DAG.ComputeNumSignBits(ExtOpA, DemandedElts, Depth);
976   unsigned NumSignedB = DAG.ComputeNumSignBits(ExtOpB, DemandedElts, Depth);
977   unsigned NumSigned = std::min(NumSignedA, NumSignedB) - 1;
978   unsigned NumZeroA =
979       DAG.computeKnownBits(ExtOpA, DemandedElts, Depth).countMinLeadingZeros();
980   unsigned NumZeroB =
981       DAG.computeKnownBits(ExtOpB, DemandedElts, Depth).countMinLeadingZeros();
982   unsigned NumZero = std::min(NumZeroA, NumZeroB);
983 
984   switch (ShiftOpc) {
985   default:
986     llvm_unreachable("Unexpected ShiftOpc in combineShiftToAVG");
987   case ISD::SRA: {
988     if (NumZero >= 2 && NumSigned < NumZero) {
989       IsSigned = false;
990       KnownBits = NumZero;
991       break;
992     }
993     if (NumSigned >= 1) {
994       IsSigned = true;
995       KnownBits = NumSigned;
996       break;
997     }
998     return SDValue();
999   }
1000   case ISD::SRL: {
1001     if (NumZero >= 1 && NumSigned < NumZero) {
1002       IsSigned = false;
1003       KnownBits = NumZero;
1004       break;
1005     }
1006     if (NumSigned >= 1 && DemandedBits.isSignBitClear()) {
1007       IsSigned = true;
1008       KnownBits = NumSigned;
1009       break;
1010     }
1011     return SDValue();
1012   }
1013   }
1014 
1015   unsigned AVGOpc = IsCeil ? (IsSigned ? ISD::AVGCEILS : ISD::AVGCEILU)
1016                            : (IsSigned ? ISD::AVGFLOORS : ISD::AVGFLOORU);
1017 
1018   // Find the smallest power-2 type that is legal for this vector size and
1019   // operation, given the original type size and the number of known sign/zero
1020   // bits.
1021   EVT VT = Op.getValueType();
1022   unsigned MinWidth =
1023       std::max<unsigned>(VT.getScalarSizeInBits() - KnownBits, 8);
1024   EVT NVT = EVT::getIntegerVT(*DAG.getContext(), PowerOf2Ceil(MinWidth));
1025   if (VT.isVector())
1026     NVT = EVT::getVectorVT(*DAG.getContext(), NVT, VT.getVectorElementCount());
1027   if (!TLI.isOperationLegalOrCustom(AVGOpc, NVT))
1028     return SDValue();
1029 
1030   SDLoc DL(Op);
1031   SDValue ResultAVG =
1032       DAG.getNode(AVGOpc, DL, NVT, DAG.getNode(ISD::TRUNCATE, DL, NVT, ExtOpA),
1033                   DAG.getNode(ISD::TRUNCATE, DL, NVT, ExtOpB));
1034   return DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, DL, VT,
1035                      ResultAVG);
1036 }
1037 
1038 /// Look at Op. At this point, we know that only the OriginalDemandedBits of the
1039 /// result of Op are ever used downstream. If we can use this information to
1040 /// simplify Op, create a new simplified DAG node and return true, returning the
1041 /// original and new nodes in Old and New. Otherwise, analyze the expression and
1042 /// return a mask of Known bits for the expression (used to simplify the
1043 /// caller).  The Known bits may only be accurate for those bits in the
1044 /// OriginalDemandedBits and OriginalDemandedElts.
1045 bool TargetLowering::SimplifyDemandedBits(
1046     SDValue Op, const APInt &OriginalDemandedBits,
1047     const APInt &OriginalDemandedElts, KnownBits &Known, TargetLoweringOpt &TLO,
1048     unsigned Depth, bool AssumeSingleUse) const {
1049   unsigned BitWidth = OriginalDemandedBits.getBitWidth();
1050   assert(Op.getScalarValueSizeInBits() == BitWidth &&
1051          "Mask size mismatches value type size!");
1052 
1053   // Don't know anything.
1054   Known = KnownBits(BitWidth);
1055 
1056   // TODO: We can probably do more work on calculating the known bits and
1057   // simplifying the operations for scalable vectors, but for now we just
1058   // bail out.
1059   if (Op.getValueType().isScalableVector())
1060     return false;
1061 
1062   bool IsLE = TLO.DAG.getDataLayout().isLittleEndian();
1063   unsigned NumElts = OriginalDemandedElts.getBitWidth();
1064   assert((!Op.getValueType().isVector() ||
1065           NumElts == Op.getValueType().getVectorNumElements()) &&
1066          "Unexpected vector size");
1067 
1068   APInt DemandedBits = OriginalDemandedBits;
1069   APInt DemandedElts = OriginalDemandedElts;
1070   SDLoc dl(Op);
1071   auto &DL = TLO.DAG.getDataLayout();
1072 
1073   // Undef operand.
1074   if (Op.isUndef())
1075     return false;
1076 
1077   if (Op.getOpcode() == ISD::Constant) {
1078     // We know all of the bits for a constant!
1079     Known = KnownBits::makeConstant(cast<ConstantSDNode>(Op)->getAPIntValue());
1080     return false;
1081   }
1082 
1083   if (Op.getOpcode() == ISD::ConstantFP) {
1084     // We know all of the bits for a floating point constant!
1085     Known = KnownBits::makeConstant(
1086         cast<ConstantFPSDNode>(Op)->getValueAPF().bitcastToAPInt());
1087     return false;
1088   }
1089 
1090   // Other users may use these bits.
1091   EVT VT = Op.getValueType();
1092   if (!Op.getNode()->hasOneUse() && !AssumeSingleUse) {
1093     if (Depth != 0) {
1094       // If not at the root, Just compute the Known bits to
1095       // simplify things downstream.
1096       Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth);
1097       return false;
1098     }
1099     // If this is the root being simplified, allow it to have multiple uses,
1100     // just set the DemandedBits/Elts to all bits.
1101     DemandedBits = APInt::getAllOnes(BitWidth);
1102     DemandedElts = APInt::getAllOnes(NumElts);
1103   } else if (OriginalDemandedBits == 0 || OriginalDemandedElts == 0) {
1104     // Not demanding any bits/elts from Op.
1105     return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT));
1106   } else if (Depth >= SelectionDAG::MaxRecursionDepth) {
1107     // Limit search depth.
1108     return false;
1109   }
1110 
1111   KnownBits Known2;
1112   switch (Op.getOpcode()) {
1113   case ISD::TargetConstant:
1114     llvm_unreachable("Can't simplify this node");
1115   case ISD::SCALAR_TO_VECTOR: {
1116     if (!DemandedElts[0])
1117       return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT));
1118 
1119     KnownBits SrcKnown;
1120     SDValue Src = Op.getOperand(0);
1121     unsigned SrcBitWidth = Src.getScalarValueSizeInBits();
1122     APInt SrcDemandedBits = DemandedBits.zext(SrcBitWidth);
1123     if (SimplifyDemandedBits(Src, SrcDemandedBits, SrcKnown, TLO, Depth + 1))
1124       return true;
1125 
1126     // Upper elements are undef, so only get the knownbits if we just demand
1127     // the bottom element.
1128     if (DemandedElts == 1)
1129       Known = SrcKnown.anyextOrTrunc(BitWidth);
1130     break;
1131   }
1132   case ISD::BUILD_VECTOR:
1133     // Collect the known bits that are shared by every demanded element.
1134     // TODO: Call SimplifyDemandedBits for non-constant demanded elements.
1135     Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth);
1136     return false; // Don't fall through, will infinitely loop.
1137   case ISD::LOAD: {
1138     auto *LD = cast<LoadSDNode>(Op);
1139     if (getTargetConstantFromLoad(LD)) {
1140       Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth);
1141       return false; // Don't fall through, will infinitely loop.
1142     }
1143     if (ISD::isZEXTLoad(Op.getNode()) && Op.getResNo() == 0) {
1144       // If this is a ZEXTLoad and we are looking at the loaded value.
1145       EVT MemVT = LD->getMemoryVT();
1146       unsigned MemBits = MemVT.getScalarSizeInBits();
1147       Known.Zero.setBitsFrom(MemBits);
1148       return false; // Don't fall through, will infinitely loop.
1149     }
1150     break;
1151   }
1152   case ISD::INSERT_VECTOR_ELT: {
1153     SDValue Vec = Op.getOperand(0);
1154     SDValue Scl = Op.getOperand(1);
1155     auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2));
1156     EVT VecVT = Vec.getValueType();
1157 
1158     // If index isn't constant, assume we need all vector elements AND the
1159     // inserted element.
1160     APInt DemandedVecElts(DemandedElts);
1161     if (CIdx && CIdx->getAPIntValue().ult(VecVT.getVectorNumElements())) {
1162       unsigned Idx = CIdx->getZExtValue();
1163       DemandedVecElts.clearBit(Idx);
1164 
1165       // Inserted element is not required.
1166       if (!DemandedElts[Idx])
1167         return TLO.CombineTo(Op, Vec);
1168     }
1169 
1170     KnownBits KnownScl;
1171     unsigned NumSclBits = Scl.getScalarValueSizeInBits();
1172     APInt DemandedSclBits = DemandedBits.zextOrTrunc(NumSclBits);
1173     if (SimplifyDemandedBits(Scl, DemandedSclBits, KnownScl, TLO, Depth + 1))
1174       return true;
1175 
1176     Known = KnownScl.anyextOrTrunc(BitWidth);
1177 
1178     KnownBits KnownVec;
1179     if (SimplifyDemandedBits(Vec, DemandedBits, DemandedVecElts, KnownVec, TLO,
1180                              Depth + 1))
1181       return true;
1182 
1183     if (!!DemandedVecElts)
1184       Known = KnownBits::commonBits(Known, KnownVec);
1185 
1186     return false;
1187   }
1188   case ISD::INSERT_SUBVECTOR: {
1189     // Demand any elements from the subvector and the remainder from the src its
1190     // inserted into.
1191     SDValue Src = Op.getOperand(0);
1192     SDValue Sub = Op.getOperand(1);
1193     uint64_t Idx = Op.getConstantOperandVal(2);
1194     unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
1195     APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
1196     APInt DemandedSrcElts = DemandedElts;
1197     DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx);
1198 
1199     KnownBits KnownSub, KnownSrc;
1200     if (SimplifyDemandedBits(Sub, DemandedBits, DemandedSubElts, KnownSub, TLO,
1201                              Depth + 1))
1202       return true;
1203     if (SimplifyDemandedBits(Src, DemandedBits, DemandedSrcElts, KnownSrc, TLO,
1204                              Depth + 1))
1205       return true;
1206 
1207     Known.Zero.setAllBits();
1208     Known.One.setAllBits();
1209     if (!!DemandedSubElts)
1210       Known = KnownBits::commonBits(Known, KnownSub);
1211     if (!!DemandedSrcElts)
1212       Known = KnownBits::commonBits(Known, KnownSrc);
1213 
1214     // Attempt to avoid multi-use src if we don't need anything from it.
1215     if (!DemandedBits.isAllOnes() || !DemandedSubElts.isAllOnes() ||
1216         !DemandedSrcElts.isAllOnes()) {
1217       SDValue NewSub = SimplifyMultipleUseDemandedBits(
1218           Sub, DemandedBits, DemandedSubElts, TLO.DAG, Depth + 1);
1219       SDValue NewSrc = SimplifyMultipleUseDemandedBits(
1220           Src, DemandedBits, DemandedSrcElts, TLO.DAG, Depth + 1);
1221       if (NewSub || NewSrc) {
1222         NewSub = NewSub ? NewSub : Sub;
1223         NewSrc = NewSrc ? NewSrc : Src;
1224         SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, NewSrc, NewSub,
1225                                         Op.getOperand(2));
1226         return TLO.CombineTo(Op, NewOp);
1227       }
1228     }
1229     break;
1230   }
1231   case ISD::EXTRACT_SUBVECTOR: {
1232     // Offset the demanded elts by the subvector index.
1233     SDValue Src = Op.getOperand(0);
1234     if (Src.getValueType().isScalableVector())
1235       break;
1236     uint64_t Idx = Op.getConstantOperandVal(1);
1237     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
1238     APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
1239 
1240     if (SimplifyDemandedBits(Src, DemandedBits, DemandedSrcElts, Known, TLO,
1241                              Depth + 1))
1242       return true;
1243 
1244     // Attempt to avoid multi-use src if we don't need anything from it.
1245     if (!DemandedBits.isAllOnes() || !DemandedSrcElts.isAllOnes()) {
1246       SDValue DemandedSrc = SimplifyMultipleUseDemandedBits(
1247           Src, DemandedBits, DemandedSrcElts, TLO.DAG, Depth + 1);
1248       if (DemandedSrc) {
1249         SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, DemandedSrc,
1250                                         Op.getOperand(1));
1251         return TLO.CombineTo(Op, NewOp);
1252       }
1253     }
1254     break;
1255   }
1256   case ISD::CONCAT_VECTORS: {
1257     Known.Zero.setAllBits();
1258     Known.One.setAllBits();
1259     EVT SubVT = Op.getOperand(0).getValueType();
1260     unsigned NumSubVecs = Op.getNumOperands();
1261     unsigned NumSubElts = SubVT.getVectorNumElements();
1262     for (unsigned i = 0; i != NumSubVecs; ++i) {
1263       APInt DemandedSubElts =
1264           DemandedElts.extractBits(NumSubElts, i * NumSubElts);
1265       if (SimplifyDemandedBits(Op.getOperand(i), DemandedBits, DemandedSubElts,
1266                                Known2, TLO, Depth + 1))
1267         return true;
1268       // Known bits are shared by every demanded subvector element.
1269       if (!!DemandedSubElts)
1270         Known = KnownBits::commonBits(Known, Known2);
1271     }
1272     break;
1273   }
1274   case ISD::VECTOR_SHUFFLE: {
1275     ArrayRef<int> ShuffleMask = cast<ShuffleVectorSDNode>(Op)->getMask();
1276 
1277     // Collect demanded elements from shuffle operands..
1278     APInt DemandedLHS(NumElts, 0);
1279     APInt DemandedRHS(NumElts, 0);
1280     for (unsigned i = 0; i != NumElts; ++i) {
1281       if (!DemandedElts[i])
1282         continue;
1283       int M = ShuffleMask[i];
1284       if (M < 0) {
1285         // For UNDEF elements, we don't know anything about the common state of
1286         // the shuffle result.
1287         DemandedLHS.clearAllBits();
1288         DemandedRHS.clearAllBits();
1289         break;
1290       }
1291       assert(0 <= M && M < (int)(2 * NumElts) && "Shuffle index out of range");
1292       if (M < (int)NumElts)
1293         DemandedLHS.setBit(M);
1294       else
1295         DemandedRHS.setBit(M - NumElts);
1296     }
1297 
1298     if (!!DemandedLHS || !!DemandedRHS) {
1299       SDValue Op0 = Op.getOperand(0);
1300       SDValue Op1 = Op.getOperand(1);
1301 
1302       Known.Zero.setAllBits();
1303       Known.One.setAllBits();
1304       if (!!DemandedLHS) {
1305         if (SimplifyDemandedBits(Op0, DemandedBits, DemandedLHS, Known2, TLO,
1306                                  Depth + 1))
1307           return true;
1308         Known = KnownBits::commonBits(Known, Known2);
1309       }
1310       if (!!DemandedRHS) {
1311         if (SimplifyDemandedBits(Op1, DemandedBits, DemandedRHS, Known2, TLO,
1312                                  Depth + 1))
1313           return true;
1314         Known = KnownBits::commonBits(Known, Known2);
1315       }
1316 
1317       // Attempt to avoid multi-use ops if we don't need anything from them.
1318       SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits(
1319           Op0, DemandedBits, DemandedLHS, TLO.DAG, Depth + 1);
1320       SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits(
1321           Op1, DemandedBits, DemandedRHS, TLO.DAG, Depth + 1);
1322       if (DemandedOp0 || DemandedOp1) {
1323         Op0 = DemandedOp0 ? DemandedOp0 : Op0;
1324         Op1 = DemandedOp1 ? DemandedOp1 : Op1;
1325         SDValue NewOp = TLO.DAG.getVectorShuffle(VT, dl, Op0, Op1, ShuffleMask);
1326         return TLO.CombineTo(Op, NewOp);
1327       }
1328     }
1329     break;
1330   }
1331   case ISD::AND: {
1332     SDValue Op0 = Op.getOperand(0);
1333     SDValue Op1 = Op.getOperand(1);
1334 
1335     // If the RHS is a constant, check to see if the LHS would be zero without
1336     // using the bits from the RHS.  Below, we use knowledge about the RHS to
1337     // simplify the LHS, here we're using information from the LHS to simplify
1338     // the RHS.
1339     if (ConstantSDNode *RHSC = isConstOrConstSplat(Op1)) {
1340       // Do not increment Depth here; that can cause an infinite loop.
1341       KnownBits LHSKnown = TLO.DAG.computeKnownBits(Op0, DemandedElts, Depth);
1342       // If the LHS already has zeros where RHSC does, this 'and' is dead.
1343       if ((LHSKnown.Zero & DemandedBits) ==
1344           (~RHSC->getAPIntValue() & DemandedBits))
1345         return TLO.CombineTo(Op, Op0);
1346 
1347       // If any of the set bits in the RHS are known zero on the LHS, shrink
1348       // the constant.
1349       if (ShrinkDemandedConstant(Op, ~LHSKnown.Zero & DemandedBits,
1350                                  DemandedElts, TLO))
1351         return true;
1352 
1353       // Bitwise-not (xor X, -1) is a special case: we don't usually shrink its
1354       // constant, but if this 'and' is only clearing bits that were just set by
1355       // the xor, then this 'and' can be eliminated by shrinking the mask of
1356       // the xor. For example, for a 32-bit X:
1357       // and (xor (srl X, 31), -1), 1 --> xor (srl X, 31), 1
1358       if (isBitwiseNot(Op0) && Op0.hasOneUse() &&
1359           LHSKnown.One == ~RHSC->getAPIntValue()) {
1360         SDValue Xor = TLO.DAG.getNode(ISD::XOR, dl, VT, Op0.getOperand(0), Op1);
1361         return TLO.CombineTo(Op, Xor);
1362       }
1363     }
1364 
1365     if (SimplifyDemandedBits(Op1, DemandedBits, DemandedElts, Known, TLO,
1366                              Depth + 1))
1367       return true;
1368     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
1369     if (SimplifyDemandedBits(Op0, ~Known.Zero & DemandedBits, DemandedElts,
1370                              Known2, TLO, Depth + 1))
1371       return true;
1372     assert(!Known2.hasConflict() && "Bits known to be one AND zero?");
1373 
1374     // Attempt to avoid multi-use ops if we don't need anything from them.
1375     if (!DemandedBits.isAllOnes() || !DemandedElts.isAllOnes()) {
1376       SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits(
1377           Op0, DemandedBits, DemandedElts, TLO.DAG, Depth + 1);
1378       SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits(
1379           Op1, DemandedBits, DemandedElts, TLO.DAG, Depth + 1);
1380       if (DemandedOp0 || DemandedOp1) {
1381         Op0 = DemandedOp0 ? DemandedOp0 : Op0;
1382         Op1 = DemandedOp1 ? DemandedOp1 : Op1;
1383         SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1);
1384         return TLO.CombineTo(Op, NewOp);
1385       }
1386     }
1387 
1388     // If all of the demanded bits are known one on one side, return the other.
1389     // These bits cannot contribute to the result of the 'and'.
1390     if (DemandedBits.isSubsetOf(Known2.Zero | Known.One))
1391       return TLO.CombineTo(Op, Op0);
1392     if (DemandedBits.isSubsetOf(Known.Zero | Known2.One))
1393       return TLO.CombineTo(Op, Op1);
1394     // If all of the demanded bits in the inputs are known zeros, return zero.
1395     if (DemandedBits.isSubsetOf(Known.Zero | Known2.Zero))
1396       return TLO.CombineTo(Op, TLO.DAG.getConstant(0, dl, VT));
1397     // If the RHS is a constant, see if we can simplify it.
1398     if (ShrinkDemandedConstant(Op, ~Known2.Zero & DemandedBits, DemandedElts,
1399                                TLO))
1400       return true;
1401     // If the operation can be done in a smaller type, do so.
1402     if (ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO))
1403       return true;
1404 
1405     Known &= Known2;
1406     break;
1407   }
1408   case ISD::OR: {
1409     SDValue Op0 = Op.getOperand(0);
1410     SDValue Op1 = Op.getOperand(1);
1411 
1412     if (SimplifyDemandedBits(Op1, DemandedBits, DemandedElts, Known, TLO,
1413                              Depth + 1))
1414       return true;
1415     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
1416     if (SimplifyDemandedBits(Op0, ~Known.One & DemandedBits, DemandedElts,
1417                              Known2, TLO, Depth + 1))
1418       return true;
1419     assert(!Known2.hasConflict() && "Bits known to be one AND zero?");
1420 
1421     // Attempt to avoid multi-use ops if we don't need anything from them.
1422     if (!DemandedBits.isAllOnes() || !DemandedElts.isAllOnes()) {
1423       SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits(
1424           Op0, DemandedBits, DemandedElts, TLO.DAG, Depth + 1);
1425       SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits(
1426           Op1, DemandedBits, DemandedElts, TLO.DAG, Depth + 1);
1427       if (DemandedOp0 || DemandedOp1) {
1428         Op0 = DemandedOp0 ? DemandedOp0 : Op0;
1429         Op1 = DemandedOp1 ? DemandedOp1 : Op1;
1430         SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1);
1431         return TLO.CombineTo(Op, NewOp);
1432       }
1433     }
1434 
1435     // If all of the demanded bits are known zero on one side, return the other.
1436     // These bits cannot contribute to the result of the 'or'.
1437     if (DemandedBits.isSubsetOf(Known2.One | Known.Zero))
1438       return TLO.CombineTo(Op, Op0);
1439     if (DemandedBits.isSubsetOf(Known.One | Known2.Zero))
1440       return TLO.CombineTo(Op, Op1);
1441     // If the RHS is a constant, see if we can simplify it.
1442     if (ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO))
1443       return true;
1444     // If the operation can be done in a smaller type, do so.
1445     if (ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO))
1446       return true;
1447 
1448     Known |= Known2;
1449     break;
1450   }
1451   case ISD::XOR: {
1452     SDValue Op0 = Op.getOperand(0);
1453     SDValue Op1 = Op.getOperand(1);
1454 
1455     if (SimplifyDemandedBits(Op1, DemandedBits, DemandedElts, Known, TLO,
1456                              Depth + 1))
1457       return true;
1458     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
1459     if (SimplifyDemandedBits(Op0, DemandedBits, DemandedElts, Known2, TLO,
1460                              Depth + 1))
1461       return true;
1462     assert(!Known2.hasConflict() && "Bits known to be one AND zero?");
1463 
1464     // Attempt to avoid multi-use ops if we don't need anything from them.
1465     if (!DemandedBits.isAllOnes() || !DemandedElts.isAllOnes()) {
1466       SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits(
1467           Op0, DemandedBits, DemandedElts, TLO.DAG, Depth + 1);
1468       SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits(
1469           Op1, DemandedBits, DemandedElts, TLO.DAG, Depth + 1);
1470       if (DemandedOp0 || DemandedOp1) {
1471         Op0 = DemandedOp0 ? DemandedOp0 : Op0;
1472         Op1 = DemandedOp1 ? DemandedOp1 : Op1;
1473         SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1);
1474         return TLO.CombineTo(Op, NewOp);
1475       }
1476     }
1477 
1478     // If all of the demanded bits are known zero on one side, return the other.
1479     // These bits cannot contribute to the result of the 'xor'.
1480     if (DemandedBits.isSubsetOf(Known.Zero))
1481       return TLO.CombineTo(Op, Op0);
1482     if (DemandedBits.isSubsetOf(Known2.Zero))
1483       return TLO.CombineTo(Op, Op1);
1484     // If the operation can be done in a smaller type, do so.
1485     if (ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO))
1486       return true;
1487 
1488     // If all of the unknown bits are known to be zero on one side or the other
1489     // turn this into an *inclusive* or.
1490     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1491     if (DemandedBits.isSubsetOf(Known.Zero | Known2.Zero))
1492       return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::OR, dl, VT, Op0, Op1));
1493 
1494     ConstantSDNode* C = isConstOrConstSplat(Op1, DemandedElts);
1495     if (C) {
1496       // If one side is a constant, and all of the set bits in the constant are
1497       // also known set on the other side, turn this into an AND, as we know
1498       // the bits will be cleared.
1499       //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1500       // NB: it is okay if more bits are known than are requested
1501       if (C->getAPIntValue() == Known2.One) {
1502         SDValue ANDC =
1503             TLO.DAG.getConstant(~C->getAPIntValue() & DemandedBits, dl, VT);
1504         return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::AND, dl, VT, Op0, ANDC));
1505       }
1506 
1507       // If the RHS is a constant, see if we can change it. Don't alter a -1
1508       // constant because that's a 'not' op, and that is better for combining
1509       // and codegen.
1510       if (!C->isAllOnes() && DemandedBits.isSubsetOf(C->getAPIntValue())) {
1511         // We're flipping all demanded bits. Flip the undemanded bits too.
1512         SDValue New = TLO.DAG.getNOT(dl, Op0, VT);
1513         return TLO.CombineTo(Op, New);
1514       }
1515     }
1516 
1517     // If we can't turn this into a 'not', try to shrink the constant.
1518     if (!C || !C->isAllOnes())
1519       if (ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO))
1520         return true;
1521 
1522     Known ^= Known2;
1523     break;
1524   }
1525   case ISD::SELECT:
1526     if (SimplifyDemandedBits(Op.getOperand(2), DemandedBits, Known, TLO,
1527                              Depth + 1))
1528       return true;
1529     if (SimplifyDemandedBits(Op.getOperand(1), DemandedBits, Known2, TLO,
1530                              Depth + 1))
1531       return true;
1532     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
1533     assert(!Known2.hasConflict() && "Bits known to be one AND zero?");
1534 
1535     // If the operands are constants, see if we can simplify them.
1536     if (ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO))
1537       return true;
1538 
1539     // Only known if known in both the LHS and RHS.
1540     Known = KnownBits::commonBits(Known, Known2);
1541     break;
1542   case ISD::VSELECT:
1543     if (SimplifyDemandedBits(Op.getOperand(2), DemandedBits, DemandedElts,
1544                              Known, TLO, Depth + 1))
1545       return true;
1546     if (SimplifyDemandedBits(Op.getOperand(1), DemandedBits, DemandedElts,
1547                              Known2, TLO, Depth + 1))
1548       return true;
1549     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
1550     assert(!Known2.hasConflict() && "Bits known to be one AND zero?");
1551 
1552     // Only known if known in both the LHS and RHS.
1553     Known = KnownBits::commonBits(Known, Known2);
1554     break;
1555   case ISD::SELECT_CC:
1556     if (SimplifyDemandedBits(Op.getOperand(3), DemandedBits, Known, TLO,
1557                              Depth + 1))
1558       return true;
1559     if (SimplifyDemandedBits(Op.getOperand(2), DemandedBits, Known2, TLO,
1560                              Depth + 1))
1561       return true;
1562     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
1563     assert(!Known2.hasConflict() && "Bits known to be one AND zero?");
1564 
1565     // If the operands are constants, see if we can simplify them.
1566     if (ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO))
1567       return true;
1568 
1569     // Only known if known in both the LHS and RHS.
1570     Known = KnownBits::commonBits(Known, Known2);
1571     break;
1572   case ISD::SETCC: {
1573     SDValue Op0 = Op.getOperand(0);
1574     SDValue Op1 = Op.getOperand(1);
1575     ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
1576     // If (1) we only need the sign-bit, (2) the setcc operands are the same
1577     // width as the setcc result, and (3) the result of a setcc conforms to 0 or
1578     // -1, we may be able to bypass the setcc.
1579     if (DemandedBits.isSignMask() &&
1580         Op0.getScalarValueSizeInBits() == BitWidth &&
1581         getBooleanContents(Op0.getValueType()) ==
1582             BooleanContent::ZeroOrNegativeOneBooleanContent) {
1583       // If we're testing X < 0, then this compare isn't needed - just use X!
1584       // FIXME: We're limiting to integer types here, but this should also work
1585       // if we don't care about FP signed-zero. The use of SETLT with FP means
1586       // that we don't care about NaNs.
1587       if (CC == ISD::SETLT && Op1.getValueType().isInteger() &&
1588           (isNullConstant(Op1) || ISD::isBuildVectorAllZeros(Op1.getNode())))
1589         return TLO.CombineTo(Op, Op0);
1590 
1591       // TODO: Should we check for other forms of sign-bit comparisons?
1592       // Examples: X <= -1, X >= 0
1593     }
1594     if (getBooleanContents(Op0.getValueType()) ==
1595             TargetLowering::ZeroOrOneBooleanContent &&
1596         BitWidth > 1)
1597       Known.Zero.setBitsFrom(1);
1598     break;
1599   }
1600   case ISD::SHL: {
1601     SDValue Op0 = Op.getOperand(0);
1602     SDValue Op1 = Op.getOperand(1);
1603     EVT ShiftVT = Op1.getValueType();
1604 
1605     if (const APInt *SA =
1606             TLO.DAG.getValidShiftAmountConstant(Op, DemandedElts)) {
1607       unsigned ShAmt = SA->getZExtValue();
1608       if (ShAmt == 0)
1609         return TLO.CombineTo(Op, Op0);
1610 
1611       // If this is ((X >>u C1) << ShAmt), see if we can simplify this into a
1612       // single shift.  We can do this if the bottom bits (which are shifted
1613       // out) are never demanded.
1614       // TODO - support non-uniform vector amounts.
1615       if (Op0.getOpcode() == ISD::SRL) {
1616         if (!DemandedBits.intersects(APInt::getLowBitsSet(BitWidth, ShAmt))) {
1617           if (const APInt *SA2 =
1618                   TLO.DAG.getValidShiftAmountConstant(Op0, DemandedElts)) {
1619             unsigned C1 = SA2->getZExtValue();
1620             unsigned Opc = ISD::SHL;
1621             int Diff = ShAmt - C1;
1622             if (Diff < 0) {
1623               Diff = -Diff;
1624               Opc = ISD::SRL;
1625             }
1626             SDValue NewSA = TLO.DAG.getConstant(Diff, dl, ShiftVT);
1627             return TLO.CombineTo(
1628                 Op, TLO.DAG.getNode(Opc, dl, VT, Op0.getOperand(0), NewSA));
1629           }
1630         }
1631       }
1632 
1633       // Convert (shl (anyext x, c)) to (anyext (shl x, c)) if the high bits
1634       // are not demanded. This will likely allow the anyext to be folded away.
1635       // TODO - support non-uniform vector amounts.
1636       if (Op0.getOpcode() == ISD::ANY_EXTEND) {
1637         SDValue InnerOp = Op0.getOperand(0);
1638         EVT InnerVT = InnerOp.getValueType();
1639         unsigned InnerBits = InnerVT.getScalarSizeInBits();
1640         if (ShAmt < InnerBits && DemandedBits.getActiveBits() <= InnerBits &&
1641             isTypeDesirableForOp(ISD::SHL, InnerVT)) {
1642           EVT ShTy = getShiftAmountTy(InnerVT, DL);
1643           if (!APInt(BitWidth, ShAmt).isIntN(ShTy.getSizeInBits()))
1644             ShTy = InnerVT;
1645           SDValue NarrowShl =
1646               TLO.DAG.getNode(ISD::SHL, dl, InnerVT, InnerOp,
1647                               TLO.DAG.getConstant(ShAmt, dl, ShTy));
1648           return TLO.CombineTo(
1649               Op, TLO.DAG.getNode(ISD::ANY_EXTEND, dl, VT, NarrowShl));
1650         }
1651 
1652         // Repeat the SHL optimization above in cases where an extension
1653         // intervenes: (shl (anyext (shr x, c1)), c2) to
1654         // (shl (anyext x), c2-c1).  This requires that the bottom c1 bits
1655         // aren't demanded (as above) and that the shifted upper c1 bits of
1656         // x aren't demanded.
1657         // TODO - support non-uniform vector amounts.
1658         if (Op0.hasOneUse() && InnerOp.getOpcode() == ISD::SRL &&
1659             InnerOp.hasOneUse()) {
1660           if (const APInt *SA2 =
1661                   TLO.DAG.getValidShiftAmountConstant(InnerOp, DemandedElts)) {
1662             unsigned InnerShAmt = SA2->getZExtValue();
1663             if (InnerShAmt < ShAmt && InnerShAmt < InnerBits &&
1664                 DemandedBits.getActiveBits() <=
1665                     (InnerBits - InnerShAmt + ShAmt) &&
1666                 DemandedBits.countTrailingZeros() >= ShAmt) {
1667               SDValue NewSA =
1668                   TLO.DAG.getConstant(ShAmt - InnerShAmt, dl, ShiftVT);
1669               SDValue NewExt = TLO.DAG.getNode(ISD::ANY_EXTEND, dl, VT,
1670                                                InnerOp.getOperand(0));
1671               return TLO.CombineTo(
1672                   Op, TLO.DAG.getNode(ISD::SHL, dl, VT, NewExt, NewSA));
1673             }
1674           }
1675         }
1676       }
1677 
1678       APInt InDemandedMask = DemandedBits.lshr(ShAmt);
1679       if (SimplifyDemandedBits(Op0, InDemandedMask, DemandedElts, Known, TLO,
1680                                Depth + 1))
1681         return true;
1682       assert(!Known.hasConflict() && "Bits known to be one AND zero?");
1683       Known.Zero <<= ShAmt;
1684       Known.One <<= ShAmt;
1685       // low bits known zero.
1686       Known.Zero.setLowBits(ShAmt);
1687 
1688       // Attempt to avoid multi-use ops if we don't need anything from them.
1689       if (!InDemandedMask.isAllOnesValue() || !DemandedElts.isAllOnesValue()) {
1690         SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits(
1691             Op0, InDemandedMask, DemandedElts, TLO.DAG, Depth + 1);
1692         if (DemandedOp0) {
1693           SDValue NewOp = TLO.DAG.getNode(ISD::SHL, dl, VT, DemandedOp0, Op1);
1694           return TLO.CombineTo(Op, NewOp);
1695         }
1696       }
1697 
1698       // Try shrinking the operation as long as the shift amount will still be
1699       // in range.
1700       if ((ShAmt < DemandedBits.getActiveBits()) &&
1701           ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO))
1702         return true;
1703     }
1704 
1705     // If we are only demanding sign bits then we can use the shift source
1706     // directly.
1707     if (const APInt *MaxSA =
1708             TLO.DAG.getValidMaximumShiftAmountConstant(Op, DemandedElts)) {
1709       unsigned ShAmt = MaxSA->getZExtValue();
1710       unsigned NumSignBits =
1711           TLO.DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1);
1712       unsigned UpperDemandedBits = BitWidth - DemandedBits.countTrailingZeros();
1713       if (NumSignBits > ShAmt && (NumSignBits - ShAmt) >= (UpperDemandedBits))
1714         return TLO.CombineTo(Op, Op0);
1715     }
1716     break;
1717   }
1718   case ISD::SRL: {
1719     SDValue Op0 = Op.getOperand(0);
1720     SDValue Op1 = Op.getOperand(1);
1721     EVT ShiftVT = Op1.getValueType();
1722 
1723     // Try to match AVG patterns.
1724     if (SDValue AVG = combineShiftToAVG(Op, TLO.DAG, *this, DemandedBits,
1725                                         DemandedElts, Depth + 1))
1726       return TLO.CombineTo(Op, AVG);
1727 
1728     if (const APInt *SA =
1729             TLO.DAG.getValidShiftAmountConstant(Op, DemandedElts)) {
1730       unsigned ShAmt = SA->getZExtValue();
1731       if (ShAmt == 0)
1732         return TLO.CombineTo(Op, Op0);
1733 
1734       // If this is ((X << C1) >>u ShAmt), see if we can simplify this into a
1735       // single shift.  We can do this if the top bits (which are shifted out)
1736       // are never demanded.
1737       // TODO - support non-uniform vector amounts.
1738       if (Op0.getOpcode() == ISD::SHL) {
1739         if (!DemandedBits.intersects(APInt::getHighBitsSet(BitWidth, ShAmt))) {
1740           if (const APInt *SA2 =
1741                   TLO.DAG.getValidShiftAmountConstant(Op0, DemandedElts)) {
1742             unsigned C1 = SA2->getZExtValue();
1743             unsigned Opc = ISD::SRL;
1744             int Diff = ShAmt - C1;
1745             if (Diff < 0) {
1746               Diff = -Diff;
1747               Opc = ISD::SHL;
1748             }
1749             SDValue NewSA = TLO.DAG.getConstant(Diff, dl, ShiftVT);
1750             return TLO.CombineTo(
1751                 Op, TLO.DAG.getNode(Opc, dl, VT, Op0.getOperand(0), NewSA));
1752           }
1753         }
1754       }
1755 
1756       APInt InDemandedMask = (DemandedBits << ShAmt);
1757 
1758       // If the shift is exact, then it does demand the low bits (and knows that
1759       // they are zero).
1760       if (Op->getFlags().hasExact())
1761         InDemandedMask.setLowBits(ShAmt);
1762 
1763       // Compute the new bits that are at the top now.
1764       if (SimplifyDemandedBits(Op0, InDemandedMask, DemandedElts, Known, TLO,
1765                                Depth + 1))
1766         return true;
1767       assert(!Known.hasConflict() && "Bits known to be one AND zero?");
1768       Known.Zero.lshrInPlace(ShAmt);
1769       Known.One.lshrInPlace(ShAmt);
1770       // High bits known zero.
1771       Known.Zero.setHighBits(ShAmt);
1772     }
1773     break;
1774   }
1775   case ISD::SRA: {
1776     SDValue Op0 = Op.getOperand(0);
1777     SDValue Op1 = Op.getOperand(1);
1778     EVT ShiftVT = Op1.getValueType();
1779 
1780     // If we only want bits that already match the signbit then we don't need
1781     // to shift.
1782     unsigned NumHiDemandedBits = BitWidth - DemandedBits.countTrailingZeros();
1783     if (TLO.DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1) >=
1784         NumHiDemandedBits)
1785       return TLO.CombineTo(Op, Op0);
1786 
1787     // If this is an arithmetic shift right and only the low-bit is set, we can
1788     // always convert this into a logical shr, even if the shift amount is
1789     // variable.  The low bit of the shift cannot be an input sign bit unless
1790     // the shift amount is >= the size of the datatype, which is undefined.
1791     if (DemandedBits.isOne())
1792       return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, Op1));
1793 
1794     // Try to match AVG patterns.
1795     if (SDValue AVG = combineShiftToAVG(Op, TLO.DAG, *this, DemandedBits,
1796                                         DemandedElts, Depth + 1))
1797       return TLO.CombineTo(Op, AVG);
1798 
1799     if (const APInt *SA =
1800             TLO.DAG.getValidShiftAmountConstant(Op, DemandedElts)) {
1801       unsigned ShAmt = SA->getZExtValue();
1802       if (ShAmt == 0)
1803         return TLO.CombineTo(Op, Op0);
1804 
1805       APInt InDemandedMask = (DemandedBits << ShAmt);
1806 
1807       // If the shift is exact, then it does demand the low bits (and knows that
1808       // they are zero).
1809       if (Op->getFlags().hasExact())
1810         InDemandedMask.setLowBits(ShAmt);
1811 
1812       // If any of the demanded bits are produced by the sign extension, we also
1813       // demand the input sign bit.
1814       if (DemandedBits.countLeadingZeros() < ShAmt)
1815         InDemandedMask.setSignBit();
1816 
1817       if (SimplifyDemandedBits(Op0, InDemandedMask, DemandedElts, Known, TLO,
1818                                Depth + 1))
1819         return true;
1820       assert(!Known.hasConflict() && "Bits known to be one AND zero?");
1821       Known.Zero.lshrInPlace(ShAmt);
1822       Known.One.lshrInPlace(ShAmt);
1823 
1824       // If the input sign bit is known to be zero, or if none of the top bits
1825       // are demanded, turn this into an unsigned shift right.
1826       if (Known.Zero[BitWidth - ShAmt - 1] ||
1827           DemandedBits.countLeadingZeros() >= ShAmt) {
1828         SDNodeFlags Flags;
1829         Flags.setExact(Op->getFlags().hasExact());
1830         return TLO.CombineTo(
1831             Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, Op1, Flags));
1832       }
1833 
1834       int Log2 = DemandedBits.exactLogBase2();
1835       if (Log2 >= 0) {
1836         // The bit must come from the sign.
1837         SDValue NewSA = TLO.DAG.getConstant(BitWidth - 1 - Log2, dl, ShiftVT);
1838         return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, NewSA));
1839       }
1840 
1841       if (Known.One[BitWidth - ShAmt - 1])
1842         // New bits are known one.
1843         Known.One.setHighBits(ShAmt);
1844 
1845       // Attempt to avoid multi-use ops if we don't need anything from them.
1846       if (!InDemandedMask.isAllOnes() || !DemandedElts.isAllOnes()) {
1847         SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits(
1848             Op0, InDemandedMask, DemandedElts, TLO.DAG, Depth + 1);
1849         if (DemandedOp0) {
1850           SDValue NewOp = TLO.DAG.getNode(ISD::SRA, dl, VT, DemandedOp0, Op1);
1851           return TLO.CombineTo(Op, NewOp);
1852         }
1853       }
1854     }
1855     break;
1856   }
1857   case ISD::FSHL:
1858   case ISD::FSHR: {
1859     SDValue Op0 = Op.getOperand(0);
1860     SDValue Op1 = Op.getOperand(1);
1861     SDValue Op2 = Op.getOperand(2);
1862     bool IsFSHL = (Op.getOpcode() == ISD::FSHL);
1863 
1864     if (ConstantSDNode *SA = isConstOrConstSplat(Op2, DemandedElts)) {
1865       unsigned Amt = SA->getAPIntValue().urem(BitWidth);
1866 
1867       // For fshl, 0-shift returns the 1st arg.
1868       // For fshr, 0-shift returns the 2nd arg.
1869       if (Amt == 0) {
1870         if (SimplifyDemandedBits(IsFSHL ? Op0 : Op1, DemandedBits, DemandedElts,
1871                                  Known, TLO, Depth + 1))
1872           return true;
1873         break;
1874       }
1875 
1876       // fshl: (Op0 << Amt) | (Op1 >> (BW - Amt))
1877       // fshr: (Op0 << (BW - Amt)) | (Op1 >> Amt)
1878       APInt Demanded0 = DemandedBits.lshr(IsFSHL ? Amt : (BitWidth - Amt));
1879       APInt Demanded1 = DemandedBits << (IsFSHL ? (BitWidth - Amt) : Amt);
1880       if (SimplifyDemandedBits(Op0, Demanded0, DemandedElts, Known2, TLO,
1881                                Depth + 1))
1882         return true;
1883       if (SimplifyDemandedBits(Op1, Demanded1, DemandedElts, Known, TLO,
1884                                Depth + 1))
1885         return true;
1886 
1887       Known2.One <<= (IsFSHL ? Amt : (BitWidth - Amt));
1888       Known2.Zero <<= (IsFSHL ? Amt : (BitWidth - Amt));
1889       Known.One.lshrInPlace(IsFSHL ? (BitWidth - Amt) : Amt);
1890       Known.Zero.lshrInPlace(IsFSHL ? (BitWidth - Amt) : Amt);
1891       Known.One |= Known2.One;
1892       Known.Zero |= Known2.Zero;
1893 
1894       // Attempt to avoid multi-use ops if we don't need anything from them.
1895       if (!Demanded0.isAllOnes() || !Demanded1.isAllOnes() ||
1896           !DemandedElts.isAllOnes()) {
1897         SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits(
1898             Op0, Demanded0, DemandedElts, TLO.DAG, Depth + 1);
1899         SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits(
1900             Op1, Demanded1, DemandedElts, TLO.DAG, Depth + 1);
1901         if (DemandedOp0 || DemandedOp1) {
1902           DemandedOp0 = DemandedOp0 ? DemandedOp0 : Op0;
1903           DemandedOp1 = DemandedOp1 ? DemandedOp1 : Op1;
1904           SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, DemandedOp0,
1905                                           DemandedOp1, Op2);
1906           return TLO.CombineTo(Op, NewOp);
1907         }
1908       }
1909     }
1910 
1911     // For pow-2 bitwidths we only demand the bottom modulo amt bits.
1912     if (isPowerOf2_32(BitWidth)) {
1913       APInt DemandedAmtBits(Op2.getScalarValueSizeInBits(), BitWidth - 1);
1914       if (SimplifyDemandedBits(Op2, DemandedAmtBits, DemandedElts,
1915                                Known2, TLO, Depth + 1))
1916         return true;
1917     }
1918     break;
1919   }
1920   case ISD::ROTL:
1921   case ISD::ROTR: {
1922     SDValue Op0 = Op.getOperand(0);
1923     SDValue Op1 = Op.getOperand(1);
1924     bool IsROTL = (Op.getOpcode() == ISD::ROTL);
1925 
1926     // If we're rotating an 0/-1 value, then it stays an 0/-1 value.
1927     if (BitWidth == TLO.DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1))
1928       return TLO.CombineTo(Op, Op0);
1929 
1930     if (ConstantSDNode *SA = isConstOrConstSplat(Op1, DemandedElts)) {
1931       unsigned Amt = SA->getAPIntValue().urem(BitWidth);
1932       unsigned RevAmt = BitWidth - Amt;
1933 
1934       // rotl: (Op0 << Amt) | (Op0 >> (BW - Amt))
1935       // rotr: (Op0 << (BW - Amt)) | (Op0 >> Amt)
1936       APInt Demanded0 = DemandedBits.rotr(IsROTL ? Amt : RevAmt);
1937       if (SimplifyDemandedBits(Op0, Demanded0, DemandedElts, Known2, TLO,
1938                                Depth + 1))
1939         return true;
1940 
1941       // rot*(x, 0) --> x
1942       if (Amt == 0)
1943         return TLO.CombineTo(Op, Op0);
1944 
1945       // See if we don't demand either half of the rotated bits.
1946       if ((!TLO.LegalOperations() || isOperationLegal(ISD::SHL, VT)) &&
1947           DemandedBits.countTrailingZeros() >= (IsROTL ? Amt : RevAmt)) {
1948         Op1 = TLO.DAG.getConstant(IsROTL ? Amt : RevAmt, dl, Op1.getValueType());
1949         return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SHL, dl, VT, Op0, Op1));
1950       }
1951       if ((!TLO.LegalOperations() || isOperationLegal(ISD::SRL, VT)) &&
1952           DemandedBits.countLeadingZeros() >= (IsROTL ? RevAmt : Amt)) {
1953         Op1 = TLO.DAG.getConstant(IsROTL ? RevAmt : Amt, dl, Op1.getValueType());
1954         return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, Op1));
1955       }
1956     }
1957 
1958     // For pow-2 bitwidths we only demand the bottom modulo amt bits.
1959     if (isPowerOf2_32(BitWidth)) {
1960       APInt DemandedAmtBits(Op1.getScalarValueSizeInBits(), BitWidth - 1);
1961       if (SimplifyDemandedBits(Op1, DemandedAmtBits, DemandedElts, Known2, TLO,
1962                                Depth + 1))
1963         return true;
1964     }
1965     break;
1966   }
1967   case ISD::UMIN: {
1968     // Check if one arg is always less than (or equal) to the other arg.
1969     SDValue Op0 = Op.getOperand(0);
1970     SDValue Op1 = Op.getOperand(1);
1971     KnownBits Known0 = TLO.DAG.computeKnownBits(Op0, DemandedElts, Depth + 1);
1972     KnownBits Known1 = TLO.DAG.computeKnownBits(Op1, DemandedElts, Depth + 1);
1973     Known = KnownBits::umin(Known0, Known1);
1974     if (Optional<bool> IsULE = KnownBits::ule(Known0, Known1))
1975       return TLO.CombineTo(Op, IsULE.getValue() ? Op0 : Op1);
1976     if (Optional<bool> IsULT = KnownBits::ult(Known0, Known1))
1977       return TLO.CombineTo(Op, IsULT.getValue() ? Op0 : Op1);
1978     break;
1979   }
1980   case ISD::UMAX: {
1981     // Check if one arg is always greater than (or equal) to the other arg.
1982     SDValue Op0 = Op.getOperand(0);
1983     SDValue Op1 = Op.getOperand(1);
1984     KnownBits Known0 = TLO.DAG.computeKnownBits(Op0, DemandedElts, Depth + 1);
1985     KnownBits Known1 = TLO.DAG.computeKnownBits(Op1, DemandedElts, Depth + 1);
1986     Known = KnownBits::umax(Known0, Known1);
1987     if (Optional<bool> IsUGE = KnownBits::uge(Known0, Known1))
1988       return TLO.CombineTo(Op, IsUGE.getValue() ? Op0 : Op1);
1989     if (Optional<bool> IsUGT = KnownBits::ugt(Known0, Known1))
1990       return TLO.CombineTo(Op, IsUGT.getValue() ? Op0 : Op1);
1991     break;
1992   }
1993   case ISD::BITREVERSE: {
1994     SDValue Src = Op.getOperand(0);
1995     APInt DemandedSrcBits = DemandedBits.reverseBits();
1996     if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedElts, Known2, TLO,
1997                              Depth + 1))
1998       return true;
1999     Known.One = Known2.One.reverseBits();
2000     Known.Zero = Known2.Zero.reverseBits();
2001     break;
2002   }
2003   case ISD::BSWAP: {
2004     SDValue Src = Op.getOperand(0);
2005 
2006     // If the only bits demanded come from one byte of the bswap result,
2007     // just shift the input byte into position to eliminate the bswap.
2008     unsigned NLZ = DemandedBits.countLeadingZeros();
2009     unsigned NTZ = DemandedBits.countTrailingZeros();
2010 
2011     // Round NTZ down to the next byte.  If we have 11 trailing zeros, then
2012     // we need all the bits down to bit 8.  Likewise, round NLZ.  If we
2013     // have 14 leading zeros, round to 8.
2014     NLZ = alignDown(NLZ, 8);
2015     NTZ = alignDown(NTZ, 8);
2016     // If we need exactly one byte, we can do this transformation.
2017     if (BitWidth - NLZ - NTZ == 8) {
2018       // Replace this with either a left or right shift to get the byte into
2019       // the right place.
2020       unsigned ShiftOpcode = NLZ > NTZ ? ISD::SRL : ISD::SHL;
2021       if (!TLO.LegalOperations() || isOperationLegal(ShiftOpcode, VT)) {
2022         EVT ShiftAmtTy = getShiftAmountTy(VT, DL);
2023         unsigned ShiftAmount = NLZ > NTZ ? NLZ - NTZ : NTZ - NLZ;
2024         SDValue ShAmt = TLO.DAG.getConstant(ShiftAmount, dl, ShiftAmtTy);
2025         SDValue NewOp = TLO.DAG.getNode(ShiftOpcode, dl, VT, Src, ShAmt);
2026         return TLO.CombineTo(Op, NewOp);
2027       }
2028     }
2029 
2030     APInt DemandedSrcBits = DemandedBits.byteSwap();
2031     if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedElts, Known2, TLO,
2032                              Depth + 1))
2033       return true;
2034     Known.One = Known2.One.byteSwap();
2035     Known.Zero = Known2.Zero.byteSwap();
2036     break;
2037   }
2038   case ISD::CTPOP: {
2039     // If only 1 bit is demanded, replace with PARITY as long as we're before
2040     // op legalization.
2041     // FIXME: Limit to scalars for now.
2042     if (DemandedBits.isOne() && !TLO.LegalOps && !VT.isVector())
2043       return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::PARITY, dl, VT,
2044                                                Op.getOperand(0)));
2045 
2046     Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth);
2047     break;
2048   }
2049   case ISD::SIGN_EXTEND_INREG: {
2050     SDValue Op0 = Op.getOperand(0);
2051     EVT ExVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
2052     unsigned ExVTBits = ExVT.getScalarSizeInBits();
2053 
2054     // If we only care about the highest bit, don't bother shifting right.
2055     if (DemandedBits.isSignMask()) {
2056       unsigned MinSignedBits =
2057           TLO.DAG.ComputeMaxSignificantBits(Op0, DemandedElts, Depth + 1);
2058       bool AlreadySignExtended = ExVTBits >= MinSignedBits;
2059       // However if the input is already sign extended we expect the sign
2060       // extension to be dropped altogether later and do not simplify.
2061       if (!AlreadySignExtended) {
2062         // Compute the correct shift amount type, which must be getShiftAmountTy
2063         // for scalar types after legalization.
2064         SDValue ShiftAmt = TLO.DAG.getConstant(BitWidth - ExVTBits, dl,
2065                                                getShiftAmountTy(VT, DL));
2066         return TLO.CombineTo(Op,
2067                              TLO.DAG.getNode(ISD::SHL, dl, VT, Op0, ShiftAmt));
2068       }
2069     }
2070 
2071     // If none of the extended bits are demanded, eliminate the sextinreg.
2072     if (DemandedBits.getActiveBits() <= ExVTBits)
2073       return TLO.CombineTo(Op, Op0);
2074 
2075     APInt InputDemandedBits = DemandedBits.getLoBits(ExVTBits);
2076 
2077     // Since the sign extended bits are demanded, we know that the sign
2078     // bit is demanded.
2079     InputDemandedBits.setBit(ExVTBits - 1);
2080 
2081     if (SimplifyDemandedBits(Op0, InputDemandedBits, DemandedElts, Known, TLO,
2082                              Depth + 1))
2083       return true;
2084     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
2085 
2086     // If the sign bit of the input is known set or clear, then we know the
2087     // top bits of the result.
2088 
2089     // If the input sign bit is known zero, convert this into a zero extension.
2090     if (Known.Zero[ExVTBits - 1])
2091       return TLO.CombineTo(Op, TLO.DAG.getZeroExtendInReg(Op0, dl, ExVT));
2092 
2093     APInt Mask = APInt::getLowBitsSet(BitWidth, ExVTBits);
2094     if (Known.One[ExVTBits - 1]) { // Input sign bit known set
2095       Known.One.setBitsFrom(ExVTBits);
2096       Known.Zero &= Mask;
2097     } else { // Input sign bit unknown
2098       Known.Zero &= Mask;
2099       Known.One &= Mask;
2100     }
2101     break;
2102   }
2103   case ISD::BUILD_PAIR: {
2104     EVT HalfVT = Op.getOperand(0).getValueType();
2105     unsigned HalfBitWidth = HalfVT.getScalarSizeInBits();
2106 
2107     APInt MaskLo = DemandedBits.getLoBits(HalfBitWidth).trunc(HalfBitWidth);
2108     APInt MaskHi = DemandedBits.getHiBits(HalfBitWidth).trunc(HalfBitWidth);
2109 
2110     KnownBits KnownLo, KnownHi;
2111 
2112     if (SimplifyDemandedBits(Op.getOperand(0), MaskLo, KnownLo, TLO, Depth + 1))
2113       return true;
2114 
2115     if (SimplifyDemandedBits(Op.getOperand(1), MaskHi, KnownHi, TLO, Depth + 1))
2116       return true;
2117 
2118     Known.Zero = KnownLo.Zero.zext(BitWidth) |
2119                  KnownHi.Zero.zext(BitWidth).shl(HalfBitWidth);
2120 
2121     Known.One = KnownLo.One.zext(BitWidth) |
2122                 KnownHi.One.zext(BitWidth).shl(HalfBitWidth);
2123     break;
2124   }
2125   case ISD::ZERO_EXTEND:
2126   case ISD::ZERO_EXTEND_VECTOR_INREG: {
2127     SDValue Src = Op.getOperand(0);
2128     EVT SrcVT = Src.getValueType();
2129     unsigned InBits = SrcVT.getScalarSizeInBits();
2130     unsigned InElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1;
2131     bool IsVecInReg = Op.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG;
2132 
2133     // If none of the top bits are demanded, convert this into an any_extend.
2134     if (DemandedBits.getActiveBits() <= InBits) {
2135       // If we only need the non-extended bits of the bottom element
2136       // then we can just bitcast to the result.
2137       if (IsLE && IsVecInReg && DemandedElts == 1 &&
2138           VT.getSizeInBits() == SrcVT.getSizeInBits())
2139         return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src));
2140 
2141       unsigned Opc =
2142           IsVecInReg ? ISD::ANY_EXTEND_VECTOR_INREG : ISD::ANY_EXTEND;
2143       if (!TLO.LegalOperations() || isOperationLegal(Opc, VT))
2144         return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT, Src));
2145     }
2146 
2147     APInt InDemandedBits = DemandedBits.trunc(InBits);
2148     APInt InDemandedElts = DemandedElts.zext(InElts);
2149     if (SimplifyDemandedBits(Src, InDemandedBits, InDemandedElts, Known, TLO,
2150                              Depth + 1))
2151       return true;
2152     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
2153     assert(Known.getBitWidth() == InBits && "Src width has changed?");
2154     Known = Known.zext(BitWidth);
2155 
2156     // Attempt to avoid multi-use ops if we don't need anything from them.
2157     if (SDValue NewSrc = SimplifyMultipleUseDemandedBits(
2158             Src, InDemandedBits, InDemandedElts, TLO.DAG, Depth + 1))
2159       return TLO.CombineTo(Op, TLO.DAG.getNode(Op.getOpcode(), dl, VT, NewSrc));
2160     break;
2161   }
2162   case ISD::SIGN_EXTEND:
2163   case ISD::SIGN_EXTEND_VECTOR_INREG: {
2164     SDValue Src = Op.getOperand(0);
2165     EVT SrcVT = Src.getValueType();
2166     unsigned InBits = SrcVT.getScalarSizeInBits();
2167     unsigned InElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1;
2168     bool IsVecInReg = Op.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG;
2169 
2170     // If none of the top bits are demanded, convert this into an any_extend.
2171     if (DemandedBits.getActiveBits() <= InBits) {
2172       // If we only need the non-extended bits of the bottom element
2173       // then we can just bitcast to the result.
2174       if (IsLE && IsVecInReg && DemandedElts == 1 &&
2175           VT.getSizeInBits() == SrcVT.getSizeInBits())
2176         return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src));
2177 
2178       unsigned Opc =
2179           IsVecInReg ? ISD::ANY_EXTEND_VECTOR_INREG : ISD::ANY_EXTEND;
2180       if (!TLO.LegalOperations() || isOperationLegal(Opc, VT))
2181         return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT, Src));
2182     }
2183 
2184     APInt InDemandedBits = DemandedBits.trunc(InBits);
2185     APInt InDemandedElts = DemandedElts.zext(InElts);
2186 
2187     // Since some of the sign extended bits are demanded, we know that the sign
2188     // bit is demanded.
2189     InDemandedBits.setBit(InBits - 1);
2190 
2191     if (SimplifyDemandedBits(Src, InDemandedBits, InDemandedElts, Known, TLO,
2192                              Depth + 1))
2193       return true;
2194     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
2195     assert(Known.getBitWidth() == InBits && "Src width has changed?");
2196 
2197     // If the sign bit is known one, the top bits match.
2198     Known = Known.sext(BitWidth);
2199 
2200     // If the sign bit is known zero, convert this to a zero extend.
2201     if (Known.isNonNegative()) {
2202       unsigned Opc =
2203           IsVecInReg ? ISD::ZERO_EXTEND_VECTOR_INREG : ISD::ZERO_EXTEND;
2204       if (!TLO.LegalOperations() || isOperationLegal(Opc, VT))
2205         return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT, Src));
2206     }
2207 
2208     // Attempt to avoid multi-use ops if we don't need anything from them.
2209     if (SDValue NewSrc = SimplifyMultipleUseDemandedBits(
2210             Src, InDemandedBits, InDemandedElts, TLO.DAG, Depth + 1))
2211       return TLO.CombineTo(Op, TLO.DAG.getNode(Op.getOpcode(), dl, VT, NewSrc));
2212     break;
2213   }
2214   case ISD::ANY_EXTEND:
2215   case ISD::ANY_EXTEND_VECTOR_INREG: {
2216     SDValue Src = Op.getOperand(0);
2217     EVT SrcVT = Src.getValueType();
2218     unsigned InBits = SrcVT.getScalarSizeInBits();
2219     unsigned InElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1;
2220     bool IsVecInReg = Op.getOpcode() == ISD::ANY_EXTEND_VECTOR_INREG;
2221 
2222     // If we only need the bottom element then we can just bitcast.
2223     // TODO: Handle ANY_EXTEND?
2224     if (IsLE && IsVecInReg && DemandedElts == 1 &&
2225         VT.getSizeInBits() == SrcVT.getSizeInBits())
2226       return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src));
2227 
2228     APInt InDemandedBits = DemandedBits.trunc(InBits);
2229     APInt InDemandedElts = DemandedElts.zext(InElts);
2230     if (SimplifyDemandedBits(Src, InDemandedBits, InDemandedElts, Known, TLO,
2231                              Depth + 1))
2232       return true;
2233     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
2234     assert(Known.getBitWidth() == InBits && "Src width has changed?");
2235     Known = Known.anyext(BitWidth);
2236 
2237     // Attempt to avoid multi-use ops if we don't need anything from them.
2238     if (SDValue NewSrc = SimplifyMultipleUseDemandedBits(
2239             Src, InDemandedBits, InDemandedElts, TLO.DAG, Depth + 1))
2240       return TLO.CombineTo(Op, TLO.DAG.getNode(Op.getOpcode(), dl, VT, NewSrc));
2241     break;
2242   }
2243   case ISD::TRUNCATE: {
2244     SDValue Src = Op.getOperand(0);
2245 
2246     // Simplify the input, using demanded bit information, and compute the known
2247     // zero/one bits live out.
2248     unsigned OperandBitWidth = Src.getScalarValueSizeInBits();
2249     APInt TruncMask = DemandedBits.zext(OperandBitWidth);
2250     if (SimplifyDemandedBits(Src, TruncMask, DemandedElts, Known, TLO,
2251                              Depth + 1))
2252       return true;
2253     Known = Known.trunc(BitWidth);
2254 
2255     // Attempt to avoid multi-use ops if we don't need anything from them.
2256     if (SDValue NewSrc = SimplifyMultipleUseDemandedBits(
2257             Src, TruncMask, DemandedElts, TLO.DAG, Depth + 1))
2258       return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::TRUNCATE, dl, VT, NewSrc));
2259 
2260     // If the input is only used by this truncate, see if we can shrink it based
2261     // on the known demanded bits.
2262     if (Src.getNode()->hasOneUse()) {
2263       switch (Src.getOpcode()) {
2264       default:
2265         break;
2266       case ISD::SRL:
2267         // Shrink SRL by a constant if none of the high bits shifted in are
2268         // demanded.
2269         if (TLO.LegalTypes() && !isTypeDesirableForOp(ISD::SRL, VT))
2270           // Do not turn (vt1 truncate (vt2 srl)) into (vt1 srl) if vt1 is
2271           // undesirable.
2272           break;
2273 
2274         const APInt *ShAmtC =
2275             TLO.DAG.getValidShiftAmountConstant(Src, DemandedElts);
2276         if (!ShAmtC || ShAmtC->uge(BitWidth))
2277           break;
2278         uint64_t ShVal = ShAmtC->getZExtValue();
2279 
2280         APInt HighBits =
2281             APInt::getHighBitsSet(OperandBitWidth, OperandBitWidth - BitWidth);
2282         HighBits.lshrInPlace(ShVal);
2283         HighBits = HighBits.trunc(BitWidth);
2284 
2285         if (!(HighBits & DemandedBits)) {
2286           // None of the shifted in bits are needed.  Add a truncate of the
2287           // shift input, then shift it.
2288           SDValue NewShAmt = TLO.DAG.getConstant(
2289               ShVal, dl, getShiftAmountTy(VT, DL, TLO.LegalTypes()));
2290           SDValue NewTrunc =
2291               TLO.DAG.getNode(ISD::TRUNCATE, dl, VT, Src.getOperand(0));
2292           return TLO.CombineTo(
2293               Op, TLO.DAG.getNode(ISD::SRL, dl, VT, NewTrunc, NewShAmt));
2294         }
2295         break;
2296       }
2297     }
2298 
2299     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
2300     break;
2301   }
2302   case ISD::AssertZext: {
2303     // AssertZext demands all of the high bits, plus any of the low bits
2304     // demanded by its users.
2305     EVT ZVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
2306     APInt InMask = APInt::getLowBitsSet(BitWidth, ZVT.getSizeInBits());
2307     if (SimplifyDemandedBits(Op.getOperand(0), ~InMask | DemandedBits, Known,
2308                              TLO, Depth + 1))
2309       return true;
2310     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
2311 
2312     Known.Zero |= ~InMask;
2313     break;
2314   }
2315   case ISD::EXTRACT_VECTOR_ELT: {
2316     SDValue Src = Op.getOperand(0);
2317     SDValue Idx = Op.getOperand(1);
2318     ElementCount SrcEltCnt = Src.getValueType().getVectorElementCount();
2319     unsigned EltBitWidth = Src.getScalarValueSizeInBits();
2320 
2321     if (SrcEltCnt.isScalable())
2322       return false;
2323 
2324     // Demand the bits from every vector element without a constant index.
2325     unsigned NumSrcElts = SrcEltCnt.getFixedValue();
2326     APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
2327     if (auto *CIdx = dyn_cast<ConstantSDNode>(Idx))
2328       if (CIdx->getAPIntValue().ult(NumSrcElts))
2329         DemandedSrcElts = APInt::getOneBitSet(NumSrcElts, CIdx->getZExtValue());
2330 
2331     // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know
2332     // anything about the extended bits.
2333     APInt DemandedSrcBits = DemandedBits;
2334     if (BitWidth > EltBitWidth)
2335       DemandedSrcBits = DemandedSrcBits.trunc(EltBitWidth);
2336 
2337     if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedSrcElts, Known2, TLO,
2338                              Depth + 1))
2339       return true;
2340 
2341     // Attempt to avoid multi-use ops if we don't need anything from them.
2342     if (!DemandedSrcBits.isAllOnes() || !DemandedSrcElts.isAllOnes()) {
2343       if (SDValue DemandedSrc = SimplifyMultipleUseDemandedBits(
2344               Src, DemandedSrcBits, DemandedSrcElts, TLO.DAG, Depth + 1)) {
2345         SDValue NewOp =
2346             TLO.DAG.getNode(Op.getOpcode(), dl, VT, DemandedSrc, Idx);
2347         return TLO.CombineTo(Op, NewOp);
2348       }
2349     }
2350 
2351     Known = Known2;
2352     if (BitWidth > EltBitWidth)
2353       Known = Known.anyext(BitWidth);
2354     break;
2355   }
2356   case ISD::BITCAST: {
2357     SDValue Src = Op.getOperand(0);
2358     EVT SrcVT = Src.getValueType();
2359     unsigned NumSrcEltBits = SrcVT.getScalarSizeInBits();
2360 
2361     // If this is an FP->Int bitcast and if the sign bit is the only
2362     // thing demanded, turn this into a FGETSIGN.
2363     if (!TLO.LegalOperations() && !VT.isVector() && !SrcVT.isVector() &&
2364         DemandedBits == APInt::getSignMask(Op.getValueSizeInBits()) &&
2365         SrcVT.isFloatingPoint()) {
2366       bool OpVTLegal = isOperationLegalOrCustom(ISD::FGETSIGN, VT);
2367       bool i32Legal = isOperationLegalOrCustom(ISD::FGETSIGN, MVT::i32);
2368       if ((OpVTLegal || i32Legal) && VT.isSimple() && SrcVT != MVT::f16 &&
2369           SrcVT != MVT::f128) {
2370         // Cannot eliminate/lower SHL for f128 yet.
2371         EVT Ty = OpVTLegal ? VT : MVT::i32;
2372         // Make a FGETSIGN + SHL to move the sign bit into the appropriate
2373         // place.  We expect the SHL to be eliminated by other optimizations.
2374         SDValue Sign = TLO.DAG.getNode(ISD::FGETSIGN, dl, Ty, Src);
2375         unsigned OpVTSizeInBits = Op.getValueSizeInBits();
2376         if (!OpVTLegal && OpVTSizeInBits > 32)
2377           Sign = TLO.DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Sign);
2378         unsigned ShVal = Op.getValueSizeInBits() - 1;
2379         SDValue ShAmt = TLO.DAG.getConstant(ShVal, dl, VT);
2380         return TLO.CombineTo(Op,
2381                              TLO.DAG.getNode(ISD::SHL, dl, VT, Sign, ShAmt));
2382       }
2383     }
2384 
2385     // Bitcast from a vector using SimplifyDemanded Bits/VectorElts.
2386     // Demand the elt/bit if any of the original elts/bits are demanded.
2387     if (SrcVT.isVector() && (BitWidth % NumSrcEltBits) == 0) {
2388       unsigned Scale = BitWidth / NumSrcEltBits;
2389       unsigned NumSrcElts = SrcVT.getVectorNumElements();
2390       APInt DemandedSrcBits = APInt::getZero(NumSrcEltBits);
2391       APInt DemandedSrcElts = APInt::getZero(NumSrcElts);
2392       for (unsigned i = 0; i != Scale; ++i) {
2393         unsigned EltOffset = IsLE ? i : (Scale - 1 - i);
2394         unsigned BitOffset = EltOffset * NumSrcEltBits;
2395         APInt Sub = DemandedBits.extractBits(NumSrcEltBits, BitOffset);
2396         if (!Sub.isZero()) {
2397           DemandedSrcBits |= Sub;
2398           for (unsigned j = 0; j != NumElts; ++j)
2399             if (DemandedElts[j])
2400               DemandedSrcElts.setBit((j * Scale) + i);
2401         }
2402       }
2403 
2404       APInt KnownSrcUndef, KnownSrcZero;
2405       if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, KnownSrcUndef,
2406                                      KnownSrcZero, TLO, Depth + 1))
2407         return true;
2408 
2409       KnownBits KnownSrcBits;
2410       if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedSrcElts,
2411                                KnownSrcBits, TLO, Depth + 1))
2412         return true;
2413     } else if (IsLE && (NumSrcEltBits % BitWidth) == 0) {
2414       // TODO - bigendian once we have test coverage.
2415       unsigned Scale = NumSrcEltBits / BitWidth;
2416       unsigned NumSrcElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1;
2417       APInt DemandedSrcBits = APInt::getZero(NumSrcEltBits);
2418       APInt DemandedSrcElts = APInt::getZero(NumSrcElts);
2419       for (unsigned i = 0; i != NumElts; ++i)
2420         if (DemandedElts[i]) {
2421           unsigned Offset = (i % Scale) * BitWidth;
2422           DemandedSrcBits.insertBits(DemandedBits, Offset);
2423           DemandedSrcElts.setBit(i / Scale);
2424         }
2425 
2426       if (SrcVT.isVector()) {
2427         APInt KnownSrcUndef, KnownSrcZero;
2428         if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, KnownSrcUndef,
2429                                        KnownSrcZero, TLO, Depth + 1))
2430           return true;
2431       }
2432 
2433       KnownBits KnownSrcBits;
2434       if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedSrcElts,
2435                                KnownSrcBits, TLO, Depth + 1))
2436         return true;
2437     }
2438 
2439     // If this is a bitcast, let computeKnownBits handle it.  Only do this on a
2440     // recursive call where Known may be useful to the caller.
2441     if (Depth > 0) {
2442       Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth);
2443       return false;
2444     }
2445     break;
2446   }
2447   case ISD::MUL:
2448     if (DemandedBits.isPowerOf2()) {
2449       // The LSB of X*Y is set only if (X & 1) == 1 and (Y & 1) == 1.
2450       // If we demand exactly one bit N and we have "X * (C' << N)" where C' is
2451       // odd (has LSB set), then the left-shifted low bit of X is the answer.
2452       unsigned CTZ = DemandedBits.countTrailingZeros();
2453       ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(1), DemandedElts);
2454       if (C && C->getAPIntValue().countTrailingZeros() == CTZ) {
2455         EVT ShiftAmtTy = getShiftAmountTy(VT, TLO.DAG.getDataLayout());
2456         SDValue AmtC = TLO.DAG.getConstant(CTZ, dl, ShiftAmtTy);
2457         SDValue Shl = TLO.DAG.getNode(ISD::SHL, dl, VT, Op.getOperand(0), AmtC);
2458         return TLO.CombineTo(Op, Shl);
2459       }
2460     }
2461     // For a squared value "X * X", the bottom 2 bits are 0 and X[0] because:
2462     // X * X is odd iff X is odd.
2463     // 'Quadratic Reciprocity': X * X -> 0 for bit[1]
2464     if (Op.getOperand(0) == Op.getOperand(1) && DemandedBits.ult(4)) {
2465       SDValue One = TLO.DAG.getConstant(1, dl, VT);
2466       SDValue And1 = TLO.DAG.getNode(ISD::AND, dl, VT, Op.getOperand(0), One);
2467       return TLO.CombineTo(Op, And1);
2468     }
2469     LLVM_FALLTHROUGH;
2470   case ISD::ADD:
2471   case ISD::SUB: {
2472     // Add, Sub, and Mul don't demand any bits in positions beyond that
2473     // of the highest bit demanded of them.
2474     SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
2475     SDNodeFlags Flags = Op.getNode()->getFlags();
2476     unsigned DemandedBitsLZ = DemandedBits.countLeadingZeros();
2477     APInt LoMask = APInt::getLowBitsSet(BitWidth, BitWidth - DemandedBitsLZ);
2478     if (SimplifyDemandedBits(Op0, LoMask, DemandedElts, Known2, TLO,
2479                              Depth + 1) ||
2480         SimplifyDemandedBits(Op1, LoMask, DemandedElts, Known2, TLO,
2481                              Depth + 1) ||
2482         // See if the operation should be performed at a smaller bit width.
2483         ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO)) {
2484       if (Flags.hasNoSignedWrap() || Flags.hasNoUnsignedWrap()) {
2485         // Disable the nsw and nuw flags. We can no longer guarantee that we
2486         // won't wrap after simplification.
2487         Flags.setNoSignedWrap(false);
2488         Flags.setNoUnsignedWrap(false);
2489         SDValue NewOp =
2490             TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1, Flags);
2491         return TLO.CombineTo(Op, NewOp);
2492       }
2493       return true;
2494     }
2495 
2496     // Attempt to avoid multi-use ops if we don't need anything from them.
2497     if (!LoMask.isAllOnes() || !DemandedElts.isAllOnes()) {
2498       SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits(
2499           Op0, LoMask, DemandedElts, TLO.DAG, Depth + 1);
2500       SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits(
2501           Op1, LoMask, DemandedElts, TLO.DAG, Depth + 1);
2502       if (DemandedOp0 || DemandedOp1) {
2503         Flags.setNoSignedWrap(false);
2504         Flags.setNoUnsignedWrap(false);
2505         Op0 = DemandedOp0 ? DemandedOp0 : Op0;
2506         Op1 = DemandedOp1 ? DemandedOp1 : Op1;
2507         SDValue NewOp =
2508             TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1, Flags);
2509         return TLO.CombineTo(Op, NewOp);
2510       }
2511     }
2512 
2513     // If we have a constant operand, we may be able to turn it into -1 if we
2514     // do not demand the high bits. This can make the constant smaller to
2515     // encode, allow more general folding, or match specialized instruction
2516     // patterns (eg, 'blsr' on x86). Don't bother changing 1 to -1 because that
2517     // is probably not useful (and could be detrimental).
2518     ConstantSDNode *C = isConstOrConstSplat(Op1);
2519     APInt HighMask = APInt::getHighBitsSet(BitWidth, DemandedBitsLZ);
2520     if (C && !C->isAllOnes() && !C->isOne() &&
2521         (C->getAPIntValue() | HighMask).isAllOnes()) {
2522       SDValue Neg1 = TLO.DAG.getAllOnesConstant(dl, VT);
2523       // Disable the nsw and nuw flags. We can no longer guarantee that we
2524       // won't wrap after simplification.
2525       Flags.setNoSignedWrap(false);
2526       Flags.setNoUnsignedWrap(false);
2527       SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Neg1, Flags);
2528       return TLO.CombineTo(Op, NewOp);
2529     }
2530 
2531     // Match a multiply with a disguised negated-power-of-2 and convert to a
2532     // an equivalent shift-left amount.
2533     // Example: (X * MulC) + Op1 --> Op1 - (X << log2(-MulC))
2534     auto getShiftLeftAmt = [&HighMask](SDValue Mul) -> unsigned {
2535       if (Mul.getOpcode() != ISD::MUL || !Mul.hasOneUse())
2536         return 0;
2537 
2538       // Don't touch opaque constants. Also, ignore zero and power-of-2
2539       // multiplies. Those will get folded later.
2540       ConstantSDNode *MulC = isConstOrConstSplat(Mul.getOperand(1));
2541       if (MulC && !MulC->isOpaque() && !MulC->isZero() &&
2542           !MulC->getAPIntValue().isPowerOf2()) {
2543         APInt UnmaskedC = MulC->getAPIntValue() | HighMask;
2544         if (UnmaskedC.isNegatedPowerOf2())
2545           return (-UnmaskedC).logBase2();
2546       }
2547       return 0;
2548     };
2549 
2550     auto foldMul = [&](ISD::NodeType NT, SDValue X, SDValue Y, unsigned ShlAmt) {
2551       EVT ShiftAmtTy = getShiftAmountTy(VT, TLO.DAG.getDataLayout());
2552       SDValue ShlAmtC = TLO.DAG.getConstant(ShlAmt, dl, ShiftAmtTy);
2553       SDValue Shl = TLO.DAG.getNode(ISD::SHL, dl, VT, X, ShlAmtC);
2554       SDValue Res = TLO.DAG.getNode(NT, dl, VT, Y, Shl);
2555       return TLO.CombineTo(Op, Res);
2556     };
2557 
2558     if (isOperationLegalOrCustom(ISD::SHL, VT)) {
2559       if (Op.getOpcode() == ISD::ADD) {
2560         // (X * MulC) + Op1 --> Op1 - (X << log2(-MulC))
2561         if (unsigned ShAmt = getShiftLeftAmt(Op0))
2562           return foldMul(ISD::SUB, Op0.getOperand(0), Op1, ShAmt);
2563         // Op0 + (X * MulC) --> Op0 - (X << log2(-MulC))
2564         if (unsigned ShAmt = getShiftLeftAmt(Op1))
2565           return foldMul(ISD::SUB, Op1.getOperand(0), Op0, ShAmt);
2566       }
2567       if (Op.getOpcode() == ISD::SUB) {
2568         // Op0 - (X * MulC) --> Op0 + (X << log2(-MulC))
2569         if (unsigned ShAmt = getShiftLeftAmt(Op1))
2570           return foldMul(ISD::ADD, Op1.getOperand(0), Op0, ShAmt);
2571       }
2572     }
2573 
2574     LLVM_FALLTHROUGH;
2575   }
2576   default:
2577     if (Op.getOpcode() >= ISD::BUILTIN_OP_END) {
2578       if (SimplifyDemandedBitsForTargetNode(Op, DemandedBits, DemandedElts,
2579                                             Known, TLO, Depth))
2580         return true;
2581       break;
2582     }
2583 
2584     // Just use computeKnownBits to compute output bits.
2585     Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth);
2586     break;
2587   }
2588 
2589   // If we know the value of all of the demanded bits, return this as a
2590   // constant.
2591   if (DemandedBits.isSubsetOf(Known.Zero | Known.One)) {
2592     // Avoid folding to a constant if any OpaqueConstant is involved.
2593     const SDNode *N = Op.getNode();
2594     for (SDNode *Op :
2595          llvm::make_range(SDNodeIterator::begin(N), SDNodeIterator::end(N))) {
2596       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
2597         if (C->isOpaque())
2598           return false;
2599     }
2600     if (VT.isInteger())
2601       return TLO.CombineTo(Op, TLO.DAG.getConstant(Known.One, dl, VT));
2602     if (VT.isFloatingPoint())
2603       return TLO.CombineTo(
2604           Op,
2605           TLO.DAG.getConstantFP(
2606               APFloat(TLO.DAG.EVTToAPFloatSemantics(VT), Known.One), dl, VT));
2607   }
2608 
2609   return false;
2610 }
2611 
2612 bool TargetLowering::SimplifyDemandedVectorElts(SDValue Op,
2613                                                 const APInt &DemandedElts,
2614                                                 DAGCombinerInfo &DCI) const {
2615   SelectionDAG &DAG = DCI.DAG;
2616   TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
2617                         !DCI.isBeforeLegalizeOps());
2618 
2619   APInt KnownUndef, KnownZero;
2620   bool Simplified =
2621       SimplifyDemandedVectorElts(Op, DemandedElts, KnownUndef, KnownZero, TLO);
2622   if (Simplified) {
2623     DCI.AddToWorklist(Op.getNode());
2624     DCI.CommitTargetLoweringOpt(TLO);
2625   }
2626 
2627   return Simplified;
2628 }
2629 
2630 /// Given a vector binary operation and known undefined elements for each input
2631 /// operand, compute whether each element of the output is undefined.
2632 static APInt getKnownUndefForVectorBinop(SDValue BO, SelectionDAG &DAG,
2633                                          const APInt &UndefOp0,
2634                                          const APInt &UndefOp1) {
2635   EVT VT = BO.getValueType();
2636   assert(DAG.getTargetLoweringInfo().isBinOp(BO.getOpcode()) && VT.isVector() &&
2637          "Vector binop only");
2638 
2639   EVT EltVT = VT.getVectorElementType();
2640   unsigned NumElts = VT.getVectorNumElements();
2641   assert(UndefOp0.getBitWidth() == NumElts &&
2642          UndefOp1.getBitWidth() == NumElts && "Bad type for undef analysis");
2643 
2644   auto getUndefOrConstantElt = [&](SDValue V, unsigned Index,
2645                                    const APInt &UndefVals) {
2646     if (UndefVals[Index])
2647       return DAG.getUNDEF(EltVT);
2648 
2649     if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) {
2650       // Try hard to make sure that the getNode() call is not creating temporary
2651       // nodes. Ignore opaque integers because they do not constant fold.
2652       SDValue Elt = BV->getOperand(Index);
2653       auto *C = dyn_cast<ConstantSDNode>(Elt);
2654       if (isa<ConstantFPSDNode>(Elt) || Elt.isUndef() || (C && !C->isOpaque()))
2655         return Elt;
2656     }
2657 
2658     return SDValue();
2659   };
2660 
2661   APInt KnownUndef = APInt::getZero(NumElts);
2662   for (unsigned i = 0; i != NumElts; ++i) {
2663     // If both inputs for this element are either constant or undef and match
2664     // the element type, compute the constant/undef result for this element of
2665     // the vector.
2666     // TODO: Ideally we would use FoldConstantArithmetic() here, but that does
2667     // not handle FP constants. The code within getNode() should be refactored
2668     // to avoid the danger of creating a bogus temporary node here.
2669     SDValue C0 = getUndefOrConstantElt(BO.getOperand(0), i, UndefOp0);
2670     SDValue C1 = getUndefOrConstantElt(BO.getOperand(1), i, UndefOp1);
2671     if (C0 && C1 && C0.getValueType() == EltVT && C1.getValueType() == EltVT)
2672       if (DAG.getNode(BO.getOpcode(), SDLoc(BO), EltVT, C0, C1).isUndef())
2673         KnownUndef.setBit(i);
2674   }
2675   return KnownUndef;
2676 }
2677 
2678 bool TargetLowering::SimplifyDemandedVectorElts(
2679     SDValue Op, const APInt &OriginalDemandedElts, APInt &KnownUndef,
2680     APInt &KnownZero, TargetLoweringOpt &TLO, unsigned Depth,
2681     bool AssumeSingleUse) const {
2682   EVT VT = Op.getValueType();
2683   unsigned Opcode = Op.getOpcode();
2684   APInt DemandedElts = OriginalDemandedElts;
2685   unsigned NumElts = DemandedElts.getBitWidth();
2686   assert(VT.isVector() && "Expected vector op");
2687 
2688   KnownUndef = KnownZero = APInt::getZero(NumElts);
2689 
2690   const TargetLowering &TLI = TLO.DAG.getTargetLoweringInfo();
2691   if (!TLI.shouldSimplifyDemandedVectorElts(Op, TLO))
2692     return false;
2693 
2694   // TODO: For now we assume we know nothing about scalable vectors.
2695   if (VT.isScalableVector())
2696     return false;
2697 
2698   assert(VT.getVectorNumElements() == NumElts &&
2699          "Mask size mismatches value type element count!");
2700 
2701   // Undef operand.
2702   if (Op.isUndef()) {
2703     KnownUndef.setAllBits();
2704     return false;
2705   }
2706 
2707   // If Op has other users, assume that all elements are needed.
2708   if (!Op.getNode()->hasOneUse() && !AssumeSingleUse)
2709     DemandedElts.setAllBits();
2710 
2711   // Not demanding any elements from Op.
2712   if (DemandedElts == 0) {
2713     KnownUndef.setAllBits();
2714     return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT));
2715   }
2716 
2717   // Limit search depth.
2718   if (Depth >= SelectionDAG::MaxRecursionDepth)
2719     return false;
2720 
2721   SDLoc DL(Op);
2722   unsigned EltSizeInBits = VT.getScalarSizeInBits();
2723   bool IsLE = TLO.DAG.getDataLayout().isLittleEndian();
2724 
2725   // Helper for demanding the specified elements and all the bits of both binary
2726   // operands.
2727   auto SimplifyDemandedVectorEltsBinOp = [&](SDValue Op0, SDValue Op1) {
2728     SDValue NewOp0 = SimplifyMultipleUseDemandedVectorElts(Op0, DemandedElts,
2729                                                            TLO.DAG, Depth + 1);
2730     SDValue NewOp1 = SimplifyMultipleUseDemandedVectorElts(Op1, DemandedElts,
2731                                                            TLO.DAG, Depth + 1);
2732     if (NewOp0 || NewOp1) {
2733       SDValue NewOp = TLO.DAG.getNode(
2734           Opcode, SDLoc(Op), VT, NewOp0 ? NewOp0 : Op0, NewOp1 ? NewOp1 : Op1);
2735       return TLO.CombineTo(Op, NewOp);
2736     }
2737     return false;
2738   };
2739 
2740   switch (Opcode) {
2741   case ISD::SCALAR_TO_VECTOR: {
2742     if (!DemandedElts[0]) {
2743       KnownUndef.setAllBits();
2744       return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT));
2745     }
2746     SDValue ScalarSrc = Op.getOperand(0);
2747     if (ScalarSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
2748       SDValue Src = ScalarSrc.getOperand(0);
2749       SDValue Idx = ScalarSrc.getOperand(1);
2750       EVT SrcVT = Src.getValueType();
2751 
2752       ElementCount SrcEltCnt = SrcVT.getVectorElementCount();
2753 
2754       if (SrcEltCnt.isScalable())
2755         return false;
2756 
2757       unsigned NumSrcElts = SrcEltCnt.getFixedValue();
2758       if (isNullConstant(Idx)) {
2759         APInt SrcDemandedElts = APInt::getOneBitSet(NumSrcElts, 0);
2760         APInt SrcUndef = KnownUndef.zextOrTrunc(NumSrcElts);
2761         APInt SrcZero = KnownZero.zextOrTrunc(NumSrcElts);
2762         if (SimplifyDemandedVectorElts(Src, SrcDemandedElts, SrcUndef, SrcZero,
2763                                        TLO, Depth + 1))
2764           return true;
2765       }
2766     }
2767     KnownUndef.setHighBits(NumElts - 1);
2768     break;
2769   }
2770   case ISD::BITCAST: {
2771     SDValue Src = Op.getOperand(0);
2772     EVT SrcVT = Src.getValueType();
2773 
2774     // We only handle vectors here.
2775     // TODO - investigate calling SimplifyDemandedBits/ComputeKnownBits?
2776     if (!SrcVT.isVector())
2777       break;
2778 
2779     // Fast handling of 'identity' bitcasts.
2780     unsigned NumSrcElts = SrcVT.getVectorNumElements();
2781     if (NumSrcElts == NumElts)
2782       return SimplifyDemandedVectorElts(Src, DemandedElts, KnownUndef,
2783                                         KnownZero, TLO, Depth + 1);
2784 
2785     APInt SrcDemandedElts, SrcZero, SrcUndef;
2786 
2787     // Bitcast from 'large element' src vector to 'small element' vector, we
2788     // must demand a source element if any DemandedElt maps to it.
2789     if ((NumElts % NumSrcElts) == 0) {
2790       unsigned Scale = NumElts / NumSrcElts;
2791       SrcDemandedElts = APIntOps::ScaleBitMask(DemandedElts, NumSrcElts);
2792       if (SimplifyDemandedVectorElts(Src, SrcDemandedElts, SrcUndef, SrcZero,
2793                                      TLO, Depth + 1))
2794         return true;
2795 
2796       // Try calling SimplifyDemandedBits, converting demanded elts to the bits
2797       // of the large element.
2798       // TODO - bigendian once we have test coverage.
2799       if (IsLE) {
2800         unsigned SrcEltSizeInBits = SrcVT.getScalarSizeInBits();
2801         APInt SrcDemandedBits = APInt::getZero(SrcEltSizeInBits);
2802         for (unsigned i = 0; i != NumElts; ++i)
2803           if (DemandedElts[i]) {
2804             unsigned Ofs = (i % Scale) * EltSizeInBits;
2805             SrcDemandedBits.setBits(Ofs, Ofs + EltSizeInBits);
2806           }
2807 
2808         KnownBits Known;
2809         if (SimplifyDemandedBits(Src, SrcDemandedBits, SrcDemandedElts, Known,
2810                                  TLO, Depth + 1))
2811           return true;
2812 
2813         // The bitcast has split each wide element into a number of
2814         // narrow subelements. We have just computed the Known bits
2815         // for wide elements. See if element splitting results in
2816         // some subelements being zero. Only for demanded elements!
2817         for (unsigned SubElt = 0; SubElt != Scale; ++SubElt) {
2818           if (!Known.Zero.extractBits(EltSizeInBits, SubElt * EltSizeInBits)
2819                    .isAllOnes())
2820             continue;
2821           for (unsigned SrcElt = 0; SrcElt != NumSrcElts; ++SrcElt) {
2822             unsigned Elt = Scale * SrcElt + SubElt;
2823             if (DemandedElts[Elt])
2824               KnownZero.setBit(Elt);
2825           }
2826         }
2827       }
2828 
2829       // If the src element is zero/undef then all the output elements will be -
2830       // only demanded elements are guaranteed to be correct.
2831       for (unsigned i = 0; i != NumSrcElts; ++i) {
2832         if (SrcDemandedElts[i]) {
2833           if (SrcZero[i])
2834             KnownZero.setBits(i * Scale, (i + 1) * Scale);
2835           if (SrcUndef[i])
2836             KnownUndef.setBits(i * Scale, (i + 1) * Scale);
2837         }
2838       }
2839     }
2840 
2841     // Bitcast from 'small element' src vector to 'large element' vector, we
2842     // demand all smaller source elements covered by the larger demanded element
2843     // of this vector.
2844     if ((NumSrcElts % NumElts) == 0) {
2845       unsigned Scale = NumSrcElts / NumElts;
2846       SrcDemandedElts = APIntOps::ScaleBitMask(DemandedElts, NumSrcElts);
2847       if (SimplifyDemandedVectorElts(Src, SrcDemandedElts, SrcUndef, SrcZero,
2848                                      TLO, Depth + 1))
2849         return true;
2850 
2851       // If all the src elements covering an output element are zero/undef, then
2852       // the output element will be as well, assuming it was demanded.
2853       for (unsigned i = 0; i != NumElts; ++i) {
2854         if (DemandedElts[i]) {
2855           if (SrcZero.extractBits(Scale, i * Scale).isAllOnes())
2856             KnownZero.setBit(i);
2857           if (SrcUndef.extractBits(Scale, i * Scale).isAllOnes())
2858             KnownUndef.setBit(i);
2859         }
2860       }
2861     }
2862     break;
2863   }
2864   case ISD::BUILD_VECTOR: {
2865     // Check all elements and simplify any unused elements with UNDEF.
2866     if (!DemandedElts.isAllOnes()) {
2867       // Don't simplify BROADCASTS.
2868       if (llvm::any_of(Op->op_values(),
2869                        [&](SDValue Elt) { return Op.getOperand(0) != Elt; })) {
2870         SmallVector<SDValue, 32> Ops(Op->op_begin(), Op->op_end());
2871         bool Updated = false;
2872         for (unsigned i = 0; i != NumElts; ++i) {
2873           if (!DemandedElts[i] && !Ops[i].isUndef()) {
2874             Ops[i] = TLO.DAG.getUNDEF(Ops[0].getValueType());
2875             KnownUndef.setBit(i);
2876             Updated = true;
2877           }
2878         }
2879         if (Updated)
2880           return TLO.CombineTo(Op, TLO.DAG.getBuildVector(VT, DL, Ops));
2881       }
2882     }
2883     for (unsigned i = 0; i != NumElts; ++i) {
2884       SDValue SrcOp = Op.getOperand(i);
2885       if (SrcOp.isUndef()) {
2886         KnownUndef.setBit(i);
2887       } else if (EltSizeInBits == SrcOp.getScalarValueSizeInBits() &&
2888                  (isNullConstant(SrcOp) || isNullFPConstant(SrcOp))) {
2889         KnownZero.setBit(i);
2890       }
2891     }
2892     break;
2893   }
2894   case ISD::CONCAT_VECTORS: {
2895     EVT SubVT = Op.getOperand(0).getValueType();
2896     unsigned NumSubVecs = Op.getNumOperands();
2897     unsigned NumSubElts = SubVT.getVectorNumElements();
2898     for (unsigned i = 0; i != NumSubVecs; ++i) {
2899       SDValue SubOp = Op.getOperand(i);
2900       APInt SubElts = DemandedElts.extractBits(NumSubElts, i * NumSubElts);
2901       APInt SubUndef, SubZero;
2902       if (SimplifyDemandedVectorElts(SubOp, SubElts, SubUndef, SubZero, TLO,
2903                                      Depth + 1))
2904         return true;
2905       KnownUndef.insertBits(SubUndef, i * NumSubElts);
2906       KnownZero.insertBits(SubZero, i * NumSubElts);
2907     }
2908 
2909     // Attempt to avoid multi-use ops if we don't need anything from them.
2910     if (!DemandedElts.isAllOnes()) {
2911       bool FoundNewSub = false;
2912       SmallVector<SDValue, 2> DemandedSubOps;
2913       for (unsigned i = 0; i != NumSubVecs; ++i) {
2914         SDValue SubOp = Op.getOperand(i);
2915         APInt SubElts = DemandedElts.extractBits(NumSubElts, i * NumSubElts);
2916         SDValue NewSubOp = SimplifyMultipleUseDemandedVectorElts(
2917             SubOp, SubElts, TLO.DAG, Depth + 1);
2918         DemandedSubOps.push_back(NewSubOp ? NewSubOp : SubOp);
2919         FoundNewSub = NewSubOp ? true : FoundNewSub;
2920       }
2921       if (FoundNewSub) {
2922         SDValue NewOp =
2923             TLO.DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, DemandedSubOps);
2924         return TLO.CombineTo(Op, NewOp);
2925       }
2926     }
2927     break;
2928   }
2929   case ISD::INSERT_SUBVECTOR: {
2930     // Demand any elements from the subvector and the remainder from the src its
2931     // inserted into.
2932     SDValue Src = Op.getOperand(0);
2933     SDValue Sub = Op.getOperand(1);
2934     uint64_t Idx = Op.getConstantOperandVal(2);
2935     unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
2936     APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
2937     APInt DemandedSrcElts = DemandedElts;
2938     DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx);
2939 
2940     APInt SubUndef, SubZero;
2941     if (SimplifyDemandedVectorElts(Sub, DemandedSubElts, SubUndef, SubZero, TLO,
2942                                    Depth + 1))
2943       return true;
2944 
2945     // If none of the src operand elements are demanded, replace it with undef.
2946     if (!DemandedSrcElts && !Src.isUndef())
2947       return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
2948                                                TLO.DAG.getUNDEF(VT), Sub,
2949                                                Op.getOperand(2)));
2950 
2951     if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, KnownUndef, KnownZero,
2952                                    TLO, Depth + 1))
2953       return true;
2954     KnownUndef.insertBits(SubUndef, Idx);
2955     KnownZero.insertBits(SubZero, Idx);
2956 
2957     // Attempt to avoid multi-use ops if we don't need anything from them.
2958     if (!DemandedSrcElts.isAllOnes() || !DemandedSubElts.isAllOnes()) {
2959       SDValue NewSrc = SimplifyMultipleUseDemandedVectorElts(
2960           Src, DemandedSrcElts, TLO.DAG, Depth + 1);
2961       SDValue NewSub = SimplifyMultipleUseDemandedVectorElts(
2962           Sub, DemandedSubElts, TLO.DAG, Depth + 1);
2963       if (NewSrc || NewSub) {
2964         NewSrc = NewSrc ? NewSrc : Src;
2965         NewSub = NewSub ? NewSub : Sub;
2966         SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, NewSrc,
2967                                         NewSub, Op.getOperand(2));
2968         return TLO.CombineTo(Op, NewOp);
2969       }
2970     }
2971     break;
2972   }
2973   case ISD::EXTRACT_SUBVECTOR: {
2974     // Offset the demanded elts by the subvector index.
2975     SDValue Src = Op.getOperand(0);
2976     if (Src.getValueType().isScalableVector())
2977       break;
2978     uint64_t Idx = Op.getConstantOperandVal(1);
2979     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
2980     APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
2981 
2982     APInt SrcUndef, SrcZero;
2983     if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, SrcUndef, SrcZero, TLO,
2984                                    Depth + 1))
2985       return true;
2986     KnownUndef = SrcUndef.extractBits(NumElts, Idx);
2987     KnownZero = SrcZero.extractBits(NumElts, Idx);
2988 
2989     // Attempt to avoid multi-use ops if we don't need anything from them.
2990     if (!DemandedElts.isAllOnes()) {
2991       SDValue NewSrc = SimplifyMultipleUseDemandedVectorElts(
2992           Src, DemandedSrcElts, TLO.DAG, Depth + 1);
2993       if (NewSrc) {
2994         SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, NewSrc,
2995                                         Op.getOperand(1));
2996         return TLO.CombineTo(Op, NewOp);
2997       }
2998     }
2999     break;
3000   }
3001   case ISD::INSERT_VECTOR_ELT: {
3002     SDValue Vec = Op.getOperand(0);
3003     SDValue Scl = Op.getOperand(1);
3004     auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2));
3005 
3006     // For a legal, constant insertion index, if we don't need this insertion
3007     // then strip it, else remove it from the demanded elts.
3008     if (CIdx && CIdx->getAPIntValue().ult(NumElts)) {
3009       unsigned Idx = CIdx->getZExtValue();
3010       if (!DemandedElts[Idx])
3011         return TLO.CombineTo(Op, Vec);
3012 
3013       APInt DemandedVecElts(DemandedElts);
3014       DemandedVecElts.clearBit(Idx);
3015       if (SimplifyDemandedVectorElts(Vec, DemandedVecElts, KnownUndef,
3016                                      KnownZero, TLO, Depth + 1))
3017         return true;
3018 
3019       KnownUndef.setBitVal(Idx, Scl.isUndef());
3020 
3021       KnownZero.setBitVal(Idx, isNullConstant(Scl) || isNullFPConstant(Scl));
3022       break;
3023     }
3024 
3025     APInt VecUndef, VecZero;
3026     if (SimplifyDemandedVectorElts(Vec, DemandedElts, VecUndef, VecZero, TLO,
3027                                    Depth + 1))
3028       return true;
3029     // Without knowing the insertion index we can't set KnownUndef/KnownZero.
3030     break;
3031   }
3032   case ISD::VSELECT: {
3033     // Try to transform the select condition based on the current demanded
3034     // elements.
3035     // TODO: If a condition element is undef, we can choose from one arm of the
3036     //       select (and if one arm is undef, then we can propagate that to the
3037     //       result).
3038     // TODO - add support for constant vselect masks (see IR version of this).
3039     APInt UnusedUndef, UnusedZero;
3040     if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedElts, UnusedUndef,
3041                                    UnusedZero, TLO, Depth + 1))
3042       return true;
3043 
3044     // See if we can simplify either vselect operand.
3045     APInt DemandedLHS(DemandedElts);
3046     APInt DemandedRHS(DemandedElts);
3047     APInt UndefLHS, ZeroLHS;
3048     APInt UndefRHS, ZeroRHS;
3049     if (SimplifyDemandedVectorElts(Op.getOperand(1), DemandedLHS, UndefLHS,
3050                                    ZeroLHS, TLO, Depth + 1))
3051       return true;
3052     if (SimplifyDemandedVectorElts(Op.getOperand(2), DemandedRHS, UndefRHS,
3053                                    ZeroRHS, TLO, Depth + 1))
3054       return true;
3055 
3056     KnownUndef = UndefLHS & UndefRHS;
3057     KnownZero = ZeroLHS & ZeroRHS;
3058     break;
3059   }
3060   case ISD::VECTOR_SHUFFLE: {
3061     ArrayRef<int> ShuffleMask = cast<ShuffleVectorSDNode>(Op)->getMask();
3062 
3063     // Collect demanded elements from shuffle operands..
3064     APInt DemandedLHS(NumElts, 0);
3065     APInt DemandedRHS(NumElts, 0);
3066     for (unsigned i = 0; i != NumElts; ++i) {
3067       int M = ShuffleMask[i];
3068       if (M < 0 || !DemandedElts[i])
3069         continue;
3070       assert(0 <= M && M < (int)(2 * NumElts) && "Shuffle index out of range");
3071       if (M < (int)NumElts)
3072         DemandedLHS.setBit(M);
3073       else
3074         DemandedRHS.setBit(M - NumElts);
3075     }
3076 
3077     // See if we can simplify either shuffle operand.
3078     APInt UndefLHS, ZeroLHS;
3079     APInt UndefRHS, ZeroRHS;
3080     if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedLHS, UndefLHS,
3081                                    ZeroLHS, TLO, Depth + 1))
3082       return true;
3083     if (SimplifyDemandedVectorElts(Op.getOperand(1), DemandedRHS, UndefRHS,
3084                                    ZeroRHS, TLO, Depth + 1))
3085       return true;
3086 
3087     // Simplify mask using undef elements from LHS/RHS.
3088     bool Updated = false;
3089     bool IdentityLHS = true, IdentityRHS = true;
3090     SmallVector<int, 32> NewMask(ShuffleMask.begin(), ShuffleMask.end());
3091     for (unsigned i = 0; i != NumElts; ++i) {
3092       int &M = NewMask[i];
3093       if (M < 0)
3094         continue;
3095       if (!DemandedElts[i] || (M < (int)NumElts && UndefLHS[M]) ||
3096           (M >= (int)NumElts && UndefRHS[M - NumElts])) {
3097         Updated = true;
3098         M = -1;
3099       }
3100       IdentityLHS &= (M < 0) || (M == (int)i);
3101       IdentityRHS &= (M < 0) || ((M - NumElts) == i);
3102     }
3103 
3104     // Update legal shuffle masks based on demanded elements if it won't reduce
3105     // to Identity which can cause premature removal of the shuffle mask.
3106     if (Updated && !IdentityLHS && !IdentityRHS && !TLO.LegalOps) {
3107       SDValue LegalShuffle =
3108           buildLegalVectorShuffle(VT, DL, Op.getOperand(0), Op.getOperand(1),
3109                                   NewMask, TLO.DAG);
3110       if (LegalShuffle)
3111         return TLO.CombineTo(Op, LegalShuffle);
3112     }
3113 
3114     // Propagate undef/zero elements from LHS/RHS.
3115     for (unsigned i = 0; i != NumElts; ++i) {
3116       int M = ShuffleMask[i];
3117       if (M < 0) {
3118         KnownUndef.setBit(i);
3119       } else if (M < (int)NumElts) {
3120         if (UndefLHS[M])
3121           KnownUndef.setBit(i);
3122         if (ZeroLHS[M])
3123           KnownZero.setBit(i);
3124       } else {
3125         if (UndefRHS[M - NumElts])
3126           KnownUndef.setBit(i);
3127         if (ZeroRHS[M - NumElts])
3128           KnownZero.setBit(i);
3129       }
3130     }
3131     break;
3132   }
3133   case ISD::ANY_EXTEND_VECTOR_INREG:
3134   case ISD::SIGN_EXTEND_VECTOR_INREG:
3135   case ISD::ZERO_EXTEND_VECTOR_INREG: {
3136     APInt SrcUndef, SrcZero;
3137     SDValue Src = Op.getOperand(0);
3138     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
3139     APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts);
3140     if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, SrcUndef, SrcZero, TLO,
3141                                    Depth + 1))
3142       return true;
3143     KnownZero = SrcZero.zextOrTrunc(NumElts);
3144     KnownUndef = SrcUndef.zextOrTrunc(NumElts);
3145 
3146     if (IsLE && Op.getOpcode() == ISD::ANY_EXTEND_VECTOR_INREG &&
3147         Op.getValueSizeInBits() == Src.getValueSizeInBits() &&
3148         DemandedSrcElts == 1) {
3149       // aext - if we just need the bottom element then we can bitcast.
3150       return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src));
3151     }
3152 
3153     if (Op.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG) {
3154       // zext(undef) upper bits are guaranteed to be zero.
3155       if (DemandedElts.isSubsetOf(KnownUndef))
3156         return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT));
3157       KnownUndef.clearAllBits();
3158 
3159       // zext - if we just need the bottom element then we can mask:
3160       // zext(and(x,c)) -> and(x,c') iff the zext is the only user of the and.
3161       if (IsLE && DemandedSrcElts == 1 && Src.getOpcode() == ISD::AND &&
3162           Op->isOnlyUserOf(Src.getNode()) &&
3163           Op.getValueSizeInBits() == Src.getValueSizeInBits()) {
3164         SDLoc DL(Op);
3165         EVT SrcVT = Src.getValueType();
3166         EVT SrcSVT = SrcVT.getScalarType();
3167         SmallVector<SDValue> MaskElts;
3168         MaskElts.push_back(TLO.DAG.getAllOnesConstant(DL, SrcSVT));
3169         MaskElts.append(NumSrcElts - 1, TLO.DAG.getConstant(0, DL, SrcSVT));
3170         SDValue Mask = TLO.DAG.getBuildVector(SrcVT, DL, MaskElts);
3171         if (SDValue Fold = TLO.DAG.FoldConstantArithmetic(
3172                 ISD::AND, DL, SrcVT, {Src.getOperand(1), Mask})) {
3173           Fold = TLO.DAG.getNode(ISD::AND, DL, SrcVT, Src.getOperand(0), Fold);
3174           return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Fold));
3175         }
3176       }
3177     }
3178     break;
3179   }
3180 
3181   // TODO: There are more binop opcodes that could be handled here - MIN,
3182   // MAX, saturated math, etc.
3183   case ISD::ADD: {
3184     SDValue Op0 = Op.getOperand(0);
3185     SDValue Op1 = Op.getOperand(1);
3186     if (Op0 == Op1 && Op->isOnlyUserOf(Op0.getNode())) {
3187       APInt UndefLHS, ZeroLHS;
3188       if (SimplifyDemandedVectorElts(Op0, DemandedElts, UndefLHS, ZeroLHS, TLO,
3189                                      Depth + 1, /*AssumeSingleUse*/ true))
3190         return true;
3191     }
3192     LLVM_FALLTHROUGH;
3193   }
3194   case ISD::OR:
3195   case ISD::XOR:
3196   case ISD::SUB:
3197   case ISD::FADD:
3198   case ISD::FSUB:
3199   case ISD::FMUL:
3200   case ISD::FDIV:
3201   case ISD::FREM: {
3202     SDValue Op0 = Op.getOperand(0);
3203     SDValue Op1 = Op.getOperand(1);
3204 
3205     APInt UndefRHS, ZeroRHS;
3206     if (SimplifyDemandedVectorElts(Op1, DemandedElts, UndefRHS, ZeroRHS, TLO,
3207                                    Depth + 1))
3208       return true;
3209     APInt UndefLHS, ZeroLHS;
3210     if (SimplifyDemandedVectorElts(Op0, DemandedElts, UndefLHS, ZeroLHS, TLO,
3211                                    Depth + 1))
3212       return true;
3213 
3214     KnownZero = ZeroLHS & ZeroRHS;
3215     KnownUndef = getKnownUndefForVectorBinop(Op, TLO.DAG, UndefLHS, UndefRHS);
3216 
3217     // Attempt to avoid multi-use ops if we don't need anything from them.
3218     // TODO - use KnownUndef to relax the demandedelts?
3219     if (!DemandedElts.isAllOnes())
3220       if (SimplifyDemandedVectorEltsBinOp(Op0, Op1))
3221         return true;
3222     break;
3223   }
3224   case ISD::SHL:
3225   case ISD::SRL:
3226   case ISD::SRA:
3227   case ISD::ROTL:
3228   case ISD::ROTR: {
3229     SDValue Op0 = Op.getOperand(0);
3230     SDValue Op1 = Op.getOperand(1);
3231 
3232     APInt UndefRHS, ZeroRHS;
3233     if (SimplifyDemandedVectorElts(Op1, DemandedElts, UndefRHS, ZeroRHS, TLO,
3234                                    Depth + 1))
3235       return true;
3236     APInt UndefLHS, ZeroLHS;
3237     if (SimplifyDemandedVectorElts(Op0, DemandedElts, UndefLHS, ZeroLHS, TLO,
3238                                    Depth + 1))
3239       return true;
3240 
3241     KnownZero = ZeroLHS;
3242     KnownUndef = UndefLHS & UndefRHS; // TODO: use getKnownUndefForVectorBinop?
3243 
3244     // Attempt to avoid multi-use ops if we don't need anything from them.
3245     // TODO - use KnownUndef to relax the demandedelts?
3246     if (!DemandedElts.isAllOnes())
3247       if (SimplifyDemandedVectorEltsBinOp(Op0, Op1))
3248         return true;
3249     break;
3250   }
3251   case ISD::MUL:
3252   case ISD::AND: {
3253     SDValue Op0 = Op.getOperand(0);
3254     SDValue Op1 = Op.getOperand(1);
3255 
3256     APInt SrcUndef, SrcZero;
3257     if (SimplifyDemandedVectorElts(Op1, DemandedElts, SrcUndef, SrcZero, TLO,
3258                                    Depth + 1))
3259       return true;
3260     if (SimplifyDemandedVectorElts(Op0, DemandedElts, KnownUndef, KnownZero,
3261                                    TLO, Depth + 1))
3262       return true;
3263 
3264     // If either side has a zero element, then the result element is zero, even
3265     // if the other is an UNDEF.
3266     // TODO: Extend getKnownUndefForVectorBinop to also deal with known zeros
3267     // and then handle 'and' nodes with the rest of the binop opcodes.
3268     KnownZero |= SrcZero;
3269     KnownUndef &= SrcUndef;
3270     KnownUndef &= ~KnownZero;
3271 
3272     // Attempt to avoid multi-use ops if we don't need anything from them.
3273     // TODO - use KnownUndef to relax the demandedelts?
3274     if (!DemandedElts.isAllOnes())
3275       if (SimplifyDemandedVectorEltsBinOp(Op0, Op1))
3276         return true;
3277     break;
3278   }
3279   case ISD::TRUNCATE:
3280   case ISD::SIGN_EXTEND:
3281   case ISD::ZERO_EXTEND:
3282     if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedElts, KnownUndef,
3283                                    KnownZero, TLO, Depth + 1))
3284       return true;
3285 
3286     if (Op.getOpcode() == ISD::ZERO_EXTEND) {
3287       // zext(undef) upper bits are guaranteed to be zero.
3288       if (DemandedElts.isSubsetOf(KnownUndef))
3289         return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT));
3290       KnownUndef.clearAllBits();
3291     }
3292     break;
3293   default: {
3294     if (Op.getOpcode() >= ISD::BUILTIN_OP_END) {
3295       if (SimplifyDemandedVectorEltsForTargetNode(Op, DemandedElts, KnownUndef,
3296                                                   KnownZero, TLO, Depth))
3297         return true;
3298     } else {
3299       KnownBits Known;
3300       APInt DemandedBits = APInt::getAllOnes(EltSizeInBits);
3301       if (SimplifyDemandedBits(Op, DemandedBits, OriginalDemandedElts, Known,
3302                                TLO, Depth, AssumeSingleUse))
3303         return true;
3304     }
3305     break;
3306   }
3307   }
3308   assert((KnownUndef & KnownZero) == 0 && "Elements flagged as undef AND zero");
3309 
3310   // Constant fold all undef cases.
3311   // TODO: Handle zero cases as well.
3312   if (DemandedElts.isSubsetOf(KnownUndef))
3313     return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT));
3314 
3315   return false;
3316 }
3317 
3318 /// Determine which of the bits specified in Mask are known to be either zero or
3319 /// one and return them in the Known.
3320 void TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
3321                                                    KnownBits &Known,
3322                                                    const APInt &DemandedElts,
3323                                                    const SelectionDAG &DAG,
3324                                                    unsigned Depth) const {
3325   assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
3326           Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
3327           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
3328           Op.getOpcode() == ISD::INTRINSIC_VOID) &&
3329          "Should use MaskedValueIsZero if you don't know whether Op"
3330          " is a target node!");
3331   Known.resetAll();
3332 }
3333 
3334 void TargetLowering::computeKnownBitsForTargetInstr(
3335     GISelKnownBits &Analysis, Register R, KnownBits &Known,
3336     const APInt &DemandedElts, const MachineRegisterInfo &MRI,
3337     unsigned Depth) const {
3338   Known.resetAll();
3339 }
3340 
3341 void TargetLowering::computeKnownBitsForFrameIndex(
3342   const int FrameIdx, KnownBits &Known, const MachineFunction &MF) const {
3343   // The low bits are known zero if the pointer is aligned.
3344   Known.Zero.setLowBits(Log2(MF.getFrameInfo().getObjectAlign(FrameIdx)));
3345 }
3346 
3347 Align TargetLowering::computeKnownAlignForTargetInstr(
3348   GISelKnownBits &Analysis, Register R, const MachineRegisterInfo &MRI,
3349   unsigned Depth) const {
3350   return Align(1);
3351 }
3352 
3353 /// This method can be implemented by targets that want to expose additional
3354 /// information about sign bits to the DAG Combiner.
3355 unsigned TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
3356                                                          const APInt &,
3357                                                          const SelectionDAG &,
3358                                                          unsigned Depth) const {
3359   assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
3360           Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
3361           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
3362           Op.getOpcode() == ISD::INTRINSIC_VOID) &&
3363          "Should use ComputeNumSignBits if you don't know whether Op"
3364          " is a target node!");
3365   return 1;
3366 }
3367 
3368 unsigned TargetLowering::computeNumSignBitsForTargetInstr(
3369   GISelKnownBits &Analysis, Register R, const APInt &DemandedElts,
3370   const MachineRegisterInfo &MRI, unsigned Depth) const {
3371   return 1;
3372 }
3373 
3374 bool TargetLowering::SimplifyDemandedVectorEltsForTargetNode(
3375     SDValue Op, const APInt &DemandedElts, APInt &KnownUndef, APInt &KnownZero,
3376     TargetLoweringOpt &TLO, unsigned Depth) const {
3377   assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
3378           Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
3379           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
3380           Op.getOpcode() == ISD::INTRINSIC_VOID) &&
3381          "Should use SimplifyDemandedVectorElts if you don't know whether Op"
3382          " is a target node!");
3383   return false;
3384 }
3385 
3386 bool TargetLowering::SimplifyDemandedBitsForTargetNode(
3387     SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
3388     KnownBits &Known, TargetLoweringOpt &TLO, unsigned Depth) const {
3389   assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
3390           Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
3391           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
3392           Op.getOpcode() == ISD::INTRINSIC_VOID) &&
3393          "Should use SimplifyDemandedBits if you don't know whether Op"
3394          " is a target node!");
3395   computeKnownBitsForTargetNode(Op, Known, DemandedElts, TLO.DAG, Depth);
3396   return false;
3397 }
3398 
3399 SDValue TargetLowering::SimplifyMultipleUseDemandedBitsForTargetNode(
3400     SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
3401     SelectionDAG &DAG, unsigned Depth) const {
3402   assert(
3403       (Op.getOpcode() >= ISD::BUILTIN_OP_END ||
3404        Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
3405        Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
3406        Op.getOpcode() == ISD::INTRINSIC_VOID) &&
3407       "Should use SimplifyMultipleUseDemandedBits if you don't know whether Op"
3408       " is a target node!");
3409   return SDValue();
3410 }
3411 
3412 SDValue
3413 TargetLowering::buildLegalVectorShuffle(EVT VT, const SDLoc &DL, SDValue N0,
3414                                         SDValue N1, MutableArrayRef<int> Mask,
3415                                         SelectionDAG &DAG) const {
3416   bool LegalMask = isShuffleMaskLegal(Mask, VT);
3417   if (!LegalMask) {
3418     std::swap(N0, N1);
3419     ShuffleVectorSDNode::commuteMask(Mask);
3420     LegalMask = isShuffleMaskLegal(Mask, VT);
3421   }
3422 
3423   if (!LegalMask)
3424     return SDValue();
3425 
3426   return DAG.getVectorShuffle(VT, DL, N0, N1, Mask);
3427 }
3428 
3429 const Constant *TargetLowering::getTargetConstantFromLoad(LoadSDNode*) const {
3430   return nullptr;
3431 }
3432 
3433 bool TargetLowering::isGuaranteedNotToBeUndefOrPoisonForTargetNode(
3434     SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
3435     bool PoisonOnly, unsigned Depth) const {
3436   assert(
3437       (Op.getOpcode() >= ISD::BUILTIN_OP_END ||
3438        Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
3439        Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
3440        Op.getOpcode() == ISD::INTRINSIC_VOID) &&
3441       "Should use isGuaranteedNotToBeUndefOrPoison if you don't know whether Op"
3442       " is a target node!");
3443   return false;
3444 }
3445 
3446 bool TargetLowering::isKnownNeverNaNForTargetNode(SDValue Op,
3447                                                   const SelectionDAG &DAG,
3448                                                   bool SNaN,
3449                                                   unsigned Depth) const {
3450   assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
3451           Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
3452           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
3453           Op.getOpcode() == ISD::INTRINSIC_VOID) &&
3454          "Should use isKnownNeverNaN if you don't know whether Op"
3455          " is a target node!");
3456   return false;
3457 }
3458 
3459 bool TargetLowering::isSplatValueForTargetNode(SDValue Op,
3460                                                const APInt &DemandedElts,
3461                                                APInt &UndefElts,
3462                                                unsigned Depth) const {
3463   assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
3464           Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
3465           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
3466           Op.getOpcode() == ISD::INTRINSIC_VOID) &&
3467          "Should use isSplatValue if you don't know whether Op"
3468          " is a target node!");
3469   return false;
3470 }
3471 
3472 // FIXME: Ideally, this would use ISD::isConstantSplatVector(), but that must
3473 // work with truncating build vectors and vectors with elements of less than
3474 // 8 bits.
3475 bool TargetLowering::isConstTrueVal(SDValue N) const {
3476   if (!N)
3477     return false;
3478 
3479   unsigned EltWidth;
3480   APInt CVal;
3481   if (ConstantSDNode *CN = isConstOrConstSplat(N, /*AllowUndefs=*/false,
3482                                                /*AllowTruncation=*/true)) {
3483     CVal = CN->getAPIntValue();
3484     EltWidth = N.getValueType().getScalarSizeInBits();
3485   } else
3486     return false;
3487 
3488   // If this is a truncating splat, truncate the splat value.
3489   // Otherwise, we may fail to match the expected values below.
3490   if (EltWidth < CVal.getBitWidth())
3491     CVal = CVal.trunc(EltWidth);
3492 
3493   switch (getBooleanContents(N.getValueType())) {
3494   case UndefinedBooleanContent:
3495     return CVal[0];
3496   case ZeroOrOneBooleanContent:
3497     return CVal.isOne();
3498   case ZeroOrNegativeOneBooleanContent:
3499     return CVal.isAllOnes();
3500   }
3501 
3502   llvm_unreachable("Invalid boolean contents");
3503 }
3504 
3505 bool TargetLowering::isConstFalseVal(SDValue N) const {
3506   if (!N)
3507     return false;
3508 
3509   const ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N);
3510   if (!CN) {
3511     const BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
3512     if (!BV)
3513       return false;
3514 
3515     // Only interested in constant splats, we don't care about undef
3516     // elements in identifying boolean constants and getConstantSplatNode
3517     // returns NULL if all ops are undef;
3518     CN = BV->getConstantSplatNode();
3519     if (!CN)
3520       return false;
3521   }
3522 
3523   if (getBooleanContents(N->getValueType(0)) == UndefinedBooleanContent)
3524     return !CN->getAPIntValue()[0];
3525 
3526   return CN->isZero();
3527 }
3528 
3529 bool TargetLowering::isExtendedTrueVal(const ConstantSDNode *N, EVT VT,
3530                                        bool SExt) const {
3531   if (VT == MVT::i1)
3532     return N->isOne();
3533 
3534   TargetLowering::BooleanContent Cnt = getBooleanContents(VT);
3535   switch (Cnt) {
3536   case TargetLowering::ZeroOrOneBooleanContent:
3537     // An extended value of 1 is always true, unless its original type is i1,
3538     // in which case it will be sign extended to -1.
3539     return (N->isOne() && !SExt) || (SExt && (N->getValueType(0) != MVT::i1));
3540   case TargetLowering::UndefinedBooleanContent:
3541   case TargetLowering::ZeroOrNegativeOneBooleanContent:
3542     return N->isAllOnes() && SExt;
3543   }
3544   llvm_unreachable("Unexpected enumeration.");
3545 }
3546 
3547 /// This helper function of SimplifySetCC tries to optimize the comparison when
3548 /// either operand of the SetCC node is a bitwise-and instruction.
3549 SDValue TargetLowering::foldSetCCWithAnd(EVT VT, SDValue N0, SDValue N1,
3550                                          ISD::CondCode Cond, const SDLoc &DL,
3551                                          DAGCombinerInfo &DCI) const {
3552   if (N1.getOpcode() == ISD::AND && N0.getOpcode() != ISD::AND)
3553     std::swap(N0, N1);
3554 
3555   SelectionDAG &DAG = DCI.DAG;
3556   EVT OpVT = N0.getValueType();
3557   if (N0.getOpcode() != ISD::AND || !OpVT.isInteger() ||
3558       (Cond != ISD::SETEQ && Cond != ISD::SETNE))
3559     return SDValue();
3560 
3561   // (X & Y) != 0 --> zextOrTrunc(X & Y)
3562   // iff everything but LSB is known zero:
3563   if (Cond == ISD::SETNE && isNullConstant(N1) &&
3564       (getBooleanContents(OpVT) == TargetLowering::UndefinedBooleanContent ||
3565        getBooleanContents(OpVT) == TargetLowering::ZeroOrOneBooleanContent)) {
3566     unsigned NumEltBits = OpVT.getScalarSizeInBits();
3567     APInt UpperBits = APInt::getHighBitsSet(NumEltBits, NumEltBits - 1);
3568     if (DAG.MaskedValueIsZero(N0, UpperBits))
3569       return DAG.getBoolExtOrTrunc(N0, DL, VT, OpVT);
3570   }
3571 
3572   // Match these patterns in any of their permutations:
3573   // (X & Y) == Y
3574   // (X & Y) != Y
3575   SDValue X, Y;
3576   if (N0.getOperand(0) == N1) {
3577     X = N0.getOperand(1);
3578     Y = N0.getOperand(0);
3579   } else if (N0.getOperand(1) == N1) {
3580     X = N0.getOperand(0);
3581     Y = N0.getOperand(1);
3582   } else {
3583     return SDValue();
3584   }
3585 
3586   SDValue Zero = DAG.getConstant(0, DL, OpVT);
3587   if (DAG.isKnownToBeAPowerOfTwo(Y)) {
3588     // Simplify X & Y == Y to X & Y != 0 if Y has exactly one bit set.
3589     // Note that where Y is variable and is known to have at most one bit set
3590     // (for example, if it is Z & 1) we cannot do this; the expressions are not
3591     // equivalent when Y == 0.
3592     assert(OpVT.isInteger());
3593     Cond = ISD::getSetCCInverse(Cond, OpVT);
3594     if (DCI.isBeforeLegalizeOps() ||
3595         isCondCodeLegal(Cond, N0.getSimpleValueType()))
3596       return DAG.getSetCC(DL, VT, N0, Zero, Cond);
3597   } else if (N0.hasOneUse() && hasAndNotCompare(Y)) {
3598     // If the target supports an 'and-not' or 'and-complement' logic operation,
3599     // try to use that to make a comparison operation more efficient.
3600     // But don't do this transform if the mask is a single bit because there are
3601     // more efficient ways to deal with that case (for example, 'bt' on x86 or
3602     // 'rlwinm' on PPC).
3603 
3604     // Bail out if the compare operand that we want to turn into a zero is
3605     // already a zero (otherwise, infinite loop).
3606     auto *YConst = dyn_cast<ConstantSDNode>(Y);
3607     if (YConst && YConst->isZero())
3608       return SDValue();
3609 
3610     // Transform this into: ~X & Y == 0.
3611     SDValue NotX = DAG.getNOT(SDLoc(X), X, OpVT);
3612     SDValue NewAnd = DAG.getNode(ISD::AND, SDLoc(N0), OpVT, NotX, Y);
3613     return DAG.getSetCC(DL, VT, NewAnd, Zero, Cond);
3614   }
3615 
3616   return SDValue();
3617 }
3618 
3619 /// There are multiple IR patterns that could be checking whether certain
3620 /// truncation of a signed number would be lossy or not. The pattern which is
3621 /// best at IR level, may not lower optimally. Thus, we want to unfold it.
3622 /// We are looking for the following pattern: (KeptBits is a constant)
3623 ///   (add %x, (1 << (KeptBits-1))) srccond (1 << KeptBits)
3624 /// KeptBits won't be bitwidth(x), that will be constant-folded to true/false.
3625 /// KeptBits also can't be 1, that would have been folded to  %x dstcond 0
3626 /// We will unfold it into the natural trunc+sext pattern:
3627 ///   ((%x << C) a>> C) dstcond %x
3628 /// Where  C = bitwidth(x) - KeptBits  and  C u< bitwidth(x)
3629 SDValue TargetLowering::optimizeSetCCOfSignedTruncationCheck(
3630     EVT SCCVT, SDValue N0, SDValue N1, ISD::CondCode Cond, DAGCombinerInfo &DCI,
3631     const SDLoc &DL) const {
3632   // We must be comparing with a constant.
3633   ConstantSDNode *C1;
3634   if (!(C1 = dyn_cast<ConstantSDNode>(N1)))
3635     return SDValue();
3636 
3637   // N0 should be:  add %x, (1 << (KeptBits-1))
3638   if (N0->getOpcode() != ISD::ADD)
3639     return SDValue();
3640 
3641   // And we must be 'add'ing a constant.
3642   ConstantSDNode *C01;
3643   if (!(C01 = dyn_cast<ConstantSDNode>(N0->getOperand(1))))
3644     return SDValue();
3645 
3646   SDValue X = N0->getOperand(0);
3647   EVT XVT = X.getValueType();
3648 
3649   // Validate constants ...
3650 
3651   APInt I1 = C1->getAPIntValue();
3652 
3653   ISD::CondCode NewCond;
3654   if (Cond == ISD::CondCode::SETULT) {
3655     NewCond = ISD::CondCode::SETEQ;
3656   } else if (Cond == ISD::CondCode::SETULE) {
3657     NewCond = ISD::CondCode::SETEQ;
3658     // But need to 'canonicalize' the constant.
3659     I1 += 1;
3660   } else if (Cond == ISD::CondCode::SETUGT) {
3661     NewCond = ISD::CondCode::SETNE;
3662     // But need to 'canonicalize' the constant.
3663     I1 += 1;
3664   } else if (Cond == ISD::CondCode::SETUGE) {
3665     NewCond = ISD::CondCode::SETNE;
3666   } else
3667     return SDValue();
3668 
3669   APInt I01 = C01->getAPIntValue();
3670 
3671   auto checkConstants = [&I1, &I01]() -> bool {
3672     // Both of them must be power-of-two, and the constant from setcc is bigger.
3673     return I1.ugt(I01) && I1.isPowerOf2() && I01.isPowerOf2();
3674   };
3675 
3676   if (checkConstants()) {
3677     // Great, e.g. got  icmp ult i16 (add i16 %x, 128), 256
3678   } else {
3679     // What if we invert constants? (and the target predicate)
3680     I1.negate();
3681     I01.negate();
3682     assert(XVT.isInteger());
3683     NewCond = getSetCCInverse(NewCond, XVT);
3684     if (!checkConstants())
3685       return SDValue();
3686     // Great, e.g. got  icmp uge i16 (add i16 %x, -128), -256
3687   }
3688 
3689   // They are power-of-two, so which bit is set?
3690   const unsigned KeptBits = I1.logBase2();
3691   const unsigned KeptBitsMinusOne = I01.logBase2();
3692 
3693   // Magic!
3694   if (KeptBits != (KeptBitsMinusOne + 1))
3695     return SDValue();
3696   assert(KeptBits > 0 && KeptBits < XVT.getSizeInBits() && "unreachable");
3697 
3698   // We don't want to do this in every single case.
3699   SelectionDAG &DAG = DCI.DAG;
3700   if (!DAG.getTargetLoweringInfo().shouldTransformSignedTruncationCheck(
3701           XVT, KeptBits))
3702     return SDValue();
3703 
3704   const unsigned MaskedBits = XVT.getSizeInBits() - KeptBits;
3705   assert(MaskedBits > 0 && MaskedBits < XVT.getSizeInBits() && "unreachable");
3706 
3707   // Unfold into:  ((%x << C) a>> C) cond %x
3708   // Where 'cond' will be either 'eq' or 'ne'.
3709   SDValue ShiftAmt = DAG.getConstant(MaskedBits, DL, XVT);
3710   SDValue T0 = DAG.getNode(ISD::SHL, DL, XVT, X, ShiftAmt);
3711   SDValue T1 = DAG.getNode(ISD::SRA, DL, XVT, T0, ShiftAmt);
3712   SDValue T2 = DAG.getSetCC(DL, SCCVT, T1, X, NewCond);
3713 
3714   return T2;
3715 }
3716 
3717 // (X & (C l>>/<< Y)) ==/!= 0  -->  ((X <</l>> Y) & C) ==/!= 0
3718 SDValue TargetLowering::optimizeSetCCByHoistingAndByConstFromLogicalShift(
3719     EVT SCCVT, SDValue N0, SDValue N1C, ISD::CondCode Cond,
3720     DAGCombinerInfo &DCI, const SDLoc &DL) const {
3721   assert(isConstOrConstSplat(N1C) &&
3722          isConstOrConstSplat(N1C)->getAPIntValue().isZero() &&
3723          "Should be a comparison with 0.");
3724   assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
3725          "Valid only for [in]equality comparisons.");
3726 
3727   unsigned NewShiftOpcode;
3728   SDValue X, C, Y;
3729 
3730   SelectionDAG &DAG = DCI.DAG;
3731   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3732 
3733   // Look for '(C l>>/<< Y)'.
3734   auto Match = [&NewShiftOpcode, &X, &C, &Y, &TLI, &DAG](SDValue V) {
3735     // The shift should be one-use.
3736     if (!V.hasOneUse())
3737       return false;
3738     unsigned OldShiftOpcode = V.getOpcode();
3739     switch (OldShiftOpcode) {
3740     case ISD::SHL:
3741       NewShiftOpcode = ISD::SRL;
3742       break;
3743     case ISD::SRL:
3744       NewShiftOpcode = ISD::SHL;
3745       break;
3746     default:
3747       return false; // must be a logical shift.
3748     }
3749     // We should be shifting a constant.
3750     // FIXME: best to use isConstantOrConstantVector().
3751     C = V.getOperand(0);
3752     ConstantSDNode *CC =
3753         isConstOrConstSplat(C, /*AllowUndefs=*/true, /*AllowTruncation=*/true);
3754     if (!CC)
3755       return false;
3756     Y = V.getOperand(1);
3757 
3758     ConstantSDNode *XC =
3759         isConstOrConstSplat(X, /*AllowUndefs=*/true, /*AllowTruncation=*/true);
3760     return TLI.shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd(
3761         X, XC, CC, Y, OldShiftOpcode, NewShiftOpcode, DAG);
3762   };
3763 
3764   // LHS of comparison should be an one-use 'and'.
3765   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
3766     return SDValue();
3767 
3768   X = N0.getOperand(0);
3769   SDValue Mask = N0.getOperand(1);
3770 
3771   // 'and' is commutative!
3772   if (!Match(Mask)) {
3773     std::swap(X, Mask);
3774     if (!Match(Mask))
3775       return SDValue();
3776   }
3777 
3778   EVT VT = X.getValueType();
3779 
3780   // Produce:
3781   // ((X 'OppositeShiftOpcode' Y) & C) Cond 0
3782   SDValue T0 = DAG.getNode(NewShiftOpcode, DL, VT, X, Y);
3783   SDValue T1 = DAG.getNode(ISD::AND, DL, VT, T0, C);
3784   SDValue T2 = DAG.getSetCC(DL, SCCVT, T1, N1C, Cond);
3785   return T2;
3786 }
3787 
3788 /// Try to fold an equality comparison with a {add/sub/xor} binary operation as
3789 /// the 1st operand (N0). Callers are expected to swap the N0/N1 parameters to
3790 /// handle the commuted versions of these patterns.
3791 SDValue TargetLowering::foldSetCCWithBinOp(EVT VT, SDValue N0, SDValue N1,
3792                                            ISD::CondCode Cond, const SDLoc &DL,
3793                                            DAGCombinerInfo &DCI) const {
3794   unsigned BOpcode = N0.getOpcode();
3795   assert((BOpcode == ISD::ADD || BOpcode == ISD::SUB || BOpcode == ISD::XOR) &&
3796          "Unexpected binop");
3797   assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) && "Unexpected condcode");
3798 
3799   // (X + Y) == X --> Y == 0
3800   // (X - Y) == X --> Y == 0
3801   // (X ^ Y) == X --> Y == 0
3802   SelectionDAG &DAG = DCI.DAG;
3803   EVT OpVT = N0.getValueType();
3804   SDValue X = N0.getOperand(0);
3805   SDValue Y = N0.getOperand(1);
3806   if (X == N1)
3807     return DAG.getSetCC(DL, VT, Y, DAG.getConstant(0, DL, OpVT), Cond);
3808 
3809   if (Y != N1)
3810     return SDValue();
3811 
3812   // (X + Y) == Y --> X == 0
3813   // (X ^ Y) == Y --> X == 0
3814   if (BOpcode == ISD::ADD || BOpcode == ISD::XOR)
3815     return DAG.getSetCC(DL, VT, X, DAG.getConstant(0, DL, OpVT), Cond);
3816 
3817   // The shift would not be valid if the operands are boolean (i1).
3818   if (!N0.hasOneUse() || OpVT.getScalarSizeInBits() == 1)
3819     return SDValue();
3820 
3821   // (X - Y) == Y --> X == Y << 1
3822   EVT ShiftVT = getShiftAmountTy(OpVT, DAG.getDataLayout(),
3823                                  !DCI.isBeforeLegalize());
3824   SDValue One = DAG.getConstant(1, DL, ShiftVT);
3825   SDValue YShl1 = DAG.getNode(ISD::SHL, DL, N1.getValueType(), Y, One);
3826   if (!DCI.isCalledByLegalizer())
3827     DCI.AddToWorklist(YShl1.getNode());
3828   return DAG.getSetCC(DL, VT, X, YShl1, Cond);
3829 }
3830 
3831 static SDValue simplifySetCCWithCTPOP(const TargetLowering &TLI, EVT VT,
3832                                       SDValue N0, const APInt &C1,
3833                                       ISD::CondCode Cond, const SDLoc &dl,
3834                                       SelectionDAG &DAG) {
3835   // Look through truncs that don't change the value of a ctpop.
3836   // FIXME: Add vector support? Need to be careful with setcc result type below.
3837   SDValue CTPOP = N0;
3838   if (N0.getOpcode() == ISD::TRUNCATE && N0.hasOneUse() && !VT.isVector() &&
3839       N0.getScalarValueSizeInBits() > Log2_32(N0.getOperand(0).getScalarValueSizeInBits()))
3840     CTPOP = N0.getOperand(0);
3841 
3842   if (CTPOP.getOpcode() != ISD::CTPOP || !CTPOP.hasOneUse())
3843     return SDValue();
3844 
3845   EVT CTVT = CTPOP.getValueType();
3846   SDValue CTOp = CTPOP.getOperand(0);
3847 
3848   // If this is a vector CTPOP, keep the CTPOP if it is legal.
3849   // TODO: Should we check if CTPOP is legal(or custom) for scalars?
3850   if (VT.isVector() && TLI.isOperationLegal(ISD::CTPOP, CTVT))
3851     return SDValue();
3852 
3853   // (ctpop x) u< 2 -> (x & x-1) == 0
3854   // (ctpop x) u> 1 -> (x & x-1) != 0
3855   if (Cond == ISD::SETULT || Cond == ISD::SETUGT) {
3856     unsigned CostLimit = TLI.getCustomCtpopCost(CTVT, Cond);
3857     if (C1.ugt(CostLimit + (Cond == ISD::SETULT)))
3858       return SDValue();
3859     if (C1 == 0 && (Cond == ISD::SETULT))
3860       return SDValue(); // This is handled elsewhere.
3861 
3862     unsigned Passes = C1.getLimitedValue() - (Cond == ISD::SETULT);
3863 
3864     SDValue NegOne = DAG.getAllOnesConstant(dl, CTVT);
3865     SDValue Result = CTOp;
3866     for (unsigned i = 0; i < Passes; i++) {
3867       SDValue Add = DAG.getNode(ISD::ADD, dl, CTVT, Result, NegOne);
3868       Result = DAG.getNode(ISD::AND, dl, CTVT, Result, Add);
3869     }
3870     ISD::CondCode CC = Cond == ISD::SETULT ? ISD::SETEQ : ISD::SETNE;
3871     return DAG.getSetCC(dl, VT, Result, DAG.getConstant(0, dl, CTVT), CC);
3872   }
3873 
3874   // If ctpop is not supported, expand a power-of-2 comparison based on it.
3875   if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && C1 == 1) {
3876     // For scalars, keep CTPOP if it is legal or custom.
3877     if (!VT.isVector() && TLI.isOperationLegalOrCustom(ISD::CTPOP, CTVT))
3878       return SDValue();
3879     // This is based on X86's custom lowering for CTPOP which produces more
3880     // instructions than the expansion here.
3881 
3882     // (ctpop x) == 1 --> (x != 0) && ((x & x-1) == 0)
3883     // (ctpop x) != 1 --> (x == 0) || ((x & x-1) != 0)
3884     SDValue Zero = DAG.getConstant(0, dl, CTVT);
3885     SDValue NegOne = DAG.getAllOnesConstant(dl, CTVT);
3886     assert(CTVT.isInteger());
3887     ISD::CondCode InvCond = ISD::getSetCCInverse(Cond, CTVT);
3888     SDValue Add = DAG.getNode(ISD::ADD, dl, CTVT, CTOp, NegOne);
3889     SDValue And = DAG.getNode(ISD::AND, dl, CTVT, CTOp, Add);
3890     SDValue LHS = DAG.getSetCC(dl, VT, CTOp, Zero, InvCond);
3891     SDValue RHS = DAG.getSetCC(dl, VT, And, Zero, Cond);
3892     unsigned LogicOpcode = Cond == ISD::SETEQ ? ISD::AND : ISD::OR;
3893     return DAG.getNode(LogicOpcode, dl, VT, LHS, RHS);
3894   }
3895 
3896   return SDValue();
3897 }
3898 
3899 static SDValue foldSetCCWithRotate(EVT VT, SDValue N0, SDValue N1,
3900                                    ISD::CondCode Cond, const SDLoc &dl,
3901                                    SelectionDAG &DAG) {
3902   if (Cond != ISD::SETEQ && Cond != ISD::SETNE)
3903     return SDValue();
3904 
3905   auto *C1 = isConstOrConstSplat(N1, /* AllowUndefs */ true);
3906   if (!C1 || !(C1->isZero() || C1->isAllOnes()))
3907     return SDValue();
3908 
3909   auto getRotateSource = [](SDValue X) {
3910     if (X.getOpcode() == ISD::ROTL || X.getOpcode() == ISD::ROTR)
3911       return X.getOperand(0);
3912     return SDValue();
3913   };
3914 
3915   // Peek through a rotated value compared against 0 or -1:
3916   // (rot X, Y) == 0/-1 --> X == 0/-1
3917   // (rot X, Y) != 0/-1 --> X != 0/-1
3918   if (SDValue R = getRotateSource(N0))
3919     return DAG.getSetCC(dl, VT, R, N1, Cond);
3920 
3921   // Peek through an 'or' of a rotated value compared against 0:
3922   // or (rot X, Y), Z ==/!= 0 --> (or X, Z) ==/!= 0
3923   // or Z, (rot X, Y) ==/!= 0 --> (or X, Z) ==/!= 0
3924   //
3925   // TODO: Add the 'and' with -1 sibling.
3926   // TODO: Recurse through a series of 'or' ops to find the rotate.
3927   EVT OpVT = N0.getValueType();
3928   if (N0.hasOneUse() && N0.getOpcode() == ISD::OR && C1->isZero()) {
3929     if (SDValue R = getRotateSource(N0.getOperand(0))) {
3930       SDValue NewOr = DAG.getNode(ISD::OR, dl, OpVT, R, N0.getOperand(1));
3931       return DAG.getSetCC(dl, VT, NewOr, N1, Cond);
3932     }
3933     if (SDValue R = getRotateSource(N0.getOperand(1))) {
3934       SDValue NewOr = DAG.getNode(ISD::OR, dl, OpVT, R, N0.getOperand(0));
3935       return DAG.getSetCC(dl, VT, NewOr, N1, Cond);
3936     }
3937   }
3938 
3939   return SDValue();
3940 }
3941 
3942 static SDValue foldSetCCWithFunnelShift(EVT VT, SDValue N0, SDValue N1,
3943                                         ISD::CondCode Cond, const SDLoc &dl,
3944                                         SelectionDAG &DAG) {
3945   // If we are testing for all-bits-clear, we might be able to do that with
3946   // less shifting since bit-order does not matter.
3947   if (Cond != ISD::SETEQ && Cond != ISD::SETNE)
3948     return SDValue();
3949 
3950   auto *C1 = isConstOrConstSplat(N1, /* AllowUndefs */ true);
3951   if (!C1 || !C1->isZero())
3952     return SDValue();
3953 
3954   if (!N0.hasOneUse() ||
3955       (N0.getOpcode() != ISD::FSHL && N0.getOpcode() != ISD::FSHR))
3956     return SDValue();
3957 
3958   unsigned BitWidth = N0.getScalarValueSizeInBits();
3959   auto *ShAmtC = isConstOrConstSplat(N0.getOperand(2));
3960   if (!ShAmtC || ShAmtC->getAPIntValue().uge(BitWidth))
3961     return SDValue();
3962 
3963   // Canonicalize fshr as fshl to reduce pattern-matching.
3964   unsigned ShAmt = ShAmtC->getZExtValue();
3965   if (N0.getOpcode() == ISD::FSHR)
3966     ShAmt = BitWidth - ShAmt;
3967 
3968   // Match an 'or' with a specific operand 'Other' in either commuted variant.
3969   SDValue X, Y;
3970   auto matchOr = [&X, &Y](SDValue Or, SDValue Other) {
3971     if (Or.getOpcode() != ISD::OR || !Or.hasOneUse())
3972       return false;
3973     if (Or.getOperand(0) == Other) {
3974       X = Or.getOperand(0);
3975       Y = Or.getOperand(1);
3976       return true;
3977     }
3978     if (Or.getOperand(1) == Other) {
3979       X = Or.getOperand(1);
3980       Y = Or.getOperand(0);
3981       return true;
3982     }
3983     return false;
3984   };
3985 
3986   EVT OpVT = N0.getValueType();
3987   EVT ShAmtVT = N0.getOperand(2).getValueType();
3988   SDValue F0 = N0.getOperand(0);
3989   SDValue F1 = N0.getOperand(1);
3990   if (matchOr(F0, F1)) {
3991     // fshl (or X, Y), X, C ==/!= 0 --> or (shl Y, C), X ==/!= 0
3992     SDValue NewShAmt = DAG.getConstant(ShAmt, dl, ShAmtVT);
3993     SDValue Shift = DAG.getNode(ISD::SHL, dl, OpVT, Y, NewShAmt);
3994     SDValue NewOr = DAG.getNode(ISD::OR, dl, OpVT, Shift, X);
3995     return DAG.getSetCC(dl, VT, NewOr, N1, Cond);
3996   }
3997   if (matchOr(F1, F0)) {
3998     // fshl X, (or X, Y), C ==/!= 0 --> or (srl Y, BW-C), X ==/!= 0
3999     SDValue NewShAmt = DAG.getConstant(BitWidth - ShAmt, dl, ShAmtVT);
4000     SDValue Shift = DAG.getNode(ISD::SRL, dl, OpVT, Y, NewShAmt);
4001     SDValue NewOr = DAG.getNode(ISD::OR, dl, OpVT, Shift, X);
4002     return DAG.getSetCC(dl, VT, NewOr, N1, Cond);
4003   }
4004 
4005   return SDValue();
4006 }
4007 
4008 /// Try to simplify a setcc built with the specified operands and cc. If it is
4009 /// unable to simplify it, return a null SDValue.
4010 SDValue TargetLowering::SimplifySetCC(EVT VT, SDValue N0, SDValue N1,
4011                                       ISD::CondCode Cond, bool foldBooleans,
4012                                       DAGCombinerInfo &DCI,
4013                                       const SDLoc &dl) const {
4014   SelectionDAG &DAG = DCI.DAG;
4015   const DataLayout &Layout = DAG.getDataLayout();
4016   EVT OpVT = N0.getValueType();
4017 
4018   // Constant fold or commute setcc.
4019   if (SDValue Fold = DAG.FoldSetCC(VT, N0, N1, Cond, dl))
4020     return Fold;
4021 
4022   bool N0ConstOrSplat =
4023       isConstOrConstSplat(N0, /*AllowUndefs*/ false, /*AllowTruncate*/ true);
4024   bool N1ConstOrSplat =
4025       isConstOrConstSplat(N1, /*AllowUndefs*/ false, /*AllowTruncate*/ true);
4026 
4027   // Ensure that the constant occurs on the RHS and fold constant comparisons.
4028   // TODO: Handle non-splat vector constants. All undef causes trouble.
4029   // FIXME: We can't yet fold constant scalable vector splats, so avoid an
4030   // infinite loop here when we encounter one.
4031   ISD::CondCode SwappedCC = ISD::getSetCCSwappedOperands(Cond);
4032   if (N0ConstOrSplat && (!OpVT.isScalableVector() || !N1ConstOrSplat) &&
4033       (DCI.isBeforeLegalizeOps() ||
4034        isCondCodeLegal(SwappedCC, N0.getSimpleValueType())))
4035     return DAG.getSetCC(dl, VT, N1, N0, SwappedCC);
4036 
4037   // If we have a subtract with the same 2 non-constant operands as this setcc
4038   // -- but in reverse order -- then try to commute the operands of this setcc
4039   // to match. A matching pair of setcc (cmp) and sub may be combined into 1
4040   // instruction on some targets.
4041   if (!N0ConstOrSplat && !N1ConstOrSplat &&
4042       (DCI.isBeforeLegalizeOps() ||
4043        isCondCodeLegal(SwappedCC, N0.getSimpleValueType())) &&
4044       DAG.doesNodeExist(ISD::SUB, DAG.getVTList(OpVT), {N1, N0}) &&
4045       !DAG.doesNodeExist(ISD::SUB, DAG.getVTList(OpVT), {N0, N1}))
4046     return DAG.getSetCC(dl, VT, N1, N0, SwappedCC);
4047 
4048   if (SDValue V = foldSetCCWithRotate(VT, N0, N1, Cond, dl, DAG))
4049     return V;
4050 
4051   if (SDValue V = foldSetCCWithFunnelShift(VT, N0, N1, Cond, dl, DAG))
4052     return V;
4053 
4054   if (auto *N1C = isConstOrConstSplat(N1)) {
4055     const APInt &C1 = N1C->getAPIntValue();
4056 
4057     // Optimize some CTPOP cases.
4058     if (SDValue V = simplifySetCCWithCTPOP(*this, VT, N0, C1, Cond, dl, DAG))
4059       return V;
4060 
4061     // If the LHS is '(srl (ctlz x), 5)', the RHS is 0/1, and this is an
4062     // equality comparison, then we're just comparing whether X itself is
4063     // zero.
4064     if (N0.getOpcode() == ISD::SRL && (C1.isZero() || C1.isOne()) &&
4065         N0.getOperand(0).getOpcode() == ISD::CTLZ &&
4066         isPowerOf2_32(N0.getScalarValueSizeInBits())) {
4067       if (ConstantSDNode *ShAmt = isConstOrConstSplat(N0.getOperand(1))) {
4068         if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
4069             ShAmt->getAPIntValue() == Log2_32(N0.getScalarValueSizeInBits())) {
4070           if ((C1 == 0) == (Cond == ISD::SETEQ)) {
4071             // (srl (ctlz x), 5) == 0  -> X != 0
4072             // (srl (ctlz x), 5) != 1  -> X != 0
4073             Cond = ISD::SETNE;
4074           } else {
4075             // (srl (ctlz x), 5) != 0  -> X == 0
4076             // (srl (ctlz x), 5) == 1  -> X == 0
4077             Cond = ISD::SETEQ;
4078           }
4079           SDValue Zero = DAG.getConstant(0, dl, N0.getValueType());
4080           return DAG.getSetCC(dl, VT, N0.getOperand(0).getOperand(0), Zero,
4081                               Cond);
4082         }
4083       }
4084     }
4085   }
4086 
4087   // FIXME: Support vectors.
4088   if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) {
4089     const APInt &C1 = N1C->getAPIntValue();
4090 
4091     // (zext x) == C --> x == (trunc C)
4092     // (sext x) == C --> x == (trunc C)
4093     if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
4094         DCI.isBeforeLegalize() && N0->hasOneUse()) {
4095       unsigned MinBits = N0.getValueSizeInBits();
4096       SDValue PreExt;
4097       bool Signed = false;
4098       if (N0->getOpcode() == ISD::ZERO_EXTEND) {
4099         // ZExt
4100         MinBits = N0->getOperand(0).getValueSizeInBits();
4101         PreExt = N0->getOperand(0);
4102       } else if (N0->getOpcode() == ISD::AND) {
4103         // DAGCombine turns costly ZExts into ANDs
4104         if (auto *C = dyn_cast<ConstantSDNode>(N0->getOperand(1)))
4105           if ((C->getAPIntValue()+1).isPowerOf2()) {
4106             MinBits = C->getAPIntValue().countTrailingOnes();
4107             PreExt = N0->getOperand(0);
4108           }
4109       } else if (N0->getOpcode() == ISD::SIGN_EXTEND) {
4110         // SExt
4111         MinBits = N0->getOperand(0).getValueSizeInBits();
4112         PreExt = N0->getOperand(0);
4113         Signed = true;
4114       } else if (auto *LN0 = dyn_cast<LoadSDNode>(N0)) {
4115         // ZEXTLOAD / SEXTLOAD
4116         if (LN0->getExtensionType() == ISD::ZEXTLOAD) {
4117           MinBits = LN0->getMemoryVT().getSizeInBits();
4118           PreExt = N0;
4119         } else if (LN0->getExtensionType() == ISD::SEXTLOAD) {
4120           Signed = true;
4121           MinBits = LN0->getMemoryVT().getSizeInBits();
4122           PreExt = N0;
4123         }
4124       }
4125 
4126       // Figure out how many bits we need to preserve this constant.
4127       unsigned ReqdBits = Signed ? C1.getMinSignedBits() : C1.getActiveBits();
4128 
4129       // Make sure we're not losing bits from the constant.
4130       if (MinBits > 0 &&
4131           MinBits < C1.getBitWidth() &&
4132           MinBits >= ReqdBits) {
4133         EVT MinVT = EVT::getIntegerVT(*DAG.getContext(), MinBits);
4134         if (isTypeDesirableForOp(ISD::SETCC, MinVT)) {
4135           // Will get folded away.
4136           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, MinVT, PreExt);
4137           if (MinBits == 1 && C1 == 1)
4138             // Invert the condition.
4139             return DAG.getSetCC(dl, VT, Trunc, DAG.getConstant(0, dl, MVT::i1),
4140                                 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
4141           SDValue C = DAG.getConstant(C1.trunc(MinBits), dl, MinVT);
4142           return DAG.getSetCC(dl, VT, Trunc, C, Cond);
4143         }
4144 
4145         // If truncating the setcc operands is not desirable, we can still
4146         // simplify the expression in some cases:
4147         // setcc ([sz]ext (setcc x, y, cc)), 0, setne) -> setcc (x, y, cc)
4148         // setcc ([sz]ext (setcc x, y, cc)), 0, seteq) -> setcc (x, y, inv(cc))
4149         // setcc (zext (setcc x, y, cc)), 1, setne) -> setcc (x, y, inv(cc))
4150         // setcc (zext (setcc x, y, cc)), 1, seteq) -> setcc (x, y, cc)
4151         // setcc (sext (setcc x, y, cc)), -1, setne) -> setcc (x, y, inv(cc))
4152         // setcc (sext (setcc x, y, cc)), -1, seteq) -> setcc (x, y, cc)
4153         SDValue TopSetCC = N0->getOperand(0);
4154         unsigned N0Opc = N0->getOpcode();
4155         bool SExt = (N0Opc == ISD::SIGN_EXTEND);
4156         if (TopSetCC.getValueType() == MVT::i1 && VT == MVT::i1 &&
4157             TopSetCC.getOpcode() == ISD::SETCC &&
4158             (N0Opc == ISD::ZERO_EXTEND || N0Opc == ISD::SIGN_EXTEND) &&
4159             (isConstFalseVal(N1) ||
4160              isExtendedTrueVal(N1C, N0->getValueType(0), SExt))) {
4161 
4162           bool Inverse = (N1C->isZero() && Cond == ISD::SETEQ) ||
4163                          (!N1C->isZero() && Cond == ISD::SETNE);
4164 
4165           if (!Inverse)
4166             return TopSetCC;
4167 
4168           ISD::CondCode InvCond = ISD::getSetCCInverse(
4169               cast<CondCodeSDNode>(TopSetCC.getOperand(2))->get(),
4170               TopSetCC.getOperand(0).getValueType());
4171           return DAG.getSetCC(dl, VT, TopSetCC.getOperand(0),
4172                                       TopSetCC.getOperand(1),
4173                                       InvCond);
4174         }
4175       }
4176     }
4177 
4178     // If the LHS is '(and load, const)', the RHS is 0, the test is for
4179     // equality or unsigned, and all 1 bits of the const are in the same
4180     // partial word, see if we can shorten the load.
4181     if (DCI.isBeforeLegalize() &&
4182         !ISD::isSignedIntSetCC(Cond) &&
4183         N0.getOpcode() == ISD::AND && C1 == 0 &&
4184         N0.getNode()->hasOneUse() &&
4185         isa<LoadSDNode>(N0.getOperand(0)) &&
4186         N0.getOperand(0).getNode()->hasOneUse() &&
4187         isa<ConstantSDNode>(N0.getOperand(1))) {
4188       LoadSDNode *Lod = cast<LoadSDNode>(N0.getOperand(0));
4189       APInt bestMask;
4190       unsigned bestWidth = 0, bestOffset = 0;
4191       if (Lod->isSimple() && Lod->isUnindexed()) {
4192         unsigned origWidth = N0.getValueSizeInBits();
4193         unsigned maskWidth = origWidth;
4194         // We can narrow (e.g.) 16-bit extending loads on 32-bit target to
4195         // 8 bits, but have to be careful...
4196         if (Lod->getExtensionType() != ISD::NON_EXTLOAD)
4197           origWidth = Lod->getMemoryVT().getSizeInBits();
4198         const APInt &Mask = N0.getConstantOperandAPInt(1);
4199         for (unsigned width = origWidth / 2; width>=8; width /= 2) {
4200           APInt newMask = APInt::getLowBitsSet(maskWidth, width);
4201           for (unsigned offset=0; offset<origWidth/width; offset++) {
4202             if (Mask.isSubsetOf(newMask)) {
4203               if (Layout.isLittleEndian())
4204                 bestOffset = (uint64_t)offset * (width/8);
4205               else
4206                 bestOffset = (origWidth/width - offset - 1) * (width/8);
4207               bestMask = Mask.lshr(offset * (width/8) * 8);
4208               bestWidth = width;
4209               break;
4210             }
4211             newMask <<= width;
4212           }
4213         }
4214       }
4215       if (bestWidth) {
4216         EVT newVT = EVT::getIntegerVT(*DAG.getContext(), bestWidth);
4217         if (newVT.isRound() &&
4218             shouldReduceLoadWidth(Lod, ISD::NON_EXTLOAD, newVT)) {
4219           SDValue Ptr = Lod->getBasePtr();
4220           if (bestOffset != 0)
4221             Ptr =
4222                 DAG.getMemBasePlusOffset(Ptr, TypeSize::Fixed(bestOffset), dl);
4223           SDValue NewLoad =
4224               DAG.getLoad(newVT, dl, Lod->getChain(), Ptr,
4225                           Lod->getPointerInfo().getWithOffset(bestOffset),
4226                           Lod->getOriginalAlign());
4227           return DAG.getSetCC(dl, VT,
4228                               DAG.getNode(ISD::AND, dl, newVT, NewLoad,
4229                                       DAG.getConstant(bestMask.trunc(bestWidth),
4230                                                       dl, newVT)),
4231                               DAG.getConstant(0LL, dl, newVT), Cond);
4232         }
4233       }
4234     }
4235 
4236     // If the LHS is a ZERO_EXTEND, perform the comparison on the input.
4237     if (N0.getOpcode() == ISD::ZERO_EXTEND) {
4238       unsigned InSize = N0.getOperand(0).getValueSizeInBits();
4239 
4240       // If the comparison constant has bits in the upper part, the
4241       // zero-extended value could never match.
4242       if (C1.intersects(APInt::getHighBitsSet(C1.getBitWidth(),
4243                                               C1.getBitWidth() - InSize))) {
4244         switch (Cond) {
4245         case ISD::SETUGT:
4246         case ISD::SETUGE:
4247         case ISD::SETEQ:
4248           return DAG.getConstant(0, dl, VT);
4249         case ISD::SETULT:
4250         case ISD::SETULE:
4251         case ISD::SETNE:
4252           return DAG.getConstant(1, dl, VT);
4253         case ISD::SETGT:
4254         case ISD::SETGE:
4255           // True if the sign bit of C1 is set.
4256           return DAG.getConstant(C1.isNegative(), dl, VT);
4257         case ISD::SETLT:
4258         case ISD::SETLE:
4259           // True if the sign bit of C1 isn't set.
4260           return DAG.getConstant(C1.isNonNegative(), dl, VT);
4261         default:
4262           break;
4263         }
4264       }
4265 
4266       // Otherwise, we can perform the comparison with the low bits.
4267       switch (Cond) {
4268       case ISD::SETEQ:
4269       case ISD::SETNE:
4270       case ISD::SETUGT:
4271       case ISD::SETUGE:
4272       case ISD::SETULT:
4273       case ISD::SETULE: {
4274         EVT newVT = N0.getOperand(0).getValueType();
4275         if (DCI.isBeforeLegalizeOps() ||
4276             (isOperationLegal(ISD::SETCC, newVT) &&
4277              isCondCodeLegal(Cond, newVT.getSimpleVT()))) {
4278           EVT NewSetCCVT = getSetCCResultType(Layout, *DAG.getContext(), newVT);
4279           SDValue NewConst = DAG.getConstant(C1.trunc(InSize), dl, newVT);
4280 
4281           SDValue NewSetCC = DAG.getSetCC(dl, NewSetCCVT, N0.getOperand(0),
4282                                           NewConst, Cond);
4283           return DAG.getBoolExtOrTrunc(NewSetCC, dl, VT, N0.getValueType());
4284         }
4285         break;
4286       }
4287       default:
4288         break; // todo, be more careful with signed comparisons
4289       }
4290     } else if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
4291                (Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
4292                !isSExtCheaperThanZExt(cast<VTSDNode>(N0.getOperand(1))->getVT(),
4293                                       OpVT)) {
4294       EVT ExtSrcTy = cast<VTSDNode>(N0.getOperand(1))->getVT();
4295       unsigned ExtSrcTyBits = ExtSrcTy.getSizeInBits();
4296       EVT ExtDstTy = N0.getValueType();
4297       unsigned ExtDstTyBits = ExtDstTy.getSizeInBits();
4298 
4299       // If the constant doesn't fit into the number of bits for the source of
4300       // the sign extension, it is impossible for both sides to be equal.
4301       if (C1.getMinSignedBits() > ExtSrcTyBits)
4302         return DAG.getBoolConstant(Cond == ISD::SETNE, dl, VT, OpVT);
4303 
4304       assert(ExtDstTy == N0.getOperand(0).getValueType() &&
4305              ExtDstTy != ExtSrcTy && "Unexpected types!");
4306       APInt Imm = APInt::getLowBitsSet(ExtDstTyBits, ExtSrcTyBits);
4307       SDValue ZextOp = DAG.getNode(ISD::AND, dl, ExtDstTy, N0.getOperand(0),
4308                                    DAG.getConstant(Imm, dl, ExtDstTy));
4309       if (!DCI.isCalledByLegalizer())
4310         DCI.AddToWorklist(ZextOp.getNode());
4311       // Otherwise, make this a use of a zext.
4312       return DAG.getSetCC(dl, VT, ZextOp,
4313                           DAG.getConstant(C1 & Imm, dl, ExtDstTy), Cond);
4314     } else if ((N1C->isZero() || N1C->isOne()) &&
4315                (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
4316       // SETCC (SETCC), [0|1], [EQ|NE]  -> SETCC
4317       if (N0.getOpcode() == ISD::SETCC &&
4318           isTypeLegal(VT) && VT.bitsLE(N0.getValueType()) &&
4319           (N0.getValueType() == MVT::i1 ||
4320            getBooleanContents(N0.getOperand(0).getValueType()) ==
4321                        ZeroOrOneBooleanContent)) {
4322         bool TrueWhenTrue = (Cond == ISD::SETEQ) ^ (!N1C->isOne());
4323         if (TrueWhenTrue)
4324           return DAG.getNode(ISD::TRUNCATE, dl, VT, N0);
4325         // Invert the condition.
4326         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4327         CC = ISD::getSetCCInverse(CC, N0.getOperand(0).getValueType());
4328         if (DCI.isBeforeLegalizeOps() ||
4329             isCondCodeLegal(CC, N0.getOperand(0).getSimpleValueType()))
4330           return DAG.getSetCC(dl, VT, N0.getOperand(0), N0.getOperand(1), CC);
4331       }
4332 
4333       if ((N0.getOpcode() == ISD::XOR ||
4334            (N0.getOpcode() == ISD::AND &&
4335             N0.getOperand(0).getOpcode() == ISD::XOR &&
4336             N0.getOperand(1) == N0.getOperand(0).getOperand(1))) &&
4337           isOneConstant(N0.getOperand(1))) {
4338         // If this is (X^1) == 0/1, swap the RHS and eliminate the xor.  We
4339         // can only do this if the top bits are known zero.
4340         unsigned BitWidth = N0.getValueSizeInBits();
4341         if (DAG.MaskedValueIsZero(N0,
4342                                   APInt::getHighBitsSet(BitWidth,
4343                                                         BitWidth-1))) {
4344           // Okay, get the un-inverted input value.
4345           SDValue Val;
4346           if (N0.getOpcode() == ISD::XOR) {
4347             Val = N0.getOperand(0);
4348           } else {
4349             assert(N0.getOpcode() == ISD::AND &&
4350                     N0.getOperand(0).getOpcode() == ISD::XOR);
4351             // ((X^1)&1)^1 -> X & 1
4352             Val = DAG.getNode(ISD::AND, dl, N0.getValueType(),
4353                               N0.getOperand(0).getOperand(0),
4354                               N0.getOperand(1));
4355           }
4356 
4357           return DAG.getSetCC(dl, VT, Val, N1,
4358                               Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
4359         }
4360       } else if (N1C->isOne()) {
4361         SDValue Op0 = N0;
4362         if (Op0.getOpcode() == ISD::TRUNCATE)
4363           Op0 = Op0.getOperand(0);
4364 
4365         if ((Op0.getOpcode() == ISD::XOR) &&
4366             Op0.getOperand(0).getOpcode() == ISD::SETCC &&
4367             Op0.getOperand(1).getOpcode() == ISD::SETCC) {
4368           SDValue XorLHS = Op0.getOperand(0);
4369           SDValue XorRHS = Op0.getOperand(1);
4370           // Ensure that the input setccs return an i1 type or 0/1 value.
4371           if (Op0.getValueType() == MVT::i1 ||
4372               (getBooleanContents(XorLHS.getOperand(0).getValueType()) ==
4373                       ZeroOrOneBooleanContent &&
4374                getBooleanContents(XorRHS.getOperand(0).getValueType()) ==
4375                         ZeroOrOneBooleanContent)) {
4376             // (xor (setcc), (setcc)) == / != 1 -> (setcc) != / == (setcc)
4377             Cond = (Cond == ISD::SETEQ) ? ISD::SETNE : ISD::SETEQ;
4378             return DAG.getSetCC(dl, VT, XorLHS, XorRHS, Cond);
4379           }
4380         }
4381         if (Op0.getOpcode() == ISD::AND && isOneConstant(Op0.getOperand(1))) {
4382           // If this is (X&1) == / != 1, normalize it to (X&1) != / == 0.
4383           if (Op0.getValueType().bitsGT(VT))
4384             Op0 = DAG.getNode(ISD::AND, dl, VT,
4385                           DAG.getNode(ISD::TRUNCATE, dl, VT, Op0.getOperand(0)),
4386                           DAG.getConstant(1, dl, VT));
4387           else if (Op0.getValueType().bitsLT(VT))
4388             Op0 = DAG.getNode(ISD::AND, dl, VT,
4389                         DAG.getNode(ISD::ANY_EXTEND, dl, VT, Op0.getOperand(0)),
4390                         DAG.getConstant(1, dl, VT));
4391 
4392           return DAG.getSetCC(dl, VT, Op0,
4393                               DAG.getConstant(0, dl, Op0.getValueType()),
4394                               Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
4395         }
4396         if (Op0.getOpcode() == ISD::AssertZext &&
4397             cast<VTSDNode>(Op0.getOperand(1))->getVT() == MVT::i1)
4398           return DAG.getSetCC(dl, VT, Op0,
4399                               DAG.getConstant(0, dl, Op0.getValueType()),
4400                               Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
4401       }
4402     }
4403 
4404     // Given:
4405     //   icmp eq/ne (urem %x, %y), 0
4406     // Iff %x has 0 or 1 bits set, and %y has at least 2 bits set, omit 'urem':
4407     //   icmp eq/ne %x, 0
4408     if (N0.getOpcode() == ISD::UREM && N1C->isZero() &&
4409         (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
4410       KnownBits XKnown = DAG.computeKnownBits(N0.getOperand(0));
4411       KnownBits YKnown = DAG.computeKnownBits(N0.getOperand(1));
4412       if (XKnown.countMaxPopulation() == 1 && YKnown.countMinPopulation() >= 2)
4413         return DAG.getSetCC(dl, VT, N0.getOperand(0), N1, Cond);
4414     }
4415 
4416     // Fold set_cc seteq (ashr X, BW-1), -1 -> set_cc setlt X, 0
4417     //  and set_cc setne (ashr X, BW-1), -1 -> set_cc setge X, 0
4418     if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
4419         N0.getOpcode() == ISD::SRA && isa<ConstantSDNode>(N0.getOperand(1)) &&
4420         N0.getConstantOperandAPInt(1) == OpVT.getScalarSizeInBits() - 1 &&
4421         N1C && N1C->isAllOnes()) {
4422       return DAG.getSetCC(dl, VT, N0.getOperand(0),
4423                           DAG.getConstant(0, dl, OpVT),
4424                           Cond == ISD::SETEQ ? ISD::SETLT : ISD::SETGE);
4425     }
4426 
4427     if (SDValue V =
4428             optimizeSetCCOfSignedTruncationCheck(VT, N0, N1, Cond, DCI, dl))
4429       return V;
4430   }
4431 
4432   // These simplifications apply to splat vectors as well.
4433   // TODO: Handle more splat vector cases.
4434   if (auto *N1C = isConstOrConstSplat(N1)) {
4435     const APInt &C1 = N1C->getAPIntValue();
4436 
4437     APInt MinVal, MaxVal;
4438     unsigned OperandBitSize = N1C->getValueType(0).getScalarSizeInBits();
4439     if (ISD::isSignedIntSetCC(Cond)) {
4440       MinVal = APInt::getSignedMinValue(OperandBitSize);
4441       MaxVal = APInt::getSignedMaxValue(OperandBitSize);
4442     } else {
4443       MinVal = APInt::getMinValue(OperandBitSize);
4444       MaxVal = APInt::getMaxValue(OperandBitSize);
4445     }
4446 
4447     // Canonicalize GE/LE comparisons to use GT/LT comparisons.
4448     if (Cond == ISD::SETGE || Cond == ISD::SETUGE) {
4449       // X >= MIN --> true
4450       if (C1 == MinVal)
4451         return DAG.getBoolConstant(true, dl, VT, OpVT);
4452 
4453       if (!VT.isVector()) { // TODO: Support this for vectors.
4454         // X >= C0 --> X > (C0 - 1)
4455         APInt C = C1 - 1;
4456         ISD::CondCode NewCC = (Cond == ISD::SETGE) ? ISD::SETGT : ISD::SETUGT;
4457         if ((DCI.isBeforeLegalizeOps() ||
4458              isCondCodeLegal(NewCC, VT.getSimpleVT())) &&
4459             (!N1C->isOpaque() || (C.getBitWidth() <= 64 &&
4460                                   isLegalICmpImmediate(C.getSExtValue())))) {
4461           return DAG.getSetCC(dl, VT, N0,
4462                               DAG.getConstant(C, dl, N1.getValueType()),
4463                               NewCC);
4464         }
4465       }
4466     }
4467 
4468     if (Cond == ISD::SETLE || Cond == ISD::SETULE) {
4469       // X <= MAX --> true
4470       if (C1 == MaxVal)
4471         return DAG.getBoolConstant(true, dl, VT, OpVT);
4472 
4473       // X <= C0 --> X < (C0 + 1)
4474       if (!VT.isVector()) { // TODO: Support this for vectors.
4475         APInt C = C1 + 1;
4476         ISD::CondCode NewCC = (Cond == ISD::SETLE) ? ISD::SETLT : ISD::SETULT;
4477         if ((DCI.isBeforeLegalizeOps() ||
4478              isCondCodeLegal(NewCC, VT.getSimpleVT())) &&
4479             (!N1C->isOpaque() || (C.getBitWidth() <= 64 &&
4480                                   isLegalICmpImmediate(C.getSExtValue())))) {
4481           return DAG.getSetCC(dl, VT, N0,
4482                               DAG.getConstant(C, dl, N1.getValueType()),
4483                               NewCC);
4484         }
4485       }
4486     }
4487 
4488     if (Cond == ISD::SETLT || Cond == ISD::SETULT) {
4489       if (C1 == MinVal)
4490         return DAG.getBoolConstant(false, dl, VT, OpVT); // X < MIN --> false
4491 
4492       // TODO: Support this for vectors after legalize ops.
4493       if (!VT.isVector() || DCI.isBeforeLegalizeOps()) {
4494         // Canonicalize setlt X, Max --> setne X, Max
4495         if (C1 == MaxVal)
4496           return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE);
4497 
4498         // If we have setult X, 1, turn it into seteq X, 0
4499         if (C1 == MinVal+1)
4500           return DAG.getSetCC(dl, VT, N0,
4501                               DAG.getConstant(MinVal, dl, N0.getValueType()),
4502                               ISD::SETEQ);
4503       }
4504     }
4505 
4506     if (Cond == ISD::SETGT || Cond == ISD::SETUGT) {
4507       if (C1 == MaxVal)
4508         return DAG.getBoolConstant(false, dl, VT, OpVT); // X > MAX --> false
4509 
4510       // TODO: Support this for vectors after legalize ops.
4511       if (!VT.isVector() || DCI.isBeforeLegalizeOps()) {
4512         // Canonicalize setgt X, Min --> setne X, Min
4513         if (C1 == MinVal)
4514           return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE);
4515 
4516         // If we have setugt X, Max-1, turn it into seteq X, Max
4517         if (C1 == MaxVal-1)
4518           return DAG.getSetCC(dl, VT, N0,
4519                               DAG.getConstant(MaxVal, dl, N0.getValueType()),
4520                               ISD::SETEQ);
4521       }
4522     }
4523 
4524     if (Cond == ISD::SETEQ || Cond == ISD::SETNE) {
4525       // (X & (C l>>/<< Y)) ==/!= 0  -->  ((X <</l>> Y) & C) ==/!= 0
4526       if (C1.isZero())
4527         if (SDValue CC = optimizeSetCCByHoistingAndByConstFromLogicalShift(
4528                 VT, N0, N1, Cond, DCI, dl))
4529           return CC;
4530 
4531       // For all/any comparisons, replace or(x,shl(y,bw/2)) with and/or(x,y).
4532       // For example, when high 32-bits of i64 X are known clear:
4533       // all bits clear: (X | (Y<<32)) ==  0 --> (X | Y) ==  0
4534       // all bits set:   (X | (Y<<32)) == -1 --> (X & Y) == -1
4535       bool CmpZero = N1C->getAPIntValue().isZero();
4536       bool CmpNegOne = N1C->getAPIntValue().isAllOnes();
4537       if ((CmpZero || CmpNegOne) && N0.hasOneUse()) {
4538         // Match or(lo,shl(hi,bw/2)) pattern.
4539         auto IsConcat = [&](SDValue V, SDValue &Lo, SDValue &Hi) {
4540           unsigned EltBits = V.getScalarValueSizeInBits();
4541           if (V.getOpcode() != ISD::OR || (EltBits % 2) != 0)
4542             return false;
4543           SDValue LHS = V.getOperand(0);
4544           SDValue RHS = V.getOperand(1);
4545           APInt HiBits = APInt::getHighBitsSet(EltBits, EltBits / 2);
4546           // Unshifted element must have zero upperbits.
4547           if (RHS.getOpcode() == ISD::SHL &&
4548               isa<ConstantSDNode>(RHS.getOperand(1)) &&
4549               RHS.getConstantOperandAPInt(1) == (EltBits / 2) &&
4550               DAG.MaskedValueIsZero(LHS, HiBits)) {
4551             Lo = LHS;
4552             Hi = RHS.getOperand(0);
4553             return true;
4554           }
4555           if (LHS.getOpcode() == ISD::SHL &&
4556               isa<ConstantSDNode>(LHS.getOperand(1)) &&
4557               LHS.getConstantOperandAPInt(1) == (EltBits / 2) &&
4558               DAG.MaskedValueIsZero(RHS, HiBits)) {
4559             Lo = RHS;
4560             Hi = LHS.getOperand(0);
4561             return true;
4562           }
4563           return false;
4564         };
4565 
4566         auto MergeConcat = [&](SDValue Lo, SDValue Hi) {
4567           unsigned EltBits = N0.getScalarValueSizeInBits();
4568           unsigned HalfBits = EltBits / 2;
4569           APInt HiBits = APInt::getHighBitsSet(EltBits, HalfBits);
4570           SDValue LoBits = DAG.getConstant(~HiBits, dl, OpVT);
4571           SDValue HiMask = DAG.getNode(ISD::AND, dl, OpVT, Hi, LoBits);
4572           SDValue NewN0 =
4573               DAG.getNode(CmpZero ? ISD::OR : ISD::AND, dl, OpVT, Lo, HiMask);
4574           SDValue NewN1 = CmpZero ? DAG.getConstant(0, dl, OpVT) : LoBits;
4575           return DAG.getSetCC(dl, VT, NewN0, NewN1, Cond);
4576         };
4577 
4578         SDValue Lo, Hi;
4579         if (IsConcat(N0, Lo, Hi))
4580           return MergeConcat(Lo, Hi);
4581 
4582         if (N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR) {
4583           SDValue Lo0, Lo1, Hi0, Hi1;
4584           if (IsConcat(N0.getOperand(0), Lo0, Hi0) &&
4585               IsConcat(N0.getOperand(1), Lo1, Hi1)) {
4586             return MergeConcat(DAG.getNode(N0.getOpcode(), dl, OpVT, Lo0, Lo1),
4587                                DAG.getNode(N0.getOpcode(), dl, OpVT, Hi0, Hi1));
4588           }
4589         }
4590       }
4591     }
4592 
4593     // If we have "setcc X, C0", check to see if we can shrink the immediate
4594     // by changing cc.
4595     // TODO: Support this for vectors after legalize ops.
4596     if (!VT.isVector() || DCI.isBeforeLegalizeOps()) {
4597       // SETUGT X, SINTMAX  -> SETLT X, 0
4598       // SETUGE X, SINTMIN -> SETLT X, 0
4599       if ((Cond == ISD::SETUGT && C1.isMaxSignedValue()) ||
4600           (Cond == ISD::SETUGE && C1.isMinSignedValue()))
4601         return DAG.getSetCC(dl, VT, N0,
4602                             DAG.getConstant(0, dl, N1.getValueType()),
4603                             ISD::SETLT);
4604 
4605       // SETULT X, SINTMIN  -> SETGT X, -1
4606       // SETULE X, SINTMAX  -> SETGT X, -1
4607       if ((Cond == ISD::SETULT && C1.isMinSignedValue()) ||
4608           (Cond == ISD::SETULE && C1.isMaxSignedValue()))
4609         return DAG.getSetCC(dl, VT, N0,
4610                             DAG.getAllOnesConstant(dl, N1.getValueType()),
4611                             ISD::SETGT);
4612     }
4613   }
4614 
4615   // Back to non-vector simplifications.
4616   // TODO: Can we do these for vector splats?
4617   if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) {
4618     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4619     const APInt &C1 = N1C->getAPIntValue();
4620     EVT ShValTy = N0.getValueType();
4621 
4622     // Fold bit comparisons when we can. This will result in an
4623     // incorrect value when boolean false is negative one, unless
4624     // the bitsize is 1 in which case the false value is the same
4625     // in practice regardless of the representation.
4626     if ((VT.getSizeInBits() == 1 ||
4627          getBooleanContents(N0.getValueType()) == ZeroOrOneBooleanContent) &&
4628         (Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
4629         (VT == ShValTy || (isTypeLegal(VT) && VT.bitsLE(ShValTy))) &&
4630         N0.getOpcode() == ISD::AND) {
4631       if (auto *AndRHS = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
4632         EVT ShiftTy =
4633             getShiftAmountTy(ShValTy, Layout, !DCI.isBeforeLegalize());
4634         if (Cond == ISD::SETNE && C1 == 0) {// (X & 8) != 0  -->  (X & 8) >> 3
4635           // Perform the xform if the AND RHS is a single bit.
4636           unsigned ShCt = AndRHS->getAPIntValue().logBase2();
4637           if (AndRHS->getAPIntValue().isPowerOf2() &&
4638               !TLI.shouldAvoidTransformToShift(ShValTy, ShCt)) {
4639             return DAG.getNode(ISD::TRUNCATE, dl, VT,
4640                                DAG.getNode(ISD::SRL, dl, ShValTy, N0,
4641                                            DAG.getConstant(ShCt, dl, ShiftTy)));
4642           }
4643         } else if (Cond == ISD::SETEQ && C1 == AndRHS->getAPIntValue()) {
4644           // (X & 8) == 8  -->  (X & 8) >> 3
4645           // Perform the xform if C1 is a single bit.
4646           unsigned ShCt = C1.logBase2();
4647           if (C1.isPowerOf2() &&
4648               !TLI.shouldAvoidTransformToShift(ShValTy, ShCt)) {
4649             return DAG.getNode(ISD::TRUNCATE, dl, VT,
4650                                DAG.getNode(ISD::SRL, dl, ShValTy, N0,
4651                                            DAG.getConstant(ShCt, dl, ShiftTy)));
4652           }
4653         }
4654       }
4655     }
4656 
4657     if (C1.getMinSignedBits() <= 64 &&
4658         !isLegalICmpImmediate(C1.getSExtValue())) {
4659       EVT ShiftTy = getShiftAmountTy(ShValTy, Layout, !DCI.isBeforeLegalize());
4660       // (X & -256) == 256 -> (X >> 8) == 1
4661       if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
4662           N0.getOpcode() == ISD::AND && N0.hasOneUse()) {
4663         if (auto *AndRHS = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
4664           const APInt &AndRHSC = AndRHS->getAPIntValue();
4665           if (AndRHSC.isNegatedPowerOf2() && (AndRHSC & C1) == C1) {
4666             unsigned ShiftBits = AndRHSC.countTrailingZeros();
4667             if (!TLI.shouldAvoidTransformToShift(ShValTy, ShiftBits)) {
4668               SDValue Shift =
4669                 DAG.getNode(ISD::SRL, dl, ShValTy, N0.getOperand(0),
4670                             DAG.getConstant(ShiftBits, dl, ShiftTy));
4671               SDValue CmpRHS = DAG.getConstant(C1.lshr(ShiftBits), dl, ShValTy);
4672               return DAG.getSetCC(dl, VT, Shift, CmpRHS, Cond);
4673             }
4674           }
4675         }
4676       } else if (Cond == ISD::SETULT || Cond == ISD::SETUGE ||
4677                  Cond == ISD::SETULE || Cond == ISD::SETUGT) {
4678         bool AdjOne = (Cond == ISD::SETULE || Cond == ISD::SETUGT);
4679         // X <  0x100000000 -> (X >> 32) <  1
4680         // X >= 0x100000000 -> (X >> 32) >= 1
4681         // X <= 0x0ffffffff -> (X >> 32) <  1
4682         // X >  0x0ffffffff -> (X >> 32) >= 1
4683         unsigned ShiftBits;
4684         APInt NewC = C1;
4685         ISD::CondCode NewCond = Cond;
4686         if (AdjOne) {
4687           ShiftBits = C1.countTrailingOnes();
4688           NewC = NewC + 1;
4689           NewCond = (Cond == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
4690         } else {
4691           ShiftBits = C1.countTrailingZeros();
4692         }
4693         NewC.lshrInPlace(ShiftBits);
4694         if (ShiftBits && NewC.getMinSignedBits() <= 64 &&
4695             isLegalICmpImmediate(NewC.getSExtValue()) &&
4696             !TLI.shouldAvoidTransformToShift(ShValTy, ShiftBits)) {
4697           SDValue Shift = DAG.getNode(ISD::SRL, dl, ShValTy, N0,
4698                                       DAG.getConstant(ShiftBits, dl, ShiftTy));
4699           SDValue CmpRHS = DAG.getConstant(NewC, dl, ShValTy);
4700           return DAG.getSetCC(dl, VT, Shift, CmpRHS, NewCond);
4701         }
4702       }
4703     }
4704   }
4705 
4706   if (!isa<ConstantFPSDNode>(N0) && isa<ConstantFPSDNode>(N1)) {
4707     auto *CFP = cast<ConstantFPSDNode>(N1);
4708     assert(!CFP->getValueAPF().isNaN() && "Unexpected NaN value");
4709 
4710     // Otherwise, we know the RHS is not a NaN.  Simplify the node to drop the
4711     // constant if knowing that the operand is non-nan is enough.  We prefer to
4712     // have SETO(x,x) instead of SETO(x, 0.0) because this avoids having to
4713     // materialize 0.0.
4714     if (Cond == ISD::SETO || Cond == ISD::SETUO)
4715       return DAG.getSetCC(dl, VT, N0, N0, Cond);
4716 
4717     // setcc (fneg x), C -> setcc swap(pred) x, -C
4718     if (N0.getOpcode() == ISD::FNEG) {
4719       ISD::CondCode SwapCond = ISD::getSetCCSwappedOperands(Cond);
4720       if (DCI.isBeforeLegalizeOps() ||
4721           isCondCodeLegal(SwapCond, N0.getSimpleValueType())) {
4722         SDValue NegN1 = DAG.getNode(ISD::FNEG, dl, N0.getValueType(), N1);
4723         return DAG.getSetCC(dl, VT, N0.getOperand(0), NegN1, SwapCond);
4724       }
4725     }
4726 
4727     // If the condition is not legal, see if we can find an equivalent one
4728     // which is legal.
4729     if (!isCondCodeLegal(Cond, N0.getSimpleValueType())) {
4730       // If the comparison was an awkward floating-point == or != and one of
4731       // the comparison operands is infinity or negative infinity, convert the
4732       // condition to a less-awkward <= or >=.
4733       if (CFP->getValueAPF().isInfinity()) {
4734         bool IsNegInf = CFP->getValueAPF().isNegative();
4735         ISD::CondCode NewCond = ISD::SETCC_INVALID;
4736         switch (Cond) {
4737         case ISD::SETOEQ: NewCond = IsNegInf ? ISD::SETOLE : ISD::SETOGE; break;
4738         case ISD::SETUEQ: NewCond = IsNegInf ? ISD::SETULE : ISD::SETUGE; break;
4739         case ISD::SETUNE: NewCond = IsNegInf ? ISD::SETUGT : ISD::SETULT; break;
4740         case ISD::SETONE: NewCond = IsNegInf ? ISD::SETOGT : ISD::SETOLT; break;
4741         default: break;
4742         }
4743         if (NewCond != ISD::SETCC_INVALID &&
4744             isCondCodeLegal(NewCond, N0.getSimpleValueType()))
4745           return DAG.getSetCC(dl, VT, N0, N1, NewCond);
4746       }
4747     }
4748   }
4749 
4750   if (N0 == N1) {
4751     // The sext(setcc()) => setcc() optimization relies on the appropriate
4752     // constant being emitted.
4753     assert(!N0.getValueType().isInteger() &&
4754            "Integer types should be handled by FoldSetCC");
4755 
4756     bool EqTrue = ISD::isTrueWhenEqual(Cond);
4757     unsigned UOF = ISD::getUnorderedFlavor(Cond);
4758     if (UOF == 2) // FP operators that are undefined on NaNs.
4759       return DAG.getBoolConstant(EqTrue, dl, VT, OpVT);
4760     if (UOF == unsigned(EqTrue))
4761       return DAG.getBoolConstant(EqTrue, dl, VT, OpVT);
4762     // Otherwise, we can't fold it.  However, we can simplify it to SETUO/SETO
4763     // if it is not already.
4764     ISD::CondCode NewCond = UOF == 0 ? ISD::SETO : ISD::SETUO;
4765     if (NewCond != Cond &&
4766         (DCI.isBeforeLegalizeOps() ||
4767                             isCondCodeLegal(NewCond, N0.getSimpleValueType())))
4768       return DAG.getSetCC(dl, VT, N0, N1, NewCond);
4769   }
4770 
4771   if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
4772       N0.getValueType().isInteger()) {
4773     if (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::SUB ||
4774         N0.getOpcode() == ISD::XOR) {
4775       // Simplify (X+Y) == (X+Z) -->  Y == Z
4776       if (N0.getOpcode() == N1.getOpcode()) {
4777         if (N0.getOperand(0) == N1.getOperand(0))
4778           return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(1), Cond);
4779         if (N0.getOperand(1) == N1.getOperand(1))
4780           return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(0), Cond);
4781         if (isCommutativeBinOp(N0.getOpcode())) {
4782           // If X op Y == Y op X, try other combinations.
4783           if (N0.getOperand(0) == N1.getOperand(1))
4784             return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(0),
4785                                 Cond);
4786           if (N0.getOperand(1) == N1.getOperand(0))
4787             return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(1),
4788                                 Cond);
4789         }
4790       }
4791 
4792       // If RHS is a legal immediate value for a compare instruction, we need
4793       // to be careful about increasing register pressure needlessly.
4794       bool LegalRHSImm = false;
4795 
4796       if (auto *RHSC = dyn_cast<ConstantSDNode>(N1)) {
4797         if (auto *LHSR = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
4798           // Turn (X+C1) == C2 --> X == C2-C1
4799           if (N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse())
4800             return DAG.getSetCC(
4801                 dl, VT, N0.getOperand(0),
4802                 DAG.getConstant(RHSC->getAPIntValue() - LHSR->getAPIntValue(),
4803                                 dl, N0.getValueType()),
4804                 Cond);
4805 
4806           // Turn (X^C1) == C2 --> X == C1^C2
4807           if (N0.getOpcode() == ISD::XOR && N0.getNode()->hasOneUse())
4808             return DAG.getSetCC(
4809                 dl, VT, N0.getOperand(0),
4810                 DAG.getConstant(LHSR->getAPIntValue() ^ RHSC->getAPIntValue(),
4811                                 dl, N0.getValueType()),
4812                 Cond);
4813         }
4814 
4815         // Turn (C1-X) == C2 --> X == C1-C2
4816         if (auto *SUBC = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
4817           if (N0.getOpcode() == ISD::SUB && N0.getNode()->hasOneUse())
4818             return DAG.getSetCC(
4819                 dl, VT, N0.getOperand(1),
4820                 DAG.getConstant(SUBC->getAPIntValue() - RHSC->getAPIntValue(),
4821                                 dl, N0.getValueType()),
4822                 Cond);
4823 
4824         // Could RHSC fold directly into a compare?
4825         if (RHSC->getValueType(0).getSizeInBits() <= 64)
4826           LegalRHSImm = isLegalICmpImmediate(RHSC->getSExtValue());
4827       }
4828 
4829       // (X+Y) == X --> Y == 0 and similar folds.
4830       // Don't do this if X is an immediate that can fold into a cmp
4831       // instruction and X+Y has other uses. It could be an induction variable
4832       // chain, and the transform would increase register pressure.
4833       if (!LegalRHSImm || N0.hasOneUse())
4834         if (SDValue V = foldSetCCWithBinOp(VT, N0, N1, Cond, dl, DCI))
4835           return V;
4836     }
4837 
4838     if (N1.getOpcode() == ISD::ADD || N1.getOpcode() == ISD::SUB ||
4839         N1.getOpcode() == ISD::XOR)
4840       if (SDValue V = foldSetCCWithBinOp(VT, N1, N0, Cond, dl, DCI))
4841         return V;
4842 
4843     if (SDValue V = foldSetCCWithAnd(VT, N0, N1, Cond, dl, DCI))
4844       return V;
4845   }
4846 
4847   // Fold remainder of division by a constant.
4848   if ((N0.getOpcode() == ISD::UREM || N0.getOpcode() == ISD::SREM) &&
4849       N0.hasOneUse() && (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
4850     AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
4851 
4852     // When division is cheap or optimizing for minimum size,
4853     // fall through to DIVREM creation by skipping this fold.
4854     if (!isIntDivCheap(VT, Attr) && !Attr.hasFnAttr(Attribute::MinSize)) {
4855       if (N0.getOpcode() == ISD::UREM) {
4856         if (SDValue Folded = buildUREMEqFold(VT, N0, N1, Cond, DCI, dl))
4857           return Folded;
4858       } else if (N0.getOpcode() == ISD::SREM) {
4859         if (SDValue Folded = buildSREMEqFold(VT, N0, N1, Cond, DCI, dl))
4860           return Folded;
4861       }
4862     }
4863   }
4864 
4865   // Fold away ALL boolean setcc's.
4866   if (N0.getValueType().getScalarType() == MVT::i1 && foldBooleans) {
4867     SDValue Temp;
4868     switch (Cond) {
4869     default: llvm_unreachable("Unknown integer setcc!");
4870     case ISD::SETEQ:  // X == Y  -> ~(X^Y)
4871       Temp = DAG.getNode(ISD::XOR, dl, OpVT, N0, N1);
4872       N0 = DAG.getNOT(dl, Temp, OpVT);
4873       if (!DCI.isCalledByLegalizer())
4874         DCI.AddToWorklist(Temp.getNode());
4875       break;
4876     case ISD::SETNE:  // X != Y   -->  (X^Y)
4877       N0 = DAG.getNode(ISD::XOR, dl, OpVT, N0, N1);
4878       break;
4879     case ISD::SETGT:  // X >s Y   -->  X == 0 & Y == 1  -->  ~X & Y
4880     case ISD::SETULT: // X <u Y   -->  X == 0 & Y == 1  -->  ~X & Y
4881       Temp = DAG.getNOT(dl, N0, OpVT);
4882       N0 = DAG.getNode(ISD::AND, dl, OpVT, N1, Temp);
4883       if (!DCI.isCalledByLegalizer())
4884         DCI.AddToWorklist(Temp.getNode());
4885       break;
4886     case ISD::SETLT:  // X <s Y   --> X == 1 & Y == 0  -->  ~Y & X
4887     case ISD::SETUGT: // X >u Y   --> X == 1 & Y == 0  -->  ~Y & X
4888       Temp = DAG.getNOT(dl, N1, OpVT);
4889       N0 = DAG.getNode(ISD::AND, dl, OpVT, N0, Temp);
4890       if (!DCI.isCalledByLegalizer())
4891         DCI.AddToWorklist(Temp.getNode());
4892       break;
4893     case ISD::SETULE: // X <=u Y  --> X == 0 | Y == 1  -->  ~X | Y
4894     case ISD::SETGE:  // X >=s Y  --> X == 0 | Y == 1  -->  ~X | Y
4895       Temp = DAG.getNOT(dl, N0, OpVT);
4896       N0 = DAG.getNode(ISD::OR, dl, OpVT, N1, Temp);
4897       if (!DCI.isCalledByLegalizer())
4898         DCI.AddToWorklist(Temp.getNode());
4899       break;
4900     case ISD::SETUGE: // X >=u Y  --> X == 1 | Y == 0  -->  ~Y | X
4901     case ISD::SETLE:  // X <=s Y  --> X == 1 | Y == 0  -->  ~Y | X
4902       Temp = DAG.getNOT(dl, N1, OpVT);
4903       N0 = DAG.getNode(ISD::OR, dl, OpVT, N0, Temp);
4904       break;
4905     }
4906     if (VT.getScalarType() != MVT::i1) {
4907       if (!DCI.isCalledByLegalizer())
4908         DCI.AddToWorklist(N0.getNode());
4909       // FIXME: If running after legalize, we probably can't do this.
4910       ISD::NodeType ExtendCode = getExtendForContent(getBooleanContents(OpVT));
4911       N0 = DAG.getNode(ExtendCode, dl, VT, N0);
4912     }
4913     return N0;
4914   }
4915 
4916   // Could not fold it.
4917   return SDValue();
4918 }
4919 
4920 /// Returns true (and the GlobalValue and the offset) if the node is a
4921 /// GlobalAddress + offset.
4922 bool TargetLowering::isGAPlusOffset(SDNode *WN, const GlobalValue *&GA,
4923                                     int64_t &Offset) const {
4924 
4925   SDNode *N = unwrapAddress(SDValue(WN, 0)).getNode();
4926 
4927   if (auto *GASD = dyn_cast<GlobalAddressSDNode>(N)) {
4928     GA = GASD->getGlobal();
4929     Offset += GASD->getOffset();
4930     return true;
4931   }
4932 
4933   if (N->getOpcode() == ISD::ADD) {
4934     SDValue N1 = N->getOperand(0);
4935     SDValue N2 = N->getOperand(1);
4936     if (isGAPlusOffset(N1.getNode(), GA, Offset)) {
4937       if (auto *V = dyn_cast<ConstantSDNode>(N2)) {
4938         Offset += V->getSExtValue();
4939         return true;
4940       }
4941     } else if (isGAPlusOffset(N2.getNode(), GA, Offset)) {
4942       if (auto *V = dyn_cast<ConstantSDNode>(N1)) {
4943         Offset += V->getSExtValue();
4944         return true;
4945       }
4946     }
4947   }
4948 
4949   return false;
4950 }
4951 
4952 SDValue TargetLowering::PerformDAGCombine(SDNode *N,
4953                                           DAGCombinerInfo &DCI) const {
4954   // Default implementation: no optimization.
4955   return SDValue();
4956 }
4957 
4958 //===----------------------------------------------------------------------===//
4959 //  Inline Assembler Implementation Methods
4960 //===----------------------------------------------------------------------===//
4961 
4962 TargetLowering::ConstraintType
4963 TargetLowering::getConstraintType(StringRef Constraint) const {
4964   unsigned S = Constraint.size();
4965 
4966   if (S == 1) {
4967     switch (Constraint[0]) {
4968     default: break;
4969     case 'r':
4970       return C_RegisterClass;
4971     case 'm': // memory
4972     case 'o': // offsetable
4973     case 'V': // not offsetable
4974       return C_Memory;
4975     case 'p': // Address.
4976       return C_Address;
4977     case 'n': // Simple Integer
4978     case 'E': // Floating Point Constant
4979     case 'F': // Floating Point Constant
4980       return C_Immediate;
4981     case 'i': // Simple Integer or Relocatable Constant
4982     case 's': // Relocatable Constant
4983     case 'X': // Allow ANY value.
4984     case 'I': // Target registers.
4985     case 'J':
4986     case 'K':
4987     case 'L':
4988     case 'M':
4989     case 'N':
4990     case 'O':
4991     case 'P':
4992     case '<':
4993     case '>':
4994       return C_Other;
4995     }
4996   }
4997 
4998   if (S > 1 && Constraint[0] == '{' && Constraint[S - 1] == '}') {
4999     if (S == 8 && Constraint.substr(1, 6) == "memory") // "{memory}"
5000       return C_Memory;
5001     return C_Register;
5002   }
5003   return C_Unknown;
5004 }
5005 
5006 /// Try to replace an X constraint, which matches anything, with another that
5007 /// has more specific requirements based on the type of the corresponding
5008 /// operand.
5009 const char *TargetLowering::LowerXConstraint(EVT ConstraintVT) const {
5010   if (ConstraintVT.isInteger())
5011     return "r";
5012   if (ConstraintVT.isFloatingPoint())
5013     return "f"; // works for many targets
5014   return nullptr;
5015 }
5016 
5017 SDValue TargetLowering::LowerAsmOutputForConstraint(
5018     SDValue &Chain, SDValue &Flag, const SDLoc &DL,
5019     const AsmOperandInfo &OpInfo, SelectionDAG &DAG) const {
5020   return SDValue();
5021 }
5022 
5023 /// Lower the specified operand into the Ops vector.
5024 /// If it is invalid, don't add anything to Ops.
5025 void TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
5026                                                   std::string &Constraint,
5027                                                   std::vector<SDValue> &Ops,
5028                                                   SelectionDAG &DAG) const {
5029 
5030   if (Constraint.length() > 1) return;
5031 
5032   char ConstraintLetter = Constraint[0];
5033   switch (ConstraintLetter) {
5034   default: break;
5035   case 'X':    // Allows any operand
5036   case 'i':    // Simple Integer or Relocatable Constant
5037   case 'n':    // Simple Integer
5038   case 's': {  // Relocatable Constant
5039 
5040     ConstantSDNode *C;
5041     uint64_t Offset = 0;
5042 
5043     // Match (GA) or (C) or (GA+C) or (GA-C) or ((GA+C)+C) or (((GA+C)+C)+C),
5044     // etc., since getelementpointer is variadic. We can't use
5045     // SelectionDAG::FoldSymbolOffset because it expects the GA to be accessible
5046     // while in this case the GA may be furthest from the root node which is
5047     // likely an ISD::ADD.
5048     while (true) {
5049       if ((C = dyn_cast<ConstantSDNode>(Op)) && ConstraintLetter != 's') {
5050         // gcc prints these as sign extended.  Sign extend value to 64 bits
5051         // now; without this it would get ZExt'd later in
5052         // ScheduleDAGSDNodes::EmitNode, which is very generic.
5053         bool IsBool = C->getConstantIntValue()->getBitWidth() == 1;
5054         BooleanContent BCont = getBooleanContents(MVT::i64);
5055         ISD::NodeType ExtOpc =
5056             IsBool ? getExtendForContent(BCont) : ISD::SIGN_EXTEND;
5057         int64_t ExtVal =
5058             ExtOpc == ISD::ZERO_EXTEND ? C->getZExtValue() : C->getSExtValue();
5059         Ops.push_back(
5060             DAG.getTargetConstant(Offset + ExtVal, SDLoc(C), MVT::i64));
5061         return;
5062       }
5063       if (ConstraintLetter != 'n') {
5064         if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
5065           Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
5066                                                    GA->getValueType(0),
5067                                                    Offset + GA->getOffset()));
5068           return;
5069         }
5070         if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) {
5071           Ops.push_back(DAG.getTargetBlockAddress(
5072               BA->getBlockAddress(), BA->getValueType(0),
5073               Offset + BA->getOffset(), BA->getTargetFlags()));
5074           return;
5075         }
5076         if (isa<BasicBlockSDNode>(Op)) {
5077           Ops.push_back(Op);
5078           return;
5079         }
5080       }
5081       const unsigned OpCode = Op.getOpcode();
5082       if (OpCode == ISD::ADD || OpCode == ISD::SUB) {
5083         if ((C = dyn_cast<ConstantSDNode>(Op.getOperand(0))))
5084           Op = Op.getOperand(1);
5085         // Subtraction is not commutative.
5086         else if (OpCode == ISD::ADD &&
5087                  (C = dyn_cast<ConstantSDNode>(Op.getOperand(1))))
5088           Op = Op.getOperand(0);
5089         else
5090           return;
5091         Offset += (OpCode == ISD::ADD ? 1 : -1) * C->getSExtValue();
5092         continue;
5093       }
5094       return;
5095     }
5096     break;
5097   }
5098   }
5099 }
5100 
5101 std::pair<unsigned, const TargetRegisterClass *>
5102 TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *RI,
5103                                              StringRef Constraint,
5104                                              MVT VT) const {
5105   if (Constraint.empty() || Constraint[0] != '{')
5106     return std::make_pair(0u, static_cast<TargetRegisterClass *>(nullptr));
5107   assert(*(Constraint.end() - 1) == '}' && "Not a brace enclosed constraint?");
5108 
5109   // Remove the braces from around the name.
5110   StringRef RegName(Constraint.data() + 1, Constraint.size() - 2);
5111 
5112   std::pair<unsigned, const TargetRegisterClass *> R =
5113       std::make_pair(0u, static_cast<const TargetRegisterClass *>(nullptr));
5114 
5115   // Figure out which register class contains this reg.
5116   for (const TargetRegisterClass *RC : RI->regclasses()) {
5117     // If none of the value types for this register class are valid, we
5118     // can't use it.  For example, 64-bit reg classes on 32-bit targets.
5119     if (!isLegalRC(*RI, *RC))
5120       continue;
5121 
5122     for (const MCPhysReg &PR : *RC) {
5123       if (RegName.equals_insensitive(RI->getRegAsmName(PR))) {
5124         std::pair<unsigned, const TargetRegisterClass *> S =
5125             std::make_pair(PR, RC);
5126 
5127         // If this register class has the requested value type, return it,
5128         // otherwise keep searching and return the first class found
5129         // if no other is found which explicitly has the requested type.
5130         if (RI->isTypeLegalForClass(*RC, VT))
5131           return S;
5132         if (!R.second)
5133           R = S;
5134       }
5135     }
5136   }
5137 
5138   return R;
5139 }
5140 
5141 //===----------------------------------------------------------------------===//
5142 // Constraint Selection.
5143 
5144 /// Return true of this is an input operand that is a matching constraint like
5145 /// "4".
5146 bool TargetLowering::AsmOperandInfo::isMatchingInputConstraint() const {
5147   assert(!ConstraintCode.empty() && "No known constraint!");
5148   return isdigit(static_cast<unsigned char>(ConstraintCode[0]));
5149 }
5150 
5151 /// If this is an input matching constraint, this method returns the output
5152 /// operand it matches.
5153 unsigned TargetLowering::AsmOperandInfo::getMatchedOperand() const {
5154   assert(!ConstraintCode.empty() && "No known constraint!");
5155   return atoi(ConstraintCode.c_str());
5156 }
5157 
5158 /// Split up the constraint string from the inline assembly value into the
5159 /// specific constraints and their prefixes, and also tie in the associated
5160 /// operand values.
5161 /// If this returns an empty vector, and if the constraint string itself
5162 /// isn't empty, there was an error parsing.
5163 TargetLowering::AsmOperandInfoVector
5164 TargetLowering::ParseConstraints(const DataLayout &DL,
5165                                  const TargetRegisterInfo *TRI,
5166                                  const CallBase &Call) const {
5167   /// Information about all of the constraints.
5168   AsmOperandInfoVector ConstraintOperands;
5169   const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
5170   unsigned maCount = 0; // Largest number of multiple alternative constraints.
5171 
5172   // Do a prepass over the constraints, canonicalizing them, and building up the
5173   // ConstraintOperands list.
5174   unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
5175   unsigned ResNo = 0; // ResNo - The result number of the next output.
5176 
5177   for (InlineAsm::ConstraintInfo &CI : IA->ParseConstraints()) {
5178     ConstraintOperands.emplace_back(std::move(CI));
5179     AsmOperandInfo &OpInfo = ConstraintOperands.back();
5180 
5181     // Update multiple alternative constraint count.
5182     if (OpInfo.multipleAlternatives.size() > maCount)
5183       maCount = OpInfo.multipleAlternatives.size();
5184 
5185     OpInfo.ConstraintVT = MVT::Other;
5186 
5187     // Compute the value type for each operand.
5188     switch (OpInfo.Type) {
5189     case InlineAsm::isOutput:
5190       // Indirect outputs just consume an argument.
5191       if (OpInfo.isIndirect) {
5192         OpInfo.CallOperandVal = Call.getArgOperand(ArgNo);
5193         break;
5194       }
5195 
5196       // The return value of the call is this value.  As such, there is no
5197       // corresponding argument.
5198       assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
5199       if (StructType *STy = dyn_cast<StructType>(Call.getType())) {
5200         OpInfo.ConstraintVT =
5201             getSimpleValueType(DL, STy->getElementType(ResNo));
5202       } else {
5203         assert(ResNo == 0 && "Asm only has one result!");
5204         OpInfo.ConstraintVT =
5205             getAsmOperandValueType(DL, Call.getType()).getSimpleVT();
5206       }
5207       ++ResNo;
5208       break;
5209     case InlineAsm::isInput:
5210       OpInfo.CallOperandVal = Call.getArgOperand(ArgNo);
5211       break;
5212     case InlineAsm::isClobber:
5213       // Nothing to do.
5214       break;
5215     }
5216 
5217     if (OpInfo.CallOperandVal) {
5218       llvm::Type *OpTy = OpInfo.CallOperandVal->getType();
5219       if (OpInfo.isIndirect) {
5220         OpTy = Call.getParamElementType(ArgNo);
5221         assert(OpTy && "Indirect operand must have elementtype attribute");
5222       }
5223 
5224       // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
5225       if (StructType *STy = dyn_cast<StructType>(OpTy))
5226         if (STy->getNumElements() == 1)
5227           OpTy = STy->getElementType(0);
5228 
5229       // If OpTy is not a single value, it may be a struct/union that we
5230       // can tile with integers.
5231       if (!OpTy->isSingleValueType() && OpTy->isSized()) {
5232         unsigned BitSize = DL.getTypeSizeInBits(OpTy);
5233         switch (BitSize) {
5234         default: break;
5235         case 1:
5236         case 8:
5237         case 16:
5238         case 32:
5239         case 64:
5240         case 128:
5241           OpInfo.ConstraintVT =
5242               MVT::getVT(IntegerType::get(OpTy->getContext(), BitSize), true);
5243           break;
5244         }
5245       } else if (PointerType *PT = dyn_cast<PointerType>(OpTy)) {
5246         unsigned PtrSize = DL.getPointerSizeInBits(PT->getAddressSpace());
5247         OpInfo.ConstraintVT = MVT::getIntegerVT(PtrSize);
5248       } else {
5249         OpInfo.ConstraintVT = MVT::getVT(OpTy, true);
5250       }
5251 
5252       ArgNo++;
5253     }
5254   }
5255 
5256   // If we have multiple alternative constraints, select the best alternative.
5257   if (!ConstraintOperands.empty()) {
5258     if (maCount) {
5259       unsigned bestMAIndex = 0;
5260       int bestWeight = -1;
5261       // weight:  -1 = invalid match, and 0 = so-so match to 5 = good match.
5262       int weight = -1;
5263       unsigned maIndex;
5264       // Compute the sums of the weights for each alternative, keeping track
5265       // of the best (highest weight) one so far.
5266       for (maIndex = 0; maIndex < maCount; ++maIndex) {
5267         int weightSum = 0;
5268         for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
5269              cIndex != eIndex; ++cIndex) {
5270           AsmOperandInfo &OpInfo = ConstraintOperands[cIndex];
5271           if (OpInfo.Type == InlineAsm::isClobber)
5272             continue;
5273 
5274           // If this is an output operand with a matching input operand,
5275           // look up the matching input. If their types mismatch, e.g. one
5276           // is an integer, the other is floating point, or their sizes are
5277           // different, flag it as an maCantMatch.
5278           if (OpInfo.hasMatchingInput()) {
5279             AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
5280             if (OpInfo.ConstraintVT != Input.ConstraintVT) {
5281               if ((OpInfo.ConstraintVT.isInteger() !=
5282                    Input.ConstraintVT.isInteger()) ||
5283                   (OpInfo.ConstraintVT.getSizeInBits() !=
5284                    Input.ConstraintVT.getSizeInBits())) {
5285                 weightSum = -1; // Can't match.
5286                 break;
5287               }
5288             }
5289           }
5290           weight = getMultipleConstraintMatchWeight(OpInfo, maIndex);
5291           if (weight == -1) {
5292             weightSum = -1;
5293             break;
5294           }
5295           weightSum += weight;
5296         }
5297         // Update best.
5298         if (weightSum > bestWeight) {
5299           bestWeight = weightSum;
5300           bestMAIndex = maIndex;
5301         }
5302       }
5303 
5304       // Now select chosen alternative in each constraint.
5305       for (AsmOperandInfo &cInfo : ConstraintOperands)
5306         if (cInfo.Type != InlineAsm::isClobber)
5307           cInfo.selectAlternative(bestMAIndex);
5308     }
5309   }
5310 
5311   // Check and hook up tied operands, choose constraint code to use.
5312   for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
5313        cIndex != eIndex; ++cIndex) {
5314     AsmOperandInfo &OpInfo = ConstraintOperands[cIndex];
5315 
5316     // If this is an output operand with a matching input operand, look up the
5317     // matching input. If their types mismatch, e.g. one is an integer, the
5318     // other is floating point, or their sizes are different, flag it as an
5319     // error.
5320     if (OpInfo.hasMatchingInput()) {
5321       AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
5322 
5323       if (OpInfo.ConstraintVT != Input.ConstraintVT) {
5324         std::pair<unsigned, const TargetRegisterClass *> MatchRC =
5325             getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
5326                                          OpInfo.ConstraintVT);
5327         std::pair<unsigned, const TargetRegisterClass *> InputRC =
5328             getRegForInlineAsmConstraint(TRI, Input.ConstraintCode,
5329                                          Input.ConstraintVT);
5330         if ((OpInfo.ConstraintVT.isInteger() !=
5331              Input.ConstraintVT.isInteger()) ||
5332             (MatchRC.second != InputRC.second)) {
5333           report_fatal_error("Unsupported asm: input constraint"
5334                              " with a matching output constraint of"
5335                              " incompatible type!");
5336         }
5337       }
5338     }
5339   }
5340 
5341   return ConstraintOperands;
5342 }
5343 
5344 /// Return an integer indicating how general CT is.
5345 static unsigned getConstraintGenerality(TargetLowering::ConstraintType CT) {
5346   switch (CT) {
5347   case TargetLowering::C_Immediate:
5348   case TargetLowering::C_Other:
5349   case TargetLowering::C_Unknown:
5350     return 0;
5351   case TargetLowering::C_Register:
5352     return 1;
5353   case TargetLowering::C_RegisterClass:
5354     return 2;
5355   case TargetLowering::C_Memory:
5356   case TargetLowering::C_Address:
5357     return 3;
5358   }
5359   llvm_unreachable("Invalid constraint type");
5360 }
5361 
5362 /// Examine constraint type and operand type and determine a weight value.
5363 /// This object must already have been set up with the operand type
5364 /// and the current alternative constraint selected.
5365 TargetLowering::ConstraintWeight
5366   TargetLowering::getMultipleConstraintMatchWeight(
5367     AsmOperandInfo &info, int maIndex) const {
5368   InlineAsm::ConstraintCodeVector *rCodes;
5369   if (maIndex >= (int)info.multipleAlternatives.size())
5370     rCodes = &info.Codes;
5371   else
5372     rCodes = &info.multipleAlternatives[maIndex].Codes;
5373   ConstraintWeight BestWeight = CW_Invalid;
5374 
5375   // Loop over the options, keeping track of the most general one.
5376   for (const std::string &rCode : *rCodes) {
5377     ConstraintWeight weight =
5378         getSingleConstraintMatchWeight(info, rCode.c_str());
5379     if (weight > BestWeight)
5380       BestWeight = weight;
5381   }
5382 
5383   return BestWeight;
5384 }
5385 
5386 /// Examine constraint type and operand type and determine a weight value.
5387 /// This object must already have been set up with the operand type
5388 /// and the current alternative constraint selected.
5389 TargetLowering::ConstraintWeight
5390   TargetLowering::getSingleConstraintMatchWeight(
5391     AsmOperandInfo &info, const char *constraint) const {
5392   ConstraintWeight weight = CW_Invalid;
5393   Value *CallOperandVal = info.CallOperandVal;
5394     // If we don't have a value, we can't do a match,
5395     // but allow it at the lowest weight.
5396   if (!CallOperandVal)
5397     return CW_Default;
5398   // Look at the constraint type.
5399   switch (*constraint) {
5400     case 'i': // immediate integer.
5401     case 'n': // immediate integer with a known value.
5402       if (isa<ConstantInt>(CallOperandVal))
5403         weight = CW_Constant;
5404       break;
5405     case 's': // non-explicit intregal immediate.
5406       if (isa<GlobalValue>(CallOperandVal))
5407         weight = CW_Constant;
5408       break;
5409     case 'E': // immediate float if host format.
5410     case 'F': // immediate float.
5411       if (isa<ConstantFP>(CallOperandVal))
5412         weight = CW_Constant;
5413       break;
5414     case '<': // memory operand with autodecrement.
5415     case '>': // memory operand with autoincrement.
5416     case 'm': // memory operand.
5417     case 'o': // offsettable memory operand
5418     case 'V': // non-offsettable memory operand
5419       weight = CW_Memory;
5420       break;
5421     case 'r': // general register.
5422     case 'g': // general register, memory operand or immediate integer.
5423               // note: Clang converts "g" to "imr".
5424       if (CallOperandVal->getType()->isIntegerTy())
5425         weight = CW_Register;
5426       break;
5427     case 'X': // any operand.
5428   default:
5429     weight = CW_Default;
5430     break;
5431   }
5432   return weight;
5433 }
5434 
5435 /// If there are multiple different constraints that we could pick for this
5436 /// operand (e.g. "imr") try to pick the 'best' one.
5437 /// This is somewhat tricky: constraints fall into four classes:
5438 ///    Other         -> immediates and magic values
5439 ///    Register      -> one specific register
5440 ///    RegisterClass -> a group of regs
5441 ///    Memory        -> memory
5442 /// Ideally, we would pick the most specific constraint possible: if we have
5443 /// something that fits into a register, we would pick it.  The problem here
5444 /// is that if we have something that could either be in a register or in
5445 /// memory that use of the register could cause selection of *other*
5446 /// operands to fail: they might only succeed if we pick memory.  Because of
5447 /// this the heuristic we use is:
5448 ///
5449 ///  1) If there is an 'other' constraint, and if the operand is valid for
5450 ///     that constraint, use it.  This makes us take advantage of 'i'
5451 ///     constraints when available.
5452 ///  2) Otherwise, pick the most general constraint present.  This prefers
5453 ///     'm' over 'r', for example.
5454 ///
5455 static void ChooseConstraint(TargetLowering::AsmOperandInfo &OpInfo,
5456                              const TargetLowering &TLI,
5457                              SDValue Op, SelectionDAG *DAG) {
5458   assert(OpInfo.Codes.size() > 1 && "Doesn't have multiple constraint options");
5459   unsigned BestIdx = 0;
5460   TargetLowering::ConstraintType BestType = TargetLowering::C_Unknown;
5461   int BestGenerality = -1;
5462 
5463   // Loop over the options, keeping track of the most general one.
5464   for (unsigned i = 0, e = OpInfo.Codes.size(); i != e; ++i) {
5465     TargetLowering::ConstraintType CType =
5466       TLI.getConstraintType(OpInfo.Codes[i]);
5467 
5468     // Indirect 'other' or 'immediate' constraints are not allowed.
5469     if (OpInfo.isIndirect && !(CType == TargetLowering::C_Memory ||
5470                                CType == TargetLowering::C_Register ||
5471                                CType == TargetLowering::C_RegisterClass))
5472       continue;
5473 
5474     // If this is an 'other' or 'immediate' constraint, see if the operand is
5475     // valid for it. For example, on X86 we might have an 'rI' constraint. If
5476     // the operand is an integer in the range [0..31] we want to use I (saving a
5477     // load of a register), otherwise we must use 'r'.
5478     if ((CType == TargetLowering::C_Other ||
5479          CType == TargetLowering::C_Immediate) && Op.getNode()) {
5480       assert(OpInfo.Codes[i].size() == 1 &&
5481              "Unhandled multi-letter 'other' constraint");
5482       std::vector<SDValue> ResultOps;
5483       TLI.LowerAsmOperandForConstraint(Op, OpInfo.Codes[i],
5484                                        ResultOps, *DAG);
5485       if (!ResultOps.empty()) {
5486         BestType = CType;
5487         BestIdx = i;
5488         break;
5489       }
5490     }
5491 
5492     // Things with matching constraints can only be registers, per gcc
5493     // documentation.  This mainly affects "g" constraints.
5494     if (CType == TargetLowering::C_Memory && OpInfo.hasMatchingInput())
5495       continue;
5496 
5497     // This constraint letter is more general than the previous one, use it.
5498     int Generality = getConstraintGenerality(CType);
5499     if (Generality > BestGenerality) {
5500       BestType = CType;
5501       BestIdx = i;
5502       BestGenerality = Generality;
5503     }
5504   }
5505 
5506   OpInfo.ConstraintCode = OpInfo.Codes[BestIdx];
5507   OpInfo.ConstraintType = BestType;
5508 }
5509 
5510 /// Determines the constraint code and constraint type to use for the specific
5511 /// AsmOperandInfo, setting OpInfo.ConstraintCode and OpInfo.ConstraintType.
5512 void TargetLowering::ComputeConstraintToUse(AsmOperandInfo &OpInfo,
5513                                             SDValue Op,
5514                                             SelectionDAG *DAG) const {
5515   assert(!OpInfo.Codes.empty() && "Must have at least one constraint");
5516 
5517   // Single-letter constraints ('r') are very common.
5518   if (OpInfo.Codes.size() == 1) {
5519     OpInfo.ConstraintCode = OpInfo.Codes[0];
5520     OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode);
5521   } else {
5522     ChooseConstraint(OpInfo, *this, Op, DAG);
5523   }
5524 
5525   // 'X' matches anything.
5526   if (OpInfo.ConstraintCode == "X" && OpInfo.CallOperandVal) {
5527     // Constants are handled elsewhere.  For Functions, the type here is the
5528     // type of the result, which is not what we want to look at; leave them
5529     // alone.
5530     Value *v = OpInfo.CallOperandVal;
5531     if (isa<ConstantInt>(v) || isa<Function>(v)) {
5532       return;
5533     }
5534 
5535     if (isa<BasicBlock>(v) || isa<BlockAddress>(v)) {
5536       OpInfo.ConstraintCode = "i";
5537       return;
5538     }
5539 
5540     // Otherwise, try to resolve it to something we know about by looking at
5541     // the actual operand type.
5542     if (const char *Repl = LowerXConstraint(OpInfo.ConstraintVT)) {
5543       OpInfo.ConstraintCode = Repl;
5544       OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode);
5545     }
5546   }
5547 }
5548 
5549 /// Given an exact SDIV by a constant, create a multiplication
5550 /// with the multiplicative inverse of the constant.
5551 static SDValue BuildExactSDIV(const TargetLowering &TLI, SDNode *N,
5552                               const SDLoc &dl, SelectionDAG &DAG,
5553                               SmallVectorImpl<SDNode *> &Created) {
5554   SDValue Op0 = N->getOperand(0);
5555   SDValue Op1 = N->getOperand(1);
5556   EVT VT = N->getValueType(0);
5557   EVT SVT = VT.getScalarType();
5558   EVT ShVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout());
5559   EVT ShSVT = ShVT.getScalarType();
5560 
5561   bool UseSRA = false;
5562   SmallVector<SDValue, 16> Shifts, Factors;
5563 
5564   auto BuildSDIVPattern = [&](ConstantSDNode *C) {
5565     if (C->isZero())
5566       return false;
5567     APInt Divisor = C->getAPIntValue();
5568     unsigned Shift = Divisor.countTrailingZeros();
5569     if (Shift) {
5570       Divisor.ashrInPlace(Shift);
5571       UseSRA = true;
5572     }
5573     // Calculate the multiplicative inverse, using Newton's method.
5574     APInt t;
5575     APInt Factor = Divisor;
5576     while ((t = Divisor * Factor) != 1)
5577       Factor *= APInt(Divisor.getBitWidth(), 2) - t;
5578     Shifts.push_back(DAG.getConstant(Shift, dl, ShSVT));
5579     Factors.push_back(DAG.getConstant(Factor, dl, SVT));
5580     return true;
5581   };
5582 
5583   // Collect all magic values from the build vector.
5584   if (!ISD::matchUnaryPredicate(Op1, BuildSDIVPattern))
5585     return SDValue();
5586 
5587   SDValue Shift, Factor;
5588   if (Op1.getOpcode() == ISD::BUILD_VECTOR) {
5589     Shift = DAG.getBuildVector(ShVT, dl, Shifts);
5590     Factor = DAG.getBuildVector(VT, dl, Factors);
5591   } else if (Op1.getOpcode() == ISD::SPLAT_VECTOR) {
5592     assert(Shifts.size() == 1 && Factors.size() == 1 &&
5593            "Expected matchUnaryPredicate to return one element for scalable "
5594            "vectors");
5595     Shift = DAG.getSplatVector(ShVT, dl, Shifts[0]);
5596     Factor = DAG.getSplatVector(VT, dl, Factors[0]);
5597   } else {
5598     assert(isa<ConstantSDNode>(Op1) && "Expected a constant");
5599     Shift = Shifts[0];
5600     Factor = Factors[0];
5601   }
5602 
5603   SDValue Res = Op0;
5604 
5605   // Shift the value upfront if it is even, so the LSB is one.
5606   if (UseSRA) {
5607     // TODO: For UDIV use SRL instead of SRA.
5608     SDNodeFlags Flags;
5609     Flags.setExact(true);
5610     Res = DAG.getNode(ISD::SRA, dl, VT, Res, Shift, Flags);
5611     Created.push_back(Res.getNode());
5612   }
5613 
5614   return DAG.getNode(ISD::MUL, dl, VT, Res, Factor);
5615 }
5616 
5617 SDValue TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
5618                               SelectionDAG &DAG,
5619                               SmallVectorImpl<SDNode *> &Created) const {
5620   AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
5621   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5622   if (TLI.isIntDivCheap(N->getValueType(0), Attr))
5623     return SDValue(N, 0); // Lower SDIV as SDIV
5624   return SDValue();
5625 }
5626 
5627 SDValue
5628 TargetLowering::BuildSREMPow2(SDNode *N, const APInt &Divisor,
5629                               SelectionDAG &DAG,
5630                               SmallVectorImpl<SDNode *> &Created) const {
5631   AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
5632   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5633   if (TLI.isIntDivCheap(N->getValueType(0), Attr))
5634     return SDValue(N, 0); // Lower SREM as SREM
5635   return SDValue();
5636 }
5637 
5638 /// Given an ISD::SDIV node expressing a divide by constant,
5639 /// return a DAG expression to select that will generate the same value by
5640 /// multiplying by a magic number.
5641 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
5642 SDValue TargetLowering::BuildSDIV(SDNode *N, SelectionDAG &DAG,
5643                                   bool IsAfterLegalization,
5644                                   SmallVectorImpl<SDNode *> &Created) const {
5645   SDLoc dl(N);
5646   EVT VT = N->getValueType(0);
5647   EVT SVT = VT.getScalarType();
5648   EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
5649   EVT ShSVT = ShVT.getScalarType();
5650   unsigned EltBits = VT.getScalarSizeInBits();
5651   EVT MulVT;
5652 
5653   // Check to see if we can do this.
5654   // FIXME: We should be more aggressive here.
5655   if (!isTypeLegal(VT)) {
5656     // Limit this to simple scalars for now.
5657     if (VT.isVector() || !VT.isSimple())
5658       return SDValue();
5659 
5660     // If this type will be promoted to a large enough type with a legal
5661     // multiply operation, we can go ahead and do this transform.
5662     if (getTypeAction(VT.getSimpleVT()) != TypePromoteInteger)
5663       return SDValue();
5664 
5665     MulVT = getTypeToTransformTo(*DAG.getContext(), VT);
5666     if (MulVT.getSizeInBits() < (2 * EltBits) ||
5667         !isOperationLegal(ISD::MUL, MulVT))
5668       return SDValue();
5669   }
5670 
5671   // If the sdiv has an 'exact' bit we can use a simpler lowering.
5672   if (N->getFlags().hasExact())
5673     return BuildExactSDIV(*this, N, dl, DAG, Created);
5674 
5675   SmallVector<SDValue, 16> MagicFactors, Factors, Shifts, ShiftMasks;
5676 
5677   auto BuildSDIVPattern = [&](ConstantSDNode *C) {
5678     if (C->isZero())
5679       return false;
5680 
5681     const APInt &Divisor = C->getAPIntValue();
5682     SignedDivisionByConstantInfo magics = SignedDivisionByConstantInfo::get(Divisor);
5683     int NumeratorFactor = 0;
5684     int ShiftMask = -1;
5685 
5686     if (Divisor.isOne() || Divisor.isAllOnes()) {
5687       // If d is +1/-1, we just multiply the numerator by +1/-1.
5688       NumeratorFactor = Divisor.getSExtValue();
5689       magics.Magic = 0;
5690       magics.ShiftAmount = 0;
5691       ShiftMask = 0;
5692     } else if (Divisor.isStrictlyPositive() && magics.Magic.isNegative()) {
5693       // If d > 0 and m < 0, add the numerator.
5694       NumeratorFactor = 1;
5695     } else if (Divisor.isNegative() && magics.Magic.isStrictlyPositive()) {
5696       // If d < 0 and m > 0, subtract the numerator.
5697       NumeratorFactor = -1;
5698     }
5699 
5700     MagicFactors.push_back(DAG.getConstant(magics.Magic, dl, SVT));
5701     Factors.push_back(DAG.getConstant(NumeratorFactor, dl, SVT));
5702     Shifts.push_back(DAG.getConstant(magics.ShiftAmount, dl, ShSVT));
5703     ShiftMasks.push_back(DAG.getConstant(ShiftMask, dl, SVT));
5704     return true;
5705   };
5706 
5707   SDValue N0 = N->getOperand(0);
5708   SDValue N1 = N->getOperand(1);
5709 
5710   // Collect the shifts / magic values from each element.
5711   if (!ISD::matchUnaryPredicate(N1, BuildSDIVPattern))
5712     return SDValue();
5713 
5714   SDValue MagicFactor, Factor, Shift, ShiftMask;
5715   if (N1.getOpcode() == ISD::BUILD_VECTOR) {
5716     MagicFactor = DAG.getBuildVector(VT, dl, MagicFactors);
5717     Factor = DAG.getBuildVector(VT, dl, Factors);
5718     Shift = DAG.getBuildVector(ShVT, dl, Shifts);
5719     ShiftMask = DAG.getBuildVector(VT, dl, ShiftMasks);
5720   } else if (N1.getOpcode() == ISD::SPLAT_VECTOR) {
5721     assert(MagicFactors.size() == 1 && Factors.size() == 1 &&
5722            Shifts.size() == 1 && ShiftMasks.size() == 1 &&
5723            "Expected matchUnaryPredicate to return one element for scalable "
5724            "vectors");
5725     MagicFactor = DAG.getSplatVector(VT, dl, MagicFactors[0]);
5726     Factor = DAG.getSplatVector(VT, dl, Factors[0]);
5727     Shift = DAG.getSplatVector(ShVT, dl, Shifts[0]);
5728     ShiftMask = DAG.getSplatVector(VT, dl, ShiftMasks[0]);
5729   } else {
5730     assert(isa<ConstantSDNode>(N1) && "Expected a constant");
5731     MagicFactor = MagicFactors[0];
5732     Factor = Factors[0];
5733     Shift = Shifts[0];
5734     ShiftMask = ShiftMasks[0];
5735   }
5736 
5737   // Multiply the numerator (operand 0) by the magic value.
5738   // FIXME: We should support doing a MUL in a wider type.
5739   auto GetMULHS = [&](SDValue X, SDValue Y) {
5740     // If the type isn't legal, use a wider mul of the the type calculated
5741     // earlier.
5742     if (!isTypeLegal(VT)) {
5743       X = DAG.getNode(ISD::SIGN_EXTEND, dl, MulVT, X);
5744       Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MulVT, Y);
5745       Y = DAG.getNode(ISD::MUL, dl, MulVT, X, Y);
5746       Y = DAG.getNode(ISD::SRL, dl, MulVT, Y,
5747                       DAG.getShiftAmountConstant(EltBits, MulVT, dl));
5748       return DAG.getNode(ISD::TRUNCATE, dl, VT, Y);
5749     }
5750 
5751     if (isOperationLegalOrCustom(ISD::MULHS, VT, IsAfterLegalization))
5752       return DAG.getNode(ISD::MULHS, dl, VT, X, Y);
5753     if (isOperationLegalOrCustom(ISD::SMUL_LOHI, VT, IsAfterLegalization)) {
5754       SDValue LoHi =
5755           DAG.getNode(ISD::SMUL_LOHI, dl, DAG.getVTList(VT, VT), X, Y);
5756       return SDValue(LoHi.getNode(), 1);
5757     }
5758     return SDValue();
5759   };
5760 
5761   SDValue Q = GetMULHS(N0, MagicFactor);
5762   if (!Q)
5763     return SDValue();
5764 
5765   Created.push_back(Q.getNode());
5766 
5767   // (Optionally) Add/subtract the numerator using Factor.
5768   Factor = DAG.getNode(ISD::MUL, dl, VT, N0, Factor);
5769   Created.push_back(Factor.getNode());
5770   Q = DAG.getNode(ISD::ADD, dl, VT, Q, Factor);
5771   Created.push_back(Q.getNode());
5772 
5773   // Shift right algebraic by shift value.
5774   Q = DAG.getNode(ISD::SRA, dl, VT, Q, Shift);
5775   Created.push_back(Q.getNode());
5776 
5777   // Extract the sign bit, mask it and add it to the quotient.
5778   SDValue SignShift = DAG.getConstant(EltBits - 1, dl, ShVT);
5779   SDValue T = DAG.getNode(ISD::SRL, dl, VT, Q, SignShift);
5780   Created.push_back(T.getNode());
5781   T = DAG.getNode(ISD::AND, dl, VT, T, ShiftMask);
5782   Created.push_back(T.getNode());
5783   return DAG.getNode(ISD::ADD, dl, VT, Q, T);
5784 }
5785 
5786 /// Given an ISD::UDIV node expressing a divide by constant,
5787 /// return a DAG expression to select that will generate the same value by
5788 /// multiplying by a magic number.
5789 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
5790 SDValue TargetLowering::BuildUDIV(SDNode *N, SelectionDAG &DAG,
5791                                   bool IsAfterLegalization,
5792                                   SmallVectorImpl<SDNode *> &Created) const {
5793   SDLoc dl(N);
5794   EVT VT = N->getValueType(0);
5795   EVT SVT = VT.getScalarType();
5796   EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
5797   EVT ShSVT = ShVT.getScalarType();
5798   unsigned EltBits = VT.getScalarSizeInBits();
5799   EVT MulVT;
5800 
5801   // Check to see if we can do this.
5802   // FIXME: We should be more aggressive here.
5803   if (!isTypeLegal(VT)) {
5804     // Limit this to simple scalars for now.
5805     if (VT.isVector() || !VT.isSimple())
5806       return SDValue();
5807 
5808     // If this type will be promoted to a large enough type with a legal
5809     // multiply operation, we can go ahead and do this transform.
5810     if (getTypeAction(VT.getSimpleVT()) != TypePromoteInteger)
5811       return SDValue();
5812 
5813     MulVT = getTypeToTransformTo(*DAG.getContext(), VT);
5814     if (MulVT.getSizeInBits() < (2 * EltBits) ||
5815         !isOperationLegal(ISD::MUL, MulVT))
5816       return SDValue();
5817   }
5818 
5819   bool UseNPQ = false;
5820   SmallVector<SDValue, 16> PreShifts, PostShifts, MagicFactors, NPQFactors;
5821 
5822   auto BuildUDIVPattern = [&](ConstantSDNode *C) {
5823     if (C->isZero())
5824       return false;
5825     // FIXME: We should use a narrower constant when the upper
5826     // bits are known to be zero.
5827     const APInt& Divisor = C->getAPIntValue();
5828     UnsignedDivisonByConstantInfo magics = UnsignedDivisonByConstantInfo::get(Divisor);
5829     unsigned PreShift = 0, PostShift = 0;
5830 
5831     // If the divisor is even, we can avoid using the expensive fixup by
5832     // shifting the divided value upfront.
5833     if (magics.IsAdd != 0 && !Divisor[0]) {
5834       PreShift = Divisor.countTrailingZeros();
5835       // Get magic number for the shifted divisor.
5836       magics = UnsignedDivisonByConstantInfo::get(Divisor.lshr(PreShift), PreShift);
5837       assert(magics.IsAdd == 0 && "Should use cheap fixup now");
5838     }
5839 
5840     APInt Magic = magics.Magic;
5841 
5842     unsigned SelNPQ;
5843     if (magics.IsAdd == 0 || Divisor.isOne()) {
5844       assert(magics.ShiftAmount < Divisor.getBitWidth() &&
5845              "We shouldn't generate an undefined shift!");
5846       PostShift = magics.ShiftAmount;
5847       SelNPQ = false;
5848     } else {
5849       PostShift = magics.ShiftAmount - 1;
5850       SelNPQ = true;
5851     }
5852 
5853     PreShifts.push_back(DAG.getConstant(PreShift, dl, ShSVT));
5854     MagicFactors.push_back(DAG.getConstant(Magic, dl, SVT));
5855     NPQFactors.push_back(
5856         DAG.getConstant(SelNPQ ? APInt::getOneBitSet(EltBits, EltBits - 1)
5857                                : APInt::getZero(EltBits),
5858                         dl, SVT));
5859     PostShifts.push_back(DAG.getConstant(PostShift, dl, ShSVT));
5860     UseNPQ |= SelNPQ;
5861     return true;
5862   };
5863 
5864   SDValue N0 = N->getOperand(0);
5865   SDValue N1 = N->getOperand(1);
5866 
5867   // Collect the shifts/magic values from each element.
5868   if (!ISD::matchUnaryPredicate(N1, BuildUDIVPattern))
5869     return SDValue();
5870 
5871   SDValue PreShift, PostShift, MagicFactor, NPQFactor;
5872   if (N1.getOpcode() == ISD::BUILD_VECTOR) {
5873     PreShift = DAG.getBuildVector(ShVT, dl, PreShifts);
5874     MagicFactor = DAG.getBuildVector(VT, dl, MagicFactors);
5875     NPQFactor = DAG.getBuildVector(VT, dl, NPQFactors);
5876     PostShift = DAG.getBuildVector(ShVT, dl, PostShifts);
5877   } else if (N1.getOpcode() == ISD::SPLAT_VECTOR) {
5878     assert(PreShifts.size() == 1 && MagicFactors.size() == 1 &&
5879            NPQFactors.size() == 1 && PostShifts.size() == 1 &&
5880            "Expected matchUnaryPredicate to return one for scalable vectors");
5881     PreShift = DAG.getSplatVector(ShVT, dl, PreShifts[0]);
5882     MagicFactor = DAG.getSplatVector(VT, dl, MagicFactors[0]);
5883     NPQFactor = DAG.getSplatVector(VT, dl, NPQFactors[0]);
5884     PostShift = DAG.getSplatVector(ShVT, dl, PostShifts[0]);
5885   } else {
5886     assert(isa<ConstantSDNode>(N1) && "Expected a constant");
5887     PreShift = PreShifts[0];
5888     MagicFactor = MagicFactors[0];
5889     PostShift = PostShifts[0];
5890   }
5891 
5892   SDValue Q = N0;
5893   Q = DAG.getNode(ISD::SRL, dl, VT, Q, PreShift);
5894   Created.push_back(Q.getNode());
5895 
5896   // FIXME: We should support doing a MUL in a wider type.
5897   auto GetMULHU = [&](SDValue X, SDValue Y) {
5898     // If the type isn't legal, use a wider mul of the the type calculated
5899     // earlier.
5900     if (!isTypeLegal(VT)) {
5901       X = DAG.getNode(ISD::ZERO_EXTEND, dl, MulVT, X);
5902       Y = DAG.getNode(ISD::ZERO_EXTEND, dl, MulVT, Y);
5903       Y = DAG.getNode(ISD::MUL, dl, MulVT, X, Y);
5904       Y = DAG.getNode(ISD::SRL, dl, MulVT, Y,
5905                       DAG.getShiftAmountConstant(EltBits, MulVT, dl));
5906       return DAG.getNode(ISD::TRUNCATE, dl, VT, Y);
5907     }
5908 
5909     if (isOperationLegalOrCustom(ISD::MULHU, VT, IsAfterLegalization))
5910       return DAG.getNode(ISD::MULHU, dl, VT, X, Y);
5911     if (isOperationLegalOrCustom(ISD::UMUL_LOHI, VT, IsAfterLegalization)) {
5912       SDValue LoHi =
5913           DAG.getNode(ISD::UMUL_LOHI, dl, DAG.getVTList(VT, VT), X, Y);
5914       return SDValue(LoHi.getNode(), 1);
5915     }
5916     return SDValue(); // No mulhu or equivalent
5917   };
5918 
5919   // Multiply the numerator (operand 0) by the magic value.
5920   Q = GetMULHU(Q, MagicFactor);
5921   if (!Q)
5922     return SDValue();
5923 
5924   Created.push_back(Q.getNode());
5925 
5926   if (UseNPQ) {
5927     SDValue NPQ = DAG.getNode(ISD::SUB, dl, VT, N0, Q);
5928     Created.push_back(NPQ.getNode());
5929 
5930     // For vectors we might have a mix of non-NPQ/NPQ paths, so use
5931     // MULHU to act as a SRL-by-1 for NPQ, else multiply by zero.
5932     if (VT.isVector())
5933       NPQ = GetMULHU(NPQ, NPQFactor);
5934     else
5935       NPQ = DAG.getNode(ISD::SRL, dl, VT, NPQ, DAG.getConstant(1, dl, ShVT));
5936 
5937     Created.push_back(NPQ.getNode());
5938 
5939     Q = DAG.getNode(ISD::ADD, dl, VT, NPQ, Q);
5940     Created.push_back(Q.getNode());
5941   }
5942 
5943   Q = DAG.getNode(ISD::SRL, dl, VT, Q, PostShift);
5944   Created.push_back(Q.getNode());
5945 
5946   EVT SetCCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
5947 
5948   SDValue One = DAG.getConstant(1, dl, VT);
5949   SDValue IsOne = DAG.getSetCC(dl, SetCCVT, N1, One, ISD::SETEQ);
5950   return DAG.getSelect(dl, VT, IsOne, N0, Q);
5951 }
5952 
5953 /// If all values in Values that *don't* match the predicate are same 'splat'
5954 /// value, then replace all values with that splat value.
5955 /// Else, if AlternativeReplacement was provided, then replace all values that
5956 /// do match predicate with AlternativeReplacement value.
5957 static void
5958 turnVectorIntoSplatVector(MutableArrayRef<SDValue> Values,
5959                           std::function<bool(SDValue)> Predicate,
5960                           SDValue AlternativeReplacement = SDValue()) {
5961   SDValue Replacement;
5962   // Is there a value for which the Predicate does *NOT* match? What is it?
5963   auto SplatValue = llvm::find_if_not(Values, Predicate);
5964   if (SplatValue != Values.end()) {
5965     // Does Values consist only of SplatValue's and values matching Predicate?
5966     if (llvm::all_of(Values, [Predicate, SplatValue](SDValue Value) {
5967           return Value == *SplatValue || Predicate(Value);
5968         })) // Then we shall replace values matching predicate with SplatValue.
5969       Replacement = *SplatValue;
5970   }
5971   if (!Replacement) {
5972     // Oops, we did not find the "baseline" splat value.
5973     if (!AlternativeReplacement)
5974       return; // Nothing to do.
5975     // Let's replace with provided value then.
5976     Replacement = AlternativeReplacement;
5977   }
5978   std::replace_if(Values.begin(), Values.end(), Predicate, Replacement);
5979 }
5980 
5981 /// Given an ISD::UREM used only by an ISD::SETEQ or ISD::SETNE
5982 /// where the divisor is constant and the comparison target is zero,
5983 /// return a DAG expression that will generate the same comparison result
5984 /// using only multiplications, additions and shifts/rotations.
5985 /// Ref: "Hacker's Delight" 10-17.
5986 SDValue TargetLowering::buildUREMEqFold(EVT SETCCVT, SDValue REMNode,
5987                                         SDValue CompTargetNode,
5988                                         ISD::CondCode Cond,
5989                                         DAGCombinerInfo &DCI,
5990                                         const SDLoc &DL) const {
5991   SmallVector<SDNode *, 5> Built;
5992   if (SDValue Folded = prepareUREMEqFold(SETCCVT, REMNode, CompTargetNode, Cond,
5993                                          DCI, DL, Built)) {
5994     for (SDNode *N : Built)
5995       DCI.AddToWorklist(N);
5996     return Folded;
5997   }
5998 
5999   return SDValue();
6000 }
6001 
6002 SDValue
6003 TargetLowering::prepareUREMEqFold(EVT SETCCVT, SDValue REMNode,
6004                                   SDValue CompTargetNode, ISD::CondCode Cond,
6005                                   DAGCombinerInfo &DCI, const SDLoc &DL,
6006                                   SmallVectorImpl<SDNode *> &Created) const {
6007   // fold (seteq/ne (urem N, D), 0) -> (setule/ugt (rotr (mul N, P), K), Q)
6008   // - D must be constant, with D = D0 * 2^K where D0 is odd
6009   // - P is the multiplicative inverse of D0 modulo 2^W
6010   // - Q = floor(((2^W) - 1) / D)
6011   // where W is the width of the common type of N and D.
6012   assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
6013          "Only applicable for (in)equality comparisons.");
6014 
6015   SelectionDAG &DAG = DCI.DAG;
6016 
6017   EVT VT = REMNode.getValueType();
6018   EVT SVT = VT.getScalarType();
6019   EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout(), !DCI.isBeforeLegalize());
6020   EVT ShSVT = ShVT.getScalarType();
6021 
6022   // If MUL is unavailable, we cannot proceed in any case.
6023   if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::MUL, VT))
6024     return SDValue();
6025 
6026   bool ComparingWithAllZeros = true;
6027   bool AllComparisonsWithNonZerosAreTautological = true;
6028   bool HadTautologicalLanes = false;
6029   bool AllLanesAreTautological = true;
6030   bool HadEvenDivisor = false;
6031   bool AllDivisorsArePowerOfTwo = true;
6032   bool HadTautologicalInvertedLanes = false;
6033   SmallVector<SDValue, 16> PAmts, KAmts, QAmts, IAmts;
6034 
6035   auto BuildUREMPattern = [&](ConstantSDNode *CDiv, ConstantSDNode *CCmp) {
6036     // Division by 0 is UB. Leave it to be constant-folded elsewhere.
6037     if (CDiv->isZero())
6038       return false;
6039 
6040     const APInt &D = CDiv->getAPIntValue();
6041     const APInt &Cmp = CCmp->getAPIntValue();
6042 
6043     ComparingWithAllZeros &= Cmp.isZero();
6044 
6045     // x u% C1` is *always* less than C1. So given `x u% C1 == C2`,
6046     // if C2 is not less than C1, the comparison is always false.
6047     // But we will only be able to produce the comparison that will give the
6048     // opposive tautological answer. So this lane would need to be fixed up.
6049     bool TautologicalInvertedLane = D.ule(Cmp);
6050     HadTautologicalInvertedLanes |= TautologicalInvertedLane;
6051 
6052     // If all lanes are tautological (either all divisors are ones, or divisor
6053     // is not greater than the constant we are comparing with),
6054     // we will prefer to avoid the fold.
6055     bool TautologicalLane = D.isOne() || TautologicalInvertedLane;
6056     HadTautologicalLanes |= TautologicalLane;
6057     AllLanesAreTautological &= TautologicalLane;
6058 
6059     // If we are comparing with non-zero, we need'll need  to subtract said
6060     // comparison value from the LHS. But there is no point in doing that if
6061     // every lane where we are comparing with non-zero is tautological..
6062     if (!Cmp.isZero())
6063       AllComparisonsWithNonZerosAreTautological &= TautologicalLane;
6064 
6065     // Decompose D into D0 * 2^K
6066     unsigned K = D.countTrailingZeros();
6067     assert((!D.isOne() || (K == 0)) && "For divisor '1' we won't rotate.");
6068     APInt D0 = D.lshr(K);
6069 
6070     // D is even if it has trailing zeros.
6071     HadEvenDivisor |= (K != 0);
6072     // D is a power-of-two if D0 is one.
6073     // If all divisors are power-of-two, we will prefer to avoid the fold.
6074     AllDivisorsArePowerOfTwo &= D0.isOne();
6075 
6076     // P = inv(D0, 2^W)
6077     // 2^W requires W + 1 bits, so we have to extend and then truncate.
6078     unsigned W = D.getBitWidth();
6079     APInt P = D0.zext(W + 1)
6080                   .multiplicativeInverse(APInt::getSignedMinValue(W + 1))
6081                   .trunc(W);
6082     assert(!P.isZero() && "No multiplicative inverse!"); // unreachable
6083     assert((D0 * P).isOne() && "Multiplicative inverse basic check failed.");
6084 
6085     // Q = floor((2^W - 1) u/ D)
6086     // R = ((2^W - 1) u% D)
6087     APInt Q, R;
6088     APInt::udivrem(APInt::getAllOnes(W), D, Q, R);
6089 
6090     // If we are comparing with zero, then that comparison constant is okay,
6091     // else it may need to be one less than that.
6092     if (Cmp.ugt(R))
6093       Q -= 1;
6094 
6095     assert(APInt::getAllOnes(ShSVT.getSizeInBits()).ugt(K) &&
6096            "We are expecting that K is always less than all-ones for ShSVT");
6097 
6098     // If the lane is tautological the result can be constant-folded.
6099     if (TautologicalLane) {
6100       // Set P and K amount to a bogus values so we can try to splat them.
6101       P = 0;
6102       K = -1;
6103       // And ensure that comparison constant is tautological,
6104       // it will always compare true/false.
6105       Q = -1;
6106     }
6107 
6108     PAmts.push_back(DAG.getConstant(P, DL, SVT));
6109     KAmts.push_back(
6110         DAG.getConstant(APInt(ShSVT.getSizeInBits(), K), DL, ShSVT));
6111     QAmts.push_back(DAG.getConstant(Q, DL, SVT));
6112     return true;
6113   };
6114 
6115   SDValue N = REMNode.getOperand(0);
6116   SDValue D = REMNode.getOperand(1);
6117 
6118   // Collect the values from each element.
6119   if (!ISD::matchBinaryPredicate(D, CompTargetNode, BuildUREMPattern))
6120     return SDValue();
6121 
6122   // If all lanes are tautological, the result can be constant-folded.
6123   if (AllLanesAreTautological)
6124     return SDValue();
6125 
6126   // If this is a urem by a powers-of-two, avoid the fold since it can be
6127   // best implemented as a bit test.
6128   if (AllDivisorsArePowerOfTwo)
6129     return SDValue();
6130 
6131   SDValue PVal, KVal, QVal;
6132   if (D.getOpcode() == ISD::BUILD_VECTOR) {
6133     if (HadTautologicalLanes) {
6134       // Try to turn PAmts into a splat, since we don't care about the values
6135       // that are currently '0'. If we can't, just keep '0'`s.
6136       turnVectorIntoSplatVector(PAmts, isNullConstant);
6137       // Try to turn KAmts into a splat, since we don't care about the values
6138       // that are currently '-1'. If we can't, change them to '0'`s.
6139       turnVectorIntoSplatVector(KAmts, isAllOnesConstant,
6140                                 DAG.getConstant(0, DL, ShSVT));
6141     }
6142 
6143     PVal = DAG.getBuildVector(VT, DL, PAmts);
6144     KVal = DAG.getBuildVector(ShVT, DL, KAmts);
6145     QVal = DAG.getBuildVector(VT, DL, QAmts);
6146   } else if (D.getOpcode() == ISD::SPLAT_VECTOR) {
6147     assert(PAmts.size() == 1 && KAmts.size() == 1 && QAmts.size() == 1 &&
6148            "Expected matchBinaryPredicate to return one element for "
6149            "SPLAT_VECTORs");
6150     PVal = DAG.getSplatVector(VT, DL, PAmts[0]);
6151     KVal = DAG.getSplatVector(ShVT, DL, KAmts[0]);
6152     QVal = DAG.getSplatVector(VT, DL, QAmts[0]);
6153   } else {
6154     PVal = PAmts[0];
6155     KVal = KAmts[0];
6156     QVal = QAmts[0];
6157   }
6158 
6159   if (!ComparingWithAllZeros && !AllComparisonsWithNonZerosAreTautological) {
6160     if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::SUB, VT))
6161       return SDValue(); // FIXME: Could/should use `ISD::ADD`?
6162     assert(CompTargetNode.getValueType() == N.getValueType() &&
6163            "Expecting that the types on LHS and RHS of comparisons match.");
6164     N = DAG.getNode(ISD::SUB, DL, VT, N, CompTargetNode);
6165   }
6166 
6167   // (mul N, P)
6168   SDValue Op0 = DAG.getNode(ISD::MUL, DL, VT, N, PVal);
6169   Created.push_back(Op0.getNode());
6170 
6171   // Rotate right only if any divisor was even. We avoid rotates for all-odd
6172   // divisors as a performance improvement, since rotating by 0 is a no-op.
6173   if (HadEvenDivisor) {
6174     // We need ROTR to do this.
6175     if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::ROTR, VT))
6176       return SDValue();
6177     // UREM: (rotr (mul N, P), K)
6178     Op0 = DAG.getNode(ISD::ROTR, DL, VT, Op0, KVal);
6179     Created.push_back(Op0.getNode());
6180   }
6181 
6182   // UREM: (setule/setugt (rotr (mul N, P), K), Q)
6183   SDValue NewCC =
6184       DAG.getSetCC(DL, SETCCVT, Op0, QVal,
6185                    ((Cond == ISD::SETEQ) ? ISD::SETULE : ISD::SETUGT));
6186   if (!HadTautologicalInvertedLanes)
6187     return NewCC;
6188 
6189   // If any lanes previously compared always-false, the NewCC will give
6190   // always-true result for them, so we need to fixup those lanes.
6191   // Or the other way around for inequality predicate.
6192   assert(VT.isVector() && "Can/should only get here for vectors.");
6193   Created.push_back(NewCC.getNode());
6194 
6195   // x u% C1` is *always* less than C1. So given `x u% C1 == C2`,
6196   // if C2 is not less than C1, the comparison is always false.
6197   // But we have produced the comparison that will give the
6198   // opposive tautological answer. So these lanes would need to be fixed up.
6199   SDValue TautologicalInvertedChannels =
6200       DAG.getSetCC(DL, SETCCVT, D, CompTargetNode, ISD::SETULE);
6201   Created.push_back(TautologicalInvertedChannels.getNode());
6202 
6203   // NOTE: we avoid letting illegal types through even if we're before legalize
6204   // ops – legalization has a hard time producing good code for this.
6205   if (isOperationLegalOrCustom(ISD::VSELECT, SETCCVT)) {
6206     // If we have a vector select, let's replace the comparison results in the
6207     // affected lanes with the correct tautological result.
6208     SDValue Replacement = DAG.getBoolConstant(Cond == ISD::SETEQ ? false : true,
6209                                               DL, SETCCVT, SETCCVT);
6210     return DAG.getNode(ISD::VSELECT, DL, SETCCVT, TautologicalInvertedChannels,
6211                        Replacement, NewCC);
6212   }
6213 
6214   // Else, we can just invert the comparison result in the appropriate lanes.
6215   //
6216   // NOTE: see the note above VSELECT above.
6217   if (isOperationLegalOrCustom(ISD::XOR, SETCCVT))
6218     return DAG.getNode(ISD::XOR, DL, SETCCVT, NewCC,
6219                        TautologicalInvertedChannels);
6220 
6221   return SDValue(); // Don't know how to lower.
6222 }
6223 
6224 /// Given an ISD::SREM used only by an ISD::SETEQ or ISD::SETNE
6225 /// where the divisor is constant and the comparison target is zero,
6226 /// return a DAG expression that will generate the same comparison result
6227 /// using only multiplications, additions and shifts/rotations.
6228 /// Ref: "Hacker's Delight" 10-17.
6229 SDValue TargetLowering::buildSREMEqFold(EVT SETCCVT, SDValue REMNode,
6230                                         SDValue CompTargetNode,
6231                                         ISD::CondCode Cond,
6232                                         DAGCombinerInfo &DCI,
6233                                         const SDLoc &DL) const {
6234   SmallVector<SDNode *, 7> Built;
6235   if (SDValue Folded = prepareSREMEqFold(SETCCVT, REMNode, CompTargetNode, Cond,
6236                                          DCI, DL, Built)) {
6237     assert(Built.size() <= 7 && "Max size prediction failed.");
6238     for (SDNode *N : Built)
6239       DCI.AddToWorklist(N);
6240     return Folded;
6241   }
6242 
6243   return SDValue();
6244 }
6245 
6246 SDValue
6247 TargetLowering::prepareSREMEqFold(EVT SETCCVT, SDValue REMNode,
6248                                   SDValue CompTargetNode, ISD::CondCode Cond,
6249                                   DAGCombinerInfo &DCI, const SDLoc &DL,
6250                                   SmallVectorImpl<SDNode *> &Created) const {
6251   // Fold:
6252   //   (seteq/ne (srem N, D), 0)
6253   // To:
6254   //   (setule/ugt (rotr (add (mul N, P), A), K), Q)
6255   //
6256   // - D must be constant, with D = D0 * 2^K where D0 is odd
6257   // - P is the multiplicative inverse of D0 modulo 2^W
6258   // - A = bitwiseand(floor((2^(W - 1) - 1) / D0), (-(2^k)))
6259   // - Q = floor((2 * A) / (2^K))
6260   // where W is the width of the common type of N and D.
6261   assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
6262          "Only applicable for (in)equality comparisons.");
6263 
6264   SelectionDAG &DAG = DCI.DAG;
6265 
6266   EVT VT = REMNode.getValueType();
6267   EVT SVT = VT.getScalarType();
6268   EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout(), !DCI.isBeforeLegalize());
6269   EVT ShSVT = ShVT.getScalarType();
6270 
6271   // If we are after ops legalization, and MUL is unavailable, we can not
6272   // proceed.
6273   if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::MUL, VT))
6274     return SDValue();
6275 
6276   // TODO: Could support comparing with non-zero too.
6277   ConstantSDNode *CompTarget = isConstOrConstSplat(CompTargetNode);
6278   if (!CompTarget || !CompTarget->isZero())
6279     return SDValue();
6280 
6281   bool HadIntMinDivisor = false;
6282   bool HadOneDivisor = false;
6283   bool AllDivisorsAreOnes = true;
6284   bool HadEvenDivisor = false;
6285   bool NeedToApplyOffset = false;
6286   bool AllDivisorsArePowerOfTwo = true;
6287   SmallVector<SDValue, 16> PAmts, AAmts, KAmts, QAmts;
6288 
6289   auto BuildSREMPattern = [&](ConstantSDNode *C) {
6290     // Division by 0 is UB. Leave it to be constant-folded elsewhere.
6291     if (C->isZero())
6292       return false;
6293 
6294     // FIXME: we don't fold `rem %X, -C` to `rem %X, C` in DAGCombine.
6295 
6296     // WARNING: this fold is only valid for positive divisors!
6297     APInt D = C->getAPIntValue();
6298     if (D.isNegative())
6299       D.negate(); //  `rem %X, -C` is equivalent to `rem %X, C`
6300 
6301     HadIntMinDivisor |= D.isMinSignedValue();
6302 
6303     // If all divisors are ones, we will prefer to avoid the fold.
6304     HadOneDivisor |= D.isOne();
6305     AllDivisorsAreOnes &= D.isOne();
6306 
6307     // Decompose D into D0 * 2^K
6308     unsigned K = D.countTrailingZeros();
6309     assert((!D.isOne() || (K == 0)) && "For divisor '1' we won't rotate.");
6310     APInt D0 = D.lshr(K);
6311 
6312     if (!D.isMinSignedValue()) {
6313       // D is even if it has trailing zeros; unless it's INT_MIN, in which case
6314       // we don't care about this lane in this fold, we'll special-handle it.
6315       HadEvenDivisor |= (K != 0);
6316     }
6317 
6318     // D is a power-of-two if D0 is one. This includes INT_MIN.
6319     // If all divisors are power-of-two, we will prefer to avoid the fold.
6320     AllDivisorsArePowerOfTwo &= D0.isOne();
6321 
6322     // P = inv(D0, 2^W)
6323     // 2^W requires W + 1 bits, so we have to extend and then truncate.
6324     unsigned W = D.getBitWidth();
6325     APInt P = D0.zext(W + 1)
6326                   .multiplicativeInverse(APInt::getSignedMinValue(W + 1))
6327                   .trunc(W);
6328     assert(!P.isZero() && "No multiplicative inverse!"); // unreachable
6329     assert((D0 * P).isOne() && "Multiplicative inverse basic check failed.");
6330 
6331     // A = floor((2^(W - 1) - 1) / D0) & -2^K
6332     APInt A = APInt::getSignedMaxValue(W).udiv(D0);
6333     A.clearLowBits(K);
6334 
6335     if (!D.isMinSignedValue()) {
6336       // If divisor INT_MIN, then we don't care about this lane in this fold,
6337       // we'll special-handle it.
6338       NeedToApplyOffset |= A != 0;
6339     }
6340 
6341     // Q = floor((2 * A) / (2^K))
6342     APInt Q = (2 * A).udiv(APInt::getOneBitSet(W, K));
6343 
6344     assert(APInt::getAllOnes(SVT.getSizeInBits()).ugt(A) &&
6345            "We are expecting that A is always less than all-ones for SVT");
6346     assert(APInt::getAllOnes(ShSVT.getSizeInBits()).ugt(K) &&
6347            "We are expecting that K is always less than all-ones for ShSVT");
6348 
6349     // If the divisor is 1 the result can be constant-folded. Likewise, we
6350     // don't care about INT_MIN lanes, those can be set to undef if appropriate.
6351     if (D.isOne()) {
6352       // Set P, A and K to a bogus values so we can try to splat them.
6353       P = 0;
6354       A = -1;
6355       K = -1;
6356 
6357       // x ?% 1 == 0  <-->  true  <-->  x u<= -1
6358       Q = -1;
6359     }
6360 
6361     PAmts.push_back(DAG.getConstant(P, DL, SVT));
6362     AAmts.push_back(DAG.getConstant(A, DL, SVT));
6363     KAmts.push_back(
6364         DAG.getConstant(APInt(ShSVT.getSizeInBits(), K), DL, ShSVT));
6365     QAmts.push_back(DAG.getConstant(Q, DL, SVT));
6366     return true;
6367   };
6368 
6369   SDValue N = REMNode.getOperand(0);
6370   SDValue D = REMNode.getOperand(1);
6371 
6372   // Collect the values from each element.
6373   if (!ISD::matchUnaryPredicate(D, BuildSREMPattern))
6374     return SDValue();
6375 
6376   // If this is a srem by a one, avoid the fold since it can be constant-folded.
6377   if (AllDivisorsAreOnes)
6378     return SDValue();
6379 
6380   // If this is a srem by a powers-of-two (including INT_MIN), avoid the fold
6381   // since it can be best implemented as a bit test.
6382   if (AllDivisorsArePowerOfTwo)
6383     return SDValue();
6384 
6385   SDValue PVal, AVal, KVal, QVal;
6386   if (D.getOpcode() == ISD::BUILD_VECTOR) {
6387     if (HadOneDivisor) {
6388       // Try to turn PAmts into a splat, since we don't care about the values
6389       // that are currently '0'. If we can't, just keep '0'`s.
6390       turnVectorIntoSplatVector(PAmts, isNullConstant);
6391       // Try to turn AAmts into a splat, since we don't care about the
6392       // values that are currently '-1'. If we can't, change them to '0'`s.
6393       turnVectorIntoSplatVector(AAmts, isAllOnesConstant,
6394                                 DAG.getConstant(0, DL, SVT));
6395       // Try to turn KAmts into a splat, since we don't care about the values
6396       // that are currently '-1'. If we can't, change them to '0'`s.
6397       turnVectorIntoSplatVector(KAmts, isAllOnesConstant,
6398                                 DAG.getConstant(0, DL, ShSVT));
6399     }
6400 
6401     PVal = DAG.getBuildVector(VT, DL, PAmts);
6402     AVal = DAG.getBuildVector(VT, DL, AAmts);
6403     KVal = DAG.getBuildVector(ShVT, DL, KAmts);
6404     QVal = DAG.getBuildVector(VT, DL, QAmts);
6405   } else if (D.getOpcode() == ISD::SPLAT_VECTOR) {
6406     assert(PAmts.size() == 1 && AAmts.size() == 1 && KAmts.size() == 1 &&
6407            QAmts.size() == 1 &&
6408            "Expected matchUnaryPredicate to return one element for scalable "
6409            "vectors");
6410     PVal = DAG.getSplatVector(VT, DL, PAmts[0]);
6411     AVal = DAG.getSplatVector(VT, DL, AAmts[0]);
6412     KVal = DAG.getSplatVector(ShVT, DL, KAmts[0]);
6413     QVal = DAG.getSplatVector(VT, DL, QAmts[0]);
6414   } else {
6415     assert(isa<ConstantSDNode>(D) && "Expected a constant");
6416     PVal = PAmts[0];
6417     AVal = AAmts[0];
6418     KVal = KAmts[0];
6419     QVal = QAmts[0];
6420   }
6421 
6422   // (mul N, P)
6423   SDValue Op0 = DAG.getNode(ISD::MUL, DL, VT, N, PVal);
6424   Created.push_back(Op0.getNode());
6425 
6426   if (NeedToApplyOffset) {
6427     // We need ADD to do this.
6428     if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::ADD, VT))
6429       return SDValue();
6430 
6431     // (add (mul N, P), A)
6432     Op0 = DAG.getNode(ISD::ADD, DL, VT, Op0, AVal);
6433     Created.push_back(Op0.getNode());
6434   }
6435 
6436   // Rotate right only if any divisor was even. We avoid rotates for all-odd
6437   // divisors as a performance improvement, since rotating by 0 is a no-op.
6438   if (HadEvenDivisor) {
6439     // We need ROTR to do this.
6440     if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::ROTR, VT))
6441       return SDValue();
6442     // SREM: (rotr (add (mul N, P), A), K)
6443     Op0 = DAG.getNode(ISD::ROTR, DL, VT, Op0, KVal);
6444     Created.push_back(Op0.getNode());
6445   }
6446 
6447   // SREM: (setule/setugt (rotr (add (mul N, P), A), K), Q)
6448   SDValue Fold =
6449       DAG.getSetCC(DL, SETCCVT, Op0, QVal,
6450                    ((Cond == ISD::SETEQ) ? ISD::SETULE : ISD::SETUGT));
6451 
6452   // If we didn't have lanes with INT_MIN divisor, then we're done.
6453   if (!HadIntMinDivisor)
6454     return Fold;
6455 
6456   // That fold is only valid for positive divisors. Which effectively means,
6457   // it is invalid for INT_MIN divisors. So if we have such a lane,
6458   // we must fix-up results for said lanes.
6459   assert(VT.isVector() && "Can/should only get here for vectors.");
6460 
6461   // NOTE: we avoid letting illegal types through even if we're before legalize
6462   // ops – legalization has a hard time producing good code for the code that
6463   // follows.
6464   if (!isOperationLegalOrCustom(ISD::SETEQ, VT) ||
6465       !isOperationLegalOrCustom(ISD::AND, VT) ||
6466       !isOperationLegalOrCustom(Cond, VT) ||
6467       !isOperationLegalOrCustom(ISD::VSELECT, SETCCVT))
6468     return SDValue();
6469 
6470   Created.push_back(Fold.getNode());
6471 
6472   SDValue IntMin = DAG.getConstant(
6473       APInt::getSignedMinValue(SVT.getScalarSizeInBits()), DL, VT);
6474   SDValue IntMax = DAG.getConstant(
6475       APInt::getSignedMaxValue(SVT.getScalarSizeInBits()), DL, VT);
6476   SDValue Zero =
6477       DAG.getConstant(APInt::getZero(SVT.getScalarSizeInBits()), DL, VT);
6478 
6479   // Which lanes had INT_MIN divisors? Divisor is constant, so const-folded.
6480   SDValue DivisorIsIntMin = DAG.getSetCC(DL, SETCCVT, D, IntMin, ISD::SETEQ);
6481   Created.push_back(DivisorIsIntMin.getNode());
6482 
6483   // (N s% INT_MIN) ==/!= 0  <-->  (N & INT_MAX) ==/!= 0
6484   SDValue Masked = DAG.getNode(ISD::AND, DL, VT, N, IntMax);
6485   Created.push_back(Masked.getNode());
6486   SDValue MaskedIsZero = DAG.getSetCC(DL, SETCCVT, Masked, Zero, Cond);
6487   Created.push_back(MaskedIsZero.getNode());
6488 
6489   // To produce final result we need to blend 2 vectors: 'SetCC' and
6490   // 'MaskedIsZero'. If the divisor for channel was *NOT* INT_MIN, we pick
6491   // from 'Fold', else pick from 'MaskedIsZero'. Since 'DivisorIsIntMin' is
6492   // constant-folded, select can get lowered to a shuffle with constant mask.
6493   SDValue Blended = DAG.getNode(ISD::VSELECT, DL, SETCCVT, DivisorIsIntMin,
6494                                 MaskedIsZero, Fold);
6495 
6496   return Blended;
6497 }
6498 
6499 bool TargetLowering::
6500 verifyReturnAddressArgumentIsConstant(SDValue Op, SelectionDAG &DAG) const {
6501   if (!isa<ConstantSDNode>(Op.getOperand(0))) {
6502     DAG.getContext()->emitError("argument to '__builtin_return_address' must "
6503                                 "be a constant integer");
6504     return true;
6505   }
6506 
6507   return false;
6508 }
6509 
6510 SDValue TargetLowering::getSqrtInputTest(SDValue Op, SelectionDAG &DAG,
6511                                          const DenormalMode &Mode) const {
6512   SDLoc DL(Op);
6513   EVT VT = Op.getValueType();
6514   EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
6515   SDValue FPZero = DAG.getConstantFP(0.0, DL, VT);
6516   // Testing it with denormal inputs to avoid wrong estimate.
6517   if (Mode.Input == DenormalMode::IEEE) {
6518     // This is specifically a check for the handling of denormal inputs,
6519     // not the result.
6520 
6521     // Test = fabs(X) < SmallestNormal
6522     const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT);
6523     APFloat SmallestNorm = APFloat::getSmallestNormalized(FltSem);
6524     SDValue NormC = DAG.getConstantFP(SmallestNorm, DL, VT);
6525     SDValue Fabs = DAG.getNode(ISD::FABS, DL, VT, Op);
6526     return DAG.getSetCC(DL, CCVT, Fabs, NormC, ISD::SETLT);
6527   }
6528   // Test = X == 0.0
6529   return DAG.getSetCC(DL, CCVT, Op, FPZero, ISD::SETEQ);
6530 }
6531 
6532 SDValue TargetLowering::getNegatedExpression(SDValue Op, SelectionDAG &DAG,
6533                                              bool LegalOps, bool OptForSize,
6534                                              NegatibleCost &Cost,
6535                                              unsigned Depth) const {
6536   // fneg is removable even if it has multiple uses.
6537   if (Op.getOpcode() == ISD::FNEG) {
6538     Cost = NegatibleCost::Cheaper;
6539     return Op.getOperand(0);
6540   }
6541 
6542   // Don't recurse exponentially.
6543   if (Depth > SelectionDAG::MaxRecursionDepth)
6544     return SDValue();
6545 
6546   // Pre-increment recursion depth for use in recursive calls.
6547   ++Depth;
6548   const SDNodeFlags Flags = Op->getFlags();
6549   const TargetOptions &Options = DAG.getTarget().Options;
6550   EVT VT = Op.getValueType();
6551   unsigned Opcode = Op.getOpcode();
6552 
6553   // Don't allow anything with multiple uses unless we know it is free.
6554   if (!Op.hasOneUse() && Opcode != ISD::ConstantFP) {
6555     bool IsFreeExtend = Opcode == ISD::FP_EXTEND &&
6556                         isFPExtFree(VT, Op.getOperand(0).getValueType());
6557     if (!IsFreeExtend)
6558       return SDValue();
6559   }
6560 
6561   auto RemoveDeadNode = [&](SDValue N) {
6562     if (N && N.getNode()->use_empty())
6563       DAG.RemoveDeadNode(N.getNode());
6564   };
6565 
6566   SDLoc DL(Op);
6567 
6568   // Because getNegatedExpression can delete nodes we need a handle to keep
6569   // temporary nodes alive in case the recursion manages to create an identical
6570   // node.
6571   std::list<HandleSDNode> Handles;
6572 
6573   switch (Opcode) {
6574   case ISD::ConstantFP: {
6575     // Don't invert constant FP values after legalization unless the target says
6576     // the negated constant is legal.
6577     bool IsOpLegal =
6578         isOperationLegal(ISD::ConstantFP, VT) ||
6579         isFPImmLegal(neg(cast<ConstantFPSDNode>(Op)->getValueAPF()), VT,
6580                      OptForSize);
6581 
6582     if (LegalOps && !IsOpLegal)
6583       break;
6584 
6585     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
6586     V.changeSign();
6587     SDValue CFP = DAG.getConstantFP(V, DL, VT);
6588 
6589     // If we already have the use of the negated floating constant, it is free
6590     // to negate it even it has multiple uses.
6591     if (!Op.hasOneUse() && CFP.use_empty())
6592       break;
6593     Cost = NegatibleCost::Neutral;
6594     return CFP;
6595   }
6596   case ISD::BUILD_VECTOR: {
6597     // Only permit BUILD_VECTOR of constants.
6598     if (llvm::any_of(Op->op_values(), [&](SDValue N) {
6599           return !N.isUndef() && !isa<ConstantFPSDNode>(N);
6600         }))
6601       break;
6602 
6603     bool IsOpLegal =
6604         (isOperationLegal(ISD::ConstantFP, VT) &&
6605          isOperationLegal(ISD::BUILD_VECTOR, VT)) ||
6606         llvm::all_of(Op->op_values(), [&](SDValue N) {
6607           return N.isUndef() ||
6608                  isFPImmLegal(neg(cast<ConstantFPSDNode>(N)->getValueAPF()), VT,
6609                               OptForSize);
6610         });
6611 
6612     if (LegalOps && !IsOpLegal)
6613       break;
6614 
6615     SmallVector<SDValue, 4> Ops;
6616     for (SDValue C : Op->op_values()) {
6617       if (C.isUndef()) {
6618         Ops.push_back(C);
6619         continue;
6620       }
6621       APFloat V = cast<ConstantFPSDNode>(C)->getValueAPF();
6622       V.changeSign();
6623       Ops.push_back(DAG.getConstantFP(V, DL, C.getValueType()));
6624     }
6625     Cost = NegatibleCost::Neutral;
6626     return DAG.getBuildVector(VT, DL, Ops);
6627   }
6628   case ISD::FADD: {
6629     if (!Options.NoSignedZerosFPMath && !Flags.hasNoSignedZeros())
6630       break;
6631 
6632     // After operation legalization, it might not be legal to create new FSUBs.
6633     if (LegalOps && !isOperationLegalOrCustom(ISD::FSUB, VT))
6634       break;
6635     SDValue X = Op.getOperand(0), Y = Op.getOperand(1);
6636 
6637     // fold (fneg (fadd X, Y)) -> (fsub (fneg X), Y)
6638     NegatibleCost CostX = NegatibleCost::Expensive;
6639     SDValue NegX =
6640         getNegatedExpression(X, DAG, LegalOps, OptForSize, CostX, Depth);
6641     // Prevent this node from being deleted by the next call.
6642     if (NegX)
6643       Handles.emplace_back(NegX);
6644 
6645     // fold (fneg (fadd X, Y)) -> (fsub (fneg Y), X)
6646     NegatibleCost CostY = NegatibleCost::Expensive;
6647     SDValue NegY =
6648         getNegatedExpression(Y, DAG, LegalOps, OptForSize, CostY, Depth);
6649 
6650     // We're done with the handles.
6651     Handles.clear();
6652 
6653     // Negate the X if its cost is less or equal than Y.
6654     if (NegX && (CostX <= CostY)) {
6655       Cost = CostX;
6656       SDValue N = DAG.getNode(ISD::FSUB, DL, VT, NegX, Y, Flags);
6657       if (NegY != N)
6658         RemoveDeadNode(NegY);
6659       return N;
6660     }
6661 
6662     // Negate the Y if it is not expensive.
6663     if (NegY) {
6664       Cost = CostY;
6665       SDValue N = DAG.getNode(ISD::FSUB, DL, VT, NegY, X, Flags);
6666       if (NegX != N)
6667         RemoveDeadNode(NegX);
6668       return N;
6669     }
6670     break;
6671   }
6672   case ISD::FSUB: {
6673     // We can't turn -(A-B) into B-A when we honor signed zeros.
6674     if (!Options.NoSignedZerosFPMath && !Flags.hasNoSignedZeros())
6675       break;
6676 
6677     SDValue X = Op.getOperand(0), Y = Op.getOperand(1);
6678     // fold (fneg (fsub 0, Y)) -> Y
6679     if (ConstantFPSDNode *C = isConstOrConstSplatFP(X, /*AllowUndefs*/ true))
6680       if (C->isZero()) {
6681         Cost = NegatibleCost::Cheaper;
6682         return Y;
6683       }
6684 
6685     // fold (fneg (fsub X, Y)) -> (fsub Y, X)
6686     Cost = NegatibleCost::Neutral;
6687     return DAG.getNode(ISD::FSUB, DL, VT, Y, X, Flags);
6688   }
6689   case ISD::FMUL:
6690   case ISD::FDIV: {
6691     SDValue X = Op.getOperand(0), Y = Op.getOperand(1);
6692 
6693     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
6694     NegatibleCost CostX = NegatibleCost::Expensive;
6695     SDValue NegX =
6696         getNegatedExpression(X, DAG, LegalOps, OptForSize, CostX, Depth);
6697     // Prevent this node from being deleted by the next call.
6698     if (NegX)
6699       Handles.emplace_back(NegX);
6700 
6701     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
6702     NegatibleCost CostY = NegatibleCost::Expensive;
6703     SDValue NegY =
6704         getNegatedExpression(Y, DAG, LegalOps, OptForSize, CostY, Depth);
6705 
6706     // We're done with the handles.
6707     Handles.clear();
6708 
6709     // Negate the X if its cost is less or equal than Y.
6710     if (NegX && (CostX <= CostY)) {
6711       Cost = CostX;
6712       SDValue N = DAG.getNode(Opcode, DL, VT, NegX, Y, Flags);
6713       if (NegY != N)
6714         RemoveDeadNode(NegY);
6715       return N;
6716     }
6717 
6718     // Ignore X * 2.0 because that is expected to be canonicalized to X + X.
6719     if (auto *C = isConstOrConstSplatFP(Op.getOperand(1)))
6720       if (C->isExactlyValue(2.0) && Op.getOpcode() == ISD::FMUL)
6721         break;
6722 
6723     // Negate the Y if it is not expensive.
6724     if (NegY) {
6725       Cost = CostY;
6726       SDValue N = DAG.getNode(Opcode, DL, VT, X, NegY, Flags);
6727       if (NegX != N)
6728         RemoveDeadNode(NegX);
6729       return N;
6730     }
6731     break;
6732   }
6733   case ISD::FMA:
6734   case ISD::FMAD: {
6735     if (!Options.NoSignedZerosFPMath && !Flags.hasNoSignedZeros())
6736       break;
6737 
6738     SDValue X = Op.getOperand(0), Y = Op.getOperand(1), Z = Op.getOperand(2);
6739     NegatibleCost CostZ = NegatibleCost::Expensive;
6740     SDValue NegZ =
6741         getNegatedExpression(Z, DAG, LegalOps, OptForSize, CostZ, Depth);
6742     // Give up if fail to negate the Z.
6743     if (!NegZ)
6744       break;
6745 
6746     // Prevent this node from being deleted by the next two calls.
6747     Handles.emplace_back(NegZ);
6748 
6749     // fold (fneg (fma X, Y, Z)) -> (fma (fneg X), Y, (fneg Z))
6750     NegatibleCost CostX = NegatibleCost::Expensive;
6751     SDValue NegX =
6752         getNegatedExpression(X, DAG, LegalOps, OptForSize, CostX, Depth);
6753     // Prevent this node from being deleted by the next call.
6754     if (NegX)
6755       Handles.emplace_back(NegX);
6756 
6757     // fold (fneg (fma X, Y, Z)) -> (fma X, (fneg Y), (fneg Z))
6758     NegatibleCost CostY = NegatibleCost::Expensive;
6759     SDValue NegY =
6760         getNegatedExpression(Y, DAG, LegalOps, OptForSize, CostY, Depth);
6761 
6762     // We're done with the handles.
6763     Handles.clear();
6764 
6765     // Negate the X if its cost is less or equal than Y.
6766     if (NegX && (CostX <= CostY)) {
6767       Cost = std::min(CostX, CostZ);
6768       SDValue N = DAG.getNode(Opcode, DL, VT, NegX, Y, NegZ, Flags);
6769       if (NegY != N)
6770         RemoveDeadNode(NegY);
6771       return N;
6772     }
6773 
6774     // Negate the Y if it is not expensive.
6775     if (NegY) {
6776       Cost = std::min(CostY, CostZ);
6777       SDValue N = DAG.getNode(Opcode, DL, VT, X, NegY, NegZ, Flags);
6778       if (NegX != N)
6779         RemoveDeadNode(NegX);
6780       return N;
6781     }
6782     break;
6783   }
6784 
6785   case ISD::FP_EXTEND:
6786   case ISD::FSIN:
6787     if (SDValue NegV = getNegatedExpression(Op.getOperand(0), DAG, LegalOps,
6788                                             OptForSize, Cost, Depth))
6789       return DAG.getNode(Opcode, DL, VT, NegV);
6790     break;
6791   case ISD::FP_ROUND:
6792     if (SDValue NegV = getNegatedExpression(Op.getOperand(0), DAG, LegalOps,
6793                                             OptForSize, Cost, Depth))
6794       return DAG.getNode(ISD::FP_ROUND, DL, VT, NegV, Op.getOperand(1));
6795     break;
6796   }
6797 
6798   return SDValue();
6799 }
6800 
6801 //===----------------------------------------------------------------------===//
6802 // Legalization Utilities
6803 //===----------------------------------------------------------------------===//
6804 
6805 bool TargetLowering::expandMUL_LOHI(unsigned Opcode, EVT VT, const SDLoc &dl,
6806                                     SDValue LHS, SDValue RHS,
6807                                     SmallVectorImpl<SDValue> &Result,
6808                                     EVT HiLoVT, SelectionDAG &DAG,
6809                                     MulExpansionKind Kind, SDValue LL,
6810                                     SDValue LH, SDValue RL, SDValue RH) const {
6811   assert(Opcode == ISD::MUL || Opcode == ISD::UMUL_LOHI ||
6812          Opcode == ISD::SMUL_LOHI);
6813 
6814   bool HasMULHS = (Kind == MulExpansionKind::Always) ||
6815                   isOperationLegalOrCustom(ISD::MULHS, HiLoVT);
6816   bool HasMULHU = (Kind == MulExpansionKind::Always) ||
6817                   isOperationLegalOrCustom(ISD::MULHU, HiLoVT);
6818   bool HasSMUL_LOHI = (Kind == MulExpansionKind::Always) ||
6819                       isOperationLegalOrCustom(ISD::SMUL_LOHI, HiLoVT);
6820   bool HasUMUL_LOHI = (Kind == MulExpansionKind::Always) ||
6821                       isOperationLegalOrCustom(ISD::UMUL_LOHI, HiLoVT);
6822 
6823   if (!HasMULHU && !HasMULHS && !HasUMUL_LOHI && !HasSMUL_LOHI)
6824     return false;
6825 
6826   unsigned OuterBitSize = VT.getScalarSizeInBits();
6827   unsigned InnerBitSize = HiLoVT.getScalarSizeInBits();
6828 
6829   // LL, LH, RL, and RH must be either all NULL or all set to a value.
6830   assert((LL.getNode() && LH.getNode() && RL.getNode() && RH.getNode()) ||
6831          (!LL.getNode() && !LH.getNode() && !RL.getNode() && !RH.getNode()));
6832 
6833   SDVTList VTs = DAG.getVTList(HiLoVT, HiLoVT);
6834   auto MakeMUL_LOHI = [&](SDValue L, SDValue R, SDValue &Lo, SDValue &Hi,
6835                           bool Signed) -> bool {
6836     if ((Signed && HasSMUL_LOHI) || (!Signed && HasUMUL_LOHI)) {
6837       Lo = DAG.getNode(Signed ? ISD::SMUL_LOHI : ISD::UMUL_LOHI, dl, VTs, L, R);
6838       Hi = SDValue(Lo.getNode(), 1);
6839       return true;
6840     }
6841     if ((Signed && HasMULHS) || (!Signed && HasMULHU)) {
6842       Lo = DAG.getNode(ISD::MUL, dl, HiLoVT, L, R);
6843       Hi = DAG.getNode(Signed ? ISD::MULHS : ISD::MULHU, dl, HiLoVT, L, R);
6844       return true;
6845     }
6846     return false;
6847   };
6848 
6849   SDValue Lo, Hi;
6850 
6851   if (!LL.getNode() && !RL.getNode() &&
6852       isOperationLegalOrCustom(ISD::TRUNCATE, HiLoVT)) {
6853     LL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, LHS);
6854     RL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, RHS);
6855   }
6856 
6857   if (!LL.getNode())
6858     return false;
6859 
6860   APInt HighMask = APInt::getHighBitsSet(OuterBitSize, InnerBitSize);
6861   if (DAG.MaskedValueIsZero(LHS, HighMask) &&
6862       DAG.MaskedValueIsZero(RHS, HighMask)) {
6863     // The inputs are both zero-extended.
6864     if (MakeMUL_LOHI(LL, RL, Lo, Hi, false)) {
6865       Result.push_back(Lo);
6866       Result.push_back(Hi);
6867       if (Opcode != ISD::MUL) {
6868         SDValue Zero = DAG.getConstant(0, dl, HiLoVT);
6869         Result.push_back(Zero);
6870         Result.push_back(Zero);
6871       }
6872       return true;
6873     }
6874   }
6875 
6876   if (!VT.isVector() && Opcode == ISD::MUL &&
6877       DAG.ComputeNumSignBits(LHS) > InnerBitSize &&
6878       DAG.ComputeNumSignBits(RHS) > InnerBitSize) {
6879     // The input values are both sign-extended.
6880     // TODO non-MUL case?
6881     if (MakeMUL_LOHI(LL, RL, Lo, Hi, true)) {
6882       Result.push_back(Lo);
6883       Result.push_back(Hi);
6884       return true;
6885     }
6886   }
6887 
6888   unsigned ShiftAmount = OuterBitSize - InnerBitSize;
6889   EVT ShiftAmountTy = getShiftAmountTy(VT, DAG.getDataLayout());
6890   SDValue Shift = DAG.getConstant(ShiftAmount, dl, ShiftAmountTy);
6891 
6892   if (!LH.getNode() && !RH.getNode() &&
6893       isOperationLegalOrCustom(ISD::SRL, VT) &&
6894       isOperationLegalOrCustom(ISD::TRUNCATE, HiLoVT)) {
6895     LH = DAG.getNode(ISD::SRL, dl, VT, LHS, Shift);
6896     LH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, LH);
6897     RH = DAG.getNode(ISD::SRL, dl, VT, RHS, Shift);
6898     RH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, RH);
6899   }
6900 
6901   if (!LH.getNode())
6902     return false;
6903 
6904   if (!MakeMUL_LOHI(LL, RL, Lo, Hi, false))
6905     return false;
6906 
6907   Result.push_back(Lo);
6908 
6909   if (Opcode == ISD::MUL) {
6910     RH = DAG.getNode(ISD::MUL, dl, HiLoVT, LL, RH);
6911     LH = DAG.getNode(ISD::MUL, dl, HiLoVT, LH, RL);
6912     Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, RH);
6913     Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, LH);
6914     Result.push_back(Hi);
6915     return true;
6916   }
6917 
6918   // Compute the full width result.
6919   auto Merge = [&](SDValue Lo, SDValue Hi) -> SDValue {
6920     Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Lo);
6921     Hi = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Hi);
6922     Hi = DAG.getNode(ISD::SHL, dl, VT, Hi, Shift);
6923     return DAG.getNode(ISD::OR, dl, VT, Lo, Hi);
6924   };
6925 
6926   SDValue Next = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Hi);
6927   if (!MakeMUL_LOHI(LL, RH, Lo, Hi, false))
6928     return false;
6929 
6930   // This is effectively the add part of a multiply-add of half-sized operands,
6931   // so it cannot overflow.
6932   Next = DAG.getNode(ISD::ADD, dl, VT, Next, Merge(Lo, Hi));
6933 
6934   if (!MakeMUL_LOHI(LH, RL, Lo, Hi, false))
6935     return false;
6936 
6937   SDValue Zero = DAG.getConstant(0, dl, HiLoVT);
6938   EVT BoolType = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
6939 
6940   bool UseGlue = (isOperationLegalOrCustom(ISD::ADDC, VT) &&
6941                   isOperationLegalOrCustom(ISD::ADDE, VT));
6942   if (UseGlue)
6943     Next = DAG.getNode(ISD::ADDC, dl, DAG.getVTList(VT, MVT::Glue), Next,
6944                        Merge(Lo, Hi));
6945   else
6946     Next = DAG.getNode(ISD::ADDCARRY, dl, DAG.getVTList(VT, BoolType), Next,
6947                        Merge(Lo, Hi), DAG.getConstant(0, dl, BoolType));
6948 
6949   SDValue Carry = Next.getValue(1);
6950   Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next));
6951   Next = DAG.getNode(ISD::SRL, dl, VT, Next, Shift);
6952 
6953   if (!MakeMUL_LOHI(LH, RH, Lo, Hi, Opcode == ISD::SMUL_LOHI))
6954     return false;
6955 
6956   if (UseGlue)
6957     Hi = DAG.getNode(ISD::ADDE, dl, DAG.getVTList(HiLoVT, MVT::Glue), Hi, Zero,
6958                      Carry);
6959   else
6960     Hi = DAG.getNode(ISD::ADDCARRY, dl, DAG.getVTList(HiLoVT, BoolType), Hi,
6961                      Zero, Carry);
6962 
6963   Next = DAG.getNode(ISD::ADD, dl, VT, Next, Merge(Lo, Hi));
6964 
6965   if (Opcode == ISD::SMUL_LOHI) {
6966     SDValue NextSub = DAG.getNode(ISD::SUB, dl, VT, Next,
6967                                   DAG.getNode(ISD::ZERO_EXTEND, dl, VT, RL));
6968     Next = DAG.getSelectCC(dl, LH, Zero, NextSub, Next, ISD::SETLT);
6969 
6970     NextSub = DAG.getNode(ISD::SUB, dl, VT, Next,
6971                           DAG.getNode(ISD::ZERO_EXTEND, dl, VT, LL));
6972     Next = DAG.getSelectCC(dl, RH, Zero, NextSub, Next, ISD::SETLT);
6973   }
6974 
6975   Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next));
6976   Next = DAG.getNode(ISD::SRL, dl, VT, Next, Shift);
6977   Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next));
6978   return true;
6979 }
6980 
6981 bool TargetLowering::expandMUL(SDNode *N, SDValue &Lo, SDValue &Hi, EVT HiLoVT,
6982                                SelectionDAG &DAG, MulExpansionKind Kind,
6983                                SDValue LL, SDValue LH, SDValue RL,
6984                                SDValue RH) const {
6985   SmallVector<SDValue, 2> Result;
6986   bool Ok = expandMUL_LOHI(N->getOpcode(), N->getValueType(0), SDLoc(N),
6987                            N->getOperand(0), N->getOperand(1), Result, HiLoVT,
6988                            DAG, Kind, LL, LH, RL, RH);
6989   if (Ok) {
6990     assert(Result.size() == 2);
6991     Lo = Result[0];
6992     Hi = Result[1];
6993   }
6994   return Ok;
6995 }
6996 
6997 // Check that (every element of) Z is undef or not an exact multiple of BW.
6998 static bool isNonZeroModBitWidthOrUndef(SDValue Z, unsigned BW) {
6999   return ISD::matchUnaryPredicate(
7000       Z,
7001       [=](ConstantSDNode *C) { return !C || C->getAPIntValue().urem(BW) != 0; },
7002       true);
7003 }
7004 
7005 SDValue TargetLowering::expandFunnelShift(SDNode *Node,
7006                                           SelectionDAG &DAG) const {
7007   EVT VT = Node->getValueType(0);
7008 
7009   if (VT.isVector() && (!isOperationLegalOrCustom(ISD::SHL, VT) ||
7010                         !isOperationLegalOrCustom(ISD::SRL, VT) ||
7011                         !isOperationLegalOrCustom(ISD::SUB, VT) ||
7012                         !isOperationLegalOrCustomOrPromote(ISD::OR, VT)))
7013     return SDValue();
7014 
7015   SDValue X = Node->getOperand(0);
7016   SDValue Y = Node->getOperand(1);
7017   SDValue Z = Node->getOperand(2);
7018 
7019   unsigned BW = VT.getScalarSizeInBits();
7020   bool IsFSHL = Node->getOpcode() == ISD::FSHL;
7021   SDLoc DL(SDValue(Node, 0));
7022 
7023   EVT ShVT = Z.getValueType();
7024 
7025   // If a funnel shift in the other direction is more supported, use it.
7026   unsigned RevOpcode = IsFSHL ? ISD::FSHR : ISD::FSHL;
7027   if (!isOperationLegalOrCustom(Node->getOpcode(), VT) &&
7028       isOperationLegalOrCustom(RevOpcode, VT) && isPowerOf2_32(BW)) {
7029     if (isNonZeroModBitWidthOrUndef(Z, BW)) {
7030       // fshl X, Y, Z -> fshr X, Y, -Z
7031       // fshr X, Y, Z -> fshl X, Y, -Z
7032       SDValue Zero = DAG.getConstant(0, DL, ShVT);
7033       Z = DAG.getNode(ISD::SUB, DL, VT, Zero, Z);
7034     } else {
7035       // fshl X, Y, Z -> fshr (srl X, 1), (fshr X, Y, 1), ~Z
7036       // fshr X, Y, Z -> fshl (fshl X, Y, 1), (shl Y, 1), ~Z
7037       SDValue One = DAG.getConstant(1, DL, ShVT);
7038       if (IsFSHL) {
7039         Y = DAG.getNode(RevOpcode, DL, VT, X, Y, One);
7040         X = DAG.getNode(ISD::SRL, DL, VT, X, One);
7041       } else {
7042         X = DAG.getNode(RevOpcode, DL, VT, X, Y, One);
7043         Y = DAG.getNode(ISD::SHL, DL, VT, Y, One);
7044       }
7045       Z = DAG.getNOT(DL, Z, ShVT);
7046     }
7047     return DAG.getNode(RevOpcode, DL, VT, X, Y, Z);
7048   }
7049 
7050   SDValue ShX, ShY;
7051   SDValue ShAmt, InvShAmt;
7052   if (isNonZeroModBitWidthOrUndef(Z, BW)) {
7053     // fshl: X << C | Y >> (BW - C)
7054     // fshr: X << (BW - C) | Y >> C
7055     // where C = Z % BW is not zero
7056     SDValue BitWidthC = DAG.getConstant(BW, DL, ShVT);
7057     ShAmt = DAG.getNode(ISD::UREM, DL, ShVT, Z, BitWidthC);
7058     InvShAmt = DAG.getNode(ISD::SUB, DL, ShVT, BitWidthC, ShAmt);
7059     ShX = DAG.getNode(ISD::SHL, DL, VT, X, IsFSHL ? ShAmt : InvShAmt);
7060     ShY = DAG.getNode(ISD::SRL, DL, VT, Y, IsFSHL ? InvShAmt : ShAmt);
7061   } else {
7062     // fshl: X << (Z % BW) | Y >> 1 >> (BW - 1 - (Z % BW))
7063     // fshr: X << 1 << (BW - 1 - (Z % BW)) | Y >> (Z % BW)
7064     SDValue Mask = DAG.getConstant(BW - 1, DL, ShVT);
7065     if (isPowerOf2_32(BW)) {
7066       // Z % BW -> Z & (BW - 1)
7067       ShAmt = DAG.getNode(ISD::AND, DL, ShVT, Z, Mask);
7068       // (BW - 1) - (Z % BW) -> ~Z & (BW - 1)
7069       InvShAmt = DAG.getNode(ISD::AND, DL, ShVT, DAG.getNOT(DL, Z, ShVT), Mask);
7070     } else {
7071       SDValue BitWidthC = DAG.getConstant(BW, DL, ShVT);
7072       ShAmt = DAG.getNode(ISD::UREM, DL, ShVT, Z, BitWidthC);
7073       InvShAmt = DAG.getNode(ISD::SUB, DL, ShVT, Mask, ShAmt);
7074     }
7075 
7076     SDValue One = DAG.getConstant(1, DL, ShVT);
7077     if (IsFSHL) {
7078       ShX = DAG.getNode(ISD::SHL, DL, VT, X, ShAmt);
7079       SDValue ShY1 = DAG.getNode(ISD::SRL, DL, VT, Y, One);
7080       ShY = DAG.getNode(ISD::SRL, DL, VT, ShY1, InvShAmt);
7081     } else {
7082       SDValue ShX1 = DAG.getNode(ISD::SHL, DL, VT, X, One);
7083       ShX = DAG.getNode(ISD::SHL, DL, VT, ShX1, InvShAmt);
7084       ShY = DAG.getNode(ISD::SRL, DL, VT, Y, ShAmt);
7085     }
7086   }
7087   return DAG.getNode(ISD::OR, DL, VT, ShX, ShY);
7088 }
7089 
7090 // TODO: Merge with expandFunnelShift.
7091 SDValue TargetLowering::expandROT(SDNode *Node, bool AllowVectorOps,
7092                                   SelectionDAG &DAG) const {
7093   EVT VT = Node->getValueType(0);
7094   unsigned EltSizeInBits = VT.getScalarSizeInBits();
7095   bool IsLeft = Node->getOpcode() == ISD::ROTL;
7096   SDValue Op0 = Node->getOperand(0);
7097   SDValue Op1 = Node->getOperand(1);
7098   SDLoc DL(SDValue(Node, 0));
7099 
7100   EVT ShVT = Op1.getValueType();
7101   SDValue Zero = DAG.getConstant(0, DL, ShVT);
7102 
7103   // If a rotate in the other direction is more supported, use it.
7104   unsigned RevRot = IsLeft ? ISD::ROTR : ISD::ROTL;
7105   if (!isOperationLegalOrCustom(Node->getOpcode(), VT) &&
7106       isOperationLegalOrCustom(RevRot, VT) && isPowerOf2_32(EltSizeInBits)) {
7107     SDValue Sub = DAG.getNode(ISD::SUB, DL, ShVT, Zero, Op1);
7108     return DAG.getNode(RevRot, DL, VT, Op0, Sub);
7109   }
7110 
7111   if (!AllowVectorOps && VT.isVector() &&
7112       (!isOperationLegalOrCustom(ISD::SHL, VT) ||
7113        !isOperationLegalOrCustom(ISD::SRL, VT) ||
7114        !isOperationLegalOrCustom(ISD::SUB, VT) ||
7115        !isOperationLegalOrCustomOrPromote(ISD::OR, VT) ||
7116        !isOperationLegalOrCustomOrPromote(ISD::AND, VT)))
7117     return SDValue();
7118 
7119   unsigned ShOpc = IsLeft ? ISD::SHL : ISD::SRL;
7120   unsigned HsOpc = IsLeft ? ISD::SRL : ISD::SHL;
7121   SDValue BitWidthMinusOneC = DAG.getConstant(EltSizeInBits - 1, DL, ShVT);
7122   SDValue ShVal;
7123   SDValue HsVal;
7124   if (isPowerOf2_32(EltSizeInBits)) {
7125     // (rotl x, c) -> x << (c & (w - 1)) | x >> (-c & (w - 1))
7126     // (rotr x, c) -> x >> (c & (w - 1)) | x << (-c & (w - 1))
7127     SDValue NegOp1 = DAG.getNode(ISD::SUB, DL, ShVT, Zero, Op1);
7128     SDValue ShAmt = DAG.getNode(ISD::AND, DL, ShVT, Op1, BitWidthMinusOneC);
7129     ShVal = DAG.getNode(ShOpc, DL, VT, Op0, ShAmt);
7130     SDValue HsAmt = DAG.getNode(ISD::AND, DL, ShVT, NegOp1, BitWidthMinusOneC);
7131     HsVal = DAG.getNode(HsOpc, DL, VT, Op0, HsAmt);
7132   } else {
7133     // (rotl x, c) -> x << (c % w) | x >> 1 >> (w - 1 - (c % w))
7134     // (rotr x, c) -> x >> (c % w) | x << 1 << (w - 1 - (c % w))
7135     SDValue BitWidthC = DAG.getConstant(EltSizeInBits, DL, ShVT);
7136     SDValue ShAmt = DAG.getNode(ISD::UREM, DL, ShVT, Op1, BitWidthC);
7137     ShVal = DAG.getNode(ShOpc, DL, VT, Op0, ShAmt);
7138     SDValue HsAmt = DAG.getNode(ISD::SUB, DL, ShVT, BitWidthMinusOneC, ShAmt);
7139     SDValue One = DAG.getConstant(1, DL, ShVT);
7140     HsVal =
7141         DAG.getNode(HsOpc, DL, VT, DAG.getNode(HsOpc, DL, VT, Op0, One), HsAmt);
7142   }
7143   return DAG.getNode(ISD::OR, DL, VT, ShVal, HsVal);
7144 }
7145 
7146 void TargetLowering::expandShiftParts(SDNode *Node, SDValue &Lo, SDValue &Hi,
7147                                       SelectionDAG &DAG) const {
7148   assert(Node->getNumOperands() == 3 && "Not a double-shift!");
7149   EVT VT = Node->getValueType(0);
7150   unsigned VTBits = VT.getScalarSizeInBits();
7151   assert(isPowerOf2_32(VTBits) && "Power-of-two integer type expected");
7152 
7153   bool IsSHL = Node->getOpcode() == ISD::SHL_PARTS;
7154   bool IsSRA = Node->getOpcode() == ISD::SRA_PARTS;
7155   SDValue ShOpLo = Node->getOperand(0);
7156   SDValue ShOpHi = Node->getOperand(1);
7157   SDValue ShAmt = Node->getOperand(2);
7158   EVT ShAmtVT = ShAmt.getValueType();
7159   EVT ShAmtCCVT =
7160       getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), ShAmtVT);
7161   SDLoc dl(Node);
7162 
7163   // ISD::FSHL and ISD::FSHR have defined overflow behavior but ISD::SHL and
7164   // ISD::SRA/L nodes haven't. Insert an AND to be safe, it's usually optimized
7165   // away during isel.
7166   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, ShAmtVT, ShAmt,
7167                                   DAG.getConstant(VTBits - 1, dl, ShAmtVT));
7168   SDValue Tmp1 = IsSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7169                                      DAG.getConstant(VTBits - 1, dl, ShAmtVT))
7170                        : DAG.getConstant(0, dl, VT);
7171 
7172   SDValue Tmp2, Tmp3;
7173   if (IsSHL) {
7174     Tmp2 = DAG.getNode(ISD::FSHL, dl, VT, ShOpHi, ShOpLo, ShAmt);
7175     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
7176   } else {
7177     Tmp2 = DAG.getNode(ISD::FSHR, dl, VT, ShOpHi, ShOpLo, ShAmt);
7178     Tmp3 = DAG.getNode(IsSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
7179   }
7180 
7181   // If the shift amount is larger or equal than the width of a part we don't
7182   // use the result from the FSHL/FSHR. Insert a test and select the appropriate
7183   // values for large shift amounts.
7184   SDValue AndNode = DAG.getNode(ISD::AND, dl, ShAmtVT, ShAmt,
7185                                 DAG.getConstant(VTBits, dl, ShAmtVT));
7186   SDValue Cond = DAG.getSetCC(dl, ShAmtCCVT, AndNode,
7187                               DAG.getConstant(0, dl, ShAmtVT), ISD::SETNE);
7188 
7189   if (IsSHL) {
7190     Hi = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp3, Tmp2);
7191     Lo = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp1, Tmp3);
7192   } else {
7193     Lo = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp3, Tmp2);
7194     Hi = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp1, Tmp3);
7195   }
7196 }
7197 
7198 bool TargetLowering::expandFP_TO_SINT(SDNode *Node, SDValue &Result,
7199                                       SelectionDAG &DAG) const {
7200   unsigned OpNo = Node->isStrictFPOpcode() ? 1 : 0;
7201   SDValue Src = Node->getOperand(OpNo);
7202   EVT SrcVT = Src.getValueType();
7203   EVT DstVT = Node->getValueType(0);
7204   SDLoc dl(SDValue(Node, 0));
7205 
7206   // FIXME: Only f32 to i64 conversions are supported.
7207   if (SrcVT != MVT::f32 || DstVT != MVT::i64)
7208     return false;
7209 
7210   if (Node->isStrictFPOpcode())
7211     // When a NaN is converted to an integer a trap is allowed. We can't
7212     // use this expansion here because it would eliminate that trap. Other
7213     // traps are also allowed and cannot be eliminated. See
7214     // IEEE 754-2008 sec 5.8.
7215     return false;
7216 
7217   // Expand f32 -> i64 conversion
7218   // This algorithm comes from compiler-rt's implementation of fixsfdi:
7219   // https://github.com/llvm/llvm-project/blob/main/compiler-rt/lib/builtins/fixsfdi.c
7220   unsigned SrcEltBits = SrcVT.getScalarSizeInBits();
7221   EVT IntVT = SrcVT.changeTypeToInteger();
7222   EVT IntShVT = getShiftAmountTy(IntVT, DAG.getDataLayout());
7223 
7224   SDValue ExponentMask = DAG.getConstant(0x7F800000, dl, IntVT);
7225   SDValue ExponentLoBit = DAG.getConstant(23, dl, IntVT);
7226   SDValue Bias = DAG.getConstant(127, dl, IntVT);
7227   SDValue SignMask = DAG.getConstant(APInt::getSignMask(SrcEltBits), dl, IntVT);
7228   SDValue SignLowBit = DAG.getConstant(SrcEltBits - 1, dl, IntVT);
7229   SDValue MantissaMask = DAG.getConstant(0x007FFFFF, dl, IntVT);
7230 
7231   SDValue Bits = DAG.getNode(ISD::BITCAST, dl, IntVT, Src);
7232 
7233   SDValue ExponentBits = DAG.getNode(
7234       ISD::SRL, dl, IntVT, DAG.getNode(ISD::AND, dl, IntVT, Bits, ExponentMask),
7235       DAG.getZExtOrTrunc(ExponentLoBit, dl, IntShVT));
7236   SDValue Exponent = DAG.getNode(ISD::SUB, dl, IntVT, ExponentBits, Bias);
7237 
7238   SDValue Sign = DAG.getNode(ISD::SRA, dl, IntVT,
7239                              DAG.getNode(ISD::AND, dl, IntVT, Bits, SignMask),
7240                              DAG.getZExtOrTrunc(SignLowBit, dl, IntShVT));
7241   Sign = DAG.getSExtOrTrunc(Sign, dl, DstVT);
7242 
7243   SDValue R = DAG.getNode(ISD::OR, dl, IntVT,
7244                           DAG.getNode(ISD::AND, dl, IntVT, Bits, MantissaMask),
7245                           DAG.getConstant(0x00800000, dl, IntVT));
7246 
7247   R = DAG.getZExtOrTrunc(R, dl, DstVT);
7248 
7249   R = DAG.getSelectCC(
7250       dl, Exponent, ExponentLoBit,
7251       DAG.getNode(ISD::SHL, dl, DstVT, R,
7252                   DAG.getZExtOrTrunc(
7253                       DAG.getNode(ISD::SUB, dl, IntVT, Exponent, ExponentLoBit),
7254                       dl, IntShVT)),
7255       DAG.getNode(ISD::SRL, dl, DstVT, R,
7256                   DAG.getZExtOrTrunc(
7257                       DAG.getNode(ISD::SUB, dl, IntVT, ExponentLoBit, Exponent),
7258                       dl, IntShVT)),
7259       ISD::SETGT);
7260 
7261   SDValue Ret = DAG.getNode(ISD::SUB, dl, DstVT,
7262                             DAG.getNode(ISD::XOR, dl, DstVT, R, Sign), Sign);
7263 
7264   Result = DAG.getSelectCC(dl, Exponent, DAG.getConstant(0, dl, IntVT),
7265                            DAG.getConstant(0, dl, DstVT), Ret, ISD::SETLT);
7266   return true;
7267 }
7268 
7269 bool TargetLowering::expandFP_TO_UINT(SDNode *Node, SDValue &Result,
7270                                       SDValue &Chain,
7271                                       SelectionDAG &DAG) const {
7272   SDLoc dl(SDValue(Node, 0));
7273   unsigned OpNo = Node->isStrictFPOpcode() ? 1 : 0;
7274   SDValue Src = Node->getOperand(OpNo);
7275 
7276   EVT SrcVT = Src.getValueType();
7277   EVT DstVT = Node->getValueType(0);
7278   EVT SetCCVT =
7279       getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT);
7280   EVT DstSetCCVT =
7281       getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), DstVT);
7282 
7283   // Only expand vector types if we have the appropriate vector bit operations.
7284   unsigned SIntOpcode = Node->isStrictFPOpcode() ? ISD::STRICT_FP_TO_SINT :
7285                                                    ISD::FP_TO_SINT;
7286   if (DstVT.isVector() && (!isOperationLegalOrCustom(SIntOpcode, DstVT) ||
7287                            !isOperationLegalOrCustomOrPromote(ISD::XOR, SrcVT)))
7288     return false;
7289 
7290   // If the maximum float value is smaller then the signed integer range,
7291   // the destination signmask can't be represented by the float, so we can
7292   // just use FP_TO_SINT directly.
7293   const fltSemantics &APFSem = DAG.EVTToAPFloatSemantics(SrcVT);
7294   APFloat APF(APFSem, APInt::getZero(SrcVT.getScalarSizeInBits()));
7295   APInt SignMask = APInt::getSignMask(DstVT.getScalarSizeInBits());
7296   if (APFloat::opOverflow &
7297       APF.convertFromAPInt(SignMask, false, APFloat::rmNearestTiesToEven)) {
7298     if (Node->isStrictFPOpcode()) {
7299       Result = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, { DstVT, MVT::Other },
7300                            { Node->getOperand(0), Src });
7301       Chain = Result.getValue(1);
7302     } else
7303       Result = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, Src);
7304     return true;
7305   }
7306 
7307   // Don't expand it if there isn't cheap fsub instruction.
7308   if (!isOperationLegalOrCustom(
7309           Node->isStrictFPOpcode() ? ISD::STRICT_FSUB : ISD::FSUB, SrcVT))
7310     return false;
7311 
7312   SDValue Cst = DAG.getConstantFP(APF, dl, SrcVT);
7313   SDValue Sel;
7314 
7315   if (Node->isStrictFPOpcode()) {
7316     Sel = DAG.getSetCC(dl, SetCCVT, Src, Cst, ISD::SETLT,
7317                        Node->getOperand(0), /*IsSignaling*/ true);
7318     Chain = Sel.getValue(1);
7319   } else {
7320     Sel = DAG.getSetCC(dl, SetCCVT, Src, Cst, ISD::SETLT);
7321   }
7322 
7323   bool Strict = Node->isStrictFPOpcode() ||
7324                 shouldUseStrictFP_TO_INT(SrcVT, DstVT, /*IsSigned*/ false);
7325 
7326   if (Strict) {
7327     // Expand based on maximum range of FP_TO_SINT, if the value exceeds the
7328     // signmask then offset (the result of which should be fully representable).
7329     // Sel = Src < 0x8000000000000000
7330     // FltOfs = select Sel, 0, 0x8000000000000000
7331     // IntOfs = select Sel, 0, 0x8000000000000000
7332     // Result = fp_to_sint(Src - FltOfs) ^ IntOfs
7333 
7334     // TODO: Should any fast-math-flags be set for the FSUB?
7335     SDValue FltOfs = DAG.getSelect(dl, SrcVT, Sel,
7336                                    DAG.getConstantFP(0.0, dl, SrcVT), Cst);
7337     Sel = DAG.getBoolExtOrTrunc(Sel, dl, DstSetCCVT, DstVT);
7338     SDValue IntOfs = DAG.getSelect(dl, DstVT, Sel,
7339                                    DAG.getConstant(0, dl, DstVT),
7340                                    DAG.getConstant(SignMask, dl, DstVT));
7341     SDValue SInt;
7342     if (Node->isStrictFPOpcode()) {
7343       SDValue Val = DAG.getNode(ISD::STRICT_FSUB, dl, { SrcVT, MVT::Other },
7344                                 { Chain, Src, FltOfs });
7345       SInt = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, { DstVT, MVT::Other },
7346                          { Val.getValue(1), Val });
7347       Chain = SInt.getValue(1);
7348     } else {
7349       SDValue Val = DAG.getNode(ISD::FSUB, dl, SrcVT, Src, FltOfs);
7350       SInt = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, Val);
7351     }
7352     Result = DAG.getNode(ISD::XOR, dl, DstVT, SInt, IntOfs);
7353   } else {
7354     // Expand based on maximum range of FP_TO_SINT:
7355     // True = fp_to_sint(Src)
7356     // False = 0x8000000000000000 + fp_to_sint(Src - 0x8000000000000000)
7357     // Result = select (Src < 0x8000000000000000), True, False
7358 
7359     SDValue True = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, Src);
7360     // TODO: Should any fast-math-flags be set for the FSUB?
7361     SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT,
7362                                 DAG.getNode(ISD::FSUB, dl, SrcVT, Src, Cst));
7363     False = DAG.getNode(ISD::XOR, dl, DstVT, False,
7364                         DAG.getConstant(SignMask, dl, DstVT));
7365     Sel = DAG.getBoolExtOrTrunc(Sel, dl, DstSetCCVT, DstVT);
7366     Result = DAG.getSelect(dl, DstVT, Sel, True, False);
7367   }
7368   return true;
7369 }
7370 
7371 bool TargetLowering::expandUINT_TO_FP(SDNode *Node, SDValue &Result,
7372                                       SDValue &Chain,
7373                                       SelectionDAG &DAG) const {
7374   // This transform is not correct for converting 0 when rounding mode is set
7375   // to round toward negative infinity which will produce -0.0. So disable under
7376   // strictfp.
7377   if (Node->isStrictFPOpcode())
7378     return false;
7379 
7380   SDValue Src = Node->getOperand(0);
7381   EVT SrcVT = Src.getValueType();
7382   EVT DstVT = Node->getValueType(0);
7383 
7384   if (SrcVT.getScalarType() != MVT::i64 || DstVT.getScalarType() != MVT::f64)
7385     return false;
7386 
7387   // Only expand vector types if we have the appropriate vector bit operations.
7388   if (SrcVT.isVector() && (!isOperationLegalOrCustom(ISD::SRL, SrcVT) ||
7389                            !isOperationLegalOrCustom(ISD::FADD, DstVT) ||
7390                            !isOperationLegalOrCustom(ISD::FSUB, DstVT) ||
7391                            !isOperationLegalOrCustomOrPromote(ISD::OR, SrcVT) ||
7392                            !isOperationLegalOrCustomOrPromote(ISD::AND, SrcVT)))
7393     return false;
7394 
7395   SDLoc dl(SDValue(Node, 0));
7396   EVT ShiftVT = getShiftAmountTy(SrcVT, DAG.getDataLayout());
7397 
7398   // Implementation of unsigned i64 to f64 following the algorithm in
7399   // __floatundidf in compiler_rt.  This implementation performs rounding
7400   // correctly in all rounding modes with the exception of converting 0
7401   // when rounding toward negative infinity. In that case the fsub will produce
7402   // -0.0. This will be added to +0.0 and produce -0.0 which is incorrect.
7403   SDValue TwoP52 = DAG.getConstant(UINT64_C(0x4330000000000000), dl, SrcVT);
7404   SDValue TwoP84PlusTwoP52 = DAG.getConstantFP(
7405       BitsToDouble(UINT64_C(0x4530000000100000)), dl, DstVT);
7406   SDValue TwoP84 = DAG.getConstant(UINT64_C(0x4530000000000000), dl, SrcVT);
7407   SDValue LoMask = DAG.getConstant(UINT64_C(0x00000000FFFFFFFF), dl, SrcVT);
7408   SDValue HiShift = DAG.getConstant(32, dl, ShiftVT);
7409 
7410   SDValue Lo = DAG.getNode(ISD::AND, dl, SrcVT, Src, LoMask);
7411   SDValue Hi = DAG.getNode(ISD::SRL, dl, SrcVT, Src, HiShift);
7412   SDValue LoOr = DAG.getNode(ISD::OR, dl, SrcVT, Lo, TwoP52);
7413   SDValue HiOr = DAG.getNode(ISD::OR, dl, SrcVT, Hi, TwoP84);
7414   SDValue LoFlt = DAG.getBitcast(DstVT, LoOr);
7415   SDValue HiFlt = DAG.getBitcast(DstVT, HiOr);
7416   SDValue HiSub =
7417       DAG.getNode(ISD::FSUB, dl, DstVT, HiFlt, TwoP84PlusTwoP52);
7418   Result = DAG.getNode(ISD::FADD, dl, DstVT, LoFlt, HiSub);
7419   return true;
7420 }
7421 
7422 SDValue
7423 TargetLowering::createSelectForFMINNUM_FMAXNUM(SDNode *Node,
7424                                                SelectionDAG &DAG) const {
7425   unsigned Opcode = Node->getOpcode();
7426   assert((Opcode == ISD::FMINNUM || Opcode == ISD::FMAXNUM ||
7427           Opcode == ISD::STRICT_FMINNUM || Opcode == ISD::STRICT_FMAXNUM) &&
7428          "Wrong opcode");
7429 
7430   if (Node->getFlags().hasNoNaNs()) {
7431     ISD::CondCode Pred = Opcode == ISD::FMINNUM ? ISD::SETLT : ISD::SETGT;
7432     SDValue Op1 = Node->getOperand(0);
7433     SDValue Op2 = Node->getOperand(1);
7434     SDValue SelCC = DAG.getSelectCC(SDLoc(Node), Op1, Op2, Op1, Op2, Pred);
7435     // Copy FMF flags, but always set the no-signed-zeros flag
7436     // as this is implied by the FMINNUM/FMAXNUM semantics.
7437     SDNodeFlags Flags = Node->getFlags();
7438     Flags.setNoSignedZeros(true);
7439     SelCC->setFlags(Flags);
7440     return SelCC;
7441   }
7442 
7443   return SDValue();
7444 }
7445 
7446 SDValue TargetLowering::expandFMINNUM_FMAXNUM(SDNode *Node,
7447                                               SelectionDAG &DAG) const {
7448   SDLoc dl(Node);
7449   unsigned NewOp = Node->getOpcode() == ISD::FMINNUM ?
7450     ISD::FMINNUM_IEEE : ISD::FMAXNUM_IEEE;
7451   EVT VT = Node->getValueType(0);
7452 
7453   if (VT.isScalableVector())
7454     report_fatal_error(
7455         "Expanding fminnum/fmaxnum for scalable vectors is undefined.");
7456 
7457   if (isOperationLegalOrCustom(NewOp, VT)) {
7458     SDValue Quiet0 = Node->getOperand(0);
7459     SDValue Quiet1 = Node->getOperand(1);
7460 
7461     if (!Node->getFlags().hasNoNaNs()) {
7462       // Insert canonicalizes if it's possible we need to quiet to get correct
7463       // sNaN behavior.
7464       if (!DAG.isKnownNeverSNaN(Quiet0)) {
7465         Quiet0 = DAG.getNode(ISD::FCANONICALIZE, dl, VT, Quiet0,
7466                              Node->getFlags());
7467       }
7468       if (!DAG.isKnownNeverSNaN(Quiet1)) {
7469         Quiet1 = DAG.getNode(ISD::FCANONICALIZE, dl, VT, Quiet1,
7470                              Node->getFlags());
7471       }
7472     }
7473 
7474     return DAG.getNode(NewOp, dl, VT, Quiet0, Quiet1, Node->getFlags());
7475   }
7476 
7477   // If the target has FMINIMUM/FMAXIMUM but not FMINNUM/FMAXNUM use that
7478   // instead if there are no NaNs.
7479   if (Node->getFlags().hasNoNaNs()) {
7480     unsigned IEEE2018Op =
7481         Node->getOpcode() == ISD::FMINNUM ? ISD::FMINIMUM : ISD::FMAXIMUM;
7482     if (isOperationLegalOrCustom(IEEE2018Op, VT)) {
7483       return DAG.getNode(IEEE2018Op, dl, VT, Node->getOperand(0),
7484                          Node->getOperand(1), Node->getFlags());
7485     }
7486   }
7487 
7488   if (SDValue SelCC = createSelectForFMINNUM_FMAXNUM(Node, DAG))
7489     return SelCC;
7490 
7491   return SDValue();
7492 }
7493 
7494 SDValue TargetLowering::expandIS_FPCLASS(EVT ResultVT, SDValue Op,
7495                                          unsigned Test, SDNodeFlags Flags,
7496                                          const SDLoc &DL,
7497                                          SelectionDAG &DAG) const {
7498   EVT OperandVT = Op.getValueType();
7499   assert(OperandVT.isFloatingPoint());
7500 
7501   // Degenerated cases.
7502   if (Test == 0)
7503     return DAG.getBoolConstant(false, DL, ResultVT, OperandVT);
7504   if ((Test & fcAllFlags) == fcAllFlags)
7505     return DAG.getBoolConstant(true, DL, ResultVT, OperandVT);
7506 
7507   // PPC double double is a pair of doubles, of which the higher part determines
7508   // the value class.
7509   if (OperandVT == MVT::ppcf128) {
7510     Op = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::f64, Op,
7511                      DAG.getConstant(1, DL, MVT::i32));
7512     OperandVT = MVT::f64;
7513   }
7514 
7515   // Some checks may be represented as inversion of simpler check, for example
7516   // "inf|normal|subnormal|zero" => !"nan".
7517   bool IsInverted = false;
7518   if (unsigned InvertedCheck = getInvertedFPClassTest(Test)) {
7519     IsInverted = true;
7520     Test = InvertedCheck;
7521   }
7522 
7523   // Floating-point type properties.
7524   EVT ScalarFloatVT = OperandVT.getScalarType();
7525   const Type *FloatTy = ScalarFloatVT.getTypeForEVT(*DAG.getContext());
7526   const llvm::fltSemantics &Semantics = FloatTy->getFltSemantics();
7527   bool IsF80 = (ScalarFloatVT == MVT::f80);
7528 
7529   // Some checks can be implemented using float comparisons, if floating point
7530   // exceptions are ignored.
7531   if (Flags.hasNoFPExcept() &&
7532       isOperationLegalOrCustom(ISD::SETCC, OperandVT.getScalarType())) {
7533     if (Test == fcZero)
7534       return DAG.getSetCC(DL, ResultVT, Op,
7535                           DAG.getConstantFP(0.0, DL, OperandVT),
7536                           IsInverted ? ISD::SETUNE : ISD::SETOEQ);
7537     if (Test == fcNan)
7538       return DAG.getSetCC(DL, ResultVT, Op, Op,
7539                           IsInverted ? ISD::SETO : ISD::SETUO);
7540   }
7541 
7542   // In the general case use integer operations.
7543   unsigned BitSize = OperandVT.getScalarSizeInBits();
7544   EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), BitSize);
7545   if (OperandVT.isVector())
7546     IntVT = EVT::getVectorVT(*DAG.getContext(), IntVT,
7547                              OperandVT.getVectorElementCount());
7548   SDValue OpAsInt = DAG.getBitcast(IntVT, Op);
7549 
7550   // Various masks.
7551   APInt SignBit = APInt::getSignMask(BitSize);
7552   APInt ValueMask = APInt::getSignedMaxValue(BitSize);     // All bits but sign.
7553   APInt Inf = APFloat::getInf(Semantics).bitcastToAPInt(); // Exp and int bit.
7554   const unsigned ExplicitIntBitInF80 = 63;
7555   APInt ExpMask = Inf;
7556   if (IsF80)
7557     ExpMask.clearBit(ExplicitIntBitInF80);
7558   APInt AllOneMantissa = APFloat::getLargest(Semantics).bitcastToAPInt() & ~Inf;
7559   APInt QNaNBitMask =
7560       APInt::getOneBitSet(BitSize, AllOneMantissa.getActiveBits() - 1);
7561   APInt InvertionMask = APInt::getAllOnesValue(ResultVT.getScalarSizeInBits());
7562 
7563   SDValue ValueMaskV = DAG.getConstant(ValueMask, DL, IntVT);
7564   SDValue SignBitV = DAG.getConstant(SignBit, DL, IntVT);
7565   SDValue ExpMaskV = DAG.getConstant(ExpMask, DL, IntVT);
7566   SDValue ZeroV = DAG.getConstant(0, DL, IntVT);
7567   SDValue InfV = DAG.getConstant(Inf, DL, IntVT);
7568   SDValue ResultInvertionMask = DAG.getConstant(InvertionMask, DL, ResultVT);
7569 
7570   SDValue Res;
7571   const auto appendResult = [&](SDValue PartialRes) {
7572     if (PartialRes) {
7573       if (Res)
7574         Res = DAG.getNode(ISD::OR, DL, ResultVT, Res, PartialRes);
7575       else
7576         Res = PartialRes;
7577     }
7578   };
7579 
7580   SDValue IntBitIsSetV; // Explicit integer bit in f80 mantissa is set.
7581   const auto getIntBitIsSet = [&]() -> SDValue {
7582     if (!IntBitIsSetV) {
7583       APInt IntBitMask(BitSize, 0);
7584       IntBitMask.setBit(ExplicitIntBitInF80);
7585       SDValue IntBitMaskV = DAG.getConstant(IntBitMask, DL, IntVT);
7586       SDValue IntBitV = DAG.getNode(ISD::AND, DL, IntVT, OpAsInt, IntBitMaskV);
7587       IntBitIsSetV = DAG.getSetCC(DL, ResultVT, IntBitV, ZeroV, ISD::SETNE);
7588     }
7589     return IntBitIsSetV;
7590   };
7591 
7592   // Split the value into sign bit and absolute value.
7593   SDValue AbsV = DAG.getNode(ISD::AND, DL, IntVT, OpAsInt, ValueMaskV);
7594   SDValue SignV = DAG.getSetCC(DL, ResultVT, OpAsInt,
7595                                DAG.getConstant(0.0, DL, IntVT), ISD::SETLT);
7596 
7597   // Tests that involve more than one class should be processed first.
7598   SDValue PartialRes;
7599 
7600   if (IsF80)
7601     ; // Detect finite numbers of f80 by checking individual classes because
7602       // they have different settings of the explicit integer bit.
7603   else if ((Test & fcFinite) == fcFinite) {
7604     // finite(V) ==> abs(V) < exp_mask
7605     PartialRes = DAG.getSetCC(DL, ResultVT, AbsV, ExpMaskV, ISD::SETLT);
7606     Test &= ~fcFinite;
7607   } else if ((Test & fcFinite) == fcPosFinite) {
7608     // finite(V) && V > 0 ==> V < exp_mask
7609     PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, ExpMaskV, ISD::SETULT);
7610     Test &= ~fcPosFinite;
7611   } else if ((Test & fcFinite) == fcNegFinite) {
7612     // finite(V) && V < 0 ==> abs(V) < exp_mask && signbit == 1
7613     PartialRes = DAG.getSetCC(DL, ResultVT, AbsV, ExpMaskV, ISD::SETLT);
7614     PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, SignV);
7615     Test &= ~fcNegFinite;
7616   }
7617   appendResult(PartialRes);
7618 
7619   // Check for individual classes.
7620 
7621   if (unsigned PartialCheck = Test & fcZero) {
7622     if (PartialCheck == fcPosZero)
7623       PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, ZeroV, ISD::SETEQ);
7624     else if (PartialCheck == fcZero)
7625       PartialRes = DAG.getSetCC(DL, ResultVT, AbsV, ZeroV, ISD::SETEQ);
7626     else // ISD::fcNegZero
7627       PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, SignBitV, ISD::SETEQ);
7628     appendResult(PartialRes);
7629   }
7630 
7631   if (unsigned PartialCheck = Test & fcInf) {
7632     if (PartialCheck == fcPosInf)
7633       PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, InfV, ISD::SETEQ);
7634     else if (PartialCheck == fcInf)
7635       PartialRes = DAG.getSetCC(DL, ResultVT, AbsV, InfV, ISD::SETEQ);
7636     else { // ISD::fcNegInf
7637       APInt NegInf = APFloat::getInf(Semantics, true).bitcastToAPInt();
7638       SDValue NegInfV = DAG.getConstant(NegInf, DL, IntVT);
7639       PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, NegInfV, ISD::SETEQ);
7640     }
7641     appendResult(PartialRes);
7642   }
7643 
7644   if (unsigned PartialCheck = Test & fcNan) {
7645     APInt InfWithQnanBit = Inf | QNaNBitMask;
7646     SDValue InfWithQnanBitV = DAG.getConstant(InfWithQnanBit, DL, IntVT);
7647     if (PartialCheck == fcNan) {
7648       // isnan(V) ==> abs(V) > int(inf)
7649       PartialRes = DAG.getSetCC(DL, ResultVT, AbsV, InfV, ISD::SETGT);
7650       if (IsF80) {
7651         // Recognize unsupported values as NaNs for compatibility with glibc.
7652         // In them (exp(V)==0) == int_bit.
7653         SDValue ExpBits = DAG.getNode(ISD::AND, DL, IntVT, AbsV, ExpMaskV);
7654         SDValue ExpIsZero =
7655             DAG.getSetCC(DL, ResultVT, ExpBits, ZeroV, ISD::SETEQ);
7656         SDValue IsPseudo =
7657             DAG.getSetCC(DL, ResultVT, getIntBitIsSet(), ExpIsZero, ISD::SETEQ);
7658         PartialRes = DAG.getNode(ISD::OR, DL, ResultVT, PartialRes, IsPseudo);
7659       }
7660     } else if (PartialCheck == fcQNan) {
7661       // isquiet(V) ==> abs(V) >= (unsigned(Inf) | quiet_bit)
7662       PartialRes =
7663           DAG.getSetCC(DL, ResultVT, AbsV, InfWithQnanBitV, ISD::SETGE);
7664     } else { // ISD::fcSNan
7665       // issignaling(V) ==> abs(V) > unsigned(Inf) &&
7666       //                    abs(V) < (unsigned(Inf) | quiet_bit)
7667       SDValue IsNan = DAG.getSetCC(DL, ResultVT, AbsV, InfV, ISD::SETGT);
7668       SDValue IsNotQnan =
7669           DAG.getSetCC(DL, ResultVT, AbsV, InfWithQnanBitV, ISD::SETLT);
7670       PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, IsNan, IsNotQnan);
7671     }
7672     appendResult(PartialRes);
7673   }
7674 
7675   if (unsigned PartialCheck = Test & fcSubnormal) {
7676     // issubnormal(V) ==> unsigned(abs(V) - 1) < (all mantissa bits set)
7677     // issubnormal(V) && V>0 ==> unsigned(V - 1) < (all mantissa bits set)
7678     SDValue V = (PartialCheck == fcPosSubnormal) ? OpAsInt : AbsV;
7679     SDValue MantissaV = DAG.getConstant(AllOneMantissa, DL, IntVT);
7680     SDValue VMinusOneV =
7681         DAG.getNode(ISD::SUB, DL, IntVT, V, DAG.getConstant(1, DL, IntVT));
7682     PartialRes = DAG.getSetCC(DL, ResultVT, VMinusOneV, MantissaV, ISD::SETULT);
7683     if (PartialCheck == fcNegSubnormal)
7684       PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, SignV);
7685     appendResult(PartialRes);
7686   }
7687 
7688   if (unsigned PartialCheck = Test & fcNormal) {
7689     // isnormal(V) ==> (0 < exp < max_exp) ==> (unsigned(exp-1) < (max_exp-1))
7690     APInt ExpLSB = ExpMask & ~(ExpMask.shl(1));
7691     SDValue ExpLSBV = DAG.getConstant(ExpLSB, DL, IntVT);
7692     SDValue ExpMinus1 = DAG.getNode(ISD::SUB, DL, IntVT, AbsV, ExpLSBV);
7693     APInt ExpLimit = ExpMask - ExpLSB;
7694     SDValue ExpLimitV = DAG.getConstant(ExpLimit, DL, IntVT);
7695     PartialRes = DAG.getSetCC(DL, ResultVT, ExpMinus1, ExpLimitV, ISD::SETULT);
7696     if (PartialCheck == fcNegNormal)
7697       PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, SignV);
7698     else if (PartialCheck == fcPosNormal) {
7699       SDValue PosSignV =
7700           DAG.getNode(ISD::XOR, DL, ResultVT, SignV, ResultInvertionMask);
7701       PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, PosSignV);
7702     }
7703     if (IsF80)
7704       PartialRes =
7705           DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, getIntBitIsSet());
7706     appendResult(PartialRes);
7707   }
7708 
7709   if (!Res)
7710     return DAG.getConstant(IsInverted, DL, ResultVT);
7711   if (IsInverted)
7712     Res = DAG.getNode(ISD::XOR, DL, ResultVT, Res, ResultInvertionMask);
7713   return Res;
7714 }
7715 
7716 // Only expand vector types if we have the appropriate vector bit operations.
7717 static bool canExpandVectorCTPOP(const TargetLowering &TLI, EVT VT) {
7718   assert(VT.isVector() && "Expected vector type");
7719   unsigned Len = VT.getScalarSizeInBits();
7720   return TLI.isOperationLegalOrCustom(ISD::ADD, VT) &&
7721          TLI.isOperationLegalOrCustom(ISD::SUB, VT) &&
7722          TLI.isOperationLegalOrCustom(ISD::SRL, VT) &&
7723          (Len == 8 || TLI.isOperationLegalOrCustom(ISD::MUL, VT)) &&
7724          TLI.isOperationLegalOrCustomOrPromote(ISD::AND, VT);
7725 }
7726 
7727 SDValue TargetLowering::expandCTPOP(SDNode *Node, SelectionDAG &DAG) const {
7728   SDLoc dl(Node);
7729   EVT VT = Node->getValueType(0);
7730   EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
7731   SDValue Op = Node->getOperand(0);
7732   unsigned Len = VT.getScalarSizeInBits();
7733   assert(VT.isInteger() && "CTPOP not implemented for this type.");
7734 
7735   // TODO: Add support for irregular type lengths.
7736   if (!(Len <= 128 && Len % 8 == 0))
7737     return SDValue();
7738 
7739   // Only expand vector types if we have the appropriate vector bit operations.
7740   if (VT.isVector() && !canExpandVectorCTPOP(*this, VT))
7741     return SDValue();
7742 
7743   // This is the "best" algorithm from
7744   // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
7745   SDValue Mask55 =
7746       DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x55)), dl, VT);
7747   SDValue Mask33 =
7748       DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x33)), dl, VT);
7749   SDValue Mask0F =
7750       DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x0F)), dl, VT);
7751 
7752   // v = v - ((v >> 1) & 0x55555555...)
7753   Op = DAG.getNode(ISD::SUB, dl, VT, Op,
7754                    DAG.getNode(ISD::AND, dl, VT,
7755                                DAG.getNode(ISD::SRL, dl, VT, Op,
7756                                            DAG.getConstant(1, dl, ShVT)),
7757                                Mask55));
7758   // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
7759   Op = DAG.getNode(ISD::ADD, dl, VT, DAG.getNode(ISD::AND, dl, VT, Op, Mask33),
7760                    DAG.getNode(ISD::AND, dl, VT,
7761                                DAG.getNode(ISD::SRL, dl, VT, Op,
7762                                            DAG.getConstant(2, dl, ShVT)),
7763                                Mask33));
7764   // v = (v + (v >> 4)) & 0x0F0F0F0F...
7765   Op = DAG.getNode(ISD::AND, dl, VT,
7766                    DAG.getNode(ISD::ADD, dl, VT, Op,
7767                                DAG.getNode(ISD::SRL, dl, VT, Op,
7768                                            DAG.getConstant(4, dl, ShVT))),
7769                    Mask0F);
7770 
7771   if (Len <= 8)
7772     return Op;
7773 
7774   // Avoid the multiply if we only have 2 bytes to add.
7775   // TODO: Only doing this for scalars because vectors weren't as obviously
7776   // improved.
7777   if (Len == 16 && !VT.isVector()) {
7778     // v = (v + (v >> 8)) & 0x00FF;
7779     return DAG.getNode(ISD::AND, dl, VT,
7780                      DAG.getNode(ISD::ADD, dl, VT, Op,
7781                                  DAG.getNode(ISD::SRL, dl, VT, Op,
7782                                              DAG.getConstant(8, dl, ShVT))),
7783                      DAG.getConstant(0xFF, dl, VT));
7784   }
7785 
7786   // v = (v * 0x01010101...) >> (Len - 8)
7787   SDValue Mask01 =
7788       DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x01)), dl, VT);
7789   return DAG.getNode(ISD::SRL, dl, VT,
7790                      DAG.getNode(ISD::MUL, dl, VT, Op, Mask01),
7791                      DAG.getConstant(Len - 8, dl, ShVT));
7792 }
7793 
7794 SDValue TargetLowering::expandCTLZ(SDNode *Node, SelectionDAG &DAG) const {
7795   SDLoc dl(Node);
7796   EVT VT = Node->getValueType(0);
7797   EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
7798   SDValue Op = Node->getOperand(0);
7799   unsigned NumBitsPerElt = VT.getScalarSizeInBits();
7800 
7801   // If the non-ZERO_UNDEF version is supported we can use that instead.
7802   if (Node->getOpcode() == ISD::CTLZ_ZERO_UNDEF &&
7803       isOperationLegalOrCustom(ISD::CTLZ, VT))
7804     return DAG.getNode(ISD::CTLZ, dl, VT, Op);
7805 
7806   // If the ZERO_UNDEF version is supported use that and handle the zero case.
7807   if (isOperationLegalOrCustom(ISD::CTLZ_ZERO_UNDEF, VT)) {
7808     EVT SetCCVT =
7809         getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
7810     SDValue CTLZ = DAG.getNode(ISD::CTLZ_ZERO_UNDEF, dl, VT, Op);
7811     SDValue Zero = DAG.getConstant(0, dl, VT);
7812     SDValue SrcIsZero = DAG.getSetCC(dl, SetCCVT, Op, Zero, ISD::SETEQ);
7813     return DAG.getSelect(dl, VT, SrcIsZero,
7814                          DAG.getConstant(NumBitsPerElt, dl, VT), CTLZ);
7815   }
7816 
7817   // Only expand vector types if we have the appropriate vector bit operations.
7818   // This includes the operations needed to expand CTPOP if it isn't supported.
7819   if (VT.isVector() && (!isPowerOf2_32(NumBitsPerElt) ||
7820                         (!isOperationLegalOrCustom(ISD::CTPOP, VT) &&
7821                          !canExpandVectorCTPOP(*this, VT)) ||
7822                         !isOperationLegalOrCustom(ISD::SRL, VT) ||
7823                         !isOperationLegalOrCustomOrPromote(ISD::OR, VT)))
7824     return SDValue();
7825 
7826   // for now, we do this:
7827   // x = x | (x >> 1);
7828   // x = x | (x >> 2);
7829   // ...
7830   // x = x | (x >>16);
7831   // x = x | (x >>32); // for 64-bit input
7832   // return popcount(~x);
7833   //
7834   // Ref: "Hacker's Delight" by Henry Warren
7835   for (unsigned i = 0; (1U << i) <= (NumBitsPerElt / 2); ++i) {
7836     SDValue Tmp = DAG.getConstant(1ULL << i, dl, ShVT);
7837     Op = DAG.getNode(ISD::OR, dl, VT, Op,
7838                      DAG.getNode(ISD::SRL, dl, VT, Op, Tmp));
7839   }
7840   Op = DAG.getNOT(dl, Op, VT);
7841   return DAG.getNode(ISD::CTPOP, dl, VT, Op);
7842 }
7843 
7844 SDValue TargetLowering::expandCTTZ(SDNode *Node, SelectionDAG &DAG) const {
7845   SDLoc dl(Node);
7846   EVT VT = Node->getValueType(0);
7847   SDValue Op = Node->getOperand(0);
7848   unsigned NumBitsPerElt = VT.getScalarSizeInBits();
7849 
7850   // If the non-ZERO_UNDEF version is supported we can use that instead.
7851   if (Node->getOpcode() == ISD::CTTZ_ZERO_UNDEF &&
7852       isOperationLegalOrCustom(ISD::CTTZ, VT))
7853     return DAG.getNode(ISD::CTTZ, dl, VT, Op);
7854 
7855   // If the ZERO_UNDEF version is supported use that and handle the zero case.
7856   if (isOperationLegalOrCustom(ISD::CTTZ_ZERO_UNDEF, VT)) {
7857     EVT SetCCVT =
7858         getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
7859     SDValue CTTZ = DAG.getNode(ISD::CTTZ_ZERO_UNDEF, dl, VT, Op);
7860     SDValue Zero = DAG.getConstant(0, dl, VT);
7861     SDValue SrcIsZero = DAG.getSetCC(dl, SetCCVT, Op, Zero, ISD::SETEQ);
7862     return DAG.getSelect(dl, VT, SrcIsZero,
7863                          DAG.getConstant(NumBitsPerElt, dl, VT), CTTZ);
7864   }
7865 
7866   // Only expand vector types if we have the appropriate vector bit operations.
7867   // This includes the operations needed to expand CTPOP if it isn't supported.
7868   if (VT.isVector() && (!isPowerOf2_32(NumBitsPerElt) ||
7869                         (!isOperationLegalOrCustom(ISD::CTPOP, VT) &&
7870                          !isOperationLegalOrCustom(ISD::CTLZ, VT) &&
7871                          !canExpandVectorCTPOP(*this, VT)) ||
7872                         !isOperationLegalOrCustom(ISD::SUB, VT) ||
7873                         !isOperationLegalOrCustomOrPromote(ISD::AND, VT) ||
7874                         !isOperationLegalOrCustomOrPromote(ISD::XOR, VT)))
7875     return SDValue();
7876 
7877   // for now, we use: { return popcount(~x & (x - 1)); }
7878   // unless the target has ctlz but not ctpop, in which case we use:
7879   // { return 32 - nlz(~x & (x-1)); }
7880   // Ref: "Hacker's Delight" by Henry Warren
7881   SDValue Tmp = DAG.getNode(
7882       ISD::AND, dl, VT, DAG.getNOT(dl, Op, VT),
7883       DAG.getNode(ISD::SUB, dl, VT, Op, DAG.getConstant(1, dl, VT)));
7884 
7885   // If ISD::CTLZ is legal and CTPOP isn't, then do that instead.
7886   if (isOperationLegal(ISD::CTLZ, VT) && !isOperationLegal(ISD::CTPOP, VT)) {
7887     return DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(NumBitsPerElt, dl, VT),
7888                        DAG.getNode(ISD::CTLZ, dl, VT, Tmp));
7889   }
7890 
7891   return DAG.getNode(ISD::CTPOP, dl, VT, Tmp);
7892 }
7893 
7894 SDValue TargetLowering::expandABS(SDNode *N, SelectionDAG &DAG,
7895                                   bool IsNegative) const {
7896   SDLoc dl(N);
7897   EVT VT = N->getValueType(0);
7898   EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
7899   SDValue Op = N->getOperand(0);
7900 
7901   // abs(x) -> smax(x,sub(0,x))
7902   if (!IsNegative && isOperationLegal(ISD::SUB, VT) &&
7903       isOperationLegal(ISD::SMAX, VT)) {
7904     SDValue Zero = DAG.getConstant(0, dl, VT);
7905     return DAG.getNode(ISD::SMAX, dl, VT, Op,
7906                        DAG.getNode(ISD::SUB, dl, VT, Zero, Op));
7907   }
7908 
7909   // abs(x) -> umin(x,sub(0,x))
7910   if (!IsNegative && isOperationLegal(ISD::SUB, VT) &&
7911       isOperationLegal(ISD::UMIN, VT)) {
7912     SDValue Zero = DAG.getConstant(0, dl, VT);
7913     Op = DAG.getFreeze(Op);
7914     return DAG.getNode(ISD::UMIN, dl, VT, Op,
7915                        DAG.getNode(ISD::SUB, dl, VT, Zero, Op));
7916   }
7917 
7918   // 0 - abs(x) -> smin(x, sub(0,x))
7919   if (IsNegative && isOperationLegal(ISD::SUB, VT) &&
7920       isOperationLegal(ISD::SMIN, VT)) {
7921     Op = DAG.getFreeze(Op);
7922     SDValue Zero = DAG.getConstant(0, dl, VT);
7923     return DAG.getNode(ISD::SMIN, dl, VT, Op,
7924                        DAG.getNode(ISD::SUB, dl, VT, Zero, Op));
7925   }
7926 
7927   // Only expand vector types if we have the appropriate vector operations.
7928   if (VT.isVector() &&
7929       (!isOperationLegalOrCustom(ISD::SRA, VT) ||
7930        (!IsNegative && !isOperationLegalOrCustom(ISD::ADD, VT)) ||
7931        (IsNegative && !isOperationLegalOrCustom(ISD::SUB, VT)) ||
7932        !isOperationLegalOrCustomOrPromote(ISD::XOR, VT)))
7933     return SDValue();
7934 
7935   Op = DAG.getFreeze(Op);
7936   SDValue Shift =
7937       DAG.getNode(ISD::SRA, dl, VT, Op,
7938                   DAG.getConstant(VT.getScalarSizeInBits() - 1, dl, ShVT));
7939   SDValue Xor = DAG.getNode(ISD::XOR, dl, VT, Op, Shift);
7940 
7941   // abs(x) -> Y = sra (X, size(X)-1); sub (xor (X, Y), Y)
7942   if (!IsNegative)
7943     return DAG.getNode(ISD::SUB, dl, VT, Xor, Shift);
7944 
7945   // 0 - abs(x) -> Y = sra (X, size(X)-1); sub (Y, xor (X, Y))
7946   return DAG.getNode(ISD::SUB, dl, VT, Shift, Xor);
7947 }
7948 
7949 SDValue TargetLowering::expandBSWAP(SDNode *N, SelectionDAG &DAG) const {
7950   SDLoc dl(N);
7951   EVT VT = N->getValueType(0);
7952   SDValue Op = N->getOperand(0);
7953 
7954   if (!VT.isSimple())
7955     return SDValue();
7956 
7957   EVT SHVT = getShiftAmountTy(VT, DAG.getDataLayout());
7958   SDValue Tmp1, Tmp2, Tmp3, Tmp4, Tmp5, Tmp6, Tmp7, Tmp8;
7959   switch (VT.getSimpleVT().getScalarType().SimpleTy) {
7960   default:
7961     return SDValue();
7962   case MVT::i16:
7963     // Use a rotate by 8. This can be further expanded if necessary.
7964     return DAG.getNode(ISD::ROTL, dl, VT, Op, DAG.getConstant(8, dl, SHVT));
7965   case MVT::i32:
7966     Tmp4 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(24, dl, SHVT));
7967     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(8, dl, SHVT));
7968     Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, dl, SHVT));
7969     Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(24, dl, SHVT));
7970     Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp3,
7971                        DAG.getConstant(0xFF0000, dl, VT));
7972     Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(0xFF00, dl, VT));
7973     Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp3);
7974     Tmp2 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp1);
7975     return DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp2);
7976   case MVT::i64:
7977     Tmp8 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(56, dl, SHVT));
7978     Tmp7 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(40, dl, SHVT));
7979     Tmp6 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(24, dl, SHVT));
7980     Tmp5 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(8, dl, SHVT));
7981     Tmp4 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, dl, SHVT));
7982     Tmp3 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(24, dl, SHVT));
7983     Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(40, dl, SHVT));
7984     Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(56, dl, SHVT));
7985     Tmp7 = DAG.getNode(ISD::AND, dl, VT, Tmp7,
7986                        DAG.getConstant(255ULL<<48, dl, VT));
7987     Tmp6 = DAG.getNode(ISD::AND, dl, VT, Tmp6,
7988                        DAG.getConstant(255ULL<<40, dl, VT));
7989     Tmp5 = DAG.getNode(ISD::AND, dl, VT, Tmp5,
7990                        DAG.getConstant(255ULL<<32, dl, VT));
7991     Tmp4 = DAG.getNode(ISD::AND, dl, VT, Tmp4,
7992                        DAG.getConstant(255ULL<<24, dl, VT));
7993     Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp3,
7994                        DAG.getConstant(255ULL<<16, dl, VT));
7995     Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2,
7996                        DAG.getConstant(255ULL<<8 , dl, VT));
7997     Tmp8 = DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp7);
7998     Tmp6 = DAG.getNode(ISD::OR, dl, VT, Tmp6, Tmp5);
7999     Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp3);
8000     Tmp2 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp1);
8001     Tmp8 = DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp6);
8002     Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp2);
8003     return DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp4);
8004   }
8005 }
8006 
8007 SDValue TargetLowering::expandBITREVERSE(SDNode *N, SelectionDAG &DAG) const {
8008   SDLoc dl(N);
8009   EVT VT = N->getValueType(0);
8010   SDValue Op = N->getOperand(0);
8011   EVT SHVT = getShiftAmountTy(VT, DAG.getDataLayout());
8012   unsigned Sz = VT.getScalarSizeInBits();
8013 
8014   SDValue Tmp, Tmp2, Tmp3;
8015 
8016   // If we can, perform BSWAP first and then the mask+swap the i4, then i2
8017   // and finally the i1 pairs.
8018   // TODO: We can easily support i4/i2 legal types if any target ever does.
8019   if (Sz >= 8 && isPowerOf2_32(Sz)) {
8020     // Create the masks - repeating the pattern every byte.
8021     APInt Mask4 = APInt::getSplat(Sz, APInt(8, 0x0F));
8022     APInt Mask2 = APInt::getSplat(Sz, APInt(8, 0x33));
8023     APInt Mask1 = APInt::getSplat(Sz, APInt(8, 0x55));
8024 
8025     // BSWAP if the type is wider than a single byte.
8026     Tmp = (Sz > 8 ? DAG.getNode(ISD::BSWAP, dl, VT, Op) : Op);
8027 
8028     // swap i4: ((V >> 4) & 0x0F) | ((V & 0x0F) << 4)
8029     Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Tmp, DAG.getConstant(4, dl, SHVT));
8030     Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Mask4, dl, VT));
8031     Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(Mask4, dl, VT));
8032     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(4, dl, SHVT));
8033     Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
8034 
8035     // swap i2: ((V >> 2) & 0x33) | ((V & 0x33) << 2)
8036     Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Tmp, DAG.getConstant(2, dl, SHVT));
8037     Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Mask2, dl, VT));
8038     Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(Mask2, dl, VT));
8039     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(2, dl, SHVT));
8040     Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
8041 
8042     // swap i1: ((V >> 1) & 0x55) | ((V & 0x55) << 1)
8043     Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Tmp, DAG.getConstant(1, dl, SHVT));
8044     Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Mask1, dl, VT));
8045     Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(Mask1, dl, VT));
8046     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(1, dl, SHVT));
8047     Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
8048     return Tmp;
8049   }
8050 
8051   Tmp = DAG.getConstant(0, dl, VT);
8052   for (unsigned I = 0, J = Sz-1; I < Sz; ++I, --J) {
8053     if (I < J)
8054       Tmp2 =
8055           DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(J - I, dl, SHVT));
8056     else
8057       Tmp2 =
8058           DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(I - J, dl, SHVT));
8059 
8060     APInt Shift(Sz, 1);
8061     Shift <<= J;
8062     Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Shift, dl, VT));
8063     Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp, Tmp2);
8064   }
8065 
8066   return Tmp;
8067 }
8068 
8069 std::pair<SDValue, SDValue>
8070 TargetLowering::scalarizeVectorLoad(LoadSDNode *LD,
8071                                     SelectionDAG &DAG) const {
8072   SDLoc SL(LD);
8073   SDValue Chain = LD->getChain();
8074   SDValue BasePTR = LD->getBasePtr();
8075   EVT SrcVT = LD->getMemoryVT();
8076   EVT DstVT = LD->getValueType(0);
8077   ISD::LoadExtType ExtType = LD->getExtensionType();
8078 
8079   if (SrcVT.isScalableVector())
8080     report_fatal_error("Cannot scalarize scalable vector loads");
8081 
8082   unsigned NumElem = SrcVT.getVectorNumElements();
8083 
8084   EVT SrcEltVT = SrcVT.getScalarType();
8085   EVT DstEltVT = DstVT.getScalarType();
8086 
8087   // A vector must always be stored in memory as-is, i.e. without any padding
8088   // between the elements, since various code depend on it, e.g. in the
8089   // handling of a bitcast of a vector type to int, which may be done with a
8090   // vector store followed by an integer load. A vector that does not have
8091   // elements that are byte-sized must therefore be stored as an integer
8092   // built out of the extracted vector elements.
8093   if (!SrcEltVT.isByteSized()) {
8094     unsigned NumLoadBits = SrcVT.getStoreSizeInBits();
8095     EVT LoadVT = EVT::getIntegerVT(*DAG.getContext(), NumLoadBits);
8096 
8097     unsigned NumSrcBits = SrcVT.getSizeInBits();
8098     EVT SrcIntVT = EVT::getIntegerVT(*DAG.getContext(), NumSrcBits);
8099 
8100     unsigned SrcEltBits = SrcEltVT.getSizeInBits();
8101     SDValue SrcEltBitMask = DAG.getConstant(
8102         APInt::getLowBitsSet(NumLoadBits, SrcEltBits), SL, LoadVT);
8103 
8104     // Load the whole vector and avoid masking off the top bits as it makes
8105     // the codegen worse.
8106     SDValue Load =
8107         DAG.getExtLoad(ISD::EXTLOAD, SL, LoadVT, Chain, BasePTR,
8108                        LD->getPointerInfo(), SrcIntVT, LD->getOriginalAlign(),
8109                        LD->getMemOperand()->getFlags(), LD->getAAInfo());
8110 
8111     SmallVector<SDValue, 8> Vals;
8112     for (unsigned Idx = 0; Idx < NumElem; ++Idx) {
8113       unsigned ShiftIntoIdx =
8114           (DAG.getDataLayout().isBigEndian() ? (NumElem - 1) - Idx : Idx);
8115       SDValue ShiftAmount =
8116           DAG.getShiftAmountConstant(ShiftIntoIdx * SrcEltVT.getSizeInBits(),
8117                                      LoadVT, SL, /*LegalTypes=*/false);
8118       SDValue ShiftedElt = DAG.getNode(ISD::SRL, SL, LoadVT, Load, ShiftAmount);
8119       SDValue Elt =
8120           DAG.getNode(ISD::AND, SL, LoadVT, ShiftedElt, SrcEltBitMask);
8121       SDValue Scalar = DAG.getNode(ISD::TRUNCATE, SL, SrcEltVT, Elt);
8122 
8123       if (ExtType != ISD::NON_EXTLOAD) {
8124         unsigned ExtendOp = ISD::getExtForLoadExtType(false, ExtType);
8125         Scalar = DAG.getNode(ExtendOp, SL, DstEltVT, Scalar);
8126       }
8127 
8128       Vals.push_back(Scalar);
8129     }
8130 
8131     SDValue Value = DAG.getBuildVector(DstVT, SL, Vals);
8132     return std::make_pair(Value, Load.getValue(1));
8133   }
8134 
8135   unsigned Stride = SrcEltVT.getSizeInBits() / 8;
8136   assert(SrcEltVT.isByteSized());
8137 
8138   SmallVector<SDValue, 8> Vals;
8139   SmallVector<SDValue, 8> LoadChains;
8140 
8141   for (unsigned Idx = 0; Idx < NumElem; ++Idx) {
8142     SDValue ScalarLoad =
8143         DAG.getExtLoad(ExtType, SL, DstEltVT, Chain, BasePTR,
8144                        LD->getPointerInfo().getWithOffset(Idx * Stride),
8145                        SrcEltVT, LD->getOriginalAlign(),
8146                        LD->getMemOperand()->getFlags(), LD->getAAInfo());
8147 
8148     BasePTR = DAG.getObjectPtrOffset(SL, BasePTR, TypeSize::Fixed(Stride));
8149 
8150     Vals.push_back(ScalarLoad.getValue(0));
8151     LoadChains.push_back(ScalarLoad.getValue(1));
8152   }
8153 
8154   SDValue NewChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, LoadChains);
8155   SDValue Value = DAG.getBuildVector(DstVT, SL, Vals);
8156 
8157   return std::make_pair(Value, NewChain);
8158 }
8159 
8160 SDValue TargetLowering::scalarizeVectorStore(StoreSDNode *ST,
8161                                              SelectionDAG &DAG) const {
8162   SDLoc SL(ST);
8163 
8164   SDValue Chain = ST->getChain();
8165   SDValue BasePtr = ST->getBasePtr();
8166   SDValue Value = ST->getValue();
8167   EVT StVT = ST->getMemoryVT();
8168 
8169   if (StVT.isScalableVector())
8170     report_fatal_error("Cannot scalarize scalable vector stores");
8171 
8172   // The type of the data we want to save
8173   EVT RegVT = Value.getValueType();
8174   EVT RegSclVT = RegVT.getScalarType();
8175 
8176   // The type of data as saved in memory.
8177   EVT MemSclVT = StVT.getScalarType();
8178 
8179   unsigned NumElem = StVT.getVectorNumElements();
8180 
8181   // A vector must always be stored in memory as-is, i.e. without any padding
8182   // between the elements, since various code depend on it, e.g. in the
8183   // handling of a bitcast of a vector type to int, which may be done with a
8184   // vector store followed by an integer load. A vector that does not have
8185   // elements that are byte-sized must therefore be stored as an integer
8186   // built out of the extracted vector elements.
8187   if (!MemSclVT.isByteSized()) {
8188     unsigned NumBits = StVT.getSizeInBits();
8189     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), NumBits);
8190 
8191     SDValue CurrVal = DAG.getConstant(0, SL, IntVT);
8192 
8193     for (unsigned Idx = 0; Idx < NumElem; ++Idx) {
8194       SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, RegSclVT, Value,
8195                                 DAG.getVectorIdxConstant(Idx, SL));
8196       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, MemSclVT, Elt);
8197       SDValue ExtElt = DAG.getNode(ISD::ZERO_EXTEND, SL, IntVT, Trunc);
8198       unsigned ShiftIntoIdx =
8199           (DAG.getDataLayout().isBigEndian() ? (NumElem - 1) - Idx : Idx);
8200       SDValue ShiftAmount =
8201           DAG.getConstant(ShiftIntoIdx * MemSclVT.getSizeInBits(), SL, IntVT);
8202       SDValue ShiftedElt =
8203           DAG.getNode(ISD::SHL, SL, IntVT, ExtElt, ShiftAmount);
8204       CurrVal = DAG.getNode(ISD::OR, SL, IntVT, CurrVal, ShiftedElt);
8205     }
8206 
8207     return DAG.getStore(Chain, SL, CurrVal, BasePtr, ST->getPointerInfo(),
8208                         ST->getOriginalAlign(), ST->getMemOperand()->getFlags(),
8209                         ST->getAAInfo());
8210   }
8211 
8212   // Store Stride in bytes
8213   unsigned Stride = MemSclVT.getSizeInBits() / 8;
8214   assert(Stride && "Zero stride!");
8215   // Extract each of the elements from the original vector and save them into
8216   // memory individually.
8217   SmallVector<SDValue, 8> Stores;
8218   for (unsigned Idx = 0; Idx < NumElem; ++Idx) {
8219     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, RegSclVT, Value,
8220                               DAG.getVectorIdxConstant(Idx, SL));
8221 
8222     SDValue Ptr =
8223         DAG.getObjectPtrOffset(SL, BasePtr, TypeSize::Fixed(Idx * Stride));
8224 
8225     // This scalar TruncStore may be illegal, but we legalize it later.
8226     SDValue Store = DAG.getTruncStore(
8227         Chain, SL, Elt, Ptr, ST->getPointerInfo().getWithOffset(Idx * Stride),
8228         MemSclVT, ST->getOriginalAlign(), ST->getMemOperand()->getFlags(),
8229         ST->getAAInfo());
8230 
8231     Stores.push_back(Store);
8232   }
8233 
8234   return DAG.getNode(ISD::TokenFactor, SL, MVT::Other, Stores);
8235 }
8236 
8237 std::pair<SDValue, SDValue>
8238 TargetLowering::expandUnalignedLoad(LoadSDNode *LD, SelectionDAG &DAG) const {
8239   assert(LD->getAddressingMode() == ISD::UNINDEXED &&
8240          "unaligned indexed loads not implemented!");
8241   SDValue Chain = LD->getChain();
8242   SDValue Ptr = LD->getBasePtr();
8243   EVT VT = LD->getValueType(0);
8244   EVT LoadedVT = LD->getMemoryVT();
8245   SDLoc dl(LD);
8246   auto &MF = DAG.getMachineFunction();
8247 
8248   if (VT.isFloatingPoint() || VT.isVector()) {
8249     EVT intVT = EVT::getIntegerVT(*DAG.getContext(), LoadedVT.getSizeInBits());
8250     if (isTypeLegal(intVT) && isTypeLegal(LoadedVT)) {
8251       if (!isOperationLegalOrCustom(ISD::LOAD, intVT) &&
8252           LoadedVT.isVector()) {
8253         // Scalarize the load and let the individual components be handled.
8254         return scalarizeVectorLoad(LD, DAG);
8255       }
8256 
8257       // Expand to a (misaligned) integer load of the same size,
8258       // then bitconvert to floating point or vector.
8259       SDValue newLoad = DAG.getLoad(intVT, dl, Chain, Ptr,
8260                                     LD->getMemOperand());
8261       SDValue Result = DAG.getNode(ISD::BITCAST, dl, LoadedVT, newLoad);
8262       if (LoadedVT != VT)
8263         Result = DAG.getNode(VT.isFloatingPoint() ? ISD::FP_EXTEND :
8264                              ISD::ANY_EXTEND, dl, VT, Result);
8265 
8266       return std::make_pair(Result, newLoad.getValue(1));
8267     }
8268 
8269     // Copy the value to a (aligned) stack slot using (unaligned) integer
8270     // loads and stores, then do a (aligned) load from the stack slot.
8271     MVT RegVT = getRegisterType(*DAG.getContext(), intVT);
8272     unsigned LoadedBytes = LoadedVT.getStoreSize();
8273     unsigned RegBytes = RegVT.getSizeInBits() / 8;
8274     unsigned NumRegs = (LoadedBytes + RegBytes - 1) / RegBytes;
8275 
8276     // Make sure the stack slot is also aligned for the register type.
8277     SDValue StackBase = DAG.CreateStackTemporary(LoadedVT, RegVT);
8278     auto FrameIndex = cast<FrameIndexSDNode>(StackBase.getNode())->getIndex();
8279     SmallVector<SDValue, 8> Stores;
8280     SDValue StackPtr = StackBase;
8281     unsigned Offset = 0;
8282 
8283     EVT PtrVT = Ptr.getValueType();
8284     EVT StackPtrVT = StackPtr.getValueType();
8285 
8286     SDValue PtrIncrement = DAG.getConstant(RegBytes, dl, PtrVT);
8287     SDValue StackPtrIncrement = DAG.getConstant(RegBytes, dl, StackPtrVT);
8288 
8289     // Do all but one copies using the full register width.
8290     for (unsigned i = 1; i < NumRegs; i++) {
8291       // Load one integer register's worth from the original location.
8292       SDValue Load = DAG.getLoad(
8293           RegVT, dl, Chain, Ptr, LD->getPointerInfo().getWithOffset(Offset),
8294           LD->getOriginalAlign(), LD->getMemOperand()->getFlags(),
8295           LD->getAAInfo());
8296       // Follow the load with a store to the stack slot.  Remember the store.
8297       Stores.push_back(DAG.getStore(
8298           Load.getValue(1), dl, Load, StackPtr,
8299           MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset)));
8300       // Increment the pointers.
8301       Offset += RegBytes;
8302 
8303       Ptr = DAG.getObjectPtrOffset(dl, Ptr, PtrIncrement);
8304       StackPtr = DAG.getObjectPtrOffset(dl, StackPtr, StackPtrIncrement);
8305     }
8306 
8307     // The last copy may be partial.  Do an extending load.
8308     EVT MemVT = EVT::getIntegerVT(*DAG.getContext(),
8309                                   8 * (LoadedBytes - Offset));
8310     SDValue Load =
8311         DAG.getExtLoad(ISD::EXTLOAD, dl, RegVT, Chain, Ptr,
8312                        LD->getPointerInfo().getWithOffset(Offset), MemVT,
8313                        LD->getOriginalAlign(), LD->getMemOperand()->getFlags(),
8314                        LD->getAAInfo());
8315     // Follow the load with a store to the stack slot.  Remember the store.
8316     // On big-endian machines this requires a truncating store to ensure
8317     // that the bits end up in the right place.
8318     Stores.push_back(DAG.getTruncStore(
8319         Load.getValue(1), dl, Load, StackPtr,
8320         MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset), MemVT));
8321 
8322     // The order of the stores doesn't matter - say it with a TokenFactor.
8323     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
8324 
8325     // Finally, perform the original load only redirected to the stack slot.
8326     Load = DAG.getExtLoad(LD->getExtensionType(), dl, VT, TF, StackBase,
8327                           MachinePointerInfo::getFixedStack(MF, FrameIndex, 0),
8328                           LoadedVT);
8329 
8330     // Callers expect a MERGE_VALUES node.
8331     return std::make_pair(Load, TF);
8332   }
8333 
8334   assert(LoadedVT.isInteger() && !LoadedVT.isVector() &&
8335          "Unaligned load of unsupported type.");
8336 
8337   // Compute the new VT that is half the size of the old one.  This is an
8338   // integer MVT.
8339   unsigned NumBits = LoadedVT.getSizeInBits();
8340   EVT NewLoadedVT;
8341   NewLoadedVT = EVT::getIntegerVT(*DAG.getContext(), NumBits/2);
8342   NumBits >>= 1;
8343 
8344   Align Alignment = LD->getOriginalAlign();
8345   unsigned IncrementSize = NumBits / 8;
8346   ISD::LoadExtType HiExtType = LD->getExtensionType();
8347 
8348   // If the original load is NON_EXTLOAD, the hi part load must be ZEXTLOAD.
8349   if (HiExtType == ISD::NON_EXTLOAD)
8350     HiExtType = ISD::ZEXTLOAD;
8351 
8352   // Load the value in two parts
8353   SDValue Lo, Hi;
8354   if (DAG.getDataLayout().isLittleEndian()) {
8355     Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr, LD->getPointerInfo(),
8356                         NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(),
8357                         LD->getAAInfo());
8358 
8359     Ptr = DAG.getObjectPtrOffset(dl, Ptr, TypeSize::Fixed(IncrementSize));
8360     Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr,
8361                         LD->getPointerInfo().getWithOffset(IncrementSize),
8362                         NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(),
8363                         LD->getAAInfo());
8364   } else {
8365     Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr, LD->getPointerInfo(),
8366                         NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(),
8367                         LD->getAAInfo());
8368 
8369     Ptr = DAG.getObjectPtrOffset(dl, Ptr, TypeSize::Fixed(IncrementSize));
8370     Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr,
8371                         LD->getPointerInfo().getWithOffset(IncrementSize),
8372                         NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(),
8373                         LD->getAAInfo());
8374   }
8375 
8376   // aggregate the two parts
8377   SDValue ShiftAmount =
8378       DAG.getConstant(NumBits, dl, getShiftAmountTy(Hi.getValueType(),
8379                                                     DAG.getDataLayout()));
8380   SDValue Result = DAG.getNode(ISD::SHL, dl, VT, Hi, ShiftAmount);
8381   Result = DAG.getNode(ISD::OR, dl, VT, Result, Lo);
8382 
8383   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
8384                              Hi.getValue(1));
8385 
8386   return std::make_pair(Result, TF);
8387 }
8388 
8389 SDValue TargetLowering::expandUnalignedStore(StoreSDNode *ST,
8390                                              SelectionDAG &DAG) const {
8391   assert(ST->getAddressingMode() == ISD::UNINDEXED &&
8392          "unaligned indexed stores not implemented!");
8393   SDValue Chain = ST->getChain();
8394   SDValue Ptr = ST->getBasePtr();
8395   SDValue Val = ST->getValue();
8396   EVT VT = Val.getValueType();
8397   Align Alignment = ST->getOriginalAlign();
8398   auto &MF = DAG.getMachineFunction();
8399   EVT StoreMemVT = ST->getMemoryVT();
8400 
8401   SDLoc dl(ST);
8402   if (StoreMemVT.isFloatingPoint() || StoreMemVT.isVector()) {
8403     EVT intVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
8404     if (isTypeLegal(intVT)) {
8405       if (!isOperationLegalOrCustom(ISD::STORE, intVT) &&
8406           StoreMemVT.isVector()) {
8407         // Scalarize the store and let the individual components be handled.
8408         SDValue Result = scalarizeVectorStore(ST, DAG);
8409         return Result;
8410       }
8411       // Expand to a bitconvert of the value to the integer type of the
8412       // same size, then a (misaligned) int store.
8413       // FIXME: Does not handle truncating floating point stores!
8414       SDValue Result = DAG.getNode(ISD::BITCAST, dl, intVT, Val);
8415       Result = DAG.getStore(Chain, dl, Result, Ptr, ST->getPointerInfo(),
8416                             Alignment, ST->getMemOperand()->getFlags());
8417       return Result;
8418     }
8419     // Do a (aligned) store to a stack slot, then copy from the stack slot
8420     // to the final destination using (unaligned) integer loads and stores.
8421     MVT RegVT = getRegisterType(
8422         *DAG.getContext(),
8423         EVT::getIntegerVT(*DAG.getContext(), StoreMemVT.getSizeInBits()));
8424     EVT PtrVT = Ptr.getValueType();
8425     unsigned StoredBytes = StoreMemVT.getStoreSize();
8426     unsigned RegBytes = RegVT.getSizeInBits() / 8;
8427     unsigned NumRegs = (StoredBytes + RegBytes - 1) / RegBytes;
8428 
8429     // Make sure the stack slot is also aligned for the register type.
8430     SDValue StackPtr = DAG.CreateStackTemporary(StoreMemVT, RegVT);
8431     auto FrameIndex = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
8432 
8433     // Perform the original store, only redirected to the stack slot.
8434     SDValue Store = DAG.getTruncStore(
8435         Chain, dl, Val, StackPtr,
8436         MachinePointerInfo::getFixedStack(MF, FrameIndex, 0), StoreMemVT);
8437 
8438     EVT StackPtrVT = StackPtr.getValueType();
8439 
8440     SDValue PtrIncrement = DAG.getConstant(RegBytes, dl, PtrVT);
8441     SDValue StackPtrIncrement = DAG.getConstant(RegBytes, dl, StackPtrVT);
8442     SmallVector<SDValue, 8> Stores;
8443     unsigned Offset = 0;
8444 
8445     // Do all but one copies using the full register width.
8446     for (unsigned i = 1; i < NumRegs; i++) {
8447       // Load one integer register's worth from the stack slot.
8448       SDValue Load = DAG.getLoad(
8449           RegVT, dl, Store, StackPtr,
8450           MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset));
8451       // Store it to the final location.  Remember the store.
8452       Stores.push_back(DAG.getStore(Load.getValue(1), dl, Load, Ptr,
8453                                     ST->getPointerInfo().getWithOffset(Offset),
8454                                     ST->getOriginalAlign(),
8455                                     ST->getMemOperand()->getFlags()));
8456       // Increment the pointers.
8457       Offset += RegBytes;
8458       StackPtr = DAG.getObjectPtrOffset(dl, StackPtr, StackPtrIncrement);
8459       Ptr = DAG.getObjectPtrOffset(dl, Ptr, PtrIncrement);
8460     }
8461 
8462     // The last store may be partial.  Do a truncating store.  On big-endian
8463     // machines this requires an extending load from the stack slot to ensure
8464     // that the bits are in the right place.
8465     EVT LoadMemVT =
8466         EVT::getIntegerVT(*DAG.getContext(), 8 * (StoredBytes - Offset));
8467 
8468     // Load from the stack slot.
8469     SDValue Load = DAG.getExtLoad(
8470         ISD::EXTLOAD, dl, RegVT, Store, StackPtr,
8471         MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset), LoadMemVT);
8472 
8473     Stores.push_back(
8474         DAG.getTruncStore(Load.getValue(1), dl, Load, Ptr,
8475                           ST->getPointerInfo().getWithOffset(Offset), LoadMemVT,
8476                           ST->getOriginalAlign(),
8477                           ST->getMemOperand()->getFlags(), ST->getAAInfo()));
8478     // The order of the stores doesn't matter - say it with a TokenFactor.
8479     SDValue Result = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
8480     return Result;
8481   }
8482 
8483   assert(StoreMemVT.isInteger() && !StoreMemVT.isVector() &&
8484          "Unaligned store of unknown type.");
8485   // Get the half-size VT
8486   EVT NewStoredVT = StoreMemVT.getHalfSizedIntegerVT(*DAG.getContext());
8487   unsigned NumBits = NewStoredVT.getFixedSizeInBits();
8488   unsigned IncrementSize = NumBits / 8;
8489 
8490   // Divide the stored value in two parts.
8491   SDValue ShiftAmount = DAG.getConstant(
8492       NumBits, dl, getShiftAmountTy(Val.getValueType(), DAG.getDataLayout()));
8493   SDValue Lo = Val;
8494   SDValue Hi = DAG.getNode(ISD::SRL, dl, VT, Val, ShiftAmount);
8495 
8496   // Store the two parts
8497   SDValue Store1, Store2;
8498   Store1 = DAG.getTruncStore(Chain, dl,
8499                              DAG.getDataLayout().isLittleEndian() ? Lo : Hi,
8500                              Ptr, ST->getPointerInfo(), NewStoredVT, Alignment,
8501                              ST->getMemOperand()->getFlags());
8502 
8503   Ptr = DAG.getObjectPtrOffset(dl, Ptr, TypeSize::Fixed(IncrementSize));
8504   Store2 = DAG.getTruncStore(
8505       Chain, dl, DAG.getDataLayout().isLittleEndian() ? Hi : Lo, Ptr,
8506       ST->getPointerInfo().getWithOffset(IncrementSize), NewStoredVT, Alignment,
8507       ST->getMemOperand()->getFlags(), ST->getAAInfo());
8508 
8509   SDValue Result =
8510       DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Store1, Store2);
8511   return Result;
8512 }
8513 
8514 SDValue
8515 TargetLowering::IncrementMemoryAddress(SDValue Addr, SDValue Mask,
8516                                        const SDLoc &DL, EVT DataVT,
8517                                        SelectionDAG &DAG,
8518                                        bool IsCompressedMemory) const {
8519   SDValue Increment;
8520   EVT AddrVT = Addr.getValueType();
8521   EVT MaskVT = Mask.getValueType();
8522   assert(DataVT.getVectorElementCount() == MaskVT.getVectorElementCount() &&
8523          "Incompatible types of Data and Mask");
8524   if (IsCompressedMemory) {
8525     if (DataVT.isScalableVector())
8526       report_fatal_error(
8527           "Cannot currently handle compressed memory with scalable vectors");
8528     // Incrementing the pointer according to number of '1's in the mask.
8529     EVT MaskIntVT = EVT::getIntegerVT(*DAG.getContext(), MaskVT.getSizeInBits());
8530     SDValue MaskInIntReg = DAG.getBitcast(MaskIntVT, Mask);
8531     if (MaskIntVT.getSizeInBits() < 32) {
8532       MaskInIntReg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, MaskInIntReg);
8533       MaskIntVT = MVT::i32;
8534     }
8535 
8536     // Count '1's with POPCNT.
8537     Increment = DAG.getNode(ISD::CTPOP, DL, MaskIntVT, MaskInIntReg);
8538     Increment = DAG.getZExtOrTrunc(Increment, DL, AddrVT);
8539     // Scale is an element size in bytes.
8540     SDValue Scale = DAG.getConstant(DataVT.getScalarSizeInBits() / 8, DL,
8541                                     AddrVT);
8542     Increment = DAG.getNode(ISD::MUL, DL, AddrVT, Increment, Scale);
8543   } else if (DataVT.isScalableVector()) {
8544     Increment = DAG.getVScale(DL, AddrVT,
8545                               APInt(AddrVT.getFixedSizeInBits(),
8546                                     DataVT.getStoreSize().getKnownMinSize()));
8547   } else
8548     Increment = DAG.getConstant(DataVT.getStoreSize(), DL, AddrVT);
8549 
8550   return DAG.getNode(ISD::ADD, DL, AddrVT, Addr, Increment);
8551 }
8552 
8553 static SDValue clampDynamicVectorIndex(SelectionDAG &DAG, SDValue Idx,
8554                                        EVT VecVT, const SDLoc &dl,
8555                                        ElementCount SubEC) {
8556   assert(!(SubEC.isScalable() && VecVT.isFixedLengthVector()) &&
8557          "Cannot index a scalable vector within a fixed-width vector");
8558 
8559   unsigned NElts = VecVT.getVectorMinNumElements();
8560   unsigned NumSubElts = SubEC.getKnownMinValue();
8561   EVT IdxVT = Idx.getValueType();
8562 
8563   if (VecVT.isScalableVector() && !SubEC.isScalable()) {
8564     // If this is a constant index and we know the value plus the number of the
8565     // elements in the subvector minus one is less than the minimum number of
8566     // elements then it's safe to return Idx.
8567     if (auto *IdxCst = dyn_cast<ConstantSDNode>(Idx))
8568       if (IdxCst->getZExtValue() + (NumSubElts - 1) < NElts)
8569         return Idx;
8570     SDValue VS =
8571         DAG.getVScale(dl, IdxVT, APInt(IdxVT.getFixedSizeInBits(), NElts));
8572     unsigned SubOpcode = NumSubElts <= NElts ? ISD::SUB : ISD::USUBSAT;
8573     SDValue Sub = DAG.getNode(SubOpcode, dl, IdxVT, VS,
8574                               DAG.getConstant(NumSubElts, dl, IdxVT));
8575     return DAG.getNode(ISD::UMIN, dl, IdxVT, Idx, Sub);
8576   }
8577   if (isPowerOf2_32(NElts) && NumSubElts == 1) {
8578     APInt Imm = APInt::getLowBitsSet(IdxVT.getSizeInBits(), Log2_32(NElts));
8579     return DAG.getNode(ISD::AND, dl, IdxVT, Idx,
8580                        DAG.getConstant(Imm, dl, IdxVT));
8581   }
8582   unsigned MaxIndex = NumSubElts < NElts ? NElts - NumSubElts : 0;
8583   return DAG.getNode(ISD::UMIN, dl, IdxVT, Idx,
8584                      DAG.getConstant(MaxIndex, dl, IdxVT));
8585 }
8586 
8587 SDValue TargetLowering::getVectorElementPointer(SelectionDAG &DAG,
8588                                                 SDValue VecPtr, EVT VecVT,
8589                                                 SDValue Index) const {
8590   return getVectorSubVecPointer(
8591       DAG, VecPtr, VecVT,
8592       EVT::getVectorVT(*DAG.getContext(), VecVT.getVectorElementType(), 1),
8593       Index);
8594 }
8595 
8596 SDValue TargetLowering::getVectorSubVecPointer(SelectionDAG &DAG,
8597                                                SDValue VecPtr, EVT VecVT,
8598                                                EVT SubVecVT,
8599                                                SDValue Index) const {
8600   SDLoc dl(Index);
8601   // Make sure the index type is big enough to compute in.
8602   Index = DAG.getZExtOrTrunc(Index, dl, VecPtr.getValueType());
8603 
8604   EVT EltVT = VecVT.getVectorElementType();
8605 
8606   // Calculate the element offset and add it to the pointer.
8607   unsigned EltSize = EltVT.getFixedSizeInBits() / 8; // FIXME: should be ABI size.
8608   assert(EltSize * 8 == EltVT.getFixedSizeInBits() &&
8609          "Converting bits to bytes lost precision");
8610   assert(SubVecVT.getVectorElementType() == EltVT &&
8611          "Sub-vector must be a vector with matching element type");
8612   Index = clampDynamicVectorIndex(DAG, Index, VecVT, dl,
8613                                   SubVecVT.getVectorElementCount());
8614 
8615   EVT IdxVT = Index.getValueType();
8616   if (SubVecVT.isScalableVector())
8617     Index =
8618         DAG.getNode(ISD::MUL, dl, IdxVT, Index,
8619                     DAG.getVScale(dl, IdxVT, APInt(IdxVT.getSizeInBits(), 1)));
8620 
8621   Index = DAG.getNode(ISD::MUL, dl, IdxVT, Index,
8622                       DAG.getConstant(EltSize, dl, IdxVT));
8623   return DAG.getMemBasePlusOffset(VecPtr, Index, dl);
8624 }
8625 
8626 //===----------------------------------------------------------------------===//
8627 // Implementation of Emulated TLS Model
8628 //===----------------------------------------------------------------------===//
8629 
8630 SDValue TargetLowering::LowerToTLSEmulatedModel(const GlobalAddressSDNode *GA,
8631                                                 SelectionDAG &DAG) const {
8632   // Access to address of TLS varialbe xyz is lowered to a function call:
8633   //   __emutls_get_address( address of global variable named "__emutls_v.xyz" )
8634   EVT PtrVT = getPointerTy(DAG.getDataLayout());
8635   PointerType *VoidPtrType = Type::getInt8PtrTy(*DAG.getContext());
8636   SDLoc dl(GA);
8637 
8638   ArgListTy Args;
8639   ArgListEntry Entry;
8640   std::string NameString = ("__emutls_v." + GA->getGlobal()->getName()).str();
8641   Module *VariableModule = const_cast<Module*>(GA->getGlobal()->getParent());
8642   StringRef EmuTlsVarName(NameString);
8643   GlobalVariable *EmuTlsVar = VariableModule->getNamedGlobal(EmuTlsVarName);
8644   assert(EmuTlsVar && "Cannot find EmuTlsVar ");
8645   Entry.Node = DAG.getGlobalAddress(EmuTlsVar, dl, PtrVT);
8646   Entry.Ty = VoidPtrType;
8647   Args.push_back(Entry);
8648 
8649   SDValue EmuTlsGetAddr = DAG.getExternalSymbol("__emutls_get_address", PtrVT);
8650 
8651   TargetLowering::CallLoweringInfo CLI(DAG);
8652   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode());
8653   CLI.setLibCallee(CallingConv::C, VoidPtrType, EmuTlsGetAddr, std::move(Args));
8654   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
8655 
8656   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
8657   // At last for X86 targets, maybe good for other targets too?
8658   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
8659   MFI.setAdjustsStack(true); // Is this only for X86 target?
8660   MFI.setHasCalls(true);
8661 
8662   assert((GA->getOffset() == 0) &&
8663          "Emulated TLS must have zero offset in GlobalAddressSDNode");
8664   return CallResult.first;
8665 }
8666 
8667 SDValue TargetLowering::lowerCmpEqZeroToCtlzSrl(SDValue Op,
8668                                                 SelectionDAG &DAG) const {
8669   assert((Op->getOpcode() == ISD::SETCC) && "Input has to be a SETCC node.");
8670   if (!isCtlzFast())
8671     return SDValue();
8672   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8673   SDLoc dl(Op);
8674   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
8675     if (C->isZero() && CC == ISD::SETEQ) {
8676       EVT VT = Op.getOperand(0).getValueType();
8677       SDValue Zext = Op.getOperand(0);
8678       if (VT.bitsLT(MVT::i32)) {
8679         VT = MVT::i32;
8680         Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0));
8681       }
8682       unsigned Log2b = Log2_32(VT.getSizeInBits());
8683       SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext);
8684       SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz,
8685                                 DAG.getConstant(Log2b, dl, MVT::i32));
8686       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc);
8687     }
8688   }
8689   return SDValue();
8690 }
8691 
8692 SDValue TargetLowering::expandIntMINMAX(SDNode *Node, SelectionDAG &DAG) const {
8693   SDValue Op0 = Node->getOperand(0);
8694   SDValue Op1 = Node->getOperand(1);
8695   EVT VT = Op0.getValueType();
8696   unsigned Opcode = Node->getOpcode();
8697   SDLoc DL(Node);
8698 
8699   // umin(x,y) -> sub(x,usubsat(x,y))
8700   if (Opcode == ISD::UMIN && isOperationLegal(ISD::SUB, VT) &&
8701       isOperationLegal(ISD::USUBSAT, VT)) {
8702     return DAG.getNode(ISD::SUB, DL, VT, Op0,
8703                        DAG.getNode(ISD::USUBSAT, DL, VT, Op0, Op1));
8704   }
8705 
8706   // umax(x,y) -> add(x,usubsat(y,x))
8707   if (Opcode == ISD::UMAX && isOperationLegal(ISD::ADD, VT) &&
8708       isOperationLegal(ISD::USUBSAT, VT)) {
8709     return DAG.getNode(ISD::ADD, DL, VT, Op0,
8710                        DAG.getNode(ISD::USUBSAT, DL, VT, Op1, Op0));
8711   }
8712 
8713   // Expand Y = MAX(A, B) -> Y = (A > B) ? A : B
8714   ISD::CondCode CC;
8715   switch (Opcode) {
8716   default: llvm_unreachable("How did we get here?");
8717   case ISD::SMAX: CC = ISD::SETGT; break;
8718   case ISD::SMIN: CC = ISD::SETLT; break;
8719   case ISD::UMAX: CC = ISD::SETUGT; break;
8720   case ISD::UMIN: CC = ISD::SETULT; break;
8721   }
8722 
8723   // FIXME: Should really try to split the vector in case it's legal on a
8724   // subvector.
8725   if (VT.isVector() && !isOperationLegalOrCustom(ISD::VSELECT, VT))
8726     return DAG.UnrollVectorOp(Node);
8727 
8728   EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
8729   SDValue Cond = DAG.getSetCC(DL, BoolVT, Op0, Op1, CC);
8730   return DAG.getSelect(DL, VT, Cond, Op0, Op1);
8731 }
8732 
8733 SDValue TargetLowering::expandAddSubSat(SDNode *Node, SelectionDAG &DAG) const {
8734   unsigned Opcode = Node->getOpcode();
8735   SDValue LHS = Node->getOperand(0);
8736   SDValue RHS = Node->getOperand(1);
8737   EVT VT = LHS.getValueType();
8738   SDLoc dl(Node);
8739 
8740   assert(VT == RHS.getValueType() && "Expected operands to be the same type");
8741   assert(VT.isInteger() && "Expected operands to be integers");
8742 
8743   // usub.sat(a, b) -> umax(a, b) - b
8744   if (Opcode == ISD::USUBSAT && isOperationLegal(ISD::UMAX, VT)) {
8745     SDValue Max = DAG.getNode(ISD::UMAX, dl, VT, LHS, RHS);
8746     return DAG.getNode(ISD::SUB, dl, VT, Max, RHS);
8747   }
8748 
8749   // uadd.sat(a, b) -> umin(a, ~b) + b
8750   if (Opcode == ISD::UADDSAT && isOperationLegal(ISD::UMIN, VT)) {
8751     SDValue InvRHS = DAG.getNOT(dl, RHS, VT);
8752     SDValue Min = DAG.getNode(ISD::UMIN, dl, VT, LHS, InvRHS);
8753     return DAG.getNode(ISD::ADD, dl, VT, Min, RHS);
8754   }
8755 
8756   unsigned OverflowOp;
8757   switch (Opcode) {
8758   case ISD::SADDSAT:
8759     OverflowOp = ISD::SADDO;
8760     break;
8761   case ISD::UADDSAT:
8762     OverflowOp = ISD::UADDO;
8763     break;
8764   case ISD::SSUBSAT:
8765     OverflowOp = ISD::SSUBO;
8766     break;
8767   case ISD::USUBSAT:
8768     OverflowOp = ISD::USUBO;
8769     break;
8770   default:
8771     llvm_unreachable("Expected method to receive signed or unsigned saturation "
8772                      "addition or subtraction node.");
8773   }
8774 
8775   // FIXME: Should really try to split the vector in case it's legal on a
8776   // subvector.
8777   if (VT.isVector() && !isOperationLegalOrCustom(ISD::VSELECT, VT))
8778     return DAG.UnrollVectorOp(Node);
8779 
8780   unsigned BitWidth = LHS.getScalarValueSizeInBits();
8781   EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
8782   SDValue Result = DAG.getNode(OverflowOp, dl, DAG.getVTList(VT, BoolVT), LHS, RHS);
8783   SDValue SumDiff = Result.getValue(0);
8784   SDValue Overflow = Result.getValue(1);
8785   SDValue Zero = DAG.getConstant(0, dl, VT);
8786   SDValue AllOnes = DAG.getAllOnesConstant(dl, VT);
8787 
8788   if (Opcode == ISD::UADDSAT) {
8789     if (getBooleanContents(VT) == ZeroOrNegativeOneBooleanContent) {
8790       // (LHS + RHS) | OverflowMask
8791       SDValue OverflowMask = DAG.getSExtOrTrunc(Overflow, dl, VT);
8792       return DAG.getNode(ISD::OR, dl, VT, SumDiff, OverflowMask);
8793     }
8794     // Overflow ? 0xffff.... : (LHS + RHS)
8795     return DAG.getSelect(dl, VT, Overflow, AllOnes, SumDiff);
8796   }
8797 
8798   if (Opcode == ISD::USUBSAT) {
8799     if (getBooleanContents(VT) == ZeroOrNegativeOneBooleanContent) {
8800       // (LHS - RHS) & ~OverflowMask
8801       SDValue OverflowMask = DAG.getSExtOrTrunc(Overflow, dl, VT);
8802       SDValue Not = DAG.getNOT(dl, OverflowMask, VT);
8803       return DAG.getNode(ISD::AND, dl, VT, SumDiff, Not);
8804     }
8805     // Overflow ? 0 : (LHS - RHS)
8806     return DAG.getSelect(dl, VT, Overflow, Zero, SumDiff);
8807   }
8808 
8809   // Overflow ? (SumDiff >> BW) ^ MinVal : SumDiff
8810   APInt MinVal = APInt::getSignedMinValue(BitWidth);
8811   SDValue SatMin = DAG.getConstant(MinVal, dl, VT);
8812   SDValue Shift = DAG.getNode(ISD::SRA, dl, VT, SumDiff,
8813                               DAG.getConstant(BitWidth - 1, dl, VT));
8814   Result = DAG.getNode(ISD::XOR, dl, VT, Shift, SatMin);
8815   return DAG.getSelect(dl, VT, Overflow, Result, SumDiff);
8816 }
8817 
8818 SDValue TargetLowering::expandShlSat(SDNode *Node, SelectionDAG &DAG) const {
8819   unsigned Opcode = Node->getOpcode();
8820   bool IsSigned = Opcode == ISD::SSHLSAT;
8821   SDValue LHS = Node->getOperand(0);
8822   SDValue RHS = Node->getOperand(1);
8823   EVT VT = LHS.getValueType();
8824   SDLoc dl(Node);
8825 
8826   assert((Node->getOpcode() == ISD::SSHLSAT ||
8827           Node->getOpcode() == ISD::USHLSAT) &&
8828           "Expected a SHLSAT opcode");
8829   assert(VT == RHS.getValueType() && "Expected operands to be the same type");
8830   assert(VT.isInteger() && "Expected operands to be integers");
8831 
8832   // If LHS != (LHS << RHS) >> RHS, we have overflow and must saturate.
8833 
8834   unsigned BW = VT.getScalarSizeInBits();
8835   SDValue Result = DAG.getNode(ISD::SHL, dl, VT, LHS, RHS);
8836   SDValue Orig =
8837       DAG.getNode(IsSigned ? ISD::SRA : ISD::SRL, dl, VT, Result, RHS);
8838 
8839   SDValue SatVal;
8840   if (IsSigned) {
8841     SDValue SatMin = DAG.getConstant(APInt::getSignedMinValue(BW), dl, VT);
8842     SDValue SatMax = DAG.getConstant(APInt::getSignedMaxValue(BW), dl, VT);
8843     SatVal = DAG.getSelectCC(dl, LHS, DAG.getConstant(0, dl, VT),
8844                              SatMin, SatMax, ISD::SETLT);
8845   } else {
8846     SatVal = DAG.getConstant(APInt::getMaxValue(BW), dl, VT);
8847   }
8848   Result = DAG.getSelectCC(dl, LHS, Orig, SatVal, Result, ISD::SETNE);
8849 
8850   return Result;
8851 }
8852 
8853 SDValue
8854 TargetLowering::expandFixedPointMul(SDNode *Node, SelectionDAG &DAG) const {
8855   assert((Node->getOpcode() == ISD::SMULFIX ||
8856           Node->getOpcode() == ISD::UMULFIX ||
8857           Node->getOpcode() == ISD::SMULFIXSAT ||
8858           Node->getOpcode() == ISD::UMULFIXSAT) &&
8859          "Expected a fixed point multiplication opcode");
8860 
8861   SDLoc dl(Node);
8862   SDValue LHS = Node->getOperand(0);
8863   SDValue RHS = Node->getOperand(1);
8864   EVT VT = LHS.getValueType();
8865   unsigned Scale = Node->getConstantOperandVal(2);
8866   bool Saturating = (Node->getOpcode() == ISD::SMULFIXSAT ||
8867                      Node->getOpcode() == ISD::UMULFIXSAT);
8868   bool Signed = (Node->getOpcode() == ISD::SMULFIX ||
8869                  Node->getOpcode() == ISD::SMULFIXSAT);
8870   EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
8871   unsigned VTSize = VT.getScalarSizeInBits();
8872 
8873   if (!Scale) {
8874     // [us]mul.fix(a, b, 0) -> mul(a, b)
8875     if (!Saturating) {
8876       if (isOperationLegalOrCustom(ISD::MUL, VT))
8877         return DAG.getNode(ISD::MUL, dl, VT, LHS, RHS);
8878     } else if (Signed && isOperationLegalOrCustom(ISD::SMULO, VT)) {
8879       SDValue Result =
8880           DAG.getNode(ISD::SMULO, dl, DAG.getVTList(VT, BoolVT), LHS, RHS);
8881       SDValue Product = Result.getValue(0);
8882       SDValue Overflow = Result.getValue(1);
8883       SDValue Zero = DAG.getConstant(0, dl, VT);
8884 
8885       APInt MinVal = APInt::getSignedMinValue(VTSize);
8886       APInt MaxVal = APInt::getSignedMaxValue(VTSize);
8887       SDValue SatMin = DAG.getConstant(MinVal, dl, VT);
8888       SDValue SatMax = DAG.getConstant(MaxVal, dl, VT);
8889       // Xor the inputs, if resulting sign bit is 0 the product will be
8890       // positive, else negative.
8891       SDValue Xor = DAG.getNode(ISD::XOR, dl, VT, LHS, RHS);
8892       SDValue ProdNeg = DAG.getSetCC(dl, BoolVT, Xor, Zero, ISD::SETLT);
8893       Result = DAG.getSelect(dl, VT, ProdNeg, SatMin, SatMax);
8894       return DAG.getSelect(dl, VT, Overflow, Result, Product);
8895     } else if (!Signed && isOperationLegalOrCustom(ISD::UMULO, VT)) {
8896       SDValue Result =
8897           DAG.getNode(ISD::UMULO, dl, DAG.getVTList(VT, BoolVT), LHS, RHS);
8898       SDValue Product = Result.getValue(0);
8899       SDValue Overflow = Result.getValue(1);
8900 
8901       APInt MaxVal = APInt::getMaxValue(VTSize);
8902       SDValue SatMax = DAG.getConstant(MaxVal, dl, VT);
8903       return DAG.getSelect(dl, VT, Overflow, SatMax, Product);
8904     }
8905   }
8906 
8907   assert(((Signed && Scale < VTSize) || (!Signed && Scale <= VTSize)) &&
8908          "Expected scale to be less than the number of bits if signed or at "
8909          "most the number of bits if unsigned.");
8910   assert(LHS.getValueType() == RHS.getValueType() &&
8911          "Expected both operands to be the same type");
8912 
8913   // Get the upper and lower bits of the result.
8914   SDValue Lo, Hi;
8915   unsigned LoHiOp = Signed ? ISD::SMUL_LOHI : ISD::UMUL_LOHI;
8916   unsigned HiOp = Signed ? ISD::MULHS : ISD::MULHU;
8917   if (isOperationLegalOrCustom(LoHiOp, VT)) {
8918     SDValue Result = DAG.getNode(LoHiOp, dl, DAG.getVTList(VT, VT), LHS, RHS);
8919     Lo = Result.getValue(0);
8920     Hi = Result.getValue(1);
8921   } else if (isOperationLegalOrCustom(HiOp, VT)) {
8922     Lo = DAG.getNode(ISD::MUL, dl, VT, LHS, RHS);
8923     Hi = DAG.getNode(HiOp, dl, VT, LHS, RHS);
8924   } else if (VT.isVector()) {
8925     return SDValue();
8926   } else {
8927     report_fatal_error("Unable to expand fixed point multiplication.");
8928   }
8929 
8930   if (Scale == VTSize)
8931     // Result is just the top half since we'd be shifting by the width of the
8932     // operand. Overflow impossible so this works for both UMULFIX and
8933     // UMULFIXSAT.
8934     return Hi;
8935 
8936   // The result will need to be shifted right by the scale since both operands
8937   // are scaled. The result is given to us in 2 halves, so we only want part of
8938   // both in the result.
8939   EVT ShiftTy = getShiftAmountTy(VT, DAG.getDataLayout());
8940   SDValue Result = DAG.getNode(ISD::FSHR, dl, VT, Hi, Lo,
8941                                DAG.getConstant(Scale, dl, ShiftTy));
8942   if (!Saturating)
8943     return Result;
8944 
8945   if (!Signed) {
8946     // Unsigned overflow happened if the upper (VTSize - Scale) bits (of the
8947     // widened multiplication) aren't all zeroes.
8948 
8949     // Saturate to max if ((Hi >> Scale) != 0),
8950     // which is the same as if (Hi > ((1 << Scale) - 1))
8951     APInt MaxVal = APInt::getMaxValue(VTSize);
8952     SDValue LowMask = DAG.getConstant(APInt::getLowBitsSet(VTSize, Scale),
8953                                       dl, VT);
8954     Result = DAG.getSelectCC(dl, Hi, LowMask,
8955                              DAG.getConstant(MaxVal, dl, VT), Result,
8956                              ISD::SETUGT);
8957 
8958     return Result;
8959   }
8960 
8961   // Signed overflow happened if the upper (VTSize - Scale + 1) bits (of the
8962   // widened multiplication) aren't all ones or all zeroes.
8963 
8964   SDValue SatMin = DAG.getConstant(APInt::getSignedMinValue(VTSize), dl, VT);
8965   SDValue SatMax = DAG.getConstant(APInt::getSignedMaxValue(VTSize), dl, VT);
8966 
8967   if (Scale == 0) {
8968     SDValue Sign = DAG.getNode(ISD::SRA, dl, VT, Lo,
8969                                DAG.getConstant(VTSize - 1, dl, ShiftTy));
8970     SDValue Overflow = DAG.getSetCC(dl, BoolVT, Hi, Sign, ISD::SETNE);
8971     // Saturated to SatMin if wide product is negative, and SatMax if wide
8972     // product is positive ...
8973     SDValue Zero = DAG.getConstant(0, dl, VT);
8974     SDValue ResultIfOverflow = DAG.getSelectCC(dl, Hi, Zero, SatMin, SatMax,
8975                                                ISD::SETLT);
8976     // ... but only if we overflowed.
8977     return DAG.getSelect(dl, VT, Overflow, ResultIfOverflow, Result);
8978   }
8979 
8980   //  We handled Scale==0 above so all the bits to examine is in Hi.
8981 
8982   // Saturate to max if ((Hi >> (Scale - 1)) > 0),
8983   // which is the same as if (Hi > (1 << (Scale - 1)) - 1)
8984   SDValue LowMask = DAG.getConstant(APInt::getLowBitsSet(VTSize, Scale - 1),
8985                                     dl, VT);
8986   Result = DAG.getSelectCC(dl, Hi, LowMask, SatMax, Result, ISD::SETGT);
8987   // Saturate to min if (Hi >> (Scale - 1)) < -1),
8988   // which is the same as if (HI < (-1 << (Scale - 1))
8989   SDValue HighMask =
8990       DAG.getConstant(APInt::getHighBitsSet(VTSize, VTSize - Scale + 1),
8991                       dl, VT);
8992   Result = DAG.getSelectCC(dl, Hi, HighMask, SatMin, Result, ISD::SETLT);
8993   return Result;
8994 }
8995 
8996 SDValue
8997 TargetLowering::expandFixedPointDiv(unsigned Opcode, const SDLoc &dl,
8998                                     SDValue LHS, SDValue RHS,
8999                                     unsigned Scale, SelectionDAG &DAG) const {
9000   assert((Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT ||
9001           Opcode == ISD::UDIVFIX || Opcode == ISD::UDIVFIXSAT) &&
9002          "Expected a fixed point division opcode");
9003 
9004   EVT VT = LHS.getValueType();
9005   bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT;
9006   bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT;
9007   EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
9008 
9009   // If there is enough room in the type to upscale the LHS or downscale the
9010   // RHS before the division, we can perform it in this type without having to
9011   // resize. For signed operations, the LHS headroom is the number of
9012   // redundant sign bits, and for unsigned ones it is the number of zeroes.
9013   // The headroom for the RHS is the number of trailing zeroes.
9014   unsigned LHSLead = Signed ? DAG.ComputeNumSignBits(LHS) - 1
9015                             : DAG.computeKnownBits(LHS).countMinLeadingZeros();
9016   unsigned RHSTrail = DAG.computeKnownBits(RHS).countMinTrailingZeros();
9017 
9018   // For signed saturating operations, we need to be able to detect true integer
9019   // division overflow; that is, when you have MIN / -EPS. However, this
9020   // is undefined behavior and if we emit divisions that could take such
9021   // values it may cause undesired behavior (arithmetic exceptions on x86, for
9022   // example).
9023   // Avoid this by requiring an extra bit so that we never get this case.
9024   // FIXME: This is a bit unfortunate as it means that for an 8-bit 7-scale
9025   // signed saturating division, we need to emit a whopping 32-bit division.
9026   if (LHSLead + RHSTrail < Scale + (unsigned)(Saturating && Signed))
9027     return SDValue();
9028 
9029   unsigned LHSShift = std::min(LHSLead, Scale);
9030   unsigned RHSShift = Scale - LHSShift;
9031 
9032   // At this point, we know that if we shift the LHS up by LHSShift and the
9033   // RHS down by RHSShift, we can emit a regular division with a final scaling
9034   // factor of Scale.
9035 
9036   EVT ShiftTy = getShiftAmountTy(VT, DAG.getDataLayout());
9037   if (LHSShift)
9038     LHS = DAG.getNode(ISD::SHL, dl, VT, LHS,
9039                       DAG.getConstant(LHSShift, dl, ShiftTy));
9040   if (RHSShift)
9041     RHS = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, dl, VT, RHS,
9042                       DAG.getConstant(RHSShift, dl, ShiftTy));
9043 
9044   SDValue Quot;
9045   if (Signed) {
9046     // For signed operations, if the resulting quotient is negative and the
9047     // remainder is nonzero, subtract 1 from the quotient to round towards
9048     // negative infinity.
9049     SDValue Rem;
9050     // FIXME: Ideally we would always produce an SDIVREM here, but if the
9051     // type isn't legal, SDIVREM cannot be expanded. There is no reason why
9052     // we couldn't just form a libcall, but the type legalizer doesn't do it.
9053     if (isTypeLegal(VT) &&
9054         isOperationLegalOrCustom(ISD::SDIVREM, VT)) {
9055       Quot = DAG.getNode(ISD::SDIVREM, dl,
9056                          DAG.getVTList(VT, VT),
9057                          LHS, RHS);
9058       Rem = Quot.getValue(1);
9059       Quot = Quot.getValue(0);
9060     } else {
9061       Quot = DAG.getNode(ISD::SDIV, dl, VT,
9062                          LHS, RHS);
9063       Rem = DAG.getNode(ISD::SREM, dl, VT,
9064                         LHS, RHS);
9065     }
9066     SDValue Zero = DAG.getConstant(0, dl, VT);
9067     SDValue RemNonZero = DAG.getSetCC(dl, BoolVT, Rem, Zero, ISD::SETNE);
9068     SDValue LHSNeg = DAG.getSetCC(dl, BoolVT, LHS, Zero, ISD::SETLT);
9069     SDValue RHSNeg = DAG.getSetCC(dl, BoolVT, RHS, Zero, ISD::SETLT);
9070     SDValue QuotNeg = DAG.getNode(ISD::XOR, dl, BoolVT, LHSNeg, RHSNeg);
9071     SDValue Sub1 = DAG.getNode(ISD::SUB, dl, VT, Quot,
9072                                DAG.getConstant(1, dl, VT));
9073     Quot = DAG.getSelect(dl, VT,
9074                          DAG.getNode(ISD::AND, dl, BoolVT, RemNonZero, QuotNeg),
9075                          Sub1, Quot);
9076   } else
9077     Quot = DAG.getNode(ISD::UDIV, dl, VT,
9078                        LHS, RHS);
9079 
9080   return Quot;
9081 }
9082 
9083 void TargetLowering::expandUADDSUBO(
9084     SDNode *Node, SDValue &Result, SDValue &Overflow, SelectionDAG &DAG) const {
9085   SDLoc dl(Node);
9086   SDValue LHS = Node->getOperand(0);
9087   SDValue RHS = Node->getOperand(1);
9088   bool IsAdd = Node->getOpcode() == ISD::UADDO;
9089 
9090   // If ADD/SUBCARRY is legal, use that instead.
9091   unsigned OpcCarry = IsAdd ? ISD::ADDCARRY : ISD::SUBCARRY;
9092   if (isOperationLegalOrCustom(OpcCarry, Node->getValueType(0))) {
9093     SDValue CarryIn = DAG.getConstant(0, dl, Node->getValueType(1));
9094     SDValue NodeCarry = DAG.getNode(OpcCarry, dl, Node->getVTList(),
9095                                     { LHS, RHS, CarryIn });
9096     Result = SDValue(NodeCarry.getNode(), 0);
9097     Overflow = SDValue(NodeCarry.getNode(), 1);
9098     return;
9099   }
9100 
9101   Result = DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, dl,
9102                             LHS.getValueType(), LHS, RHS);
9103 
9104   EVT ResultType = Node->getValueType(1);
9105   EVT SetCCType = getSetCCResultType(
9106       DAG.getDataLayout(), *DAG.getContext(), Node->getValueType(0));
9107   SDValue SetCC;
9108   if (IsAdd && isOneConstant(RHS)) {
9109     // Special case: uaddo X, 1 overflowed if X+1 is 0. This potential reduces
9110     // the live range of X. We assume comparing with 0 is cheap.
9111     // The general case (X + C) < C is not necessarily beneficial. Although we
9112     // reduce the live range of X, we may introduce the materialization of
9113     // constant C.
9114     SetCC =
9115         DAG.getSetCC(dl, SetCCType, Result,
9116                      DAG.getConstant(0, dl, Node->getValueType(0)), ISD::SETEQ);
9117   } else {
9118     ISD::CondCode CC = IsAdd ? ISD::SETULT : ISD::SETUGT;
9119     SetCC = DAG.getSetCC(dl, SetCCType, Result, LHS, CC);
9120   }
9121   Overflow = DAG.getBoolExtOrTrunc(SetCC, dl, ResultType, ResultType);
9122 }
9123 
9124 void TargetLowering::expandSADDSUBO(
9125     SDNode *Node, SDValue &Result, SDValue &Overflow, SelectionDAG &DAG) const {
9126   SDLoc dl(Node);
9127   SDValue LHS = Node->getOperand(0);
9128   SDValue RHS = Node->getOperand(1);
9129   bool IsAdd = Node->getOpcode() == ISD::SADDO;
9130 
9131   Result = DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, dl,
9132                             LHS.getValueType(), LHS, RHS);
9133 
9134   EVT ResultType = Node->getValueType(1);
9135   EVT OType = getSetCCResultType(
9136       DAG.getDataLayout(), *DAG.getContext(), Node->getValueType(0));
9137 
9138   // If SADDSAT/SSUBSAT is legal, compare results to detect overflow.
9139   unsigned OpcSat = IsAdd ? ISD::SADDSAT : ISD::SSUBSAT;
9140   if (isOperationLegal(OpcSat, LHS.getValueType())) {
9141     SDValue Sat = DAG.getNode(OpcSat, dl, LHS.getValueType(), LHS, RHS);
9142     SDValue SetCC = DAG.getSetCC(dl, OType, Result, Sat, ISD::SETNE);
9143     Overflow = DAG.getBoolExtOrTrunc(SetCC, dl, ResultType, ResultType);
9144     return;
9145   }
9146 
9147   SDValue Zero = DAG.getConstant(0, dl, LHS.getValueType());
9148 
9149   // For an addition, the result should be less than one of the operands (LHS)
9150   // if and only if the other operand (RHS) is negative, otherwise there will
9151   // be overflow.
9152   // For a subtraction, the result should be less than one of the operands
9153   // (LHS) if and only if the other operand (RHS) is (non-zero) positive,
9154   // otherwise there will be overflow.
9155   SDValue ResultLowerThanLHS = DAG.getSetCC(dl, OType, Result, LHS, ISD::SETLT);
9156   SDValue ConditionRHS =
9157       DAG.getSetCC(dl, OType, RHS, Zero, IsAdd ? ISD::SETLT : ISD::SETGT);
9158 
9159   Overflow = DAG.getBoolExtOrTrunc(
9160       DAG.getNode(ISD::XOR, dl, OType, ConditionRHS, ResultLowerThanLHS), dl,
9161       ResultType, ResultType);
9162 }
9163 
9164 bool TargetLowering::expandMULO(SDNode *Node, SDValue &Result,
9165                                 SDValue &Overflow, SelectionDAG &DAG) const {
9166   SDLoc dl(Node);
9167   EVT VT = Node->getValueType(0);
9168   EVT SetCCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
9169   SDValue LHS = Node->getOperand(0);
9170   SDValue RHS = Node->getOperand(1);
9171   bool isSigned = Node->getOpcode() == ISD::SMULO;
9172 
9173   // For power-of-two multiplications we can use a simpler shift expansion.
9174   if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) {
9175     const APInt &C = RHSC->getAPIntValue();
9176     // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X }
9177     if (C.isPowerOf2()) {
9178       // smulo(x, signed_min) is same as umulo(x, signed_min).
9179       bool UseArithShift = isSigned && !C.isMinSignedValue();
9180       EVT ShiftAmtTy = getShiftAmountTy(VT, DAG.getDataLayout());
9181       SDValue ShiftAmt = DAG.getConstant(C.logBase2(), dl, ShiftAmtTy);
9182       Result = DAG.getNode(ISD::SHL, dl, VT, LHS, ShiftAmt);
9183       Overflow = DAG.getSetCC(dl, SetCCVT,
9184           DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL,
9185                       dl, VT, Result, ShiftAmt),
9186           LHS, ISD::SETNE);
9187       return true;
9188     }
9189   }
9190 
9191   EVT WideVT = EVT::getIntegerVT(*DAG.getContext(), VT.getScalarSizeInBits() * 2);
9192   if (VT.isVector())
9193     WideVT =
9194         EVT::getVectorVT(*DAG.getContext(), WideVT, VT.getVectorElementCount());
9195 
9196   SDValue BottomHalf;
9197   SDValue TopHalf;
9198   static const unsigned Ops[2][3] =
9199       { { ISD::MULHU, ISD::UMUL_LOHI, ISD::ZERO_EXTEND },
9200         { ISD::MULHS, ISD::SMUL_LOHI, ISD::SIGN_EXTEND }};
9201   if (isOperationLegalOrCustom(Ops[isSigned][0], VT)) {
9202     BottomHalf = DAG.getNode(ISD::MUL, dl, VT, LHS, RHS);
9203     TopHalf = DAG.getNode(Ops[isSigned][0], dl, VT, LHS, RHS);
9204   } else if (isOperationLegalOrCustom(Ops[isSigned][1], VT)) {
9205     BottomHalf = DAG.getNode(Ops[isSigned][1], dl, DAG.getVTList(VT, VT), LHS,
9206                              RHS);
9207     TopHalf = BottomHalf.getValue(1);
9208   } else if (isTypeLegal(WideVT)) {
9209     LHS = DAG.getNode(Ops[isSigned][2], dl, WideVT, LHS);
9210     RHS = DAG.getNode(Ops[isSigned][2], dl, WideVT, RHS);
9211     SDValue Mul = DAG.getNode(ISD::MUL, dl, WideVT, LHS, RHS);
9212     BottomHalf = DAG.getNode(ISD::TRUNCATE, dl, VT, Mul);
9213     SDValue ShiftAmt = DAG.getConstant(VT.getScalarSizeInBits(), dl,
9214         getShiftAmountTy(WideVT, DAG.getDataLayout()));
9215     TopHalf = DAG.getNode(ISD::TRUNCATE, dl, VT,
9216                           DAG.getNode(ISD::SRL, dl, WideVT, Mul, ShiftAmt));
9217   } else {
9218     if (VT.isVector())
9219       return false;
9220 
9221     // We can fall back to a libcall with an illegal type for the MUL if we
9222     // have a libcall big enough.
9223     // Also, we can fall back to a division in some cases, but that's a big
9224     // performance hit in the general case.
9225     RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
9226     if (WideVT == MVT::i16)
9227       LC = RTLIB::MUL_I16;
9228     else if (WideVT == MVT::i32)
9229       LC = RTLIB::MUL_I32;
9230     else if (WideVT == MVT::i64)
9231       LC = RTLIB::MUL_I64;
9232     else if (WideVT == MVT::i128)
9233       LC = RTLIB::MUL_I128;
9234     assert(LC != RTLIB::UNKNOWN_LIBCALL && "Cannot expand this operation!");
9235 
9236     SDValue HiLHS;
9237     SDValue HiRHS;
9238     if (isSigned) {
9239       // The high part is obtained by SRA'ing all but one of the bits of low
9240       // part.
9241       unsigned LoSize = VT.getFixedSizeInBits();
9242       HiLHS =
9243           DAG.getNode(ISD::SRA, dl, VT, LHS,
9244                       DAG.getConstant(LoSize - 1, dl,
9245                                       getPointerTy(DAG.getDataLayout())));
9246       HiRHS =
9247           DAG.getNode(ISD::SRA, dl, VT, RHS,
9248                       DAG.getConstant(LoSize - 1, dl,
9249                                       getPointerTy(DAG.getDataLayout())));
9250     } else {
9251         HiLHS = DAG.getConstant(0, dl, VT);
9252         HiRHS = DAG.getConstant(0, dl, VT);
9253     }
9254 
9255     // Here we're passing the 2 arguments explicitly as 4 arguments that are
9256     // pre-lowered to the correct types. This all depends upon WideVT not
9257     // being a legal type for the architecture and thus has to be split to
9258     // two arguments.
9259     SDValue Ret;
9260     TargetLowering::MakeLibCallOptions CallOptions;
9261     CallOptions.setSExt(isSigned);
9262     CallOptions.setIsPostTypeLegalization(true);
9263     if (shouldSplitFunctionArgumentsAsLittleEndian(DAG.getDataLayout())) {
9264       // Halves of WideVT are packed into registers in different order
9265       // depending on platform endianness. This is usually handled by
9266       // the C calling convention, but we can't defer to it in
9267       // the legalizer.
9268       SDValue Args[] = { LHS, HiLHS, RHS, HiRHS };
9269       Ret = makeLibCall(DAG, LC, WideVT, Args, CallOptions, dl).first;
9270     } else {
9271       SDValue Args[] = { HiLHS, LHS, HiRHS, RHS };
9272       Ret = makeLibCall(DAG, LC, WideVT, Args, CallOptions, dl).first;
9273     }
9274     assert(Ret.getOpcode() == ISD::MERGE_VALUES &&
9275            "Ret value is a collection of constituent nodes holding result.");
9276     if (DAG.getDataLayout().isLittleEndian()) {
9277       // Same as above.
9278       BottomHalf = Ret.getOperand(0);
9279       TopHalf = Ret.getOperand(1);
9280     } else {
9281       BottomHalf = Ret.getOperand(1);
9282       TopHalf = Ret.getOperand(0);
9283     }
9284   }
9285 
9286   Result = BottomHalf;
9287   if (isSigned) {
9288     SDValue ShiftAmt = DAG.getConstant(
9289         VT.getScalarSizeInBits() - 1, dl,
9290         getShiftAmountTy(BottomHalf.getValueType(), DAG.getDataLayout()));
9291     SDValue Sign = DAG.getNode(ISD::SRA, dl, VT, BottomHalf, ShiftAmt);
9292     Overflow = DAG.getSetCC(dl, SetCCVT, TopHalf, Sign, ISD::SETNE);
9293   } else {
9294     Overflow = DAG.getSetCC(dl, SetCCVT, TopHalf,
9295                             DAG.getConstant(0, dl, VT), ISD::SETNE);
9296   }
9297 
9298   // Truncate the result if SetCC returns a larger type than needed.
9299   EVT RType = Node->getValueType(1);
9300   if (RType.bitsLT(Overflow.getValueType()))
9301     Overflow = DAG.getNode(ISD::TRUNCATE, dl, RType, Overflow);
9302 
9303   assert(RType.getSizeInBits() == Overflow.getValueSizeInBits() &&
9304          "Unexpected result type for S/UMULO legalization");
9305   return true;
9306 }
9307 
9308 SDValue TargetLowering::expandVecReduce(SDNode *Node, SelectionDAG &DAG) const {
9309   SDLoc dl(Node);
9310   unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Node->getOpcode());
9311   SDValue Op = Node->getOperand(0);
9312   EVT VT = Op.getValueType();
9313 
9314   if (VT.isScalableVector())
9315     report_fatal_error(
9316         "Expanding reductions for scalable vectors is undefined.");
9317 
9318   // Try to use a shuffle reduction for power of two vectors.
9319   if (VT.isPow2VectorType()) {
9320     while (VT.getVectorNumElements() > 1) {
9321       EVT HalfVT = VT.getHalfNumVectorElementsVT(*DAG.getContext());
9322       if (!isOperationLegalOrCustom(BaseOpcode, HalfVT))
9323         break;
9324 
9325       SDValue Lo, Hi;
9326       std::tie(Lo, Hi) = DAG.SplitVector(Op, dl);
9327       Op = DAG.getNode(BaseOpcode, dl, HalfVT, Lo, Hi);
9328       VT = HalfVT;
9329     }
9330   }
9331 
9332   EVT EltVT = VT.getVectorElementType();
9333   unsigned NumElts = VT.getVectorNumElements();
9334 
9335   SmallVector<SDValue, 8> Ops;
9336   DAG.ExtractVectorElements(Op, Ops, 0, NumElts);
9337 
9338   SDValue Res = Ops[0];
9339   for (unsigned i = 1; i < NumElts; i++)
9340     Res = DAG.getNode(BaseOpcode, dl, EltVT, Res, Ops[i], Node->getFlags());
9341 
9342   // Result type may be wider than element type.
9343   if (EltVT != Node->getValueType(0))
9344     Res = DAG.getNode(ISD::ANY_EXTEND, dl, Node->getValueType(0), Res);
9345   return Res;
9346 }
9347 
9348 SDValue TargetLowering::expandVecReduceSeq(SDNode *Node, SelectionDAG &DAG) const {
9349   SDLoc dl(Node);
9350   SDValue AccOp = Node->getOperand(0);
9351   SDValue VecOp = Node->getOperand(1);
9352   SDNodeFlags Flags = Node->getFlags();
9353 
9354   EVT VT = VecOp.getValueType();
9355   EVT EltVT = VT.getVectorElementType();
9356 
9357   if (VT.isScalableVector())
9358     report_fatal_error(
9359         "Expanding reductions for scalable vectors is undefined.");
9360 
9361   unsigned NumElts = VT.getVectorNumElements();
9362 
9363   SmallVector<SDValue, 8> Ops;
9364   DAG.ExtractVectorElements(VecOp, Ops, 0, NumElts);
9365 
9366   unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Node->getOpcode());
9367 
9368   SDValue Res = AccOp;
9369   for (unsigned i = 0; i < NumElts; i++)
9370     Res = DAG.getNode(BaseOpcode, dl, EltVT, Res, Ops[i], Flags);
9371 
9372   return Res;
9373 }
9374 
9375 bool TargetLowering::expandREM(SDNode *Node, SDValue &Result,
9376                                SelectionDAG &DAG) const {
9377   EVT VT = Node->getValueType(0);
9378   SDLoc dl(Node);
9379   bool isSigned = Node->getOpcode() == ISD::SREM;
9380   unsigned DivOpc = isSigned ? ISD::SDIV : ISD::UDIV;
9381   unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
9382   SDValue Dividend = Node->getOperand(0);
9383   SDValue Divisor = Node->getOperand(1);
9384   if (isOperationLegalOrCustom(DivRemOpc, VT)) {
9385     SDVTList VTs = DAG.getVTList(VT, VT);
9386     Result = DAG.getNode(DivRemOpc, dl, VTs, Dividend, Divisor).getValue(1);
9387     return true;
9388   }
9389   if (isOperationLegalOrCustom(DivOpc, VT)) {
9390     // X % Y -> X-X/Y*Y
9391     SDValue Divide = DAG.getNode(DivOpc, dl, VT, Dividend, Divisor);
9392     SDValue Mul = DAG.getNode(ISD::MUL, dl, VT, Divide, Divisor);
9393     Result = DAG.getNode(ISD::SUB, dl, VT, Dividend, Mul);
9394     return true;
9395   }
9396   return false;
9397 }
9398 
9399 SDValue TargetLowering::expandFP_TO_INT_SAT(SDNode *Node,
9400                                             SelectionDAG &DAG) const {
9401   bool IsSigned = Node->getOpcode() == ISD::FP_TO_SINT_SAT;
9402   SDLoc dl(SDValue(Node, 0));
9403   SDValue Src = Node->getOperand(0);
9404 
9405   // DstVT is the result type, while SatVT is the size to which we saturate
9406   EVT SrcVT = Src.getValueType();
9407   EVT DstVT = Node->getValueType(0);
9408 
9409   EVT SatVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
9410   unsigned SatWidth = SatVT.getScalarSizeInBits();
9411   unsigned DstWidth = DstVT.getScalarSizeInBits();
9412   assert(SatWidth <= DstWidth &&
9413          "Expected saturation width smaller than result width");
9414 
9415   // Determine minimum and maximum integer values and their corresponding
9416   // floating-point values.
9417   APInt MinInt, MaxInt;
9418   if (IsSigned) {
9419     MinInt = APInt::getSignedMinValue(SatWidth).sext(DstWidth);
9420     MaxInt = APInt::getSignedMaxValue(SatWidth).sext(DstWidth);
9421   } else {
9422     MinInt = APInt::getMinValue(SatWidth).zext(DstWidth);
9423     MaxInt = APInt::getMaxValue(SatWidth).zext(DstWidth);
9424   }
9425 
9426   // We cannot risk emitting FP_TO_XINT nodes with a source VT of f16, as
9427   // libcall emission cannot handle this. Large result types will fail.
9428   if (SrcVT == MVT::f16) {
9429     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, Src);
9430     SrcVT = Src.getValueType();
9431   }
9432 
9433   APFloat MinFloat(DAG.EVTToAPFloatSemantics(SrcVT));
9434   APFloat MaxFloat(DAG.EVTToAPFloatSemantics(SrcVT));
9435 
9436   APFloat::opStatus MinStatus =
9437       MinFloat.convertFromAPInt(MinInt, IsSigned, APFloat::rmTowardZero);
9438   APFloat::opStatus MaxStatus =
9439       MaxFloat.convertFromAPInt(MaxInt, IsSigned, APFloat::rmTowardZero);
9440   bool AreExactFloatBounds = !(MinStatus & APFloat::opStatus::opInexact) &&
9441                              !(MaxStatus & APFloat::opStatus::opInexact);
9442 
9443   SDValue MinFloatNode = DAG.getConstantFP(MinFloat, dl, SrcVT);
9444   SDValue MaxFloatNode = DAG.getConstantFP(MaxFloat, dl, SrcVT);
9445 
9446   // If the integer bounds are exactly representable as floats and min/max are
9447   // legal, emit a min+max+fptoi sequence. Otherwise we have to use a sequence
9448   // of comparisons and selects.
9449   bool MinMaxLegal = isOperationLegal(ISD::FMINNUM, SrcVT) &&
9450                      isOperationLegal(ISD::FMAXNUM, SrcVT);
9451   if (AreExactFloatBounds && MinMaxLegal) {
9452     SDValue Clamped = Src;
9453 
9454     // Clamp Src by MinFloat from below. If Src is NaN the result is MinFloat.
9455     Clamped = DAG.getNode(ISD::FMAXNUM, dl, SrcVT, Clamped, MinFloatNode);
9456     // Clamp by MaxFloat from above. NaN cannot occur.
9457     Clamped = DAG.getNode(ISD::FMINNUM, dl, SrcVT, Clamped, MaxFloatNode);
9458     // Convert clamped value to integer.
9459     SDValue FpToInt = DAG.getNode(IsSigned ? ISD::FP_TO_SINT : ISD::FP_TO_UINT,
9460                                   dl, DstVT, Clamped);
9461 
9462     // In the unsigned case we're done, because we mapped NaN to MinFloat,
9463     // which will cast to zero.
9464     if (!IsSigned)
9465       return FpToInt;
9466 
9467     // Otherwise, select 0 if Src is NaN.
9468     SDValue ZeroInt = DAG.getConstant(0, dl, DstVT);
9469     return DAG.getSelectCC(dl, Src, Src, ZeroInt, FpToInt,
9470                            ISD::CondCode::SETUO);
9471   }
9472 
9473   SDValue MinIntNode = DAG.getConstant(MinInt, dl, DstVT);
9474   SDValue MaxIntNode = DAG.getConstant(MaxInt, dl, DstVT);
9475 
9476   // Result of direct conversion. The assumption here is that the operation is
9477   // non-trapping and it's fine to apply it to an out-of-range value if we
9478   // select it away later.
9479   SDValue FpToInt =
9480       DAG.getNode(IsSigned ? ISD::FP_TO_SINT : ISD::FP_TO_UINT, dl, DstVT, Src);
9481 
9482   SDValue Select = FpToInt;
9483 
9484   // If Src ULT MinFloat, select MinInt. In particular, this also selects
9485   // MinInt if Src is NaN.
9486   Select = DAG.getSelectCC(dl, Src, MinFloatNode, MinIntNode, Select,
9487                            ISD::CondCode::SETULT);
9488   // If Src OGT MaxFloat, select MaxInt.
9489   Select = DAG.getSelectCC(dl, Src, MaxFloatNode, MaxIntNode, Select,
9490                            ISD::CondCode::SETOGT);
9491 
9492   // In the unsigned case we are done, because we mapped NaN to MinInt, which
9493   // is already zero.
9494   if (!IsSigned)
9495     return Select;
9496 
9497   // Otherwise, select 0 if Src is NaN.
9498   SDValue ZeroInt = DAG.getConstant(0, dl, DstVT);
9499   return DAG.getSelectCC(dl, Src, Src, ZeroInt, Select, ISD::CondCode::SETUO);
9500 }
9501 
9502 SDValue TargetLowering::expandVectorSplice(SDNode *Node,
9503                                            SelectionDAG &DAG) const {
9504   assert(Node->getOpcode() == ISD::VECTOR_SPLICE && "Unexpected opcode!");
9505   assert(Node->getValueType(0).isScalableVector() &&
9506          "Fixed length vector types expected to use SHUFFLE_VECTOR!");
9507 
9508   EVT VT = Node->getValueType(0);
9509   SDValue V1 = Node->getOperand(0);
9510   SDValue V2 = Node->getOperand(1);
9511   int64_t Imm = cast<ConstantSDNode>(Node->getOperand(2))->getSExtValue();
9512   SDLoc DL(Node);
9513 
9514   // Expand through memory thusly:
9515   //  Alloca CONCAT_VECTORS_TYPES(V1, V2) Ptr
9516   //  Store V1, Ptr
9517   //  Store V2, Ptr + sizeof(V1)
9518   //  If (Imm < 0)
9519   //    TrailingElts = -Imm
9520   //    Ptr = Ptr + sizeof(V1) - (TrailingElts * sizeof(VT.Elt))
9521   //  else
9522   //    Ptr = Ptr + (Imm * sizeof(VT.Elt))
9523   //  Res = Load Ptr
9524 
9525   Align Alignment = DAG.getReducedAlign(VT, /*UseABI=*/false);
9526 
9527   EVT MemVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
9528                                VT.getVectorElementCount() * 2);
9529   SDValue StackPtr = DAG.CreateStackTemporary(MemVT.getStoreSize(), Alignment);
9530   EVT PtrVT = StackPtr.getValueType();
9531   auto &MF = DAG.getMachineFunction();
9532   auto FrameIndex = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
9533   auto PtrInfo = MachinePointerInfo::getFixedStack(MF, FrameIndex);
9534 
9535   // Store the lo part of CONCAT_VECTORS(V1, V2)
9536   SDValue StoreV1 = DAG.getStore(DAG.getEntryNode(), DL, V1, StackPtr, PtrInfo);
9537   // Store the hi part of CONCAT_VECTORS(V1, V2)
9538   SDValue OffsetToV2 = DAG.getVScale(
9539       DL, PtrVT,
9540       APInt(PtrVT.getFixedSizeInBits(), VT.getStoreSize().getKnownMinSize()));
9541   SDValue StackPtr2 = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, OffsetToV2);
9542   SDValue StoreV2 = DAG.getStore(StoreV1, DL, V2, StackPtr2, PtrInfo);
9543 
9544   if (Imm >= 0) {
9545     // Load back the required element. getVectorElementPointer takes care of
9546     // clamping the index if it's out-of-bounds.
9547     StackPtr = getVectorElementPointer(DAG, StackPtr, VT, Node->getOperand(2));
9548     // Load the spliced result
9549     return DAG.getLoad(VT, DL, StoreV2, StackPtr,
9550                        MachinePointerInfo::getUnknownStack(MF));
9551   }
9552 
9553   uint64_t TrailingElts = -Imm;
9554 
9555   // NOTE: TrailingElts must be clamped so as not to read outside of V1:V2.
9556   TypeSize EltByteSize = VT.getVectorElementType().getStoreSize();
9557   SDValue TrailingBytes =
9558       DAG.getConstant(TrailingElts * EltByteSize, DL, PtrVT);
9559 
9560   if (TrailingElts > VT.getVectorMinNumElements()) {
9561     SDValue VLBytes = DAG.getVScale(
9562         DL, PtrVT,
9563         APInt(PtrVT.getFixedSizeInBits(), VT.getStoreSize().getKnownMinSize()));
9564     TrailingBytes = DAG.getNode(ISD::UMIN, DL, PtrVT, TrailingBytes, VLBytes);
9565   }
9566 
9567   // Calculate the start address of the spliced result.
9568   StackPtr2 = DAG.getNode(ISD::SUB, DL, PtrVT, StackPtr2, TrailingBytes);
9569 
9570   // Load the spliced result
9571   return DAG.getLoad(VT, DL, StoreV2, StackPtr2,
9572                      MachinePointerInfo::getUnknownStack(MF));
9573 }
9574 
9575 bool TargetLowering::LegalizeSetCCCondCode(SelectionDAG &DAG, EVT VT,
9576                                            SDValue &LHS, SDValue &RHS,
9577                                            SDValue &CC, SDValue Mask,
9578                                            SDValue EVL, bool &NeedInvert,
9579                                            const SDLoc &dl, SDValue &Chain,
9580                                            bool IsSignaling) const {
9581   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9582   MVT OpVT = LHS.getSimpleValueType();
9583   ISD::CondCode CCCode = cast<CondCodeSDNode>(CC)->get();
9584   NeedInvert = false;
9585   assert(!EVL == !Mask && "VP Mask and EVL must either both be set or unset");
9586   bool IsNonVP = !EVL;
9587   switch (TLI.getCondCodeAction(CCCode, OpVT)) {
9588   default:
9589     llvm_unreachable("Unknown condition code action!");
9590   case TargetLowering::Legal:
9591     // Nothing to do.
9592     break;
9593   case TargetLowering::Expand: {
9594     ISD::CondCode InvCC = ISD::getSetCCSwappedOperands(CCCode);
9595     if (TLI.isCondCodeLegalOrCustom(InvCC, OpVT)) {
9596       std::swap(LHS, RHS);
9597       CC = DAG.getCondCode(InvCC);
9598       return true;
9599     }
9600     // Swapping operands didn't work. Try inverting the condition.
9601     bool NeedSwap = false;
9602     InvCC = getSetCCInverse(CCCode, OpVT);
9603     if (!TLI.isCondCodeLegalOrCustom(InvCC, OpVT)) {
9604       // If inverting the condition is not enough, try swapping operands
9605       // on top of it.
9606       InvCC = ISD::getSetCCSwappedOperands(InvCC);
9607       NeedSwap = true;
9608     }
9609     if (TLI.isCondCodeLegalOrCustom(InvCC, OpVT)) {
9610       CC = DAG.getCondCode(InvCC);
9611       NeedInvert = true;
9612       if (NeedSwap)
9613         std::swap(LHS, RHS);
9614       return true;
9615     }
9616 
9617     ISD::CondCode CC1 = ISD::SETCC_INVALID, CC2 = ISD::SETCC_INVALID;
9618     unsigned Opc = 0;
9619     switch (CCCode) {
9620     default:
9621       llvm_unreachable("Don't know how to expand this condition!");
9622     case ISD::SETUO:
9623       if (TLI.isCondCodeLegal(ISD::SETUNE, OpVT)) {
9624         CC1 = ISD::SETUNE;
9625         CC2 = ISD::SETUNE;
9626         Opc = ISD::OR;
9627         break;
9628       }
9629       assert(TLI.isCondCodeLegal(ISD::SETOEQ, OpVT) &&
9630              "If SETUE is expanded, SETOEQ or SETUNE must be legal!");
9631       NeedInvert = true;
9632       LLVM_FALLTHROUGH;
9633     case ISD::SETO:
9634       assert(TLI.isCondCodeLegal(ISD::SETOEQ, OpVT) &&
9635              "If SETO is expanded, SETOEQ must be legal!");
9636       CC1 = ISD::SETOEQ;
9637       CC2 = ISD::SETOEQ;
9638       Opc = ISD::AND;
9639       break;
9640     case ISD::SETONE:
9641     case ISD::SETUEQ:
9642       // If the SETUO or SETO CC isn't legal, we might be able to use
9643       // SETOGT || SETOLT, inverting the result for SETUEQ. We only need one
9644       // of SETOGT/SETOLT to be legal, the other can be emulated by swapping
9645       // the operands.
9646       CC2 = ((unsigned)CCCode & 0x8U) ? ISD::SETUO : ISD::SETO;
9647       if (!TLI.isCondCodeLegal(CC2, OpVT) &&
9648           (TLI.isCondCodeLegal(ISD::SETOGT, OpVT) ||
9649            TLI.isCondCodeLegal(ISD::SETOLT, OpVT))) {
9650         CC1 = ISD::SETOGT;
9651         CC2 = ISD::SETOLT;
9652         Opc = ISD::OR;
9653         NeedInvert = ((unsigned)CCCode & 0x8U);
9654         break;
9655       }
9656       LLVM_FALLTHROUGH;
9657     case ISD::SETOEQ:
9658     case ISD::SETOGT:
9659     case ISD::SETOGE:
9660     case ISD::SETOLT:
9661     case ISD::SETOLE:
9662     case ISD::SETUNE:
9663     case ISD::SETUGT:
9664     case ISD::SETUGE:
9665     case ISD::SETULT:
9666     case ISD::SETULE:
9667       // If we are floating point, assign and break, otherwise fall through.
9668       if (!OpVT.isInteger()) {
9669         // We can use the 4th bit to tell if we are the unordered
9670         // or ordered version of the opcode.
9671         CC2 = ((unsigned)CCCode & 0x8U) ? ISD::SETUO : ISD::SETO;
9672         Opc = ((unsigned)CCCode & 0x8U) ? ISD::OR : ISD::AND;
9673         CC1 = (ISD::CondCode)(((int)CCCode & 0x7) | 0x10);
9674         break;
9675       }
9676       // Fallthrough if we are unsigned integer.
9677       LLVM_FALLTHROUGH;
9678     case ISD::SETLE:
9679     case ISD::SETGT:
9680     case ISD::SETGE:
9681     case ISD::SETLT:
9682     case ISD::SETNE:
9683     case ISD::SETEQ:
9684       // If all combinations of inverting the condition and swapping operands
9685       // didn't work then we have no means to expand the condition.
9686       llvm_unreachable("Don't know how to expand this condition!");
9687     }
9688 
9689     SDValue SetCC1, SetCC2;
9690     if (CCCode != ISD::SETO && CCCode != ISD::SETUO) {
9691       // If we aren't the ordered or unorder operation,
9692       // then the pattern is (LHS CC1 RHS) Opc (LHS CC2 RHS).
9693       if (IsNonVP) {
9694         SetCC1 = DAG.getSetCC(dl, VT, LHS, RHS, CC1, Chain, IsSignaling);
9695         SetCC2 = DAG.getSetCC(dl, VT, LHS, RHS, CC2, Chain, IsSignaling);
9696       } else {
9697         SetCC1 = DAG.getSetCCVP(dl, VT, LHS, RHS, CC1, Mask, EVL);
9698         SetCC2 = DAG.getSetCCVP(dl, VT, LHS, RHS, CC2, Mask, EVL);
9699       }
9700     } else {
9701       // Otherwise, the pattern is (LHS CC1 LHS) Opc (RHS CC2 RHS)
9702       if (IsNonVP) {
9703         SetCC1 = DAG.getSetCC(dl, VT, LHS, LHS, CC1, Chain, IsSignaling);
9704         SetCC2 = DAG.getSetCC(dl, VT, RHS, RHS, CC2, Chain, IsSignaling);
9705       } else {
9706         SetCC1 = DAG.getSetCCVP(dl, VT, LHS, LHS, CC1, Mask, EVL);
9707         SetCC2 = DAG.getSetCCVP(dl, VT, RHS, RHS, CC2, Mask, EVL);
9708       }
9709     }
9710     if (Chain)
9711       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, SetCC1.getValue(1),
9712                           SetCC2.getValue(1));
9713     if (IsNonVP)
9714       LHS = DAG.getNode(Opc, dl, VT, SetCC1, SetCC2);
9715     else {
9716       // Transform the binary opcode to the VP equivalent.
9717       assert((Opc == ISD::OR || Opc == ISD::AND) && "Unexpected opcode");
9718       Opc = Opc == ISD::OR ? ISD::VP_OR : ISD::VP_AND;
9719       LHS = DAG.getNode(Opc, dl, VT, SetCC1, SetCC2, Mask, EVL);
9720     }
9721     RHS = SDValue();
9722     CC = SDValue();
9723     return true;
9724   }
9725   }
9726   return false;
9727 }
9728