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/MachineFrameInfo.h"
17 #include "llvm/CodeGen/MachineFunction.h"
18 #include "llvm/CodeGen/MachineJumpTableInfo.h"
19 #include "llvm/CodeGen/MachineRegisterInfo.h"
20 #include "llvm/CodeGen/SelectionDAG.h"
21 #include "llvm/CodeGen/TargetRegisterInfo.h"
22 #include "llvm/IR/DataLayout.h"
23 #include "llvm/IR/DerivedTypes.h"
24 #include "llvm/IR/GlobalVariable.h"
25 #include "llvm/IR/LLVMContext.h"
26 #include "llvm/MC/MCAsmInfo.h"
27 #include "llvm/MC/MCExpr.h"
28 #include "llvm/Support/DivisionByConstantInfo.h"
29 #include "llvm/Support/ErrorHandling.h"
30 #include "llvm/Support/KnownBits.h"
31 #include "llvm/Support/MathExtras.h"
32 #include "llvm/Target/TargetMachine.h"
33 #include <cctype>
34 using namespace llvm;
35 
36 /// NOTE: The TargetMachine owns TLOF.
37 TargetLowering::TargetLowering(const TargetMachine &tm)
38     : TargetLoweringBase(tm) {}
39 
40 const char *TargetLowering::getTargetNodeName(unsigned Opcode) const {
41   return nullptr;
42 }
43 
44 bool TargetLowering::isPositionIndependent() const {
45   return getTargetMachine().isPositionIndependent();
46 }
47 
48 /// Check whether a given call node is in tail position within its function. If
49 /// so, it sets Chain to the input chain of the tail call.
50 bool TargetLowering::isInTailCallPosition(SelectionDAG &DAG, SDNode *Node,
51                                           SDValue &Chain) const {
52   const Function &F = DAG.getMachineFunction().getFunction();
53 
54   // First, check if tail calls have been disabled in this function.
55   if (F.getFnAttribute("disable-tail-calls").getValueAsBool())
56     return false;
57 
58   // Conservatively require the attributes of the call to match those of
59   // the return. Ignore following attributes because they don't affect the
60   // call sequence.
61   AttrBuilder CallerAttrs(F.getContext(), F.getAttributes().getRetAttrs());
62   for (const auto &Attr : {Attribute::Alignment, Attribute::Dereferenceable,
63                            Attribute::DereferenceableOrNull, Attribute::NoAlias,
64                            Attribute::NonNull, Attribute::NoUndef})
65     CallerAttrs.removeAttribute(Attr);
66 
67   if (CallerAttrs.hasAttributes())
68     return false;
69 
70   // It's not safe to eliminate the sign / zero extension of the return value.
71   if (CallerAttrs.contains(Attribute::ZExt) ||
72       CallerAttrs.contains(Attribute::SExt))
73     return false;
74 
75   // Check if the only use is a function return node.
76   return isUsedByReturnOnly(Node, Chain);
77 }
78 
79 bool TargetLowering::parametersInCSRMatch(const MachineRegisterInfo &MRI,
80     const uint32_t *CallerPreservedMask,
81     const SmallVectorImpl<CCValAssign> &ArgLocs,
82     const SmallVectorImpl<SDValue> &OutVals) const {
83   for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
84     const CCValAssign &ArgLoc = ArgLocs[I];
85     if (!ArgLoc.isRegLoc())
86       continue;
87     MCRegister Reg = ArgLoc.getLocReg();
88     // Only look at callee saved registers.
89     if (MachineOperand::clobbersPhysReg(CallerPreservedMask, Reg))
90       continue;
91     // Check that we pass the value used for the caller.
92     // (We look for a CopyFromReg reading a virtual register that is used
93     //  for the function live-in value of register Reg)
94     SDValue Value = OutVals[I];
95     if (Value->getOpcode() != ISD::CopyFromReg)
96       return false;
97     Register ArgReg = cast<RegisterSDNode>(Value->getOperand(1))->getReg();
98     if (MRI.getLiveInPhysReg(ArgReg) != Reg)
99       return false;
100   }
101   return true;
102 }
103 
104 /// Set CallLoweringInfo attribute flags based on a call instruction
105 /// and called function attributes.
106 void TargetLoweringBase::ArgListEntry::setAttributes(const CallBase *Call,
107                                                      unsigned ArgIdx) {
108   IsSExt = Call->paramHasAttr(ArgIdx, Attribute::SExt);
109   IsZExt = Call->paramHasAttr(ArgIdx, Attribute::ZExt);
110   IsInReg = Call->paramHasAttr(ArgIdx, Attribute::InReg);
111   IsSRet = Call->paramHasAttr(ArgIdx, Attribute::StructRet);
112   IsNest = Call->paramHasAttr(ArgIdx, Attribute::Nest);
113   IsByVal = Call->paramHasAttr(ArgIdx, Attribute::ByVal);
114   IsPreallocated = Call->paramHasAttr(ArgIdx, Attribute::Preallocated);
115   IsInAlloca = Call->paramHasAttr(ArgIdx, Attribute::InAlloca);
116   IsReturned = Call->paramHasAttr(ArgIdx, Attribute::Returned);
117   IsSwiftSelf = Call->paramHasAttr(ArgIdx, Attribute::SwiftSelf);
118   IsSwiftAsync = Call->paramHasAttr(ArgIdx, Attribute::SwiftAsync);
119   IsSwiftError = Call->paramHasAttr(ArgIdx, Attribute::SwiftError);
120   Alignment = Call->getParamStackAlign(ArgIdx);
121   IndirectType = nullptr;
122   assert(IsByVal + IsPreallocated + IsInAlloca + IsSRet <= 1 &&
123          "multiple ABI attributes?");
124   if (IsByVal) {
125     IndirectType = Call->getParamByValType(ArgIdx);
126     if (!Alignment)
127       Alignment = Call->getParamAlign(ArgIdx);
128   }
129   if (IsPreallocated)
130     IndirectType = Call->getParamPreallocatedType(ArgIdx);
131   if (IsInAlloca)
132     IndirectType = Call->getParamInAllocaType(ArgIdx);
133   if (IsSRet)
134     IndirectType = Call->getParamStructRetType(ArgIdx);
135 }
136 
137 /// Generate a libcall taking the given operands as arguments and returning a
138 /// result of type RetVT.
139 std::pair<SDValue, SDValue>
140 TargetLowering::makeLibCall(SelectionDAG &DAG, RTLIB::Libcall LC, EVT RetVT,
141                             ArrayRef<SDValue> Ops,
142                             MakeLibCallOptions CallOptions,
143                             const SDLoc &dl,
144                             SDValue InChain) const {
145   if (!InChain)
146     InChain = DAG.getEntryNode();
147 
148   TargetLowering::ArgListTy Args;
149   Args.reserve(Ops.size());
150 
151   TargetLowering::ArgListEntry Entry;
152   for (unsigned i = 0; i < Ops.size(); ++i) {
153     SDValue NewOp = Ops[i];
154     Entry.Node = NewOp;
155     Entry.Ty = Entry.Node.getValueType().getTypeForEVT(*DAG.getContext());
156     Entry.IsSExt = shouldSignExtendTypeInLibCall(NewOp.getValueType(),
157                                                  CallOptions.IsSExt);
158     Entry.IsZExt = !Entry.IsSExt;
159 
160     if (CallOptions.IsSoften &&
161         !shouldExtendTypeInLibCall(CallOptions.OpsVTBeforeSoften[i])) {
162       Entry.IsSExt = Entry.IsZExt = false;
163     }
164     Args.push_back(Entry);
165   }
166 
167   if (LC == RTLIB::UNKNOWN_LIBCALL)
168     report_fatal_error("Unsupported library call operation!");
169   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
170                                          getPointerTy(DAG.getDataLayout()));
171 
172   Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext());
173   TargetLowering::CallLoweringInfo CLI(DAG);
174   bool signExtend = shouldSignExtendTypeInLibCall(RetVT, CallOptions.IsSExt);
175   bool zeroExtend = !signExtend;
176 
177   if (CallOptions.IsSoften &&
178       !shouldExtendTypeInLibCall(CallOptions.RetVTBeforeSoften)) {
179     signExtend = zeroExtend = false;
180   }
181 
182   CLI.setDebugLoc(dl)
183       .setChain(InChain)
184       .setLibCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args))
185       .setNoReturn(CallOptions.DoesNotReturn)
186       .setDiscardResult(!CallOptions.IsReturnValueUsed)
187       .setIsPostTypeLegalization(CallOptions.IsPostTypeLegalization)
188       .setSExtResult(signExtend)
189       .setZExtResult(zeroExtend);
190   return LowerCallTo(CLI);
191 }
192 
193 bool TargetLowering::findOptimalMemOpLowering(
194     std::vector<EVT> &MemOps, unsigned Limit, const MemOp &Op, unsigned DstAS,
195     unsigned SrcAS, const AttributeList &FuncAttributes) const {
196   if (Op.isMemcpyWithFixedDstAlign() && Op.getSrcAlign() < Op.getDstAlign())
197     return false;
198 
199   EVT VT = getOptimalMemOpType(Op, FuncAttributes);
200 
201   if (VT == MVT::Other) {
202     // Use the largest integer type whose alignment constraints are satisfied.
203     // We only need to check DstAlign here as SrcAlign is always greater or
204     // equal to DstAlign (or zero).
205     VT = MVT::i64;
206     if (Op.isFixedDstAlign())
207       while (Op.getDstAlign() < (VT.getSizeInBits() / 8) &&
208              !allowsMisalignedMemoryAccesses(VT, DstAS, Op.getDstAlign()))
209         VT = (MVT::SimpleValueType)(VT.getSimpleVT().SimpleTy - 1);
210     assert(VT.isInteger());
211 
212     // Find the largest legal integer type.
213     MVT LVT = MVT::i64;
214     while (!isTypeLegal(LVT))
215       LVT = (MVT::SimpleValueType)(LVT.SimpleTy - 1);
216     assert(LVT.isInteger());
217 
218     // If the type we've chosen is larger than the largest legal integer type
219     // then use that instead.
220     if (VT.bitsGT(LVT))
221       VT = LVT;
222   }
223 
224   unsigned NumMemOps = 0;
225   uint64_t Size = Op.size();
226   while (Size) {
227     unsigned VTSize = VT.getSizeInBits() / 8;
228     while (VTSize > Size) {
229       // For now, only use non-vector load / store's for the left-over pieces.
230       EVT NewVT = VT;
231       unsigned NewVTSize;
232 
233       bool Found = false;
234       if (VT.isVector() || VT.isFloatingPoint()) {
235         NewVT = (VT.getSizeInBits() > 64) ? MVT::i64 : MVT::i32;
236         if (isOperationLegalOrCustom(ISD::STORE, NewVT) &&
237             isSafeMemOpType(NewVT.getSimpleVT()))
238           Found = true;
239         else if (NewVT == MVT::i64 &&
240                  isOperationLegalOrCustom(ISD::STORE, MVT::f64) &&
241                  isSafeMemOpType(MVT::f64)) {
242           // i64 is usually not legal on 32-bit targets, but f64 may be.
243           NewVT = MVT::f64;
244           Found = true;
245         }
246       }
247 
248       if (!Found) {
249         do {
250           NewVT = (MVT::SimpleValueType)(NewVT.getSimpleVT().SimpleTy - 1);
251           if (NewVT == MVT::i8)
252             break;
253         } while (!isSafeMemOpType(NewVT.getSimpleVT()));
254       }
255       NewVTSize = NewVT.getSizeInBits() / 8;
256 
257       // If the new VT cannot cover all of the remaining bits, then consider
258       // issuing a (or a pair of) unaligned and overlapping load / store.
259       bool Fast;
260       if (NumMemOps && Op.allowOverlap() && NewVTSize < Size &&
261           allowsMisalignedMemoryAccesses(
262               VT, DstAS, Op.isFixedDstAlign() ? Op.getDstAlign() : Align(1),
263               MachineMemOperand::MONone, &Fast) &&
264           Fast)
265         VTSize = Size;
266       else {
267         VT = NewVT;
268         VTSize = NewVTSize;
269       }
270     }
271 
272     if (++NumMemOps > Limit)
273       return false;
274 
275     MemOps.push_back(VT);
276     Size -= VTSize;
277   }
278 
279   return true;
280 }
281 
282 /// Soften the operands of a comparison. This code is shared among BR_CC,
283 /// SELECT_CC, and SETCC handlers.
284 void TargetLowering::softenSetCCOperands(SelectionDAG &DAG, EVT VT,
285                                          SDValue &NewLHS, SDValue &NewRHS,
286                                          ISD::CondCode &CCCode,
287                                          const SDLoc &dl, const SDValue OldLHS,
288                                          const SDValue OldRHS) const {
289   SDValue Chain;
290   return softenSetCCOperands(DAG, VT, NewLHS, NewRHS, CCCode, dl, OldLHS,
291                              OldRHS, Chain);
292 }
293 
294 void TargetLowering::softenSetCCOperands(SelectionDAG &DAG, EVT VT,
295                                          SDValue &NewLHS, SDValue &NewRHS,
296                                          ISD::CondCode &CCCode,
297                                          const SDLoc &dl, const SDValue OldLHS,
298                                          const SDValue OldRHS,
299                                          SDValue &Chain,
300                                          bool IsSignaling) const {
301   // FIXME: Currently we cannot really respect all IEEE predicates due to libgcc
302   // not supporting it. We can update this code when libgcc provides such
303   // functions.
304 
305   assert((VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128 || VT == MVT::ppcf128)
306          && "Unsupported setcc type!");
307 
308   // Expand into one or more soft-fp libcall(s).
309   RTLIB::Libcall LC1 = RTLIB::UNKNOWN_LIBCALL, LC2 = RTLIB::UNKNOWN_LIBCALL;
310   bool ShouldInvertCC = false;
311   switch (CCCode) {
312   case ISD::SETEQ:
313   case ISD::SETOEQ:
314     LC1 = (VT == MVT::f32) ? RTLIB::OEQ_F32 :
315           (VT == MVT::f64) ? RTLIB::OEQ_F64 :
316           (VT == MVT::f128) ? RTLIB::OEQ_F128 : RTLIB::OEQ_PPCF128;
317     break;
318   case ISD::SETNE:
319   case ISD::SETUNE:
320     LC1 = (VT == MVT::f32) ? RTLIB::UNE_F32 :
321           (VT == MVT::f64) ? RTLIB::UNE_F64 :
322           (VT == MVT::f128) ? RTLIB::UNE_F128 : RTLIB::UNE_PPCF128;
323     break;
324   case ISD::SETGE:
325   case ISD::SETOGE:
326     LC1 = (VT == MVT::f32) ? RTLIB::OGE_F32 :
327           (VT == MVT::f64) ? RTLIB::OGE_F64 :
328           (VT == MVT::f128) ? RTLIB::OGE_F128 : RTLIB::OGE_PPCF128;
329     break;
330   case ISD::SETLT:
331   case ISD::SETOLT:
332     LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 :
333           (VT == MVT::f64) ? RTLIB::OLT_F64 :
334           (VT == MVT::f128) ? RTLIB::OLT_F128 : RTLIB::OLT_PPCF128;
335     break;
336   case ISD::SETLE:
337   case ISD::SETOLE:
338     LC1 = (VT == MVT::f32) ? RTLIB::OLE_F32 :
339           (VT == MVT::f64) ? RTLIB::OLE_F64 :
340           (VT == MVT::f128) ? RTLIB::OLE_F128 : RTLIB::OLE_PPCF128;
341     break;
342   case ISD::SETGT:
343   case ISD::SETOGT:
344     LC1 = (VT == MVT::f32) ? RTLIB::OGT_F32 :
345           (VT == MVT::f64) ? RTLIB::OGT_F64 :
346           (VT == MVT::f128) ? RTLIB::OGT_F128 : RTLIB::OGT_PPCF128;
347     break;
348   case ISD::SETO:
349     ShouldInvertCC = true;
350     LLVM_FALLTHROUGH;
351   case ISD::SETUO:
352     LC1 = (VT == MVT::f32) ? RTLIB::UO_F32 :
353           (VT == MVT::f64) ? RTLIB::UO_F64 :
354           (VT == MVT::f128) ? RTLIB::UO_F128 : RTLIB::UO_PPCF128;
355     break;
356   case ISD::SETONE:
357     // SETONE = O && UNE
358     ShouldInvertCC = true;
359     LLVM_FALLTHROUGH;
360   case ISD::SETUEQ:
361     LC1 = (VT == MVT::f32) ? RTLIB::UO_F32 :
362           (VT == MVT::f64) ? RTLIB::UO_F64 :
363           (VT == MVT::f128) ? RTLIB::UO_F128 : RTLIB::UO_PPCF128;
364     LC2 = (VT == MVT::f32) ? RTLIB::OEQ_F32 :
365           (VT == MVT::f64) ? RTLIB::OEQ_F64 :
366           (VT == MVT::f128) ? RTLIB::OEQ_F128 : RTLIB::OEQ_PPCF128;
367     break;
368   default:
369     // Invert CC for unordered comparisons
370     ShouldInvertCC = true;
371     switch (CCCode) {
372     case ISD::SETULT:
373       LC1 = (VT == MVT::f32) ? RTLIB::OGE_F32 :
374             (VT == MVT::f64) ? RTLIB::OGE_F64 :
375             (VT == MVT::f128) ? RTLIB::OGE_F128 : RTLIB::OGE_PPCF128;
376       break;
377     case ISD::SETULE:
378       LC1 = (VT == MVT::f32) ? RTLIB::OGT_F32 :
379             (VT == MVT::f64) ? RTLIB::OGT_F64 :
380             (VT == MVT::f128) ? RTLIB::OGT_F128 : RTLIB::OGT_PPCF128;
381       break;
382     case ISD::SETUGT:
383       LC1 = (VT == MVT::f32) ? RTLIB::OLE_F32 :
384             (VT == MVT::f64) ? RTLIB::OLE_F64 :
385             (VT == MVT::f128) ? RTLIB::OLE_F128 : RTLIB::OLE_PPCF128;
386       break;
387     case ISD::SETUGE:
388       LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 :
389             (VT == MVT::f64) ? RTLIB::OLT_F64 :
390             (VT == MVT::f128) ? RTLIB::OLT_F128 : RTLIB::OLT_PPCF128;
391       break;
392     default: llvm_unreachable("Do not know how to soften this setcc!");
393     }
394   }
395 
396   // Use the target specific return value for comparions lib calls.
397   EVT RetVT = getCmpLibcallReturnType();
398   SDValue Ops[2] = {NewLHS, NewRHS};
399   TargetLowering::MakeLibCallOptions CallOptions;
400   EVT OpsVT[2] = { OldLHS.getValueType(),
401                    OldRHS.getValueType() };
402   CallOptions.setTypeListBeforeSoften(OpsVT, RetVT, true);
403   auto Call = makeLibCall(DAG, LC1, RetVT, Ops, CallOptions, dl, Chain);
404   NewLHS = Call.first;
405   NewRHS = DAG.getConstant(0, dl, RetVT);
406 
407   CCCode = getCmpLibcallCC(LC1);
408   if (ShouldInvertCC) {
409     assert(RetVT.isInteger());
410     CCCode = getSetCCInverse(CCCode, RetVT);
411   }
412 
413   if (LC2 == RTLIB::UNKNOWN_LIBCALL) {
414     // Update Chain.
415     Chain = Call.second;
416   } else {
417     EVT SetCCVT =
418         getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), RetVT);
419     SDValue Tmp = DAG.getSetCC(dl, SetCCVT, NewLHS, NewRHS, CCCode);
420     auto Call2 = makeLibCall(DAG, LC2, RetVT, Ops, CallOptions, dl, Chain);
421     CCCode = getCmpLibcallCC(LC2);
422     if (ShouldInvertCC)
423       CCCode = getSetCCInverse(CCCode, RetVT);
424     NewLHS = DAG.getSetCC(dl, SetCCVT, Call2.first, NewRHS, CCCode);
425     if (Chain)
426       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Call.second,
427                           Call2.second);
428     NewLHS = DAG.getNode(ShouldInvertCC ? ISD::AND : ISD::OR, dl,
429                          Tmp.getValueType(), Tmp, NewLHS);
430     NewRHS = SDValue();
431   }
432 }
433 
434 /// Return the entry encoding for a jump table in the current function. The
435 /// returned value is a member of the MachineJumpTableInfo::JTEntryKind enum.
436 unsigned TargetLowering::getJumpTableEncoding() const {
437   // In non-pic modes, just use the address of a block.
438   if (!isPositionIndependent())
439     return MachineJumpTableInfo::EK_BlockAddress;
440 
441   // In PIC mode, if the target supports a GPRel32 directive, use it.
442   if (getTargetMachine().getMCAsmInfo()->getGPRel32Directive() != nullptr)
443     return MachineJumpTableInfo::EK_GPRel32BlockAddress;
444 
445   // Otherwise, use a label difference.
446   return MachineJumpTableInfo::EK_LabelDifference32;
447 }
448 
449 SDValue TargetLowering::getPICJumpTableRelocBase(SDValue Table,
450                                                  SelectionDAG &DAG) const {
451   // If our PIC model is GP relative, use the global offset table as the base.
452   unsigned JTEncoding = getJumpTableEncoding();
453 
454   if ((JTEncoding == MachineJumpTableInfo::EK_GPRel64BlockAddress) ||
455       (JTEncoding == MachineJumpTableInfo::EK_GPRel32BlockAddress))
456     return DAG.getGLOBAL_OFFSET_TABLE(getPointerTy(DAG.getDataLayout()));
457 
458   return Table;
459 }
460 
461 /// This returns the relocation base for the given PIC jumptable, the same as
462 /// getPICJumpTableRelocBase, but as an MCExpr.
463 const MCExpr *
464 TargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
465                                              unsigned JTI,MCContext &Ctx) const{
466   // The normal PIC reloc base is the label at the start of the jump table.
467   return MCSymbolRefExpr::create(MF->getJTISymbol(JTI, Ctx), Ctx);
468 }
469 
470 bool
471 TargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
472   const TargetMachine &TM = getTargetMachine();
473   const GlobalValue *GV = GA->getGlobal();
474 
475   // If the address is not even local to this DSO we will have to load it from
476   // a got and then add the offset.
477   if (!TM.shouldAssumeDSOLocal(*GV->getParent(), GV))
478     return false;
479 
480   // If the code is position independent we will have to add a base register.
481   if (isPositionIndependent())
482     return false;
483 
484   // Otherwise we can do it.
485   return true;
486 }
487 
488 //===----------------------------------------------------------------------===//
489 //  Optimization Methods
490 //===----------------------------------------------------------------------===//
491 
492 /// If the specified instruction has a constant integer operand and there are
493 /// bits set in that constant that are not demanded, then clear those bits and
494 /// return true.
495 bool TargetLowering::ShrinkDemandedConstant(SDValue Op,
496                                             const APInt &DemandedBits,
497                                             const APInt &DemandedElts,
498                                             TargetLoweringOpt &TLO) const {
499   SDLoc DL(Op);
500   unsigned Opcode = Op.getOpcode();
501 
502   // Do target-specific constant optimization.
503   if (targetShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO))
504     return TLO.New.getNode();
505 
506   // FIXME: ISD::SELECT, ISD::SELECT_CC
507   switch (Opcode) {
508   default:
509     break;
510   case ISD::XOR:
511   case ISD::AND:
512   case ISD::OR: {
513     auto *Op1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
514     if (!Op1C || Op1C->isOpaque())
515       return false;
516 
517     // If this is a 'not' op, don't touch it because that's a canonical form.
518     const APInt &C = Op1C->getAPIntValue();
519     if (Opcode == ISD::XOR && DemandedBits.isSubsetOf(C))
520       return false;
521 
522     if (!C.isSubsetOf(DemandedBits)) {
523       EVT VT = Op.getValueType();
524       SDValue NewC = TLO.DAG.getConstant(DemandedBits & C, DL, VT);
525       SDValue NewOp = TLO.DAG.getNode(Opcode, DL, VT, Op.getOperand(0), NewC);
526       return TLO.CombineTo(Op, NewOp);
527     }
528 
529     break;
530   }
531   }
532 
533   return false;
534 }
535 
536 bool TargetLowering::ShrinkDemandedConstant(SDValue Op,
537                                             const APInt &DemandedBits,
538                                             TargetLoweringOpt &TLO) const {
539   EVT VT = Op.getValueType();
540   APInt DemandedElts = VT.isVector()
541                            ? APInt::getAllOnes(VT.getVectorNumElements())
542                            : APInt(1, 1);
543   return ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO);
544 }
545 
546 /// Convert x+y to (VT)((SmallVT)x+(SmallVT)y) if the casts are free.
547 /// This uses isZExtFree and ZERO_EXTEND for the widening cast, but it could be
548 /// generalized for targets with other types of implicit widening casts.
549 bool TargetLowering::ShrinkDemandedOp(SDValue Op, unsigned BitWidth,
550                                       const APInt &Demanded,
551                                       TargetLoweringOpt &TLO) const {
552   assert(Op.getNumOperands() == 2 &&
553          "ShrinkDemandedOp only supports binary operators!");
554   assert(Op.getNode()->getNumValues() == 1 &&
555          "ShrinkDemandedOp only supports nodes with one result!");
556 
557   SelectionDAG &DAG = TLO.DAG;
558   SDLoc dl(Op);
559 
560   // Early return, as this function cannot handle vector types.
561   if (Op.getValueType().isVector())
562     return false;
563 
564   // Don't do this if the node has another user, which may require the
565   // full value.
566   if (!Op.getNode()->hasOneUse())
567     return false;
568 
569   // Search for the smallest integer type with free casts to and from
570   // Op's type. For expedience, just check power-of-2 integer types.
571   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
572   unsigned DemandedSize = Demanded.getActiveBits();
573   unsigned SmallVTBits = DemandedSize;
574   if (!isPowerOf2_32(SmallVTBits))
575     SmallVTBits = NextPowerOf2(SmallVTBits);
576   for (; SmallVTBits < BitWidth; SmallVTBits = NextPowerOf2(SmallVTBits)) {
577     EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), SmallVTBits);
578     if (TLI.isTruncateFree(Op.getValueType(), SmallVT) &&
579         TLI.isZExtFree(SmallVT, Op.getValueType())) {
580       // We found a type with free casts.
581       SDValue X = DAG.getNode(
582           Op.getOpcode(), dl, SmallVT,
583           DAG.getNode(ISD::TRUNCATE, dl, SmallVT, Op.getOperand(0)),
584           DAG.getNode(ISD::TRUNCATE, dl, SmallVT, Op.getOperand(1)));
585       assert(DemandedSize <= SmallVTBits && "Narrowed below demanded bits?");
586       SDValue Z = DAG.getNode(ISD::ANY_EXTEND, dl, Op.getValueType(), X);
587       return TLO.CombineTo(Op, Z);
588     }
589   }
590   return false;
591 }
592 
593 bool TargetLowering::SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits,
594                                           DAGCombinerInfo &DCI) const {
595   SelectionDAG &DAG = DCI.DAG;
596   TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
597                         !DCI.isBeforeLegalizeOps());
598   KnownBits Known;
599 
600   bool Simplified = SimplifyDemandedBits(Op, DemandedBits, Known, TLO);
601   if (Simplified) {
602     DCI.AddToWorklist(Op.getNode());
603     DCI.CommitTargetLoweringOpt(TLO);
604   }
605   return Simplified;
606 }
607 
608 bool TargetLowering::SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits,
609                                           const APInt &DemandedElts,
610                                           DAGCombinerInfo &DCI) const {
611   SelectionDAG &DAG = DCI.DAG;
612   TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
613                         !DCI.isBeforeLegalizeOps());
614   KnownBits Known;
615 
616   bool Simplified =
617       SimplifyDemandedBits(Op, DemandedBits, DemandedElts, Known, TLO);
618   if (Simplified) {
619     DCI.AddToWorklist(Op.getNode());
620     DCI.CommitTargetLoweringOpt(TLO);
621   }
622   return Simplified;
623 }
624 
625 bool TargetLowering::SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits,
626                                           KnownBits &Known,
627                                           TargetLoweringOpt &TLO,
628                                           unsigned Depth,
629                                           bool AssumeSingleUse) const {
630   EVT VT = Op.getValueType();
631 
632   // TODO: We can probably do more work on calculating the known bits and
633   // simplifying the operations for scalable vectors, but for now we just
634   // bail out.
635   if (VT.isScalableVector()) {
636     // Pretend we don't know anything for now.
637     Known = KnownBits(DemandedBits.getBitWidth());
638     return false;
639   }
640 
641   APInt DemandedElts = VT.isVector()
642                            ? APInt::getAllOnes(VT.getVectorNumElements())
643                            : APInt(1, 1);
644   return SimplifyDemandedBits(Op, DemandedBits, DemandedElts, Known, TLO, Depth,
645                               AssumeSingleUse);
646 }
647 
648 // TODO: Can we merge SelectionDAG::GetDemandedBits into this?
649 // TODO: Under what circumstances can we create nodes? Constant folding?
650 SDValue TargetLowering::SimplifyMultipleUseDemandedBits(
651     SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
652     SelectionDAG &DAG, unsigned Depth) const {
653   // Limit search depth.
654   if (Depth >= SelectionDAG::MaxRecursionDepth)
655     return SDValue();
656 
657   // Ignore UNDEFs.
658   if (Op.isUndef())
659     return SDValue();
660 
661   // Not demanding any bits/elts from Op.
662   if (DemandedBits == 0 || DemandedElts == 0)
663     return DAG.getUNDEF(Op.getValueType());
664 
665   bool IsLE = DAG.getDataLayout().isLittleEndian();
666   unsigned NumElts = DemandedElts.getBitWidth();
667   unsigned BitWidth = DemandedBits.getBitWidth();
668   KnownBits LHSKnown, RHSKnown;
669   switch (Op.getOpcode()) {
670   case ISD::BITCAST: {
671     SDValue Src = peekThroughBitcasts(Op.getOperand(0));
672     EVT SrcVT = Src.getValueType();
673     EVT DstVT = Op.getValueType();
674     if (SrcVT == DstVT)
675       return Src;
676 
677     unsigned NumSrcEltBits = SrcVT.getScalarSizeInBits();
678     unsigned NumDstEltBits = DstVT.getScalarSizeInBits();
679     if (NumSrcEltBits == NumDstEltBits)
680       if (SDValue V = SimplifyMultipleUseDemandedBits(
681               Src, DemandedBits, DemandedElts, DAG, Depth + 1))
682         return DAG.getBitcast(DstVT, V);
683 
684     if (SrcVT.isVector() && (NumDstEltBits % NumSrcEltBits) == 0) {
685       unsigned Scale = NumDstEltBits / NumSrcEltBits;
686       unsigned NumSrcElts = SrcVT.getVectorNumElements();
687       APInt DemandedSrcBits = APInt::getZero(NumSrcEltBits);
688       APInt DemandedSrcElts = APInt::getZero(NumSrcElts);
689       for (unsigned i = 0; i != Scale; ++i) {
690         unsigned EltOffset = IsLE ? i : (Scale - 1 - i);
691         unsigned BitOffset = EltOffset * NumSrcEltBits;
692         APInt Sub = DemandedBits.extractBits(NumSrcEltBits, BitOffset);
693         if (!Sub.isZero()) {
694           DemandedSrcBits |= Sub;
695           for (unsigned j = 0; j != NumElts; ++j)
696             if (DemandedElts[j])
697               DemandedSrcElts.setBit((j * Scale) + i);
698         }
699       }
700 
701       if (SDValue V = SimplifyMultipleUseDemandedBits(
702               Src, DemandedSrcBits, DemandedSrcElts, DAG, Depth + 1))
703         return DAG.getBitcast(DstVT, V);
704     }
705 
706     // TODO - bigendian once we have test coverage.
707     if (IsLE && (NumSrcEltBits % NumDstEltBits) == 0) {
708       unsigned Scale = NumSrcEltBits / NumDstEltBits;
709       unsigned NumSrcElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1;
710       APInt DemandedSrcBits = APInt::getZero(NumSrcEltBits);
711       APInt DemandedSrcElts = APInt::getZero(NumSrcElts);
712       for (unsigned i = 0; i != NumElts; ++i)
713         if (DemandedElts[i]) {
714           unsigned Offset = (i % Scale) * NumDstEltBits;
715           DemandedSrcBits.insertBits(DemandedBits, Offset);
716           DemandedSrcElts.setBit(i / Scale);
717         }
718 
719       if (SDValue V = SimplifyMultipleUseDemandedBits(
720               Src, DemandedSrcBits, DemandedSrcElts, DAG, Depth + 1))
721         return DAG.getBitcast(DstVT, V);
722     }
723 
724     break;
725   }
726   case ISD::AND: {
727     LHSKnown = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
728     RHSKnown = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
729 
730     // If all of the demanded bits are known 1 on one side, return the other.
731     // These bits cannot contribute to the result of the 'and' in this
732     // context.
733     if (DemandedBits.isSubsetOf(LHSKnown.Zero | RHSKnown.One))
734       return Op.getOperand(0);
735     if (DemandedBits.isSubsetOf(RHSKnown.Zero | LHSKnown.One))
736       return Op.getOperand(1);
737     break;
738   }
739   case ISD::OR: {
740     LHSKnown = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
741     RHSKnown = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
742 
743     // If all of the demanded bits are known zero on one side, return the
744     // other.  These bits cannot contribute to the result of the 'or' in this
745     // context.
746     if (DemandedBits.isSubsetOf(LHSKnown.One | RHSKnown.Zero))
747       return Op.getOperand(0);
748     if (DemandedBits.isSubsetOf(RHSKnown.One | LHSKnown.Zero))
749       return Op.getOperand(1);
750     break;
751   }
752   case ISD::XOR: {
753     LHSKnown = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
754     RHSKnown = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
755 
756     // If all of the demanded bits are known zero on one side, return the
757     // other.
758     if (DemandedBits.isSubsetOf(RHSKnown.Zero))
759       return Op.getOperand(0);
760     if (DemandedBits.isSubsetOf(LHSKnown.Zero))
761       return Op.getOperand(1);
762     break;
763   }
764   case ISD::SHL: {
765     // If we are only demanding sign bits then we can use the shift source
766     // directly.
767     if (const APInt *MaxSA =
768             DAG.getValidMaximumShiftAmountConstant(Op, DemandedElts)) {
769       SDValue Op0 = Op.getOperand(0);
770       unsigned ShAmt = MaxSA->getZExtValue();
771       unsigned NumSignBits =
772           DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1);
773       unsigned UpperDemandedBits = BitWidth - DemandedBits.countTrailingZeros();
774       if (NumSignBits > ShAmt && (NumSignBits - ShAmt) >= (UpperDemandedBits))
775         return Op0;
776     }
777     break;
778   }
779   case ISD::SETCC: {
780     SDValue Op0 = Op.getOperand(0);
781     SDValue Op1 = Op.getOperand(1);
782     ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
783     // If (1) we only need the sign-bit, (2) the setcc operands are the same
784     // width as the setcc result, and (3) the result of a setcc conforms to 0 or
785     // -1, we may be able to bypass the setcc.
786     if (DemandedBits.isSignMask() &&
787         Op0.getScalarValueSizeInBits() == BitWidth &&
788         getBooleanContents(Op0.getValueType()) ==
789             BooleanContent::ZeroOrNegativeOneBooleanContent) {
790       // If we're testing X < 0, then this compare isn't needed - just use X!
791       // FIXME: We're limiting to integer types here, but this should also work
792       // if we don't care about FP signed-zero. The use of SETLT with FP means
793       // that we don't care about NaNs.
794       if (CC == ISD::SETLT && Op1.getValueType().isInteger() &&
795           (isNullConstant(Op1) || ISD::isBuildVectorAllZeros(Op1.getNode())))
796         return Op0;
797     }
798     break;
799   }
800   case ISD::SIGN_EXTEND_INREG: {
801     // If none of the extended bits are demanded, eliminate the sextinreg.
802     SDValue Op0 = Op.getOperand(0);
803     EVT ExVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
804     unsigned ExBits = ExVT.getScalarSizeInBits();
805     if (DemandedBits.getActiveBits() <= ExBits)
806       return Op0;
807     // If the input is already sign extended, just drop the extension.
808     unsigned NumSignBits = DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1);
809     if (NumSignBits >= (BitWidth - ExBits + 1))
810       return Op0;
811     break;
812   }
813   case ISD::ANY_EXTEND_VECTOR_INREG:
814   case ISD::SIGN_EXTEND_VECTOR_INREG:
815   case ISD::ZERO_EXTEND_VECTOR_INREG: {
816     // If we only want the lowest element and none of extended bits, then we can
817     // return the bitcasted source vector.
818     SDValue Src = Op.getOperand(0);
819     EVT SrcVT = Src.getValueType();
820     EVT DstVT = Op.getValueType();
821     if (IsLE && DemandedElts == 1 &&
822         DstVT.getSizeInBits() == SrcVT.getSizeInBits() &&
823         DemandedBits.getActiveBits() <= SrcVT.getScalarSizeInBits()) {
824       return DAG.getBitcast(DstVT, Src);
825     }
826     break;
827   }
828   case ISD::INSERT_VECTOR_ELT: {
829     // If we don't demand the inserted element, return the base vector.
830     SDValue Vec = Op.getOperand(0);
831     auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2));
832     EVT VecVT = Vec.getValueType();
833     if (CIdx && CIdx->getAPIntValue().ult(VecVT.getVectorNumElements()) &&
834         !DemandedElts[CIdx->getZExtValue()])
835       return Vec;
836     break;
837   }
838   case ISD::INSERT_SUBVECTOR: {
839     SDValue Vec = Op.getOperand(0);
840     SDValue Sub = Op.getOperand(1);
841     uint64_t Idx = Op.getConstantOperandVal(2);
842     unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
843     APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
844     // If we don't demand the inserted subvector, return the base vector.
845     if (DemandedSubElts == 0)
846       return Vec;
847     // If this simply widens the lowest subvector, see if we can do it earlier.
848     if (Idx == 0 && Vec.isUndef()) {
849       if (SDValue NewSub = SimplifyMultipleUseDemandedBits(
850               Sub, DemandedBits, DemandedSubElts, DAG, Depth + 1))
851         return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
852                            Op.getOperand(0), NewSub, Op.getOperand(2));
853     }
854     break;
855   }
856   case ISD::VECTOR_SHUFFLE: {
857     ArrayRef<int> ShuffleMask = cast<ShuffleVectorSDNode>(Op)->getMask();
858 
859     // If all the demanded elts are from one operand and are inline,
860     // then we can use the operand directly.
861     bool AllUndef = true, IdentityLHS = true, IdentityRHS = true;
862     for (unsigned i = 0; i != NumElts; ++i) {
863       int M = ShuffleMask[i];
864       if (M < 0 || !DemandedElts[i])
865         continue;
866       AllUndef = false;
867       IdentityLHS &= (M == (int)i);
868       IdentityRHS &= ((M - NumElts) == i);
869     }
870 
871     if (AllUndef)
872       return DAG.getUNDEF(Op.getValueType());
873     if (IdentityLHS)
874       return Op.getOperand(0);
875     if (IdentityRHS)
876       return Op.getOperand(1);
877     break;
878   }
879   default:
880     if (Op.getOpcode() >= ISD::BUILTIN_OP_END)
881       if (SDValue V = SimplifyMultipleUseDemandedBitsForTargetNode(
882               Op, DemandedBits, DemandedElts, DAG, Depth))
883         return V;
884     break;
885   }
886   return SDValue();
887 }
888 
889 SDValue TargetLowering::SimplifyMultipleUseDemandedBits(
890     SDValue Op, const APInt &DemandedBits, SelectionDAG &DAG,
891     unsigned Depth) const {
892   EVT VT = Op.getValueType();
893   APInt DemandedElts = VT.isVector()
894                            ? APInt::getAllOnes(VT.getVectorNumElements())
895                            : APInt(1, 1);
896   return SimplifyMultipleUseDemandedBits(Op, DemandedBits, DemandedElts, DAG,
897                                          Depth);
898 }
899 
900 SDValue TargetLowering::SimplifyMultipleUseDemandedVectorElts(
901     SDValue Op, const APInt &DemandedElts, SelectionDAG &DAG,
902     unsigned Depth) const {
903   APInt DemandedBits = APInt::getAllOnes(Op.getScalarValueSizeInBits());
904   return SimplifyMultipleUseDemandedBits(Op, DemandedBits, DemandedElts, DAG,
905                                          Depth);
906 }
907 
908 // Attempt to form ext(avgfloor(A, B)) from shr(add(ext(A), ext(B)), 1).
909 //      or to form ext(avgceil(A, B)) from shr(add(ext(A), ext(B), 1), 1).
910 static SDValue combineShiftToAVG(SDValue Op, SelectionDAG &DAG,
911                                  const TargetLowering &TLI,
912                                  const APInt &DemandedBits,
913                                  const APInt &DemandedElts,
914                                  unsigned Depth) {
915   assert((Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SRA) &&
916          "SRL or SRA node is required here!");
917   // Is the right shift using an immediate value of 1?
918   ConstantSDNode *N1C = isConstOrConstSplat(Op.getOperand(1), DemandedElts);
919   if (!N1C || !N1C->isOne())
920     return SDValue();
921 
922   // We are looking for an avgfloor
923   // add(ext, ext)
924   // or one of these as a avgceil
925   // add(add(ext, ext), 1)
926   // add(add(ext, 1), ext)
927   // add(ext, add(ext, 1))
928   SDValue Add = Op.getOperand(0);
929   if (Add.getOpcode() != ISD::ADD)
930     return SDValue();
931 
932   SDValue ExtOpA = Add.getOperand(0);
933   SDValue ExtOpB = Add.getOperand(1);
934   auto MatchOperands = [&](SDValue Op1, SDValue Op2, SDValue Op3) {
935     ConstantSDNode *ConstOp;
936     if ((ConstOp = isConstOrConstSplat(Op1, DemandedElts)) &&
937         ConstOp->isOne()) {
938       ExtOpA = Op2;
939       ExtOpB = Op3;
940       return true;
941     }
942     if ((ConstOp = isConstOrConstSplat(Op2, DemandedElts)) &&
943         ConstOp->isOne()) {
944       ExtOpA = Op1;
945       ExtOpB = Op3;
946       return true;
947     }
948     if ((ConstOp = isConstOrConstSplat(Op3, DemandedElts)) &&
949         ConstOp->isOne()) {
950       ExtOpA = Op1;
951       ExtOpB = Op2;
952       return true;
953     }
954     return false;
955   };
956   bool IsCeil =
957       (ExtOpA.getOpcode() == ISD::ADD &&
958        MatchOperands(ExtOpA.getOperand(0), ExtOpA.getOperand(1), ExtOpB)) ||
959       (ExtOpB.getOpcode() == ISD::ADD &&
960        MatchOperands(ExtOpB.getOperand(0), ExtOpB.getOperand(1), ExtOpA));
961 
962   // If the shift is signed (sra):
963   //  - Needs >= 2 sign bit for both operands.
964   //  - Needs >= 2 zero bits.
965   // If the shift is unsigned (srl):
966   //  - Needs >= 1 zero bit for both operands.
967   //  - Needs 1 demanded bit zero and >= 2 sign bits.
968   unsigned ShiftOpc = Op.getOpcode();
969   bool IsSigned = false;
970   unsigned KnownBits;
971   unsigned NumSignedA = DAG.ComputeNumSignBits(ExtOpA, DemandedElts, Depth);
972   unsigned NumSignedB = DAG.ComputeNumSignBits(ExtOpB, DemandedElts, Depth);
973   unsigned NumSigned = std::min(NumSignedA, NumSignedB) - 1;
974   unsigned NumZeroA =
975       DAG.computeKnownBits(ExtOpA, DemandedElts, Depth).countMinLeadingZeros();
976   unsigned NumZeroB =
977       DAG.computeKnownBits(ExtOpB, DemandedElts, Depth).countMinLeadingZeros();
978   unsigned NumZero = std::min(NumZeroA, NumZeroB);
979 
980   switch (ShiftOpc) {
981   default:
982     llvm_unreachable("Unexpected ShiftOpc in combineShiftToAVG");
983   case ISD::SRA: {
984     if (NumZero >= 2 && NumSigned < NumZero) {
985       IsSigned = false;
986       KnownBits = NumZero;
987       break;
988     }
989     if (NumSigned >= 1) {
990       IsSigned = true;
991       KnownBits = NumSigned;
992       break;
993     }
994     return SDValue();
995   }
996   case ISD::SRL: {
997     if (NumZero >= 1 && NumSigned < NumZero) {
998       IsSigned = false;
999       KnownBits = NumZero;
1000       break;
1001     }
1002     if (NumSigned >= 1 && DemandedBits.isSignBitClear()) {
1003       IsSigned = true;
1004       KnownBits = NumSigned;
1005       break;
1006     }
1007     return SDValue();
1008   }
1009   }
1010 
1011   unsigned AVGOpc = IsCeil ? (IsSigned ? ISD::AVGCEILS : ISD::AVGCEILU)
1012                            : (IsSigned ? ISD::AVGFLOORS : ISD::AVGFLOORU);
1013 
1014   // Find the smallest power-2 type that is legal for this vector size and
1015   // operation, given the original type size and the number of known sign/zero
1016   // bits.
1017   EVT VT = Op.getValueType();
1018   unsigned MinWidth =
1019       std::max<unsigned>(VT.getScalarSizeInBits() - KnownBits, 8);
1020   EVT NVT = EVT::getIntegerVT(*DAG.getContext(), PowerOf2Ceil(MinWidth));
1021   if (VT.isVector())
1022     NVT = EVT::getVectorVT(*DAG.getContext(), NVT, VT.getVectorElementCount());
1023   if (!TLI.isOperationLegalOrCustom(AVGOpc, NVT))
1024     return SDValue();
1025 
1026   SDLoc DL(Op);
1027   SDValue ResultAVG =
1028       DAG.getNode(AVGOpc, DL, NVT, DAG.getNode(ISD::TRUNCATE, DL, NVT, ExtOpA),
1029                   DAG.getNode(ISD::TRUNCATE, DL, NVT, ExtOpB));
1030   return DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, DL, VT,
1031                      ResultAVG);
1032 }
1033 
1034 /// Look at Op. At this point, we know that only the OriginalDemandedBits of the
1035 /// result of Op are ever used downstream. If we can use this information to
1036 /// simplify Op, create a new simplified DAG node and return true, returning the
1037 /// original and new nodes in Old and New. Otherwise, analyze the expression and
1038 /// return a mask of Known bits for the expression (used to simplify the
1039 /// caller).  The Known bits may only be accurate for those bits in the
1040 /// OriginalDemandedBits and OriginalDemandedElts.
1041 bool TargetLowering::SimplifyDemandedBits(
1042     SDValue Op, const APInt &OriginalDemandedBits,
1043     const APInt &OriginalDemandedElts, KnownBits &Known, TargetLoweringOpt &TLO,
1044     unsigned Depth, bool AssumeSingleUse) const {
1045   unsigned BitWidth = OriginalDemandedBits.getBitWidth();
1046   assert(Op.getScalarValueSizeInBits() == BitWidth &&
1047          "Mask size mismatches value type size!");
1048 
1049   // Don't know anything.
1050   Known = KnownBits(BitWidth);
1051 
1052   // TODO: We can probably do more work on calculating the known bits and
1053   // simplifying the operations for scalable vectors, but for now we just
1054   // bail out.
1055   if (Op.getValueType().isScalableVector())
1056     return false;
1057 
1058   bool IsLE = TLO.DAG.getDataLayout().isLittleEndian();
1059   unsigned NumElts = OriginalDemandedElts.getBitWidth();
1060   assert((!Op.getValueType().isVector() ||
1061           NumElts == Op.getValueType().getVectorNumElements()) &&
1062          "Unexpected vector size");
1063 
1064   APInt DemandedBits = OriginalDemandedBits;
1065   APInt DemandedElts = OriginalDemandedElts;
1066   SDLoc dl(Op);
1067   auto &DL = TLO.DAG.getDataLayout();
1068 
1069   // Undef operand.
1070   if (Op.isUndef())
1071     return false;
1072 
1073   if (Op.getOpcode() == ISD::Constant) {
1074     // We know all of the bits for a constant!
1075     Known = KnownBits::makeConstant(cast<ConstantSDNode>(Op)->getAPIntValue());
1076     return false;
1077   }
1078 
1079   if (Op.getOpcode() == ISD::ConstantFP) {
1080     // We know all of the bits for a floating point constant!
1081     Known = KnownBits::makeConstant(
1082         cast<ConstantFPSDNode>(Op)->getValueAPF().bitcastToAPInt());
1083     return false;
1084   }
1085 
1086   // Other users may use these bits.
1087   EVT VT = Op.getValueType();
1088   if (!Op.getNode()->hasOneUse() && !AssumeSingleUse) {
1089     if (Depth != 0) {
1090       // If not at the root, Just compute the Known bits to
1091       // simplify things downstream.
1092       Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth);
1093       return false;
1094     }
1095     // If this is the root being simplified, allow it to have multiple uses,
1096     // just set the DemandedBits/Elts to all bits.
1097     DemandedBits = APInt::getAllOnes(BitWidth);
1098     DemandedElts = APInt::getAllOnes(NumElts);
1099   } else if (OriginalDemandedBits == 0 || OriginalDemandedElts == 0) {
1100     // Not demanding any bits/elts from Op.
1101     return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT));
1102   } else if (Depth >= SelectionDAG::MaxRecursionDepth) {
1103     // Limit search depth.
1104     return false;
1105   }
1106 
1107   KnownBits Known2;
1108   switch (Op.getOpcode()) {
1109   case ISD::TargetConstant:
1110     llvm_unreachable("Can't simplify this node");
1111   case ISD::SCALAR_TO_VECTOR: {
1112     if (!DemandedElts[0])
1113       return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT));
1114 
1115     KnownBits SrcKnown;
1116     SDValue Src = Op.getOperand(0);
1117     unsigned SrcBitWidth = Src.getScalarValueSizeInBits();
1118     APInt SrcDemandedBits = DemandedBits.zextOrSelf(SrcBitWidth);
1119     if (SimplifyDemandedBits(Src, SrcDemandedBits, SrcKnown, TLO, Depth + 1))
1120       return true;
1121 
1122     // Upper elements are undef, so only get the knownbits if we just demand
1123     // the bottom element.
1124     if (DemandedElts == 1)
1125       Known = SrcKnown.anyextOrTrunc(BitWidth);
1126     break;
1127   }
1128   case ISD::BUILD_VECTOR:
1129     // Collect the known bits that are shared by every demanded element.
1130     // TODO: Call SimplifyDemandedBits for non-constant demanded elements.
1131     Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth);
1132     return false; // Don't fall through, will infinitely loop.
1133   case ISD::LOAD: {
1134     auto *LD = cast<LoadSDNode>(Op);
1135     if (getTargetConstantFromLoad(LD)) {
1136       Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth);
1137       return false; // Don't fall through, will infinitely loop.
1138     }
1139     if (ISD::isZEXTLoad(Op.getNode()) && Op.getResNo() == 0) {
1140       // If this is a ZEXTLoad and we are looking at the loaded value.
1141       EVT MemVT = LD->getMemoryVT();
1142       unsigned MemBits = MemVT.getScalarSizeInBits();
1143       Known.Zero.setBitsFrom(MemBits);
1144       return false; // Don't fall through, will infinitely loop.
1145     }
1146     break;
1147   }
1148   case ISD::INSERT_VECTOR_ELT: {
1149     SDValue Vec = Op.getOperand(0);
1150     SDValue Scl = Op.getOperand(1);
1151     auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2));
1152     EVT VecVT = Vec.getValueType();
1153 
1154     // If index isn't constant, assume we need all vector elements AND the
1155     // inserted element.
1156     APInt DemandedVecElts(DemandedElts);
1157     if (CIdx && CIdx->getAPIntValue().ult(VecVT.getVectorNumElements())) {
1158       unsigned Idx = CIdx->getZExtValue();
1159       DemandedVecElts.clearBit(Idx);
1160 
1161       // Inserted element is not required.
1162       if (!DemandedElts[Idx])
1163         return TLO.CombineTo(Op, Vec);
1164     }
1165 
1166     KnownBits KnownScl;
1167     unsigned NumSclBits = Scl.getScalarValueSizeInBits();
1168     APInt DemandedSclBits = DemandedBits.zextOrTrunc(NumSclBits);
1169     if (SimplifyDemandedBits(Scl, DemandedSclBits, KnownScl, TLO, Depth + 1))
1170       return true;
1171 
1172     Known = KnownScl.anyextOrTrunc(BitWidth);
1173 
1174     KnownBits KnownVec;
1175     if (SimplifyDemandedBits(Vec, DemandedBits, DemandedVecElts, KnownVec, TLO,
1176                              Depth + 1))
1177       return true;
1178 
1179     if (!!DemandedVecElts)
1180       Known = KnownBits::commonBits(Known, KnownVec);
1181 
1182     return false;
1183   }
1184   case ISD::INSERT_SUBVECTOR: {
1185     // Demand any elements from the subvector and the remainder from the src its
1186     // inserted into.
1187     SDValue Src = Op.getOperand(0);
1188     SDValue Sub = Op.getOperand(1);
1189     uint64_t Idx = Op.getConstantOperandVal(2);
1190     unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
1191     APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
1192     APInt DemandedSrcElts = DemandedElts;
1193     DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx);
1194 
1195     KnownBits KnownSub, KnownSrc;
1196     if (SimplifyDemandedBits(Sub, DemandedBits, DemandedSubElts, KnownSub, TLO,
1197                              Depth + 1))
1198       return true;
1199     if (SimplifyDemandedBits(Src, DemandedBits, DemandedSrcElts, KnownSrc, TLO,
1200                              Depth + 1))
1201       return true;
1202 
1203     Known.Zero.setAllBits();
1204     Known.One.setAllBits();
1205     if (!!DemandedSubElts)
1206       Known = KnownBits::commonBits(Known, KnownSub);
1207     if (!!DemandedSrcElts)
1208       Known = KnownBits::commonBits(Known, KnownSrc);
1209 
1210     // Attempt to avoid multi-use src if we don't need anything from it.
1211     if (!DemandedBits.isAllOnes() || !DemandedSubElts.isAllOnes() ||
1212         !DemandedSrcElts.isAllOnes()) {
1213       SDValue NewSub = SimplifyMultipleUseDemandedBits(
1214           Sub, DemandedBits, DemandedSubElts, TLO.DAG, Depth + 1);
1215       SDValue NewSrc = SimplifyMultipleUseDemandedBits(
1216           Src, DemandedBits, DemandedSrcElts, TLO.DAG, Depth + 1);
1217       if (NewSub || NewSrc) {
1218         NewSub = NewSub ? NewSub : Sub;
1219         NewSrc = NewSrc ? NewSrc : Src;
1220         SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, NewSrc, NewSub,
1221                                         Op.getOperand(2));
1222         return TLO.CombineTo(Op, NewOp);
1223       }
1224     }
1225     break;
1226   }
1227   case ISD::EXTRACT_SUBVECTOR: {
1228     // Offset the demanded elts by the subvector index.
1229     SDValue Src = Op.getOperand(0);
1230     if (Src.getValueType().isScalableVector())
1231       break;
1232     uint64_t Idx = Op.getConstantOperandVal(1);
1233     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
1234     APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx);
1235 
1236     if (SimplifyDemandedBits(Src, DemandedBits, DemandedSrcElts, Known, TLO,
1237                              Depth + 1))
1238       return true;
1239 
1240     // Attempt to avoid multi-use src if we don't need anything from it.
1241     if (!DemandedBits.isAllOnes() || !DemandedSrcElts.isAllOnes()) {
1242       SDValue DemandedSrc = SimplifyMultipleUseDemandedBits(
1243           Src, DemandedBits, DemandedSrcElts, TLO.DAG, Depth + 1);
1244       if (DemandedSrc) {
1245         SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, DemandedSrc,
1246                                         Op.getOperand(1));
1247         return TLO.CombineTo(Op, NewOp);
1248       }
1249     }
1250     break;
1251   }
1252   case ISD::CONCAT_VECTORS: {
1253     Known.Zero.setAllBits();
1254     Known.One.setAllBits();
1255     EVT SubVT = Op.getOperand(0).getValueType();
1256     unsigned NumSubVecs = Op.getNumOperands();
1257     unsigned NumSubElts = SubVT.getVectorNumElements();
1258     for (unsigned i = 0; i != NumSubVecs; ++i) {
1259       APInt DemandedSubElts =
1260           DemandedElts.extractBits(NumSubElts, i * NumSubElts);
1261       if (SimplifyDemandedBits(Op.getOperand(i), DemandedBits, DemandedSubElts,
1262                                Known2, TLO, Depth + 1))
1263         return true;
1264       // Known bits are shared by every demanded subvector element.
1265       if (!!DemandedSubElts)
1266         Known = KnownBits::commonBits(Known, Known2);
1267     }
1268     break;
1269   }
1270   case ISD::VECTOR_SHUFFLE: {
1271     ArrayRef<int> ShuffleMask = cast<ShuffleVectorSDNode>(Op)->getMask();
1272 
1273     // Collect demanded elements from shuffle operands..
1274     APInt DemandedLHS(NumElts, 0);
1275     APInt DemandedRHS(NumElts, 0);
1276     for (unsigned i = 0; i != NumElts; ++i) {
1277       if (!DemandedElts[i])
1278         continue;
1279       int M = ShuffleMask[i];
1280       if (M < 0) {
1281         // For UNDEF elements, we don't know anything about the common state of
1282         // the shuffle result.
1283         DemandedLHS.clearAllBits();
1284         DemandedRHS.clearAllBits();
1285         break;
1286       }
1287       assert(0 <= M && M < (int)(2 * NumElts) && "Shuffle index out of range");
1288       if (M < (int)NumElts)
1289         DemandedLHS.setBit(M);
1290       else
1291         DemandedRHS.setBit(M - NumElts);
1292     }
1293 
1294     if (!!DemandedLHS || !!DemandedRHS) {
1295       SDValue Op0 = Op.getOperand(0);
1296       SDValue Op1 = Op.getOperand(1);
1297 
1298       Known.Zero.setAllBits();
1299       Known.One.setAllBits();
1300       if (!!DemandedLHS) {
1301         if (SimplifyDemandedBits(Op0, DemandedBits, DemandedLHS, Known2, TLO,
1302                                  Depth + 1))
1303           return true;
1304         Known = KnownBits::commonBits(Known, Known2);
1305       }
1306       if (!!DemandedRHS) {
1307         if (SimplifyDemandedBits(Op1, DemandedBits, DemandedRHS, Known2, TLO,
1308                                  Depth + 1))
1309           return true;
1310         Known = KnownBits::commonBits(Known, Known2);
1311       }
1312 
1313       // Attempt to avoid multi-use ops if we don't need anything from them.
1314       SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits(
1315           Op0, DemandedBits, DemandedLHS, TLO.DAG, Depth + 1);
1316       SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits(
1317           Op1, DemandedBits, DemandedRHS, TLO.DAG, Depth + 1);
1318       if (DemandedOp0 || DemandedOp1) {
1319         Op0 = DemandedOp0 ? DemandedOp0 : Op0;
1320         Op1 = DemandedOp1 ? DemandedOp1 : Op1;
1321         SDValue NewOp = TLO.DAG.getVectorShuffle(VT, dl, Op0, Op1, ShuffleMask);
1322         return TLO.CombineTo(Op, NewOp);
1323       }
1324     }
1325     break;
1326   }
1327   case ISD::AND: {
1328     SDValue Op0 = Op.getOperand(0);
1329     SDValue Op1 = Op.getOperand(1);
1330 
1331     // If the RHS is a constant, check to see if the LHS would be zero without
1332     // using the bits from the RHS.  Below, we use knowledge about the RHS to
1333     // simplify the LHS, here we're using information from the LHS to simplify
1334     // the RHS.
1335     if (ConstantSDNode *RHSC = isConstOrConstSplat(Op1)) {
1336       // Do not increment Depth here; that can cause an infinite loop.
1337       KnownBits LHSKnown = TLO.DAG.computeKnownBits(Op0, DemandedElts, Depth);
1338       // If the LHS already has zeros where RHSC does, this 'and' is dead.
1339       if ((LHSKnown.Zero & DemandedBits) ==
1340           (~RHSC->getAPIntValue() & DemandedBits))
1341         return TLO.CombineTo(Op, Op0);
1342 
1343       // If any of the set bits in the RHS are known zero on the LHS, shrink
1344       // the constant.
1345       if (ShrinkDemandedConstant(Op, ~LHSKnown.Zero & DemandedBits,
1346                                  DemandedElts, TLO))
1347         return true;
1348 
1349       // Bitwise-not (xor X, -1) is a special case: we don't usually shrink its
1350       // constant, but if this 'and' is only clearing bits that were just set by
1351       // the xor, then this 'and' can be eliminated by shrinking the mask of
1352       // the xor. For example, for a 32-bit X:
1353       // and (xor (srl X, 31), -1), 1 --> xor (srl X, 31), 1
1354       if (isBitwiseNot(Op0) && Op0.hasOneUse() &&
1355           LHSKnown.One == ~RHSC->getAPIntValue()) {
1356         SDValue Xor = TLO.DAG.getNode(ISD::XOR, dl, VT, Op0.getOperand(0), Op1);
1357         return TLO.CombineTo(Op, Xor);
1358       }
1359     }
1360 
1361     if (SimplifyDemandedBits(Op1, DemandedBits, DemandedElts, Known, TLO,
1362                              Depth + 1))
1363       return true;
1364     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
1365     if (SimplifyDemandedBits(Op0, ~Known.Zero & DemandedBits, DemandedElts,
1366                              Known2, TLO, Depth + 1))
1367       return true;
1368     assert(!Known2.hasConflict() && "Bits known to be one AND zero?");
1369 
1370     // Attempt to avoid multi-use ops if we don't need anything from them.
1371     if (!DemandedBits.isAllOnes() || !DemandedElts.isAllOnes()) {
1372       SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits(
1373           Op0, DemandedBits, DemandedElts, TLO.DAG, Depth + 1);
1374       SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits(
1375           Op1, DemandedBits, DemandedElts, TLO.DAG, Depth + 1);
1376       if (DemandedOp0 || DemandedOp1) {
1377         Op0 = DemandedOp0 ? DemandedOp0 : Op0;
1378         Op1 = DemandedOp1 ? DemandedOp1 : Op1;
1379         SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1);
1380         return TLO.CombineTo(Op, NewOp);
1381       }
1382     }
1383 
1384     // If all of the demanded bits are known one on one side, return the other.
1385     // These bits cannot contribute to the result of the 'and'.
1386     if (DemandedBits.isSubsetOf(Known2.Zero | Known.One))
1387       return TLO.CombineTo(Op, Op0);
1388     if (DemandedBits.isSubsetOf(Known.Zero | Known2.One))
1389       return TLO.CombineTo(Op, Op1);
1390     // If all of the demanded bits in the inputs are known zeros, return zero.
1391     if (DemandedBits.isSubsetOf(Known.Zero | Known2.Zero))
1392       return TLO.CombineTo(Op, TLO.DAG.getConstant(0, dl, VT));
1393     // If the RHS is a constant, see if we can simplify it.
1394     if (ShrinkDemandedConstant(Op, ~Known2.Zero & DemandedBits, DemandedElts,
1395                                TLO))
1396       return true;
1397     // If the operation can be done in a smaller type, do so.
1398     if (ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO))
1399       return true;
1400 
1401     Known &= Known2;
1402     break;
1403   }
1404   case ISD::OR: {
1405     SDValue Op0 = Op.getOperand(0);
1406     SDValue Op1 = Op.getOperand(1);
1407 
1408     if (SimplifyDemandedBits(Op1, DemandedBits, DemandedElts, Known, TLO,
1409                              Depth + 1))
1410       return true;
1411     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
1412     if (SimplifyDemandedBits(Op0, ~Known.One & DemandedBits, DemandedElts,
1413                              Known2, TLO, Depth + 1))
1414       return true;
1415     assert(!Known2.hasConflict() && "Bits known to be one AND zero?");
1416 
1417     // Attempt to avoid multi-use ops if we don't need anything from them.
1418     if (!DemandedBits.isAllOnes() || !DemandedElts.isAllOnes()) {
1419       SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits(
1420           Op0, DemandedBits, DemandedElts, TLO.DAG, Depth + 1);
1421       SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits(
1422           Op1, DemandedBits, DemandedElts, TLO.DAG, Depth + 1);
1423       if (DemandedOp0 || DemandedOp1) {
1424         Op0 = DemandedOp0 ? DemandedOp0 : Op0;
1425         Op1 = DemandedOp1 ? DemandedOp1 : Op1;
1426         SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1);
1427         return TLO.CombineTo(Op, NewOp);
1428       }
1429     }
1430 
1431     // If all of the demanded bits are known zero on one side, return the other.
1432     // These bits cannot contribute to the result of the 'or'.
1433     if (DemandedBits.isSubsetOf(Known2.One | Known.Zero))
1434       return TLO.CombineTo(Op, Op0);
1435     if (DemandedBits.isSubsetOf(Known.One | Known2.Zero))
1436       return TLO.CombineTo(Op, Op1);
1437     // If the RHS is a constant, see if we can simplify it.
1438     if (ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO))
1439       return true;
1440     // If the operation can be done in a smaller type, do so.
1441     if (ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO))
1442       return true;
1443 
1444     Known |= Known2;
1445     break;
1446   }
1447   case ISD::XOR: {
1448     SDValue Op0 = Op.getOperand(0);
1449     SDValue Op1 = Op.getOperand(1);
1450 
1451     if (SimplifyDemandedBits(Op1, DemandedBits, DemandedElts, Known, TLO,
1452                              Depth + 1))
1453       return true;
1454     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
1455     if (SimplifyDemandedBits(Op0, DemandedBits, DemandedElts, Known2, TLO,
1456                              Depth + 1))
1457       return true;
1458     assert(!Known2.hasConflict() && "Bits known to be one AND zero?");
1459 
1460     // Attempt to avoid multi-use ops if we don't need anything from them.
1461     if (!DemandedBits.isAllOnes() || !DemandedElts.isAllOnes()) {
1462       SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits(
1463           Op0, DemandedBits, DemandedElts, TLO.DAG, Depth + 1);
1464       SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits(
1465           Op1, DemandedBits, DemandedElts, TLO.DAG, Depth + 1);
1466       if (DemandedOp0 || DemandedOp1) {
1467         Op0 = DemandedOp0 ? DemandedOp0 : Op0;
1468         Op1 = DemandedOp1 ? DemandedOp1 : Op1;
1469         SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1);
1470         return TLO.CombineTo(Op, NewOp);
1471       }
1472     }
1473 
1474     // If all of the demanded bits are known zero on one side, return the other.
1475     // These bits cannot contribute to the result of the 'xor'.
1476     if (DemandedBits.isSubsetOf(Known.Zero))
1477       return TLO.CombineTo(Op, Op0);
1478     if (DemandedBits.isSubsetOf(Known2.Zero))
1479       return TLO.CombineTo(Op, Op1);
1480     // If the operation can be done in a smaller type, do so.
1481     if (ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO))
1482       return true;
1483 
1484     // If all of the unknown bits are known to be zero on one side or the other
1485     // turn this into an *inclusive* or.
1486     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1487     if (DemandedBits.isSubsetOf(Known.Zero | Known2.Zero))
1488       return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::OR, dl, VT, Op0, Op1));
1489 
1490     ConstantSDNode* C = isConstOrConstSplat(Op1, DemandedElts);
1491     if (C) {
1492       // If one side is a constant, and all of the set bits in the constant are
1493       // also known set on the other side, turn this into an AND, as we know
1494       // the bits will be cleared.
1495       //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1496       // NB: it is okay if more bits are known than are requested
1497       if (C->getAPIntValue() == Known2.One) {
1498         SDValue ANDC =
1499             TLO.DAG.getConstant(~C->getAPIntValue() & DemandedBits, dl, VT);
1500         return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::AND, dl, VT, Op0, ANDC));
1501       }
1502 
1503       // If the RHS is a constant, see if we can change it. Don't alter a -1
1504       // constant because that's a 'not' op, and that is better for combining
1505       // and codegen.
1506       if (!C->isAllOnes() && DemandedBits.isSubsetOf(C->getAPIntValue())) {
1507         // We're flipping all demanded bits. Flip the undemanded bits too.
1508         SDValue New = TLO.DAG.getNOT(dl, Op0, VT);
1509         return TLO.CombineTo(Op, New);
1510       }
1511     }
1512 
1513     // If we can't turn this into a 'not', try to shrink the constant.
1514     if (!C || !C->isAllOnes())
1515       if (ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO))
1516         return true;
1517 
1518     Known ^= Known2;
1519     break;
1520   }
1521   case ISD::SELECT:
1522     if (SimplifyDemandedBits(Op.getOperand(2), DemandedBits, Known, TLO,
1523                              Depth + 1))
1524       return true;
1525     if (SimplifyDemandedBits(Op.getOperand(1), DemandedBits, Known2, TLO,
1526                              Depth + 1))
1527       return true;
1528     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
1529     assert(!Known2.hasConflict() && "Bits known to be one AND zero?");
1530 
1531     // If the operands are constants, see if we can simplify them.
1532     if (ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO))
1533       return true;
1534 
1535     // Only known if known in both the LHS and RHS.
1536     Known = KnownBits::commonBits(Known, Known2);
1537     break;
1538   case ISD::SELECT_CC:
1539     if (SimplifyDemandedBits(Op.getOperand(3), DemandedBits, Known, TLO,
1540                              Depth + 1))
1541       return true;
1542     if (SimplifyDemandedBits(Op.getOperand(2), DemandedBits, Known2, TLO,
1543                              Depth + 1))
1544       return true;
1545     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
1546     assert(!Known2.hasConflict() && "Bits known to be one AND zero?");
1547 
1548     // If the operands are constants, see if we can simplify them.
1549     if (ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO))
1550       return true;
1551 
1552     // Only known if known in both the LHS and RHS.
1553     Known = KnownBits::commonBits(Known, Known2);
1554     break;
1555   case ISD::SETCC: {
1556     SDValue Op0 = Op.getOperand(0);
1557     SDValue Op1 = Op.getOperand(1);
1558     ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
1559     // If (1) we only need the sign-bit, (2) the setcc operands are the same
1560     // width as the setcc result, and (3) the result of a setcc conforms to 0 or
1561     // -1, we may be able to bypass the setcc.
1562     if (DemandedBits.isSignMask() &&
1563         Op0.getScalarValueSizeInBits() == BitWidth &&
1564         getBooleanContents(Op0.getValueType()) ==
1565             BooleanContent::ZeroOrNegativeOneBooleanContent) {
1566       // If we're testing X < 0, then this compare isn't needed - just use X!
1567       // FIXME: We're limiting to integer types here, but this should also work
1568       // if we don't care about FP signed-zero. The use of SETLT with FP means
1569       // that we don't care about NaNs.
1570       if (CC == ISD::SETLT && Op1.getValueType().isInteger() &&
1571           (isNullConstant(Op1) || ISD::isBuildVectorAllZeros(Op1.getNode())))
1572         return TLO.CombineTo(Op, Op0);
1573 
1574       // TODO: Should we check for other forms of sign-bit comparisons?
1575       // Examples: X <= -1, X >= 0
1576     }
1577     if (getBooleanContents(Op0.getValueType()) ==
1578             TargetLowering::ZeroOrOneBooleanContent &&
1579         BitWidth > 1)
1580       Known.Zero.setBitsFrom(1);
1581     break;
1582   }
1583   case ISD::SHL: {
1584     SDValue Op0 = Op.getOperand(0);
1585     SDValue Op1 = Op.getOperand(1);
1586     EVT ShiftVT = Op1.getValueType();
1587 
1588     if (const APInt *SA =
1589             TLO.DAG.getValidShiftAmountConstant(Op, DemandedElts)) {
1590       unsigned ShAmt = SA->getZExtValue();
1591       if (ShAmt == 0)
1592         return TLO.CombineTo(Op, Op0);
1593 
1594       // If this is ((X >>u C1) << ShAmt), see if we can simplify this into a
1595       // single shift.  We can do this if the bottom bits (which are shifted
1596       // out) are never demanded.
1597       // TODO - support non-uniform vector amounts.
1598       if (Op0.getOpcode() == ISD::SRL) {
1599         if (!DemandedBits.intersects(APInt::getLowBitsSet(BitWidth, ShAmt))) {
1600           if (const APInt *SA2 =
1601                   TLO.DAG.getValidShiftAmountConstant(Op0, DemandedElts)) {
1602             unsigned C1 = SA2->getZExtValue();
1603             unsigned Opc = ISD::SHL;
1604             int Diff = ShAmt - C1;
1605             if (Diff < 0) {
1606               Diff = -Diff;
1607               Opc = ISD::SRL;
1608             }
1609             SDValue NewSA = TLO.DAG.getConstant(Diff, dl, ShiftVT);
1610             return TLO.CombineTo(
1611                 Op, TLO.DAG.getNode(Opc, dl, VT, Op0.getOperand(0), NewSA));
1612           }
1613         }
1614       }
1615 
1616       // Convert (shl (anyext x, c)) to (anyext (shl x, c)) if the high bits
1617       // are not demanded. This will likely allow the anyext to be folded away.
1618       // TODO - support non-uniform vector amounts.
1619       if (Op0.getOpcode() == ISD::ANY_EXTEND) {
1620         SDValue InnerOp = Op0.getOperand(0);
1621         EVT InnerVT = InnerOp.getValueType();
1622         unsigned InnerBits = InnerVT.getScalarSizeInBits();
1623         if (ShAmt < InnerBits && DemandedBits.getActiveBits() <= InnerBits &&
1624             isTypeDesirableForOp(ISD::SHL, InnerVT)) {
1625           EVT ShTy = getShiftAmountTy(InnerVT, DL);
1626           if (!APInt(BitWidth, ShAmt).isIntN(ShTy.getSizeInBits()))
1627             ShTy = InnerVT;
1628           SDValue NarrowShl =
1629               TLO.DAG.getNode(ISD::SHL, dl, InnerVT, InnerOp,
1630                               TLO.DAG.getConstant(ShAmt, dl, ShTy));
1631           return TLO.CombineTo(
1632               Op, TLO.DAG.getNode(ISD::ANY_EXTEND, dl, VT, NarrowShl));
1633         }
1634 
1635         // Repeat the SHL optimization above in cases where an extension
1636         // intervenes: (shl (anyext (shr x, c1)), c2) to
1637         // (shl (anyext x), c2-c1).  This requires that the bottom c1 bits
1638         // aren't demanded (as above) and that the shifted upper c1 bits of
1639         // x aren't demanded.
1640         // TODO - support non-uniform vector amounts.
1641         if (Op0.hasOneUse() && InnerOp.getOpcode() == ISD::SRL &&
1642             InnerOp.hasOneUse()) {
1643           if (const APInt *SA2 =
1644                   TLO.DAG.getValidShiftAmountConstant(InnerOp, DemandedElts)) {
1645             unsigned InnerShAmt = SA2->getZExtValue();
1646             if (InnerShAmt < ShAmt && InnerShAmt < InnerBits &&
1647                 DemandedBits.getActiveBits() <=
1648                     (InnerBits - InnerShAmt + ShAmt) &&
1649                 DemandedBits.countTrailingZeros() >= ShAmt) {
1650               SDValue NewSA =
1651                   TLO.DAG.getConstant(ShAmt - InnerShAmt, dl, ShiftVT);
1652               SDValue NewExt = TLO.DAG.getNode(ISD::ANY_EXTEND, dl, VT,
1653                                                InnerOp.getOperand(0));
1654               return TLO.CombineTo(
1655                   Op, TLO.DAG.getNode(ISD::SHL, dl, VT, NewExt, NewSA));
1656             }
1657           }
1658         }
1659       }
1660 
1661       APInt InDemandedMask = DemandedBits.lshr(ShAmt);
1662       if (SimplifyDemandedBits(Op0, InDemandedMask, DemandedElts, Known, TLO,
1663                                Depth + 1))
1664         return true;
1665       assert(!Known.hasConflict() && "Bits known to be one AND zero?");
1666       Known.Zero <<= ShAmt;
1667       Known.One <<= ShAmt;
1668       // low bits known zero.
1669       Known.Zero.setLowBits(ShAmt);
1670 
1671       // Try shrinking the operation as long as the shift amount will still be
1672       // in range.
1673       if ((ShAmt < DemandedBits.getActiveBits()) &&
1674           ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO))
1675         return true;
1676     }
1677 
1678     // If we are only demanding sign bits then we can use the shift source
1679     // directly.
1680     if (const APInt *MaxSA =
1681             TLO.DAG.getValidMaximumShiftAmountConstant(Op, DemandedElts)) {
1682       unsigned ShAmt = MaxSA->getZExtValue();
1683       unsigned NumSignBits =
1684           TLO.DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1);
1685       unsigned UpperDemandedBits = BitWidth - DemandedBits.countTrailingZeros();
1686       if (NumSignBits > ShAmt && (NumSignBits - ShAmt) >= (UpperDemandedBits))
1687         return TLO.CombineTo(Op, Op0);
1688     }
1689     break;
1690   }
1691   case ISD::SRL: {
1692     SDValue Op0 = Op.getOperand(0);
1693     SDValue Op1 = Op.getOperand(1);
1694     EVT ShiftVT = Op1.getValueType();
1695 
1696     // Try to match AVG patterns.
1697     if (SDValue AVG = combineShiftToAVG(Op, TLO.DAG, *this, DemandedBits,
1698                                         DemandedElts, Depth + 1))
1699       return TLO.CombineTo(Op, AVG);
1700 
1701     if (const APInt *SA =
1702             TLO.DAG.getValidShiftAmountConstant(Op, DemandedElts)) {
1703       unsigned ShAmt = SA->getZExtValue();
1704       if (ShAmt == 0)
1705         return TLO.CombineTo(Op, Op0);
1706 
1707       // If this is ((X << C1) >>u ShAmt), see if we can simplify this into a
1708       // single shift.  We can do this if the top bits (which are shifted out)
1709       // are never demanded.
1710       // TODO - support non-uniform vector amounts.
1711       if (Op0.getOpcode() == ISD::SHL) {
1712         if (!DemandedBits.intersects(APInt::getHighBitsSet(BitWidth, ShAmt))) {
1713           if (const APInt *SA2 =
1714                   TLO.DAG.getValidShiftAmountConstant(Op0, DemandedElts)) {
1715             unsigned C1 = SA2->getZExtValue();
1716             unsigned Opc = ISD::SRL;
1717             int Diff = ShAmt - C1;
1718             if (Diff < 0) {
1719               Diff = -Diff;
1720               Opc = ISD::SHL;
1721             }
1722             SDValue NewSA = TLO.DAG.getConstant(Diff, dl, ShiftVT);
1723             return TLO.CombineTo(
1724                 Op, TLO.DAG.getNode(Opc, dl, VT, Op0.getOperand(0), NewSA));
1725           }
1726         }
1727       }
1728 
1729       APInt InDemandedMask = (DemandedBits << ShAmt);
1730 
1731       // If the shift is exact, then it does demand the low bits (and knows that
1732       // they are zero).
1733       if (Op->getFlags().hasExact())
1734         InDemandedMask.setLowBits(ShAmt);
1735 
1736       // Compute the new bits that are at the top now.
1737       if (SimplifyDemandedBits(Op0, InDemandedMask, DemandedElts, Known, TLO,
1738                                Depth + 1))
1739         return true;
1740       assert(!Known.hasConflict() && "Bits known to be one AND zero?");
1741       Known.Zero.lshrInPlace(ShAmt);
1742       Known.One.lshrInPlace(ShAmt);
1743       // High bits known zero.
1744       Known.Zero.setHighBits(ShAmt);
1745     }
1746     break;
1747   }
1748   case ISD::SRA: {
1749     SDValue Op0 = Op.getOperand(0);
1750     SDValue Op1 = Op.getOperand(1);
1751     EVT ShiftVT = Op1.getValueType();
1752 
1753     // If we only want bits that already match the signbit then we don't need
1754     // to shift.
1755     unsigned NumHiDemandedBits = BitWidth - DemandedBits.countTrailingZeros();
1756     if (TLO.DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1) >=
1757         NumHiDemandedBits)
1758       return TLO.CombineTo(Op, Op0);
1759 
1760     // If this is an arithmetic shift right and only the low-bit is set, we can
1761     // always convert this into a logical shr, even if the shift amount is
1762     // variable.  The low bit of the shift cannot be an input sign bit unless
1763     // the shift amount is >= the size of the datatype, which is undefined.
1764     if (DemandedBits.isOne())
1765       return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, Op1));
1766 
1767     // Try to match AVG patterns.
1768     if (SDValue AVG = combineShiftToAVG(Op, TLO.DAG, *this, DemandedBits,
1769                                         DemandedElts, Depth + 1))
1770       return TLO.CombineTo(Op, AVG);
1771 
1772     if (const APInt *SA =
1773             TLO.DAG.getValidShiftAmountConstant(Op, DemandedElts)) {
1774       unsigned ShAmt = SA->getZExtValue();
1775       if (ShAmt == 0)
1776         return TLO.CombineTo(Op, Op0);
1777 
1778       APInt InDemandedMask = (DemandedBits << ShAmt);
1779 
1780       // If the shift is exact, then it does demand the low bits (and knows that
1781       // they are zero).
1782       if (Op->getFlags().hasExact())
1783         InDemandedMask.setLowBits(ShAmt);
1784 
1785       // If any of the demanded bits are produced by the sign extension, we also
1786       // demand the input sign bit.
1787       if (DemandedBits.countLeadingZeros() < ShAmt)
1788         InDemandedMask.setSignBit();
1789 
1790       if (SimplifyDemandedBits(Op0, InDemandedMask, DemandedElts, Known, TLO,
1791                                Depth + 1))
1792         return true;
1793       assert(!Known.hasConflict() && "Bits known to be one AND zero?");
1794       Known.Zero.lshrInPlace(ShAmt);
1795       Known.One.lshrInPlace(ShAmt);
1796 
1797       // If the input sign bit is known to be zero, or if none of the top bits
1798       // are demanded, turn this into an unsigned shift right.
1799       if (Known.Zero[BitWidth - ShAmt - 1] ||
1800           DemandedBits.countLeadingZeros() >= ShAmt) {
1801         SDNodeFlags Flags;
1802         Flags.setExact(Op->getFlags().hasExact());
1803         return TLO.CombineTo(
1804             Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, Op1, Flags));
1805       }
1806 
1807       int Log2 = DemandedBits.exactLogBase2();
1808       if (Log2 >= 0) {
1809         // The bit must come from the sign.
1810         SDValue NewSA = TLO.DAG.getConstant(BitWidth - 1 - Log2, dl, ShiftVT);
1811         return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, NewSA));
1812       }
1813 
1814       if (Known.One[BitWidth - ShAmt - 1])
1815         // New bits are known one.
1816         Known.One.setHighBits(ShAmt);
1817 
1818       // Attempt to avoid multi-use ops if we don't need anything from them.
1819       if (!InDemandedMask.isAllOnes() || !DemandedElts.isAllOnes()) {
1820         SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits(
1821             Op0, InDemandedMask, DemandedElts, TLO.DAG, Depth + 1);
1822         if (DemandedOp0) {
1823           SDValue NewOp = TLO.DAG.getNode(ISD::SRA, dl, VT, DemandedOp0, Op1);
1824           return TLO.CombineTo(Op, NewOp);
1825         }
1826       }
1827     }
1828     break;
1829   }
1830   case ISD::FSHL:
1831   case ISD::FSHR: {
1832     SDValue Op0 = Op.getOperand(0);
1833     SDValue Op1 = Op.getOperand(1);
1834     SDValue Op2 = Op.getOperand(2);
1835     bool IsFSHL = (Op.getOpcode() == ISD::FSHL);
1836 
1837     if (ConstantSDNode *SA = isConstOrConstSplat(Op2, DemandedElts)) {
1838       unsigned Amt = SA->getAPIntValue().urem(BitWidth);
1839 
1840       // For fshl, 0-shift returns the 1st arg.
1841       // For fshr, 0-shift returns the 2nd arg.
1842       if (Amt == 0) {
1843         if (SimplifyDemandedBits(IsFSHL ? Op0 : Op1, DemandedBits, DemandedElts,
1844                                  Known, TLO, Depth + 1))
1845           return true;
1846         break;
1847       }
1848 
1849       // fshl: (Op0 << Amt) | (Op1 >> (BW - Amt))
1850       // fshr: (Op0 << (BW - Amt)) | (Op1 >> Amt)
1851       APInt Demanded0 = DemandedBits.lshr(IsFSHL ? Amt : (BitWidth - Amt));
1852       APInt Demanded1 = DemandedBits << (IsFSHL ? (BitWidth - Amt) : Amt);
1853       if (SimplifyDemandedBits(Op0, Demanded0, DemandedElts, Known2, TLO,
1854                                Depth + 1))
1855         return true;
1856       if (SimplifyDemandedBits(Op1, Demanded1, DemandedElts, Known, TLO,
1857                                Depth + 1))
1858         return true;
1859 
1860       Known2.One <<= (IsFSHL ? Amt : (BitWidth - Amt));
1861       Known2.Zero <<= (IsFSHL ? Amt : (BitWidth - Amt));
1862       Known.One.lshrInPlace(IsFSHL ? (BitWidth - Amt) : Amt);
1863       Known.Zero.lshrInPlace(IsFSHL ? (BitWidth - Amt) : Amt);
1864       Known.One |= Known2.One;
1865       Known.Zero |= Known2.Zero;
1866     }
1867 
1868     // For pow-2 bitwidths we only demand the bottom modulo amt bits.
1869     if (isPowerOf2_32(BitWidth)) {
1870       APInt DemandedAmtBits(Op2.getScalarValueSizeInBits(), BitWidth - 1);
1871       if (SimplifyDemandedBits(Op2, DemandedAmtBits, DemandedElts,
1872                                Known2, TLO, Depth + 1))
1873         return true;
1874     }
1875     break;
1876   }
1877   case ISD::ROTL:
1878   case ISD::ROTR: {
1879     SDValue Op0 = Op.getOperand(0);
1880     SDValue Op1 = Op.getOperand(1);
1881     bool IsROTL = (Op.getOpcode() == ISD::ROTL);
1882 
1883     // If we're rotating an 0/-1 value, then it stays an 0/-1 value.
1884     if (BitWidth == TLO.DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1))
1885       return TLO.CombineTo(Op, Op0);
1886 
1887     if (ConstantSDNode *SA = isConstOrConstSplat(Op1, DemandedElts)) {
1888       unsigned Amt = SA->getAPIntValue().urem(BitWidth);
1889       unsigned RevAmt = BitWidth - Amt;
1890 
1891       // rotl: (Op0 << Amt) | (Op0 >> (BW - Amt))
1892       // rotr: (Op0 << (BW - Amt)) | (Op0 >> Amt)
1893       APInt Demanded0 = DemandedBits.rotr(IsROTL ? Amt : RevAmt);
1894       if (SimplifyDemandedBits(Op0, Demanded0, DemandedElts, Known2, TLO,
1895                                Depth + 1))
1896         return true;
1897 
1898       // rot*(x, 0) --> x
1899       if (Amt == 0)
1900         return TLO.CombineTo(Op, Op0);
1901 
1902       // See if we don't demand either half of the rotated bits.
1903       if ((!TLO.LegalOperations() || isOperationLegal(ISD::SHL, VT)) &&
1904           DemandedBits.countTrailingZeros() >= (IsROTL ? Amt : RevAmt)) {
1905         Op1 = TLO.DAG.getConstant(IsROTL ? Amt : RevAmt, dl, Op1.getValueType());
1906         return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SHL, dl, VT, Op0, Op1));
1907       }
1908       if ((!TLO.LegalOperations() || isOperationLegal(ISD::SRL, VT)) &&
1909           DemandedBits.countLeadingZeros() >= (IsROTL ? RevAmt : Amt)) {
1910         Op1 = TLO.DAG.getConstant(IsROTL ? RevAmt : Amt, dl, Op1.getValueType());
1911         return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, Op1));
1912       }
1913     }
1914 
1915     // For pow-2 bitwidths we only demand the bottom modulo amt bits.
1916     if (isPowerOf2_32(BitWidth)) {
1917       APInt DemandedAmtBits(Op1.getScalarValueSizeInBits(), BitWidth - 1);
1918       if (SimplifyDemandedBits(Op1, DemandedAmtBits, DemandedElts, Known2, TLO,
1919                                Depth + 1))
1920         return true;
1921     }
1922     break;
1923   }
1924   case ISD::UMIN: {
1925     // Check if one arg is always less than (or equal) to the other arg.
1926     SDValue Op0 = Op.getOperand(0);
1927     SDValue Op1 = Op.getOperand(1);
1928     KnownBits Known0 = TLO.DAG.computeKnownBits(Op0, DemandedElts, Depth + 1);
1929     KnownBits Known1 = TLO.DAG.computeKnownBits(Op1, DemandedElts, Depth + 1);
1930     Known = KnownBits::umin(Known0, Known1);
1931     if (Optional<bool> IsULE = KnownBits::ule(Known0, Known1))
1932       return TLO.CombineTo(Op, IsULE.getValue() ? Op0 : Op1);
1933     if (Optional<bool> IsULT = KnownBits::ult(Known0, Known1))
1934       return TLO.CombineTo(Op, IsULT.getValue() ? Op0 : Op1);
1935     break;
1936   }
1937   case ISD::UMAX: {
1938     // Check if one arg is always greater than (or equal) to the other arg.
1939     SDValue Op0 = Op.getOperand(0);
1940     SDValue Op1 = Op.getOperand(1);
1941     KnownBits Known0 = TLO.DAG.computeKnownBits(Op0, DemandedElts, Depth + 1);
1942     KnownBits Known1 = TLO.DAG.computeKnownBits(Op1, DemandedElts, Depth + 1);
1943     Known = KnownBits::umax(Known0, Known1);
1944     if (Optional<bool> IsUGE = KnownBits::uge(Known0, Known1))
1945       return TLO.CombineTo(Op, IsUGE.getValue() ? Op0 : Op1);
1946     if (Optional<bool> IsUGT = KnownBits::ugt(Known0, Known1))
1947       return TLO.CombineTo(Op, IsUGT.getValue() ? Op0 : Op1);
1948     break;
1949   }
1950   case ISD::BITREVERSE: {
1951     SDValue Src = Op.getOperand(0);
1952     APInt DemandedSrcBits = DemandedBits.reverseBits();
1953     if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedElts, Known2, TLO,
1954                              Depth + 1))
1955       return true;
1956     Known.One = Known2.One.reverseBits();
1957     Known.Zero = Known2.Zero.reverseBits();
1958     break;
1959   }
1960   case ISD::BSWAP: {
1961     SDValue Src = Op.getOperand(0);
1962 
1963     // If the only bits demanded come from one byte of the bswap result,
1964     // just shift the input byte into position to eliminate the bswap.
1965     unsigned NLZ = DemandedBits.countLeadingZeros();
1966     unsigned NTZ = DemandedBits.countTrailingZeros();
1967 
1968     // Round NTZ down to the next byte.  If we have 11 trailing zeros, then
1969     // we need all the bits down to bit 8.  Likewise, round NLZ.  If we
1970     // have 14 leading zeros, round to 8.
1971     NLZ = alignDown(NLZ, 8);
1972     NTZ = alignDown(NTZ, 8);
1973     // If we need exactly one byte, we can do this transformation.
1974     if (BitWidth - NLZ - NTZ == 8) {
1975       // Replace this with either a left or right shift to get the byte into
1976       // the right place.
1977       unsigned ShiftOpcode = NLZ > NTZ ? ISD::SRL : ISD::SHL;
1978       if (!TLO.LegalOperations() || isOperationLegal(ShiftOpcode, VT)) {
1979         EVT ShiftAmtTy = getShiftAmountTy(VT, DL);
1980         unsigned ShiftAmount = NLZ > NTZ ? NLZ - NTZ : NTZ - NLZ;
1981         SDValue ShAmt = TLO.DAG.getConstant(ShiftAmount, dl, ShiftAmtTy);
1982         SDValue NewOp = TLO.DAG.getNode(ShiftOpcode, dl, VT, Src, ShAmt);
1983         return TLO.CombineTo(Op, NewOp);
1984       }
1985     }
1986 
1987     APInt DemandedSrcBits = DemandedBits.byteSwap();
1988     if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedElts, Known2, TLO,
1989                              Depth + 1))
1990       return true;
1991     Known.One = Known2.One.byteSwap();
1992     Known.Zero = Known2.Zero.byteSwap();
1993     break;
1994   }
1995   case ISD::CTPOP: {
1996     // If only 1 bit is demanded, replace with PARITY as long as we're before
1997     // op legalization.
1998     // FIXME: Limit to scalars for now.
1999     if (DemandedBits.isOne() && !TLO.LegalOps && !VT.isVector())
2000       return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::PARITY, dl, VT,
2001                                                Op.getOperand(0)));
2002 
2003     Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth);
2004     break;
2005   }
2006   case ISD::SIGN_EXTEND_INREG: {
2007     SDValue Op0 = Op.getOperand(0);
2008     EVT ExVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
2009     unsigned ExVTBits = ExVT.getScalarSizeInBits();
2010 
2011     // If we only care about the highest bit, don't bother shifting right.
2012     if (DemandedBits.isSignMask()) {
2013       unsigned MinSignedBits =
2014           TLO.DAG.ComputeMaxSignificantBits(Op0, DemandedElts, Depth + 1);
2015       bool AlreadySignExtended = ExVTBits >= MinSignedBits;
2016       // However if the input is already sign extended we expect the sign
2017       // extension to be dropped altogether later and do not simplify.
2018       if (!AlreadySignExtended) {
2019         // Compute the correct shift amount type, which must be getShiftAmountTy
2020         // for scalar types after legalization.
2021         SDValue ShiftAmt = TLO.DAG.getConstant(BitWidth - ExVTBits, dl,
2022                                                getShiftAmountTy(VT, DL));
2023         return TLO.CombineTo(Op,
2024                              TLO.DAG.getNode(ISD::SHL, dl, VT, Op0, ShiftAmt));
2025       }
2026     }
2027 
2028     // If none of the extended bits are demanded, eliminate the sextinreg.
2029     if (DemandedBits.getActiveBits() <= ExVTBits)
2030       return TLO.CombineTo(Op, Op0);
2031 
2032     APInt InputDemandedBits = DemandedBits.getLoBits(ExVTBits);
2033 
2034     // Since the sign extended bits are demanded, we know that the sign
2035     // bit is demanded.
2036     InputDemandedBits.setBit(ExVTBits - 1);
2037 
2038     if (SimplifyDemandedBits(Op0, InputDemandedBits, Known, TLO, Depth + 1))
2039       return true;
2040     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
2041 
2042     // If the sign bit of the input is known set or clear, then we know the
2043     // top bits of the result.
2044 
2045     // If the input sign bit is known zero, convert this into a zero extension.
2046     if (Known.Zero[ExVTBits - 1])
2047       return TLO.CombineTo(Op, TLO.DAG.getZeroExtendInReg(Op0, dl, ExVT));
2048 
2049     APInt Mask = APInt::getLowBitsSet(BitWidth, ExVTBits);
2050     if (Known.One[ExVTBits - 1]) { // Input sign bit known set
2051       Known.One.setBitsFrom(ExVTBits);
2052       Known.Zero &= Mask;
2053     } else { // Input sign bit unknown
2054       Known.Zero &= Mask;
2055       Known.One &= Mask;
2056     }
2057     break;
2058   }
2059   case ISD::BUILD_PAIR: {
2060     EVT HalfVT = Op.getOperand(0).getValueType();
2061     unsigned HalfBitWidth = HalfVT.getScalarSizeInBits();
2062 
2063     APInt MaskLo = DemandedBits.getLoBits(HalfBitWidth).trunc(HalfBitWidth);
2064     APInt MaskHi = DemandedBits.getHiBits(HalfBitWidth).trunc(HalfBitWidth);
2065 
2066     KnownBits KnownLo, KnownHi;
2067 
2068     if (SimplifyDemandedBits(Op.getOperand(0), MaskLo, KnownLo, TLO, Depth + 1))
2069       return true;
2070 
2071     if (SimplifyDemandedBits(Op.getOperand(1), MaskHi, KnownHi, TLO, Depth + 1))
2072       return true;
2073 
2074     Known.Zero = KnownLo.Zero.zext(BitWidth) |
2075                  KnownHi.Zero.zext(BitWidth).shl(HalfBitWidth);
2076 
2077     Known.One = KnownLo.One.zext(BitWidth) |
2078                 KnownHi.One.zext(BitWidth).shl(HalfBitWidth);
2079     break;
2080   }
2081   case ISD::ZERO_EXTEND:
2082   case ISD::ZERO_EXTEND_VECTOR_INREG: {
2083     SDValue Src = Op.getOperand(0);
2084     EVT SrcVT = Src.getValueType();
2085     unsigned InBits = SrcVT.getScalarSizeInBits();
2086     unsigned InElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1;
2087     bool IsVecInReg = Op.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG;
2088 
2089     // If none of the top bits are demanded, convert this into an any_extend.
2090     if (DemandedBits.getActiveBits() <= InBits) {
2091       // If we only need the non-extended bits of the bottom element
2092       // then we can just bitcast to the result.
2093       if (IsLE && IsVecInReg && DemandedElts == 1 &&
2094           VT.getSizeInBits() == SrcVT.getSizeInBits())
2095         return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src));
2096 
2097       unsigned Opc =
2098           IsVecInReg ? ISD::ANY_EXTEND_VECTOR_INREG : ISD::ANY_EXTEND;
2099       if (!TLO.LegalOperations() || isOperationLegal(Opc, VT))
2100         return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT, Src));
2101     }
2102 
2103     APInt InDemandedBits = DemandedBits.trunc(InBits);
2104     APInt InDemandedElts = DemandedElts.zextOrSelf(InElts);
2105     if (SimplifyDemandedBits(Src, InDemandedBits, InDemandedElts, Known, TLO,
2106                              Depth + 1))
2107       return true;
2108     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
2109     assert(Known.getBitWidth() == InBits && "Src width has changed?");
2110     Known = Known.zext(BitWidth);
2111 
2112     // Attempt to avoid multi-use ops if we don't need anything from them.
2113     if (SDValue NewSrc = SimplifyMultipleUseDemandedBits(
2114             Src, InDemandedBits, InDemandedElts, TLO.DAG, Depth + 1))
2115       return TLO.CombineTo(Op, TLO.DAG.getNode(Op.getOpcode(), dl, VT, NewSrc));
2116     break;
2117   }
2118   case ISD::SIGN_EXTEND:
2119   case ISD::SIGN_EXTEND_VECTOR_INREG: {
2120     SDValue Src = Op.getOperand(0);
2121     EVT SrcVT = Src.getValueType();
2122     unsigned InBits = SrcVT.getScalarSizeInBits();
2123     unsigned InElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1;
2124     bool IsVecInReg = Op.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG;
2125 
2126     // If none of the top bits are demanded, convert this into an any_extend.
2127     if (DemandedBits.getActiveBits() <= InBits) {
2128       // If we only need the non-extended bits of the bottom element
2129       // then we can just bitcast to the result.
2130       if (IsLE && IsVecInReg && DemandedElts == 1 &&
2131           VT.getSizeInBits() == SrcVT.getSizeInBits())
2132         return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src));
2133 
2134       unsigned Opc =
2135           IsVecInReg ? ISD::ANY_EXTEND_VECTOR_INREG : ISD::ANY_EXTEND;
2136       if (!TLO.LegalOperations() || isOperationLegal(Opc, VT))
2137         return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT, Src));
2138     }
2139 
2140     APInt InDemandedBits = DemandedBits.trunc(InBits);
2141     APInt InDemandedElts = DemandedElts.zextOrSelf(InElts);
2142 
2143     // Since some of the sign extended bits are demanded, we know that the sign
2144     // bit is demanded.
2145     InDemandedBits.setBit(InBits - 1);
2146 
2147     if (SimplifyDemandedBits(Src, InDemandedBits, InDemandedElts, Known, TLO,
2148                              Depth + 1))
2149       return true;
2150     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
2151     assert(Known.getBitWidth() == InBits && "Src width has changed?");
2152 
2153     // If the sign bit is known one, the top bits match.
2154     Known = Known.sext(BitWidth);
2155 
2156     // If the sign bit is known zero, convert this to a zero extend.
2157     if (Known.isNonNegative()) {
2158       unsigned Opc =
2159           IsVecInReg ? ISD::ZERO_EXTEND_VECTOR_INREG : ISD::ZERO_EXTEND;
2160       if (!TLO.LegalOperations() || isOperationLegal(Opc, VT))
2161         return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT, Src));
2162     }
2163 
2164     // Attempt to avoid multi-use ops if we don't need anything from them.
2165     if (SDValue NewSrc = SimplifyMultipleUseDemandedBits(
2166             Src, InDemandedBits, InDemandedElts, TLO.DAG, Depth + 1))
2167       return TLO.CombineTo(Op, TLO.DAG.getNode(Op.getOpcode(), dl, VT, NewSrc));
2168     break;
2169   }
2170   case ISD::ANY_EXTEND:
2171   case ISD::ANY_EXTEND_VECTOR_INREG: {
2172     SDValue Src = Op.getOperand(0);
2173     EVT SrcVT = Src.getValueType();
2174     unsigned InBits = SrcVT.getScalarSizeInBits();
2175     unsigned InElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1;
2176     bool IsVecInReg = Op.getOpcode() == ISD::ANY_EXTEND_VECTOR_INREG;
2177 
2178     // If we only need the bottom element then we can just bitcast.
2179     // TODO: Handle ANY_EXTEND?
2180     if (IsLE && IsVecInReg && DemandedElts == 1 &&
2181         VT.getSizeInBits() == SrcVT.getSizeInBits())
2182       return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src));
2183 
2184     APInt InDemandedBits = DemandedBits.trunc(InBits);
2185     APInt InDemandedElts = DemandedElts.zextOrSelf(InElts);
2186     if (SimplifyDemandedBits(Src, InDemandedBits, InDemandedElts, Known, TLO,
2187                              Depth + 1))
2188       return true;
2189     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
2190     assert(Known.getBitWidth() == InBits && "Src width has changed?");
2191     Known = Known.anyext(BitWidth);
2192 
2193     // Attempt to avoid multi-use ops if we don't need anything from them.
2194     if (SDValue NewSrc = SimplifyMultipleUseDemandedBits(
2195             Src, InDemandedBits, InDemandedElts, TLO.DAG, Depth + 1))
2196       return TLO.CombineTo(Op, TLO.DAG.getNode(Op.getOpcode(), dl, VT, NewSrc));
2197     break;
2198   }
2199   case ISD::TRUNCATE: {
2200     SDValue Src = Op.getOperand(0);
2201 
2202     // Simplify the input, using demanded bit information, and compute the known
2203     // zero/one bits live out.
2204     unsigned OperandBitWidth = Src.getScalarValueSizeInBits();
2205     APInt TruncMask = DemandedBits.zext(OperandBitWidth);
2206     if (SimplifyDemandedBits(Src, TruncMask, DemandedElts, Known, TLO,
2207                              Depth + 1))
2208       return true;
2209     Known = Known.trunc(BitWidth);
2210 
2211     // Attempt to avoid multi-use ops if we don't need anything from them.
2212     if (SDValue NewSrc = SimplifyMultipleUseDemandedBits(
2213             Src, TruncMask, DemandedElts, TLO.DAG, Depth + 1))
2214       return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::TRUNCATE, dl, VT, NewSrc));
2215 
2216     // If the input is only used by this truncate, see if we can shrink it based
2217     // on the known demanded bits.
2218     if (Src.getNode()->hasOneUse()) {
2219       switch (Src.getOpcode()) {
2220       default:
2221         break;
2222       case ISD::SRL:
2223         // Shrink SRL by a constant if none of the high bits shifted in are
2224         // demanded.
2225         if (TLO.LegalTypes() && !isTypeDesirableForOp(ISD::SRL, VT))
2226           // Do not turn (vt1 truncate (vt2 srl)) into (vt1 srl) if vt1 is
2227           // undesirable.
2228           break;
2229 
2230         const APInt *ShAmtC =
2231             TLO.DAG.getValidShiftAmountConstant(Src, DemandedElts);
2232         if (!ShAmtC || ShAmtC->uge(BitWidth))
2233           break;
2234         uint64_t ShVal = ShAmtC->getZExtValue();
2235 
2236         APInt HighBits =
2237             APInt::getHighBitsSet(OperandBitWidth, OperandBitWidth - BitWidth);
2238         HighBits.lshrInPlace(ShVal);
2239         HighBits = HighBits.trunc(BitWidth);
2240 
2241         if (!(HighBits & DemandedBits)) {
2242           // None of the shifted in bits are needed.  Add a truncate of the
2243           // shift input, then shift it.
2244           SDValue NewShAmt = TLO.DAG.getConstant(
2245               ShVal, dl, getShiftAmountTy(VT, DL, TLO.LegalTypes()));
2246           SDValue NewTrunc =
2247               TLO.DAG.getNode(ISD::TRUNCATE, dl, VT, Src.getOperand(0));
2248           return TLO.CombineTo(
2249               Op, TLO.DAG.getNode(ISD::SRL, dl, VT, NewTrunc, NewShAmt));
2250         }
2251         break;
2252       }
2253     }
2254 
2255     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
2256     break;
2257   }
2258   case ISD::AssertZext: {
2259     // AssertZext demands all of the high bits, plus any of the low bits
2260     // demanded by its users.
2261     EVT ZVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
2262     APInt InMask = APInt::getLowBitsSet(BitWidth, ZVT.getSizeInBits());
2263     if (SimplifyDemandedBits(Op.getOperand(0), ~InMask | DemandedBits, Known,
2264                              TLO, Depth + 1))
2265       return true;
2266     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
2267 
2268     Known.Zero |= ~InMask;
2269     break;
2270   }
2271   case ISD::EXTRACT_VECTOR_ELT: {
2272     SDValue Src = Op.getOperand(0);
2273     SDValue Idx = Op.getOperand(1);
2274     ElementCount SrcEltCnt = Src.getValueType().getVectorElementCount();
2275     unsigned EltBitWidth = Src.getScalarValueSizeInBits();
2276 
2277     if (SrcEltCnt.isScalable())
2278       return false;
2279 
2280     // Demand the bits from every vector element without a constant index.
2281     unsigned NumSrcElts = SrcEltCnt.getFixedValue();
2282     APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
2283     if (auto *CIdx = dyn_cast<ConstantSDNode>(Idx))
2284       if (CIdx->getAPIntValue().ult(NumSrcElts))
2285         DemandedSrcElts = APInt::getOneBitSet(NumSrcElts, CIdx->getZExtValue());
2286 
2287     // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know
2288     // anything about the extended bits.
2289     APInt DemandedSrcBits = DemandedBits;
2290     if (BitWidth > EltBitWidth)
2291       DemandedSrcBits = DemandedSrcBits.trunc(EltBitWidth);
2292 
2293     if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedSrcElts, Known2, TLO,
2294                              Depth + 1))
2295       return true;
2296 
2297     // Attempt to avoid multi-use ops if we don't need anything from them.
2298     if (!DemandedSrcBits.isAllOnes() || !DemandedSrcElts.isAllOnes()) {
2299       if (SDValue DemandedSrc = SimplifyMultipleUseDemandedBits(
2300               Src, DemandedSrcBits, DemandedSrcElts, TLO.DAG, Depth + 1)) {
2301         SDValue NewOp =
2302             TLO.DAG.getNode(Op.getOpcode(), dl, VT, DemandedSrc, Idx);
2303         return TLO.CombineTo(Op, NewOp);
2304       }
2305     }
2306 
2307     Known = Known2;
2308     if (BitWidth > EltBitWidth)
2309       Known = Known.anyext(BitWidth);
2310     break;
2311   }
2312   case ISD::BITCAST: {
2313     SDValue Src = Op.getOperand(0);
2314     EVT SrcVT = Src.getValueType();
2315     unsigned NumSrcEltBits = SrcVT.getScalarSizeInBits();
2316 
2317     // If this is an FP->Int bitcast and if the sign bit is the only
2318     // thing demanded, turn this into a FGETSIGN.
2319     if (!TLO.LegalOperations() && !VT.isVector() && !SrcVT.isVector() &&
2320         DemandedBits == APInt::getSignMask(Op.getValueSizeInBits()) &&
2321         SrcVT.isFloatingPoint()) {
2322       bool OpVTLegal = isOperationLegalOrCustom(ISD::FGETSIGN, VT);
2323       bool i32Legal = isOperationLegalOrCustom(ISD::FGETSIGN, MVT::i32);
2324       if ((OpVTLegal || i32Legal) && VT.isSimple() && SrcVT != MVT::f16 &&
2325           SrcVT != MVT::f128) {
2326         // Cannot eliminate/lower SHL for f128 yet.
2327         EVT Ty = OpVTLegal ? VT : MVT::i32;
2328         // Make a FGETSIGN + SHL to move the sign bit into the appropriate
2329         // place.  We expect the SHL to be eliminated by other optimizations.
2330         SDValue Sign = TLO.DAG.getNode(ISD::FGETSIGN, dl, Ty, Src);
2331         unsigned OpVTSizeInBits = Op.getValueSizeInBits();
2332         if (!OpVTLegal && OpVTSizeInBits > 32)
2333           Sign = TLO.DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Sign);
2334         unsigned ShVal = Op.getValueSizeInBits() - 1;
2335         SDValue ShAmt = TLO.DAG.getConstant(ShVal, dl, VT);
2336         return TLO.CombineTo(Op,
2337                              TLO.DAG.getNode(ISD::SHL, dl, VT, Sign, ShAmt));
2338       }
2339     }
2340 
2341     // Bitcast from a vector using SimplifyDemanded Bits/VectorElts.
2342     // Demand the elt/bit if any of the original elts/bits are demanded.
2343     if (SrcVT.isVector() && (BitWidth % NumSrcEltBits) == 0) {
2344       unsigned Scale = BitWidth / NumSrcEltBits;
2345       unsigned NumSrcElts = SrcVT.getVectorNumElements();
2346       APInt DemandedSrcBits = APInt::getZero(NumSrcEltBits);
2347       APInt DemandedSrcElts = APInt::getZero(NumSrcElts);
2348       for (unsigned i = 0; i != Scale; ++i) {
2349         unsigned EltOffset = IsLE ? i : (Scale - 1 - i);
2350         unsigned BitOffset = EltOffset * NumSrcEltBits;
2351         APInt Sub = DemandedBits.extractBits(NumSrcEltBits, BitOffset);
2352         if (!Sub.isZero()) {
2353           DemandedSrcBits |= Sub;
2354           for (unsigned j = 0; j != NumElts; ++j)
2355             if (DemandedElts[j])
2356               DemandedSrcElts.setBit((j * Scale) + i);
2357         }
2358       }
2359 
2360       APInt KnownSrcUndef, KnownSrcZero;
2361       if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, KnownSrcUndef,
2362                                      KnownSrcZero, TLO, Depth + 1))
2363         return true;
2364 
2365       KnownBits KnownSrcBits;
2366       if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedSrcElts,
2367                                KnownSrcBits, TLO, Depth + 1))
2368         return true;
2369     } else if (IsLE && (NumSrcEltBits % BitWidth) == 0) {
2370       // TODO - bigendian once we have test coverage.
2371       unsigned Scale = NumSrcEltBits / BitWidth;
2372       unsigned NumSrcElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1;
2373       APInt DemandedSrcBits = APInt::getZero(NumSrcEltBits);
2374       APInt DemandedSrcElts = APInt::getZero(NumSrcElts);
2375       for (unsigned i = 0; i != NumElts; ++i)
2376         if (DemandedElts[i]) {
2377           unsigned Offset = (i % Scale) * BitWidth;
2378           DemandedSrcBits.insertBits(DemandedBits, Offset);
2379           DemandedSrcElts.setBit(i / Scale);
2380         }
2381 
2382       if (SrcVT.isVector()) {
2383         APInt KnownSrcUndef, KnownSrcZero;
2384         if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, KnownSrcUndef,
2385                                        KnownSrcZero, TLO, Depth + 1))
2386           return true;
2387       }
2388 
2389       KnownBits KnownSrcBits;
2390       if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedSrcElts,
2391                                KnownSrcBits, TLO, Depth + 1))
2392         return true;
2393     }
2394 
2395     // If this is a bitcast, let computeKnownBits handle it.  Only do this on a
2396     // recursive call where Known may be useful to the caller.
2397     if (Depth > 0) {
2398       Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth);
2399       return false;
2400     }
2401     break;
2402   }
2403   case ISD::MUL:
2404     if (DemandedBits.isPowerOf2()) {
2405       // The LSB of X*Y is set only if (X & 1) == 1 and (Y & 1) == 1.
2406       // If we demand exactly one bit N and we have "X * (C' << N)" where C' is
2407       // odd (has LSB set), then the left-shifted low bit of X is the answer.
2408       unsigned CTZ = DemandedBits.countTrailingZeros();
2409       ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(1), DemandedElts);
2410       if (C && C->getAPIntValue().countTrailingZeros() == CTZ) {
2411         EVT ShiftAmtTy = getShiftAmountTy(VT, TLO.DAG.getDataLayout());
2412         SDValue AmtC = TLO.DAG.getConstant(CTZ, dl, ShiftAmtTy);
2413         SDValue Shl = TLO.DAG.getNode(ISD::SHL, dl, VT, Op.getOperand(0), AmtC);
2414         return TLO.CombineTo(Op, Shl);
2415       }
2416     }
2417     // For a squared value "X * X", the bottom 2 bits are 0 and X[0] because:
2418     // X * X is odd iff X is odd.
2419     // 'Quadratic Reciprocity': X * X -> 0 for bit[1]
2420     if (Op.getOperand(0) == Op.getOperand(1) && DemandedBits.ult(4)) {
2421       SDValue One = TLO.DAG.getConstant(1, dl, VT);
2422       SDValue And1 = TLO.DAG.getNode(ISD::AND, dl, VT, Op.getOperand(0), One);
2423       return TLO.CombineTo(Op, And1);
2424     }
2425     LLVM_FALLTHROUGH;
2426   case ISD::ADD:
2427   case ISD::SUB: {
2428     // Add, Sub, and Mul don't demand any bits in positions beyond that
2429     // of the highest bit demanded of them.
2430     SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
2431     SDNodeFlags Flags = Op.getNode()->getFlags();
2432     unsigned DemandedBitsLZ = DemandedBits.countLeadingZeros();
2433     APInt LoMask = APInt::getLowBitsSet(BitWidth, BitWidth - DemandedBitsLZ);
2434     if (SimplifyDemandedBits(Op0, LoMask, DemandedElts, Known2, TLO,
2435                              Depth + 1) ||
2436         SimplifyDemandedBits(Op1, LoMask, DemandedElts, Known2, TLO,
2437                              Depth + 1) ||
2438         // See if the operation should be performed at a smaller bit width.
2439         ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO)) {
2440       if (Flags.hasNoSignedWrap() || Flags.hasNoUnsignedWrap()) {
2441         // Disable the nsw and nuw flags. We can no longer guarantee that we
2442         // won't wrap after simplification.
2443         Flags.setNoSignedWrap(false);
2444         Flags.setNoUnsignedWrap(false);
2445         SDValue NewOp =
2446             TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1, Flags);
2447         return TLO.CombineTo(Op, NewOp);
2448       }
2449       return true;
2450     }
2451 
2452     // Attempt to avoid multi-use ops if we don't need anything from them.
2453     if (!LoMask.isAllOnes() || !DemandedElts.isAllOnes()) {
2454       SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits(
2455           Op0, LoMask, DemandedElts, TLO.DAG, Depth + 1);
2456       SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits(
2457           Op1, LoMask, DemandedElts, TLO.DAG, Depth + 1);
2458       if (DemandedOp0 || DemandedOp1) {
2459         Flags.setNoSignedWrap(false);
2460         Flags.setNoUnsignedWrap(false);
2461         Op0 = DemandedOp0 ? DemandedOp0 : Op0;
2462         Op1 = DemandedOp1 ? DemandedOp1 : Op1;
2463         SDValue NewOp =
2464             TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1, Flags);
2465         return TLO.CombineTo(Op, NewOp);
2466       }
2467     }
2468 
2469     // If we have a constant operand, we may be able to turn it into -1 if we
2470     // do not demand the high bits. This can make the constant smaller to
2471     // encode, allow more general folding, or match specialized instruction
2472     // patterns (eg, 'blsr' on x86). Don't bother changing 1 to -1 because that
2473     // is probably not useful (and could be detrimental).
2474     ConstantSDNode *C = isConstOrConstSplat(Op1);
2475     APInt HighMask = APInt::getHighBitsSet(BitWidth, DemandedBitsLZ);
2476     if (C && !C->isAllOnes() && !C->isOne() &&
2477         (C->getAPIntValue() | HighMask).isAllOnes()) {
2478       SDValue Neg1 = TLO.DAG.getAllOnesConstant(dl, VT);
2479       // Disable the nsw and nuw flags. We can no longer guarantee that we
2480       // won't wrap after simplification.
2481       Flags.setNoSignedWrap(false);
2482       Flags.setNoUnsignedWrap(false);
2483       SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Neg1, Flags);
2484       return TLO.CombineTo(Op, NewOp);
2485     }
2486 
2487     // Match a multiply with a disguised negated-power-of-2 and convert to a
2488     // an equivalent shift-left amount.
2489     // Example: (X * MulC) + Op1 --> Op1 - (X << log2(-MulC))
2490     auto getShiftLeftAmt = [&HighMask](SDValue Mul) -> unsigned {
2491       if (Mul.getOpcode() != ISD::MUL || !Mul.hasOneUse())
2492         return 0;
2493 
2494       // Don't touch opaque constants. Also, ignore zero and power-of-2
2495       // multiplies. Those will get folded later.
2496       ConstantSDNode *MulC = isConstOrConstSplat(Mul.getOperand(1));
2497       if (MulC && !MulC->isOpaque() && !MulC->isZero() &&
2498           !MulC->getAPIntValue().isPowerOf2()) {
2499         APInt UnmaskedC = MulC->getAPIntValue() | HighMask;
2500         if (UnmaskedC.isNegatedPowerOf2())
2501           return (-UnmaskedC).logBase2();
2502       }
2503       return 0;
2504     };
2505 
2506     auto foldMul = [&](SDValue X, SDValue Y, unsigned ShlAmt) {
2507       EVT ShiftAmtTy = getShiftAmountTy(VT, TLO.DAG.getDataLayout());
2508       SDValue ShlAmtC = TLO.DAG.getConstant(ShlAmt, dl, ShiftAmtTy);
2509       SDValue Shl = TLO.DAG.getNode(ISD::SHL, dl, VT, X, ShlAmtC);
2510       SDValue Sub = TLO.DAG.getNode(ISD::SUB, dl, VT, Y, Shl);
2511       return TLO.CombineTo(Op, Sub);
2512     };
2513 
2514     if (isOperationLegalOrCustom(ISD::SHL, VT)) {
2515       if (Op.getOpcode() == ISD::ADD) {
2516         // (X * MulC) + Op1 --> Op1 - (X << log2(-MulC))
2517         if (unsigned ShAmt = getShiftLeftAmt(Op0))
2518           return foldMul(Op0.getOperand(0), Op1, ShAmt);
2519         // Op0 + (X * MulC) --> Op0 - (X << log2(-MulC))
2520         if (unsigned ShAmt = getShiftLeftAmt(Op1))
2521           return foldMul(Op1.getOperand(0), Op0, ShAmt);
2522         // TODO:
2523         // Op0 - (X * MulC) --> Op0 + (X << log2(-MulC))
2524       }
2525     }
2526 
2527     LLVM_FALLTHROUGH;
2528   }
2529   default:
2530     if (Op.getOpcode() >= ISD::BUILTIN_OP_END) {
2531       if (SimplifyDemandedBitsForTargetNode(Op, DemandedBits, DemandedElts,
2532                                             Known, TLO, Depth))
2533         return true;
2534       break;
2535     }
2536 
2537     // Just use computeKnownBits to compute output bits.
2538     Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth);
2539     break;
2540   }
2541 
2542   // If we know the value of all of the demanded bits, return this as a
2543   // constant.
2544   if (DemandedBits.isSubsetOf(Known.Zero | Known.One)) {
2545     // Avoid folding to a constant if any OpaqueConstant is involved.
2546     const SDNode *N = Op.getNode();
2547     for (SDNode *Op :
2548          llvm::make_range(SDNodeIterator::begin(N), SDNodeIterator::end(N))) {
2549       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
2550         if (C->isOpaque())
2551           return false;
2552     }
2553     if (VT.isInteger())
2554       return TLO.CombineTo(Op, TLO.DAG.getConstant(Known.One, dl, VT));
2555     if (VT.isFloatingPoint())
2556       return TLO.CombineTo(
2557           Op,
2558           TLO.DAG.getConstantFP(
2559               APFloat(TLO.DAG.EVTToAPFloatSemantics(VT), Known.One), dl, VT));
2560   }
2561 
2562   return false;
2563 }
2564 
2565 bool TargetLowering::SimplifyDemandedVectorElts(SDValue Op,
2566                                                 const APInt &DemandedElts,
2567                                                 DAGCombinerInfo &DCI) const {
2568   SelectionDAG &DAG = DCI.DAG;
2569   TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
2570                         !DCI.isBeforeLegalizeOps());
2571 
2572   APInt KnownUndef, KnownZero;
2573   bool Simplified =
2574       SimplifyDemandedVectorElts(Op, DemandedElts, KnownUndef, KnownZero, TLO);
2575   if (Simplified) {
2576     DCI.AddToWorklist(Op.getNode());
2577     DCI.CommitTargetLoweringOpt(TLO);
2578   }
2579 
2580   return Simplified;
2581 }
2582 
2583 /// Given a vector binary operation and known undefined elements for each input
2584 /// operand, compute whether each element of the output is undefined.
2585 static APInt getKnownUndefForVectorBinop(SDValue BO, SelectionDAG &DAG,
2586                                          const APInt &UndefOp0,
2587                                          const APInt &UndefOp1) {
2588   EVT VT = BO.getValueType();
2589   assert(DAG.getTargetLoweringInfo().isBinOp(BO.getOpcode()) && VT.isVector() &&
2590          "Vector binop only");
2591 
2592   EVT EltVT = VT.getVectorElementType();
2593   unsigned NumElts = VT.getVectorNumElements();
2594   assert(UndefOp0.getBitWidth() == NumElts &&
2595          UndefOp1.getBitWidth() == NumElts && "Bad type for undef analysis");
2596 
2597   auto getUndefOrConstantElt = [&](SDValue V, unsigned Index,
2598                                    const APInt &UndefVals) {
2599     if (UndefVals[Index])
2600       return DAG.getUNDEF(EltVT);
2601 
2602     if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) {
2603       // Try hard to make sure that the getNode() call is not creating temporary
2604       // nodes. Ignore opaque integers because they do not constant fold.
2605       SDValue Elt = BV->getOperand(Index);
2606       auto *C = dyn_cast<ConstantSDNode>(Elt);
2607       if (isa<ConstantFPSDNode>(Elt) || Elt.isUndef() || (C && !C->isOpaque()))
2608         return Elt;
2609     }
2610 
2611     return SDValue();
2612   };
2613 
2614   APInt KnownUndef = APInt::getZero(NumElts);
2615   for (unsigned i = 0; i != NumElts; ++i) {
2616     // If both inputs for this element are either constant or undef and match
2617     // the element type, compute the constant/undef result for this element of
2618     // the vector.
2619     // TODO: Ideally we would use FoldConstantArithmetic() here, but that does
2620     // not handle FP constants. The code within getNode() should be refactored
2621     // to avoid the danger of creating a bogus temporary node here.
2622     SDValue C0 = getUndefOrConstantElt(BO.getOperand(0), i, UndefOp0);
2623     SDValue C1 = getUndefOrConstantElt(BO.getOperand(1), i, UndefOp1);
2624     if (C0 && C1 && C0.getValueType() == EltVT && C1.getValueType() == EltVT)
2625       if (DAG.getNode(BO.getOpcode(), SDLoc(BO), EltVT, C0, C1).isUndef())
2626         KnownUndef.setBit(i);
2627   }
2628   return KnownUndef;
2629 }
2630 
2631 bool TargetLowering::SimplifyDemandedVectorElts(
2632     SDValue Op, const APInt &OriginalDemandedElts, APInt &KnownUndef,
2633     APInt &KnownZero, TargetLoweringOpt &TLO, unsigned Depth,
2634     bool AssumeSingleUse) const {
2635   EVT VT = Op.getValueType();
2636   unsigned Opcode = Op.getOpcode();
2637   APInt DemandedElts = OriginalDemandedElts;
2638   unsigned NumElts = DemandedElts.getBitWidth();
2639   assert(VT.isVector() && "Expected vector op");
2640 
2641   KnownUndef = KnownZero = APInt::getZero(NumElts);
2642 
2643   const TargetLowering &TLI = TLO.DAG.getTargetLoweringInfo();
2644   if (!TLI.shouldSimplifyDemandedVectorElts(Op, TLO))
2645     return false;
2646 
2647   // TODO: For now we assume we know nothing about scalable vectors.
2648   if (VT.isScalableVector())
2649     return false;
2650 
2651   assert(VT.getVectorNumElements() == NumElts &&
2652          "Mask size mismatches value type element count!");
2653 
2654   // Undef operand.
2655   if (Op.isUndef()) {
2656     KnownUndef.setAllBits();
2657     return false;
2658   }
2659 
2660   // If Op has other users, assume that all elements are needed.
2661   if (!Op.getNode()->hasOneUse() && !AssumeSingleUse)
2662     DemandedElts.setAllBits();
2663 
2664   // Not demanding any elements from Op.
2665   if (DemandedElts == 0) {
2666     KnownUndef.setAllBits();
2667     return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT));
2668   }
2669 
2670   // Limit search depth.
2671   if (Depth >= SelectionDAG::MaxRecursionDepth)
2672     return false;
2673 
2674   SDLoc DL(Op);
2675   unsigned EltSizeInBits = VT.getScalarSizeInBits();
2676   bool IsLE = TLO.DAG.getDataLayout().isLittleEndian();
2677 
2678   // Helper for demanding the specified elements and all the bits of both binary
2679   // operands.
2680   auto SimplifyDemandedVectorEltsBinOp = [&](SDValue Op0, SDValue Op1) {
2681     SDValue NewOp0 = SimplifyMultipleUseDemandedVectorElts(Op0, DemandedElts,
2682                                                            TLO.DAG, Depth + 1);
2683     SDValue NewOp1 = SimplifyMultipleUseDemandedVectorElts(Op1, DemandedElts,
2684                                                            TLO.DAG, Depth + 1);
2685     if (NewOp0 || NewOp1) {
2686       SDValue NewOp = TLO.DAG.getNode(
2687           Opcode, SDLoc(Op), VT, NewOp0 ? NewOp0 : Op0, NewOp1 ? NewOp1 : Op1);
2688       return TLO.CombineTo(Op, NewOp);
2689     }
2690     return false;
2691   };
2692 
2693   switch (Opcode) {
2694   case ISD::SCALAR_TO_VECTOR: {
2695     if (!DemandedElts[0]) {
2696       KnownUndef.setAllBits();
2697       return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT));
2698     }
2699     SDValue ScalarSrc = Op.getOperand(0);
2700     if (ScalarSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
2701       SDValue Src = ScalarSrc.getOperand(0);
2702       SDValue Idx = ScalarSrc.getOperand(1);
2703       EVT SrcVT = Src.getValueType();
2704 
2705       ElementCount SrcEltCnt = SrcVT.getVectorElementCount();
2706 
2707       if (SrcEltCnt.isScalable())
2708         return false;
2709 
2710       unsigned NumSrcElts = SrcEltCnt.getFixedValue();
2711       if (isNullConstant(Idx)) {
2712         APInt SrcDemandedElts = APInt::getOneBitSet(NumSrcElts, 0);
2713         APInt SrcUndef = KnownUndef.zextOrTrunc(NumSrcElts);
2714         APInt SrcZero = KnownZero.zextOrTrunc(NumSrcElts);
2715         if (SimplifyDemandedVectorElts(Src, SrcDemandedElts, SrcUndef, SrcZero,
2716                                        TLO, Depth + 1))
2717           return true;
2718       }
2719     }
2720     KnownUndef.setHighBits(NumElts - 1);
2721     break;
2722   }
2723   case ISD::BITCAST: {
2724     SDValue Src = Op.getOperand(0);
2725     EVT SrcVT = Src.getValueType();
2726 
2727     // We only handle vectors here.
2728     // TODO - investigate calling SimplifyDemandedBits/ComputeKnownBits?
2729     if (!SrcVT.isVector())
2730       break;
2731 
2732     // Fast handling of 'identity' bitcasts.
2733     unsigned NumSrcElts = SrcVT.getVectorNumElements();
2734     if (NumSrcElts == NumElts)
2735       return SimplifyDemandedVectorElts(Src, DemandedElts, KnownUndef,
2736                                         KnownZero, TLO, Depth + 1);
2737 
2738     APInt SrcDemandedElts, SrcZero, SrcUndef;
2739 
2740     // Bitcast from 'large element' src vector to 'small element' vector, we
2741     // must demand a source element if any DemandedElt maps to it.
2742     if ((NumElts % NumSrcElts) == 0) {
2743       unsigned Scale = NumElts / NumSrcElts;
2744       SrcDemandedElts = APIntOps::ScaleBitMask(DemandedElts, NumSrcElts);
2745       if (SimplifyDemandedVectorElts(Src, SrcDemandedElts, SrcUndef, SrcZero,
2746                                      TLO, Depth + 1))
2747         return true;
2748 
2749       // Try calling SimplifyDemandedBits, converting demanded elts to the bits
2750       // of the large element.
2751       // TODO - bigendian once we have test coverage.
2752       if (IsLE) {
2753         unsigned SrcEltSizeInBits = SrcVT.getScalarSizeInBits();
2754         APInt SrcDemandedBits = APInt::getZero(SrcEltSizeInBits);
2755         for (unsigned i = 0; i != NumElts; ++i)
2756           if (DemandedElts[i]) {
2757             unsigned Ofs = (i % Scale) * EltSizeInBits;
2758             SrcDemandedBits.setBits(Ofs, Ofs + EltSizeInBits);
2759           }
2760 
2761         KnownBits Known;
2762         if (SimplifyDemandedBits(Src, SrcDemandedBits, SrcDemandedElts, Known,
2763                                  TLO, Depth + 1))
2764           return true;
2765 
2766         // The bitcast has split each wide element into a number of
2767         // narrow subelements. We have just computed the Known bits
2768         // for wide elements. See if element splitting results in
2769         // some subelements being zero. Only for demanded elements!
2770         for (unsigned SubElt = 0; SubElt != Scale; ++SubElt) {
2771           if (!Known.Zero.extractBits(EltSizeInBits, SubElt * EltSizeInBits)
2772                    .isAllOnes())
2773             continue;
2774           for (unsigned SrcElt = 0; SrcElt != NumSrcElts; ++SrcElt) {
2775             unsigned Elt = Scale * SrcElt + SubElt;
2776             if (DemandedElts[Elt])
2777               KnownZero.setBit(Elt);
2778           }
2779         }
2780       }
2781 
2782       // If the src element is zero/undef then all the output elements will be -
2783       // only demanded elements are guaranteed to be correct.
2784       for (unsigned i = 0; i != NumSrcElts; ++i) {
2785         if (SrcDemandedElts[i]) {
2786           if (SrcZero[i])
2787             KnownZero.setBits(i * Scale, (i + 1) * Scale);
2788           if (SrcUndef[i])
2789             KnownUndef.setBits(i * Scale, (i + 1) * Scale);
2790         }
2791       }
2792     }
2793 
2794     // Bitcast from 'small element' src vector to 'large element' vector, we
2795     // demand all smaller source elements covered by the larger demanded element
2796     // of this vector.
2797     if ((NumSrcElts % NumElts) == 0) {
2798       unsigned Scale = NumSrcElts / NumElts;
2799       SrcDemandedElts = APIntOps::ScaleBitMask(DemandedElts, NumSrcElts);
2800       if (SimplifyDemandedVectorElts(Src, SrcDemandedElts, SrcUndef, SrcZero,
2801                                      TLO, Depth + 1))
2802         return true;
2803 
2804       // If all the src elements covering an output element are zero/undef, then
2805       // the output element will be as well, assuming it was demanded.
2806       for (unsigned i = 0; i != NumElts; ++i) {
2807         if (DemandedElts[i]) {
2808           if (SrcZero.extractBits(Scale, i * Scale).isAllOnes())
2809             KnownZero.setBit(i);
2810           if (SrcUndef.extractBits(Scale, i * Scale).isAllOnes())
2811             KnownUndef.setBit(i);
2812         }
2813       }
2814     }
2815     break;
2816   }
2817   case ISD::BUILD_VECTOR: {
2818     // Check all elements and simplify any unused elements with UNDEF.
2819     if (!DemandedElts.isAllOnes()) {
2820       // Don't simplify BROADCASTS.
2821       if (llvm::any_of(Op->op_values(),
2822                        [&](SDValue Elt) { return Op.getOperand(0) != Elt; })) {
2823         SmallVector<SDValue, 32> Ops(Op->op_begin(), Op->op_end());
2824         bool Updated = false;
2825         for (unsigned i = 0; i != NumElts; ++i) {
2826           if (!DemandedElts[i] && !Ops[i].isUndef()) {
2827             Ops[i] = TLO.DAG.getUNDEF(Ops[0].getValueType());
2828             KnownUndef.setBit(i);
2829             Updated = true;
2830           }
2831         }
2832         if (Updated)
2833           return TLO.CombineTo(Op, TLO.DAG.getBuildVector(VT, DL, Ops));
2834       }
2835     }
2836     for (unsigned i = 0; i != NumElts; ++i) {
2837       SDValue SrcOp = Op.getOperand(i);
2838       if (SrcOp.isUndef()) {
2839         KnownUndef.setBit(i);
2840       } else if (EltSizeInBits == SrcOp.getScalarValueSizeInBits() &&
2841                  (isNullConstant(SrcOp) || isNullFPConstant(SrcOp))) {
2842         KnownZero.setBit(i);
2843       }
2844     }
2845     break;
2846   }
2847   case ISD::CONCAT_VECTORS: {
2848     EVT SubVT = Op.getOperand(0).getValueType();
2849     unsigned NumSubVecs = Op.getNumOperands();
2850     unsigned NumSubElts = SubVT.getVectorNumElements();
2851     for (unsigned i = 0; i != NumSubVecs; ++i) {
2852       SDValue SubOp = Op.getOperand(i);
2853       APInt SubElts = DemandedElts.extractBits(NumSubElts, i * NumSubElts);
2854       APInt SubUndef, SubZero;
2855       if (SimplifyDemandedVectorElts(SubOp, SubElts, SubUndef, SubZero, TLO,
2856                                      Depth + 1))
2857         return true;
2858       KnownUndef.insertBits(SubUndef, i * NumSubElts);
2859       KnownZero.insertBits(SubZero, i * NumSubElts);
2860     }
2861     break;
2862   }
2863   case ISD::INSERT_SUBVECTOR: {
2864     // Demand any elements from the subvector and the remainder from the src its
2865     // inserted into.
2866     SDValue Src = Op.getOperand(0);
2867     SDValue Sub = Op.getOperand(1);
2868     uint64_t Idx = Op.getConstantOperandVal(2);
2869     unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
2870     APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
2871     APInt DemandedSrcElts = DemandedElts;
2872     DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx);
2873 
2874     APInt SubUndef, SubZero;
2875     if (SimplifyDemandedVectorElts(Sub, DemandedSubElts, SubUndef, SubZero, TLO,
2876                                    Depth + 1))
2877       return true;
2878 
2879     // If none of the src operand elements are demanded, replace it with undef.
2880     if (!DemandedSrcElts && !Src.isUndef())
2881       return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
2882                                                TLO.DAG.getUNDEF(VT), Sub,
2883                                                Op.getOperand(2)));
2884 
2885     if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, KnownUndef, KnownZero,
2886                                    TLO, Depth + 1))
2887       return true;
2888     KnownUndef.insertBits(SubUndef, Idx);
2889     KnownZero.insertBits(SubZero, Idx);
2890 
2891     // Attempt to avoid multi-use ops if we don't need anything from them.
2892     if (!DemandedSrcElts.isAllOnes() || !DemandedSubElts.isAllOnes()) {
2893       SDValue NewSrc = SimplifyMultipleUseDemandedVectorElts(
2894           Src, DemandedSrcElts, TLO.DAG, Depth + 1);
2895       SDValue NewSub = SimplifyMultipleUseDemandedVectorElts(
2896           Sub, DemandedSubElts, TLO.DAG, Depth + 1);
2897       if (NewSrc || NewSub) {
2898         NewSrc = NewSrc ? NewSrc : Src;
2899         NewSub = NewSub ? NewSub : Sub;
2900         SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, NewSrc,
2901                                         NewSub, Op.getOperand(2));
2902         return TLO.CombineTo(Op, NewOp);
2903       }
2904     }
2905     break;
2906   }
2907   case ISD::EXTRACT_SUBVECTOR: {
2908     // Offset the demanded elts by the subvector index.
2909     SDValue Src = Op.getOperand(0);
2910     if (Src.getValueType().isScalableVector())
2911       break;
2912     uint64_t Idx = Op.getConstantOperandVal(1);
2913     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
2914     APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx);
2915 
2916     APInt SrcUndef, SrcZero;
2917     if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, SrcUndef, SrcZero, TLO,
2918                                    Depth + 1))
2919       return true;
2920     KnownUndef = SrcUndef.extractBits(NumElts, Idx);
2921     KnownZero = SrcZero.extractBits(NumElts, Idx);
2922 
2923     // Attempt to avoid multi-use ops if we don't need anything from them.
2924     if (!DemandedElts.isAllOnes()) {
2925       SDValue NewSrc = SimplifyMultipleUseDemandedVectorElts(
2926           Src, DemandedSrcElts, TLO.DAG, Depth + 1);
2927       if (NewSrc) {
2928         SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, NewSrc,
2929                                         Op.getOperand(1));
2930         return TLO.CombineTo(Op, NewOp);
2931       }
2932     }
2933     break;
2934   }
2935   case ISD::INSERT_VECTOR_ELT: {
2936     SDValue Vec = Op.getOperand(0);
2937     SDValue Scl = Op.getOperand(1);
2938     auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2));
2939 
2940     // For a legal, constant insertion index, if we don't need this insertion
2941     // then strip it, else remove it from the demanded elts.
2942     if (CIdx && CIdx->getAPIntValue().ult(NumElts)) {
2943       unsigned Idx = CIdx->getZExtValue();
2944       if (!DemandedElts[Idx])
2945         return TLO.CombineTo(Op, Vec);
2946 
2947       APInt DemandedVecElts(DemandedElts);
2948       DemandedVecElts.clearBit(Idx);
2949       if (SimplifyDemandedVectorElts(Vec, DemandedVecElts, KnownUndef,
2950                                      KnownZero, TLO, Depth + 1))
2951         return true;
2952 
2953       KnownUndef.setBitVal(Idx, Scl.isUndef());
2954 
2955       KnownZero.setBitVal(Idx, isNullConstant(Scl) || isNullFPConstant(Scl));
2956       break;
2957     }
2958 
2959     APInt VecUndef, VecZero;
2960     if (SimplifyDemandedVectorElts(Vec, DemandedElts, VecUndef, VecZero, TLO,
2961                                    Depth + 1))
2962       return true;
2963     // Without knowing the insertion index we can't set KnownUndef/KnownZero.
2964     break;
2965   }
2966   case ISD::VSELECT: {
2967     // Try to transform the select condition based on the current demanded
2968     // elements.
2969     // TODO: If a condition element is undef, we can choose from one arm of the
2970     //       select (and if one arm is undef, then we can propagate that to the
2971     //       result).
2972     // TODO - add support for constant vselect masks (see IR version of this).
2973     APInt UnusedUndef, UnusedZero;
2974     if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedElts, UnusedUndef,
2975                                    UnusedZero, TLO, Depth + 1))
2976       return true;
2977 
2978     // See if we can simplify either vselect operand.
2979     APInt DemandedLHS(DemandedElts);
2980     APInt DemandedRHS(DemandedElts);
2981     APInt UndefLHS, ZeroLHS;
2982     APInt UndefRHS, ZeroRHS;
2983     if (SimplifyDemandedVectorElts(Op.getOperand(1), DemandedLHS, UndefLHS,
2984                                    ZeroLHS, TLO, Depth + 1))
2985       return true;
2986     if (SimplifyDemandedVectorElts(Op.getOperand(2), DemandedRHS, UndefRHS,
2987                                    ZeroRHS, TLO, Depth + 1))
2988       return true;
2989 
2990     KnownUndef = UndefLHS & UndefRHS;
2991     KnownZero = ZeroLHS & ZeroRHS;
2992     break;
2993   }
2994   case ISD::VECTOR_SHUFFLE: {
2995     ArrayRef<int> ShuffleMask = cast<ShuffleVectorSDNode>(Op)->getMask();
2996 
2997     // Collect demanded elements from shuffle operands..
2998     APInt DemandedLHS(NumElts, 0);
2999     APInt DemandedRHS(NumElts, 0);
3000     for (unsigned i = 0; i != NumElts; ++i) {
3001       int M = ShuffleMask[i];
3002       if (M < 0 || !DemandedElts[i])
3003         continue;
3004       assert(0 <= M && M < (int)(2 * NumElts) && "Shuffle index out of range");
3005       if (M < (int)NumElts)
3006         DemandedLHS.setBit(M);
3007       else
3008         DemandedRHS.setBit(M - NumElts);
3009     }
3010 
3011     // See if we can simplify either shuffle operand.
3012     APInt UndefLHS, ZeroLHS;
3013     APInt UndefRHS, ZeroRHS;
3014     if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedLHS, UndefLHS,
3015                                    ZeroLHS, TLO, Depth + 1))
3016       return true;
3017     if (SimplifyDemandedVectorElts(Op.getOperand(1), DemandedRHS, UndefRHS,
3018                                    ZeroRHS, TLO, Depth + 1))
3019       return true;
3020 
3021     // Simplify mask using undef elements from LHS/RHS.
3022     bool Updated = false;
3023     bool IdentityLHS = true, IdentityRHS = true;
3024     SmallVector<int, 32> NewMask(ShuffleMask.begin(), ShuffleMask.end());
3025     for (unsigned i = 0; i != NumElts; ++i) {
3026       int &M = NewMask[i];
3027       if (M < 0)
3028         continue;
3029       if (!DemandedElts[i] || (M < (int)NumElts && UndefLHS[M]) ||
3030           (M >= (int)NumElts && UndefRHS[M - NumElts])) {
3031         Updated = true;
3032         M = -1;
3033       }
3034       IdentityLHS &= (M < 0) || (M == (int)i);
3035       IdentityRHS &= (M < 0) || ((M - NumElts) == i);
3036     }
3037 
3038     // Update legal shuffle masks based on demanded elements if it won't reduce
3039     // to Identity which can cause premature removal of the shuffle mask.
3040     if (Updated && !IdentityLHS && !IdentityRHS && !TLO.LegalOps) {
3041       SDValue LegalShuffle =
3042           buildLegalVectorShuffle(VT, DL, Op.getOperand(0), Op.getOperand(1),
3043                                   NewMask, TLO.DAG);
3044       if (LegalShuffle)
3045         return TLO.CombineTo(Op, LegalShuffle);
3046     }
3047 
3048     // Propagate undef/zero elements from LHS/RHS.
3049     for (unsigned i = 0; i != NumElts; ++i) {
3050       int M = ShuffleMask[i];
3051       if (M < 0) {
3052         KnownUndef.setBit(i);
3053       } else if (M < (int)NumElts) {
3054         if (UndefLHS[M])
3055           KnownUndef.setBit(i);
3056         if (ZeroLHS[M])
3057           KnownZero.setBit(i);
3058       } else {
3059         if (UndefRHS[M - NumElts])
3060           KnownUndef.setBit(i);
3061         if (ZeroRHS[M - NumElts])
3062           KnownZero.setBit(i);
3063       }
3064     }
3065     break;
3066   }
3067   case ISD::ANY_EXTEND_VECTOR_INREG:
3068   case ISD::SIGN_EXTEND_VECTOR_INREG:
3069   case ISD::ZERO_EXTEND_VECTOR_INREG: {
3070     APInt SrcUndef, SrcZero;
3071     SDValue Src = Op.getOperand(0);
3072     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
3073     APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts);
3074     if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, SrcUndef, SrcZero, TLO,
3075                                    Depth + 1))
3076       return true;
3077     KnownZero = SrcZero.zextOrTrunc(NumElts);
3078     KnownUndef = SrcUndef.zextOrTrunc(NumElts);
3079 
3080     if (IsLE && Op.getOpcode() == ISD::ANY_EXTEND_VECTOR_INREG &&
3081         Op.getValueSizeInBits() == Src.getValueSizeInBits() &&
3082         DemandedSrcElts == 1) {
3083       // aext - if we just need the bottom element then we can bitcast.
3084       return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src));
3085     }
3086 
3087     if (Op.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG) {
3088       // zext(undef) upper bits are guaranteed to be zero.
3089       if (DemandedElts.isSubsetOf(KnownUndef))
3090         return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT));
3091       KnownUndef.clearAllBits();
3092 
3093       // zext - if we just need the bottom element then we can mask:
3094       // zext(and(x,c)) -> and(x,c') iff the zext is the only user of the and.
3095       if (IsLE && DemandedSrcElts == 1 && Src.getOpcode() == ISD::AND &&
3096           Op->isOnlyUserOf(Src.getNode()) &&
3097           Op.getValueSizeInBits() == Src.getValueSizeInBits()) {
3098         SDLoc DL(Op);
3099         EVT SrcVT = Src.getValueType();
3100         EVT SrcSVT = SrcVT.getScalarType();
3101         SmallVector<SDValue> MaskElts;
3102         MaskElts.push_back(TLO.DAG.getAllOnesConstant(DL, SrcSVT));
3103         MaskElts.append(NumSrcElts - 1, TLO.DAG.getConstant(0, DL, SrcSVT));
3104         SDValue Mask = TLO.DAG.getBuildVector(SrcVT, DL, MaskElts);
3105         if (SDValue Fold = TLO.DAG.FoldConstantArithmetic(
3106                 ISD::AND, DL, SrcVT, {Src.getOperand(1), Mask})) {
3107           Fold = TLO.DAG.getNode(ISD::AND, DL, SrcVT, Src.getOperand(0), Fold);
3108           return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Fold));
3109         }
3110       }
3111     }
3112     break;
3113   }
3114 
3115   // TODO: There are more binop opcodes that could be handled here - MIN,
3116   // MAX, saturated math, etc.
3117   case ISD::ADD: {
3118     SDValue Op0 = Op.getOperand(0);
3119     SDValue Op1 = Op.getOperand(1);
3120     if (Op0 == Op1 && Op->isOnlyUserOf(Op0.getNode())) {
3121       APInt UndefLHS, ZeroLHS;
3122       if (SimplifyDemandedVectorElts(Op0, DemandedElts, UndefLHS, ZeroLHS, TLO,
3123                                      Depth + 1, /*AssumeSingleUse*/ true))
3124         return true;
3125     }
3126     LLVM_FALLTHROUGH;
3127   }
3128   case ISD::OR:
3129   case ISD::XOR:
3130   case ISD::SUB:
3131   case ISD::FADD:
3132   case ISD::FSUB:
3133   case ISD::FMUL:
3134   case ISD::FDIV:
3135   case ISD::FREM: {
3136     SDValue Op0 = Op.getOperand(0);
3137     SDValue Op1 = Op.getOperand(1);
3138 
3139     APInt UndefRHS, ZeroRHS;
3140     if (SimplifyDemandedVectorElts(Op1, DemandedElts, UndefRHS, ZeroRHS, TLO,
3141                                    Depth + 1))
3142       return true;
3143     APInt UndefLHS, ZeroLHS;
3144     if (SimplifyDemandedVectorElts(Op0, DemandedElts, UndefLHS, ZeroLHS, TLO,
3145                                    Depth + 1))
3146       return true;
3147 
3148     KnownZero = ZeroLHS & ZeroRHS;
3149     KnownUndef = getKnownUndefForVectorBinop(Op, TLO.DAG, UndefLHS, UndefRHS);
3150 
3151     // Attempt to avoid multi-use ops if we don't need anything from them.
3152     // TODO - use KnownUndef to relax the demandedelts?
3153     if (!DemandedElts.isAllOnes())
3154       if (SimplifyDemandedVectorEltsBinOp(Op0, Op1))
3155         return true;
3156     break;
3157   }
3158   case ISD::SHL:
3159   case ISD::SRL:
3160   case ISD::SRA:
3161   case ISD::ROTL:
3162   case ISD::ROTR: {
3163     SDValue Op0 = Op.getOperand(0);
3164     SDValue Op1 = Op.getOperand(1);
3165 
3166     APInt UndefRHS, ZeroRHS;
3167     if (SimplifyDemandedVectorElts(Op1, DemandedElts, UndefRHS, ZeroRHS, TLO,
3168                                    Depth + 1))
3169       return true;
3170     APInt UndefLHS, ZeroLHS;
3171     if (SimplifyDemandedVectorElts(Op0, DemandedElts, UndefLHS, ZeroLHS, TLO,
3172                                    Depth + 1))
3173       return true;
3174 
3175     KnownZero = ZeroLHS;
3176     KnownUndef = UndefLHS & UndefRHS; // TODO: use getKnownUndefForVectorBinop?
3177 
3178     // Attempt to avoid multi-use ops if we don't need anything from them.
3179     // TODO - use KnownUndef to relax the demandedelts?
3180     if (!DemandedElts.isAllOnes())
3181       if (SimplifyDemandedVectorEltsBinOp(Op0, Op1))
3182         return true;
3183     break;
3184   }
3185   case ISD::MUL:
3186   case ISD::AND: {
3187     SDValue Op0 = Op.getOperand(0);
3188     SDValue Op1 = Op.getOperand(1);
3189 
3190     APInt SrcUndef, SrcZero;
3191     if (SimplifyDemandedVectorElts(Op1, DemandedElts, SrcUndef, SrcZero, TLO,
3192                                    Depth + 1))
3193       return true;
3194     if (SimplifyDemandedVectorElts(Op0, DemandedElts, KnownUndef, KnownZero,
3195                                    TLO, Depth + 1))
3196       return true;
3197 
3198     // If either side has a zero element, then the result element is zero, even
3199     // if the other is an UNDEF.
3200     // TODO: Extend getKnownUndefForVectorBinop to also deal with known zeros
3201     // and then handle 'and' nodes with the rest of the binop opcodes.
3202     KnownZero |= SrcZero;
3203     KnownUndef &= SrcUndef;
3204     KnownUndef &= ~KnownZero;
3205 
3206     // Attempt to avoid multi-use ops if we don't need anything from them.
3207     // TODO - use KnownUndef to relax the demandedelts?
3208     if (!DemandedElts.isAllOnes())
3209       if (SimplifyDemandedVectorEltsBinOp(Op0, Op1))
3210         return true;
3211     break;
3212   }
3213   case ISD::TRUNCATE:
3214   case ISD::SIGN_EXTEND:
3215   case ISD::ZERO_EXTEND:
3216     if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedElts, KnownUndef,
3217                                    KnownZero, TLO, Depth + 1))
3218       return true;
3219 
3220     if (Op.getOpcode() == ISD::ZERO_EXTEND) {
3221       // zext(undef) upper bits are guaranteed to be zero.
3222       if (DemandedElts.isSubsetOf(KnownUndef))
3223         return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT));
3224       KnownUndef.clearAllBits();
3225     }
3226     break;
3227   default: {
3228     if (Op.getOpcode() >= ISD::BUILTIN_OP_END) {
3229       if (SimplifyDemandedVectorEltsForTargetNode(Op, DemandedElts, KnownUndef,
3230                                                   KnownZero, TLO, Depth))
3231         return true;
3232     } else {
3233       KnownBits Known;
3234       APInt DemandedBits = APInt::getAllOnes(EltSizeInBits);
3235       if (SimplifyDemandedBits(Op, DemandedBits, OriginalDemandedElts, Known,
3236                                TLO, Depth, AssumeSingleUse))
3237         return true;
3238     }
3239     break;
3240   }
3241   }
3242   assert((KnownUndef & KnownZero) == 0 && "Elements flagged as undef AND zero");
3243 
3244   // Constant fold all undef cases.
3245   // TODO: Handle zero cases as well.
3246   if (DemandedElts.isSubsetOf(KnownUndef))
3247     return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT));
3248 
3249   return false;
3250 }
3251 
3252 /// Determine which of the bits specified in Mask are known to be either zero or
3253 /// one and return them in the Known.
3254 void TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
3255                                                    KnownBits &Known,
3256                                                    const APInt &DemandedElts,
3257                                                    const SelectionDAG &DAG,
3258                                                    unsigned Depth) const {
3259   assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
3260           Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
3261           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
3262           Op.getOpcode() == ISD::INTRINSIC_VOID) &&
3263          "Should use MaskedValueIsZero if you don't know whether Op"
3264          " is a target node!");
3265   Known.resetAll();
3266 }
3267 
3268 void TargetLowering::computeKnownBitsForTargetInstr(
3269     GISelKnownBits &Analysis, Register R, KnownBits &Known,
3270     const APInt &DemandedElts, const MachineRegisterInfo &MRI,
3271     unsigned Depth) const {
3272   Known.resetAll();
3273 }
3274 
3275 void TargetLowering::computeKnownBitsForFrameIndex(
3276   const int FrameIdx, KnownBits &Known, const MachineFunction &MF) const {
3277   // The low bits are known zero if the pointer is aligned.
3278   Known.Zero.setLowBits(Log2(MF.getFrameInfo().getObjectAlign(FrameIdx)));
3279 }
3280 
3281 Align TargetLowering::computeKnownAlignForTargetInstr(
3282   GISelKnownBits &Analysis, Register R, const MachineRegisterInfo &MRI,
3283   unsigned Depth) const {
3284   return Align(1);
3285 }
3286 
3287 /// This method can be implemented by targets that want to expose additional
3288 /// information about sign bits to the DAG Combiner.
3289 unsigned TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
3290                                                          const APInt &,
3291                                                          const SelectionDAG &,
3292                                                          unsigned Depth) const {
3293   assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
3294           Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
3295           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
3296           Op.getOpcode() == ISD::INTRINSIC_VOID) &&
3297          "Should use ComputeNumSignBits if you don't know whether Op"
3298          " is a target node!");
3299   return 1;
3300 }
3301 
3302 unsigned TargetLowering::computeNumSignBitsForTargetInstr(
3303   GISelKnownBits &Analysis, Register R, const APInt &DemandedElts,
3304   const MachineRegisterInfo &MRI, unsigned Depth) const {
3305   return 1;
3306 }
3307 
3308 bool TargetLowering::SimplifyDemandedVectorEltsForTargetNode(
3309     SDValue Op, const APInt &DemandedElts, APInt &KnownUndef, APInt &KnownZero,
3310     TargetLoweringOpt &TLO, unsigned Depth) const {
3311   assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
3312           Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
3313           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
3314           Op.getOpcode() == ISD::INTRINSIC_VOID) &&
3315          "Should use SimplifyDemandedVectorElts if you don't know whether Op"
3316          " is a target node!");
3317   return false;
3318 }
3319 
3320 bool TargetLowering::SimplifyDemandedBitsForTargetNode(
3321     SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
3322     KnownBits &Known, TargetLoweringOpt &TLO, unsigned Depth) const {
3323   assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
3324           Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
3325           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
3326           Op.getOpcode() == ISD::INTRINSIC_VOID) &&
3327          "Should use SimplifyDemandedBits if you don't know whether Op"
3328          " is a target node!");
3329   computeKnownBitsForTargetNode(Op, Known, DemandedElts, TLO.DAG, Depth);
3330   return false;
3331 }
3332 
3333 SDValue TargetLowering::SimplifyMultipleUseDemandedBitsForTargetNode(
3334     SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
3335     SelectionDAG &DAG, unsigned Depth) const {
3336   assert(
3337       (Op.getOpcode() >= ISD::BUILTIN_OP_END ||
3338        Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
3339        Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
3340        Op.getOpcode() == ISD::INTRINSIC_VOID) &&
3341       "Should use SimplifyMultipleUseDemandedBits if you don't know whether Op"
3342       " is a target node!");
3343   return SDValue();
3344 }
3345 
3346 SDValue
3347 TargetLowering::buildLegalVectorShuffle(EVT VT, const SDLoc &DL, SDValue N0,
3348                                         SDValue N1, MutableArrayRef<int> Mask,
3349                                         SelectionDAG &DAG) const {
3350   bool LegalMask = isShuffleMaskLegal(Mask, VT);
3351   if (!LegalMask) {
3352     std::swap(N0, N1);
3353     ShuffleVectorSDNode::commuteMask(Mask);
3354     LegalMask = isShuffleMaskLegal(Mask, VT);
3355   }
3356 
3357   if (!LegalMask)
3358     return SDValue();
3359 
3360   return DAG.getVectorShuffle(VT, DL, N0, N1, Mask);
3361 }
3362 
3363 const Constant *TargetLowering::getTargetConstantFromLoad(LoadSDNode*) const {
3364   return nullptr;
3365 }
3366 
3367 bool TargetLowering::isGuaranteedNotToBeUndefOrPoisonForTargetNode(
3368     SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
3369     bool PoisonOnly, unsigned Depth) const {
3370   assert(
3371       (Op.getOpcode() >= ISD::BUILTIN_OP_END ||
3372        Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
3373        Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
3374        Op.getOpcode() == ISD::INTRINSIC_VOID) &&
3375       "Should use isGuaranteedNotToBeUndefOrPoison if you don't know whether Op"
3376       " is a target node!");
3377   return false;
3378 }
3379 
3380 bool TargetLowering::isKnownNeverNaNForTargetNode(SDValue Op,
3381                                                   const SelectionDAG &DAG,
3382                                                   bool SNaN,
3383                                                   unsigned Depth) const {
3384   assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
3385           Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
3386           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
3387           Op.getOpcode() == ISD::INTRINSIC_VOID) &&
3388          "Should use isKnownNeverNaN if you don't know whether Op"
3389          " is a target node!");
3390   return false;
3391 }
3392 
3393 bool TargetLowering::isSplatValueForTargetNode(SDValue Op,
3394                                                const APInt &DemandedElts,
3395                                                APInt &UndefElts,
3396                                                unsigned Depth) const {
3397   assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
3398           Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
3399           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
3400           Op.getOpcode() == ISD::INTRINSIC_VOID) &&
3401          "Should use isSplatValue if you don't know whether Op"
3402          " is a target node!");
3403   return false;
3404 }
3405 
3406 // FIXME: Ideally, this would use ISD::isConstantSplatVector(), but that must
3407 // work with truncating build vectors and vectors with elements of less than
3408 // 8 bits.
3409 bool TargetLowering::isConstTrueVal(SDValue N) const {
3410   if (!N)
3411     return false;
3412 
3413   unsigned EltWidth;
3414   APInt CVal;
3415   if (ConstantSDNode *CN = isConstOrConstSplat(N, /*AllowUndefs=*/false,
3416                                                /*AllowTruncation=*/true)) {
3417     CVal = CN->getAPIntValue();
3418     EltWidth = N.getValueType().getScalarSizeInBits();
3419   } else
3420     return false;
3421 
3422   // If this is a truncating splat, truncate the splat value.
3423   // Otherwise, we may fail to match the expected values below.
3424   if (EltWidth < CVal.getBitWidth())
3425     CVal = CVal.trunc(EltWidth);
3426 
3427   switch (getBooleanContents(N.getValueType())) {
3428   case UndefinedBooleanContent:
3429     return CVal[0];
3430   case ZeroOrOneBooleanContent:
3431     return CVal.isOne();
3432   case ZeroOrNegativeOneBooleanContent:
3433     return CVal.isAllOnes();
3434   }
3435 
3436   llvm_unreachable("Invalid boolean contents");
3437 }
3438 
3439 bool TargetLowering::isConstFalseVal(SDValue N) const {
3440   if (!N)
3441     return false;
3442 
3443   const ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N);
3444   if (!CN) {
3445     const BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
3446     if (!BV)
3447       return false;
3448 
3449     // Only interested in constant splats, we don't care about undef
3450     // elements in identifying boolean constants and getConstantSplatNode
3451     // returns NULL if all ops are undef;
3452     CN = BV->getConstantSplatNode();
3453     if (!CN)
3454       return false;
3455   }
3456 
3457   if (getBooleanContents(N->getValueType(0)) == UndefinedBooleanContent)
3458     return !CN->getAPIntValue()[0];
3459 
3460   return CN->isZero();
3461 }
3462 
3463 bool TargetLowering::isExtendedTrueVal(const ConstantSDNode *N, EVT VT,
3464                                        bool SExt) const {
3465   if (VT == MVT::i1)
3466     return N->isOne();
3467 
3468   TargetLowering::BooleanContent Cnt = getBooleanContents(VT);
3469   switch (Cnt) {
3470   case TargetLowering::ZeroOrOneBooleanContent:
3471     // An extended value of 1 is always true, unless its original type is i1,
3472     // in which case it will be sign extended to -1.
3473     return (N->isOne() && !SExt) || (SExt && (N->getValueType(0) != MVT::i1));
3474   case TargetLowering::UndefinedBooleanContent:
3475   case TargetLowering::ZeroOrNegativeOneBooleanContent:
3476     return N->isAllOnes() && SExt;
3477   }
3478   llvm_unreachable("Unexpected enumeration.");
3479 }
3480 
3481 /// This helper function of SimplifySetCC tries to optimize the comparison when
3482 /// either operand of the SetCC node is a bitwise-and instruction.
3483 SDValue TargetLowering::foldSetCCWithAnd(EVT VT, SDValue N0, SDValue N1,
3484                                          ISD::CondCode Cond, const SDLoc &DL,
3485                                          DAGCombinerInfo &DCI) const {
3486   if (N1.getOpcode() == ISD::AND && N0.getOpcode() != ISD::AND)
3487     std::swap(N0, N1);
3488 
3489   SelectionDAG &DAG = DCI.DAG;
3490   EVT OpVT = N0.getValueType();
3491   if (N0.getOpcode() != ISD::AND || !OpVT.isInteger() ||
3492       (Cond != ISD::SETEQ && Cond != ISD::SETNE))
3493     return SDValue();
3494 
3495   // (X & Y) != 0 --> zextOrTrunc(X & Y)
3496   // iff everything but LSB is known zero:
3497   if (Cond == ISD::SETNE && isNullConstant(N1) &&
3498       (getBooleanContents(OpVT) == TargetLowering::UndefinedBooleanContent ||
3499        getBooleanContents(OpVT) == TargetLowering::ZeroOrOneBooleanContent)) {
3500     unsigned NumEltBits = OpVT.getScalarSizeInBits();
3501     APInt UpperBits = APInt::getHighBitsSet(NumEltBits, NumEltBits - 1);
3502     if (DAG.MaskedValueIsZero(N0, UpperBits))
3503       return DAG.getBoolExtOrTrunc(N0, DL, VT, OpVT);
3504   }
3505 
3506   // Match these patterns in any of their permutations:
3507   // (X & Y) == Y
3508   // (X & Y) != Y
3509   SDValue X, Y;
3510   if (N0.getOperand(0) == N1) {
3511     X = N0.getOperand(1);
3512     Y = N0.getOperand(0);
3513   } else if (N0.getOperand(1) == N1) {
3514     X = N0.getOperand(0);
3515     Y = N0.getOperand(1);
3516   } else {
3517     return SDValue();
3518   }
3519 
3520   SDValue Zero = DAG.getConstant(0, DL, OpVT);
3521   if (DAG.isKnownToBeAPowerOfTwo(Y)) {
3522     // Simplify X & Y == Y to X & Y != 0 if Y has exactly one bit set.
3523     // Note that where Y is variable and is known to have at most one bit set
3524     // (for example, if it is Z & 1) we cannot do this; the expressions are not
3525     // equivalent when Y == 0.
3526     assert(OpVT.isInteger());
3527     Cond = ISD::getSetCCInverse(Cond, OpVT);
3528     if (DCI.isBeforeLegalizeOps() ||
3529         isCondCodeLegal(Cond, N0.getSimpleValueType()))
3530       return DAG.getSetCC(DL, VT, N0, Zero, Cond);
3531   } else if (N0.hasOneUse() && hasAndNotCompare(Y)) {
3532     // If the target supports an 'and-not' or 'and-complement' logic operation,
3533     // try to use that to make a comparison operation more efficient.
3534     // But don't do this transform if the mask is a single bit because there are
3535     // more efficient ways to deal with that case (for example, 'bt' on x86 or
3536     // 'rlwinm' on PPC).
3537 
3538     // Bail out if the compare operand that we want to turn into a zero is
3539     // already a zero (otherwise, infinite loop).
3540     auto *YConst = dyn_cast<ConstantSDNode>(Y);
3541     if (YConst && YConst->isZero())
3542       return SDValue();
3543 
3544     // Transform this into: ~X & Y == 0.
3545     SDValue NotX = DAG.getNOT(SDLoc(X), X, OpVT);
3546     SDValue NewAnd = DAG.getNode(ISD::AND, SDLoc(N0), OpVT, NotX, Y);
3547     return DAG.getSetCC(DL, VT, NewAnd, Zero, Cond);
3548   }
3549 
3550   return SDValue();
3551 }
3552 
3553 /// There are multiple IR patterns that could be checking whether certain
3554 /// truncation of a signed number would be lossy or not. The pattern which is
3555 /// best at IR level, may not lower optimally. Thus, we want to unfold it.
3556 /// We are looking for the following pattern: (KeptBits is a constant)
3557 ///   (add %x, (1 << (KeptBits-1))) srccond (1 << KeptBits)
3558 /// KeptBits won't be bitwidth(x), that will be constant-folded to true/false.
3559 /// KeptBits also can't be 1, that would have been folded to  %x dstcond 0
3560 /// We will unfold it into the natural trunc+sext pattern:
3561 ///   ((%x << C) a>> C) dstcond %x
3562 /// Where  C = bitwidth(x) - KeptBits  and  C u< bitwidth(x)
3563 SDValue TargetLowering::optimizeSetCCOfSignedTruncationCheck(
3564     EVT SCCVT, SDValue N0, SDValue N1, ISD::CondCode Cond, DAGCombinerInfo &DCI,
3565     const SDLoc &DL) const {
3566   // We must be comparing with a constant.
3567   ConstantSDNode *C1;
3568   if (!(C1 = dyn_cast<ConstantSDNode>(N1)))
3569     return SDValue();
3570 
3571   // N0 should be:  add %x, (1 << (KeptBits-1))
3572   if (N0->getOpcode() != ISD::ADD)
3573     return SDValue();
3574 
3575   // And we must be 'add'ing a constant.
3576   ConstantSDNode *C01;
3577   if (!(C01 = dyn_cast<ConstantSDNode>(N0->getOperand(1))))
3578     return SDValue();
3579 
3580   SDValue X = N0->getOperand(0);
3581   EVT XVT = X.getValueType();
3582 
3583   // Validate constants ...
3584 
3585   APInt I1 = C1->getAPIntValue();
3586 
3587   ISD::CondCode NewCond;
3588   if (Cond == ISD::CondCode::SETULT) {
3589     NewCond = ISD::CondCode::SETEQ;
3590   } else if (Cond == ISD::CondCode::SETULE) {
3591     NewCond = ISD::CondCode::SETEQ;
3592     // But need to 'canonicalize' the constant.
3593     I1 += 1;
3594   } else if (Cond == ISD::CondCode::SETUGT) {
3595     NewCond = ISD::CondCode::SETNE;
3596     // But need to 'canonicalize' the constant.
3597     I1 += 1;
3598   } else if (Cond == ISD::CondCode::SETUGE) {
3599     NewCond = ISD::CondCode::SETNE;
3600   } else
3601     return SDValue();
3602 
3603   APInt I01 = C01->getAPIntValue();
3604 
3605   auto checkConstants = [&I1, &I01]() -> bool {
3606     // Both of them must be power-of-two, and the constant from setcc is bigger.
3607     return I1.ugt(I01) && I1.isPowerOf2() && I01.isPowerOf2();
3608   };
3609 
3610   if (checkConstants()) {
3611     // Great, e.g. got  icmp ult i16 (add i16 %x, 128), 256
3612   } else {
3613     // What if we invert constants? (and the target predicate)
3614     I1.negate();
3615     I01.negate();
3616     assert(XVT.isInteger());
3617     NewCond = getSetCCInverse(NewCond, XVT);
3618     if (!checkConstants())
3619       return SDValue();
3620     // Great, e.g. got  icmp uge i16 (add i16 %x, -128), -256
3621   }
3622 
3623   // They are power-of-two, so which bit is set?
3624   const unsigned KeptBits = I1.logBase2();
3625   const unsigned KeptBitsMinusOne = I01.logBase2();
3626 
3627   // Magic!
3628   if (KeptBits != (KeptBitsMinusOne + 1))
3629     return SDValue();
3630   assert(KeptBits > 0 && KeptBits < XVT.getSizeInBits() && "unreachable");
3631 
3632   // We don't want to do this in every single case.
3633   SelectionDAG &DAG = DCI.DAG;
3634   if (!DAG.getTargetLoweringInfo().shouldTransformSignedTruncationCheck(
3635           XVT, KeptBits))
3636     return SDValue();
3637 
3638   const unsigned MaskedBits = XVT.getSizeInBits() - KeptBits;
3639   assert(MaskedBits > 0 && MaskedBits < XVT.getSizeInBits() && "unreachable");
3640 
3641   // Unfold into:  ((%x << C) a>> C) cond %x
3642   // Where 'cond' will be either 'eq' or 'ne'.
3643   SDValue ShiftAmt = DAG.getConstant(MaskedBits, DL, XVT);
3644   SDValue T0 = DAG.getNode(ISD::SHL, DL, XVT, X, ShiftAmt);
3645   SDValue T1 = DAG.getNode(ISD::SRA, DL, XVT, T0, ShiftAmt);
3646   SDValue T2 = DAG.getSetCC(DL, SCCVT, T1, X, NewCond);
3647 
3648   return T2;
3649 }
3650 
3651 // (X & (C l>>/<< Y)) ==/!= 0  -->  ((X <</l>> Y) & C) ==/!= 0
3652 SDValue TargetLowering::optimizeSetCCByHoistingAndByConstFromLogicalShift(
3653     EVT SCCVT, SDValue N0, SDValue N1C, ISD::CondCode Cond,
3654     DAGCombinerInfo &DCI, const SDLoc &DL) const {
3655   assert(isConstOrConstSplat(N1C) &&
3656          isConstOrConstSplat(N1C)->getAPIntValue().isZero() &&
3657          "Should be a comparison with 0.");
3658   assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
3659          "Valid only for [in]equality comparisons.");
3660 
3661   unsigned NewShiftOpcode;
3662   SDValue X, C, Y;
3663 
3664   SelectionDAG &DAG = DCI.DAG;
3665   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3666 
3667   // Look for '(C l>>/<< Y)'.
3668   auto Match = [&NewShiftOpcode, &X, &C, &Y, &TLI, &DAG](SDValue V) {
3669     // The shift should be one-use.
3670     if (!V.hasOneUse())
3671       return false;
3672     unsigned OldShiftOpcode = V.getOpcode();
3673     switch (OldShiftOpcode) {
3674     case ISD::SHL:
3675       NewShiftOpcode = ISD::SRL;
3676       break;
3677     case ISD::SRL:
3678       NewShiftOpcode = ISD::SHL;
3679       break;
3680     default:
3681       return false; // must be a logical shift.
3682     }
3683     // We should be shifting a constant.
3684     // FIXME: best to use isConstantOrConstantVector().
3685     C = V.getOperand(0);
3686     ConstantSDNode *CC =
3687         isConstOrConstSplat(C, /*AllowUndefs=*/true, /*AllowTruncation=*/true);
3688     if (!CC)
3689       return false;
3690     Y = V.getOperand(1);
3691 
3692     ConstantSDNode *XC =
3693         isConstOrConstSplat(X, /*AllowUndefs=*/true, /*AllowTruncation=*/true);
3694     return TLI.shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd(
3695         X, XC, CC, Y, OldShiftOpcode, NewShiftOpcode, DAG);
3696   };
3697 
3698   // LHS of comparison should be an one-use 'and'.
3699   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
3700     return SDValue();
3701 
3702   X = N0.getOperand(0);
3703   SDValue Mask = N0.getOperand(1);
3704 
3705   // 'and' is commutative!
3706   if (!Match(Mask)) {
3707     std::swap(X, Mask);
3708     if (!Match(Mask))
3709       return SDValue();
3710   }
3711 
3712   EVT VT = X.getValueType();
3713 
3714   // Produce:
3715   // ((X 'OppositeShiftOpcode' Y) & C) Cond 0
3716   SDValue T0 = DAG.getNode(NewShiftOpcode, DL, VT, X, Y);
3717   SDValue T1 = DAG.getNode(ISD::AND, DL, VT, T0, C);
3718   SDValue T2 = DAG.getSetCC(DL, SCCVT, T1, N1C, Cond);
3719   return T2;
3720 }
3721 
3722 /// Try to fold an equality comparison with a {add/sub/xor} binary operation as
3723 /// the 1st operand (N0). Callers are expected to swap the N0/N1 parameters to
3724 /// handle the commuted versions of these patterns.
3725 SDValue TargetLowering::foldSetCCWithBinOp(EVT VT, SDValue N0, SDValue N1,
3726                                            ISD::CondCode Cond, const SDLoc &DL,
3727                                            DAGCombinerInfo &DCI) const {
3728   unsigned BOpcode = N0.getOpcode();
3729   assert((BOpcode == ISD::ADD || BOpcode == ISD::SUB || BOpcode == ISD::XOR) &&
3730          "Unexpected binop");
3731   assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) && "Unexpected condcode");
3732 
3733   // (X + Y) == X --> Y == 0
3734   // (X - Y) == X --> Y == 0
3735   // (X ^ Y) == X --> Y == 0
3736   SelectionDAG &DAG = DCI.DAG;
3737   EVT OpVT = N0.getValueType();
3738   SDValue X = N0.getOperand(0);
3739   SDValue Y = N0.getOperand(1);
3740   if (X == N1)
3741     return DAG.getSetCC(DL, VT, Y, DAG.getConstant(0, DL, OpVT), Cond);
3742 
3743   if (Y != N1)
3744     return SDValue();
3745 
3746   // (X + Y) == Y --> X == 0
3747   // (X ^ Y) == Y --> X == 0
3748   if (BOpcode == ISD::ADD || BOpcode == ISD::XOR)
3749     return DAG.getSetCC(DL, VT, X, DAG.getConstant(0, DL, OpVT), Cond);
3750 
3751   // The shift would not be valid if the operands are boolean (i1).
3752   if (!N0.hasOneUse() || OpVT.getScalarSizeInBits() == 1)
3753     return SDValue();
3754 
3755   // (X - Y) == Y --> X == Y << 1
3756   EVT ShiftVT = getShiftAmountTy(OpVT, DAG.getDataLayout(),
3757                                  !DCI.isBeforeLegalize());
3758   SDValue One = DAG.getConstant(1, DL, ShiftVT);
3759   SDValue YShl1 = DAG.getNode(ISD::SHL, DL, N1.getValueType(), Y, One);
3760   if (!DCI.isCalledByLegalizer())
3761     DCI.AddToWorklist(YShl1.getNode());
3762   return DAG.getSetCC(DL, VT, X, YShl1, Cond);
3763 }
3764 
3765 static SDValue simplifySetCCWithCTPOP(const TargetLowering &TLI, EVT VT,
3766                                       SDValue N0, const APInt &C1,
3767                                       ISD::CondCode Cond, const SDLoc &dl,
3768                                       SelectionDAG &DAG) {
3769   // Look through truncs that don't change the value of a ctpop.
3770   // FIXME: Add vector support? Need to be careful with setcc result type below.
3771   SDValue CTPOP = N0;
3772   if (N0.getOpcode() == ISD::TRUNCATE && N0.hasOneUse() && !VT.isVector() &&
3773       N0.getScalarValueSizeInBits() > Log2_32(N0.getOperand(0).getScalarValueSizeInBits()))
3774     CTPOP = N0.getOperand(0);
3775 
3776   if (CTPOP.getOpcode() != ISD::CTPOP || !CTPOP.hasOneUse())
3777     return SDValue();
3778 
3779   EVT CTVT = CTPOP.getValueType();
3780   SDValue CTOp = CTPOP.getOperand(0);
3781 
3782   // If this is a vector CTPOP, keep the CTPOP if it is legal.
3783   // TODO: Should we check if CTPOP is legal(or custom) for scalars?
3784   if (VT.isVector() && TLI.isOperationLegal(ISD::CTPOP, CTVT))
3785     return SDValue();
3786 
3787   // (ctpop x) u< 2 -> (x & x-1) == 0
3788   // (ctpop x) u> 1 -> (x & x-1) != 0
3789   if (Cond == ISD::SETULT || Cond == ISD::SETUGT) {
3790     unsigned CostLimit = TLI.getCustomCtpopCost(CTVT, Cond);
3791     if (C1.ugt(CostLimit + (Cond == ISD::SETULT)))
3792       return SDValue();
3793     if (C1 == 0 && (Cond == ISD::SETULT))
3794       return SDValue(); // This is handled elsewhere.
3795 
3796     unsigned Passes = C1.getLimitedValue() - (Cond == ISD::SETULT);
3797 
3798     SDValue NegOne = DAG.getAllOnesConstant(dl, CTVT);
3799     SDValue Result = CTOp;
3800     for (unsigned i = 0; i < Passes; i++) {
3801       SDValue Add = DAG.getNode(ISD::ADD, dl, CTVT, Result, NegOne);
3802       Result = DAG.getNode(ISD::AND, dl, CTVT, Result, Add);
3803     }
3804     ISD::CondCode CC = Cond == ISD::SETULT ? ISD::SETEQ : ISD::SETNE;
3805     return DAG.getSetCC(dl, VT, Result, DAG.getConstant(0, dl, CTVT), CC);
3806   }
3807 
3808   // If ctpop is not supported, expand a power-of-2 comparison based on it.
3809   if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && C1 == 1) {
3810     // For scalars, keep CTPOP if it is legal or custom.
3811     if (!VT.isVector() && TLI.isOperationLegalOrCustom(ISD::CTPOP, CTVT))
3812       return SDValue();
3813     // This is based on X86's custom lowering for CTPOP which produces more
3814     // instructions than the expansion here.
3815 
3816     // (ctpop x) == 1 --> (x != 0) && ((x & x-1) == 0)
3817     // (ctpop x) != 1 --> (x == 0) || ((x & x-1) != 0)
3818     SDValue Zero = DAG.getConstant(0, dl, CTVT);
3819     SDValue NegOne = DAG.getAllOnesConstant(dl, CTVT);
3820     assert(CTVT.isInteger());
3821     ISD::CondCode InvCond = ISD::getSetCCInverse(Cond, CTVT);
3822     SDValue Add = DAG.getNode(ISD::ADD, dl, CTVT, CTOp, NegOne);
3823     SDValue And = DAG.getNode(ISD::AND, dl, CTVT, CTOp, Add);
3824     SDValue LHS = DAG.getSetCC(dl, VT, CTOp, Zero, InvCond);
3825     SDValue RHS = DAG.getSetCC(dl, VT, And, Zero, Cond);
3826     unsigned LogicOpcode = Cond == ISD::SETEQ ? ISD::AND : ISD::OR;
3827     return DAG.getNode(LogicOpcode, dl, VT, LHS, RHS);
3828   }
3829 
3830   return SDValue();
3831 }
3832 
3833 static SDValue foldSetCCWithRotate(EVT VT, SDValue N0, SDValue N1,
3834                                    ISD::CondCode Cond, const SDLoc &dl,
3835                                    SelectionDAG &DAG) {
3836   if (Cond != ISD::SETEQ && Cond != ISD::SETNE)
3837     return SDValue();
3838 
3839   auto *C1 = isConstOrConstSplat(N1, /* AllowUndefs */ true);
3840   if (!C1 || !(C1->isZero() || C1->isAllOnes()))
3841     return SDValue();
3842 
3843   auto getRotateSource = [](SDValue X) {
3844     if (X.getOpcode() == ISD::ROTL || X.getOpcode() == ISD::ROTR)
3845       return X.getOperand(0);
3846     return SDValue();
3847   };
3848 
3849   // Peek through a rotated value compared against 0 or -1:
3850   // (rot X, Y) == 0/-1 --> X == 0/-1
3851   // (rot X, Y) != 0/-1 --> X != 0/-1
3852   if (SDValue R = getRotateSource(N0))
3853     return DAG.getSetCC(dl, VT, R, N1, Cond);
3854 
3855   // Peek through an 'or' of a rotated value compared against 0:
3856   // or (rot X, Y), Z ==/!= 0 --> (or X, Z) ==/!= 0
3857   // or Z, (rot X, Y) ==/!= 0 --> (or X, Z) ==/!= 0
3858   //
3859   // TODO: Add the 'and' with -1 sibling.
3860   // TODO: Recurse through a series of 'or' ops to find the rotate.
3861   EVT OpVT = N0.getValueType();
3862   if (N0.hasOneUse() && N0.getOpcode() == ISD::OR && C1->isZero()) {
3863     if (SDValue R = getRotateSource(N0.getOperand(0))) {
3864       SDValue NewOr = DAG.getNode(ISD::OR, dl, OpVT, R, N0.getOperand(1));
3865       return DAG.getSetCC(dl, VT, NewOr, N1, Cond);
3866     }
3867     if (SDValue R = getRotateSource(N0.getOperand(1))) {
3868       SDValue NewOr = DAG.getNode(ISD::OR, dl, OpVT, R, N0.getOperand(0));
3869       return DAG.getSetCC(dl, VT, NewOr, N1, Cond);
3870     }
3871   }
3872 
3873   return SDValue();
3874 }
3875 
3876 /// Try to simplify a setcc built with the specified operands and cc. If it is
3877 /// unable to simplify it, return a null SDValue.
3878 SDValue TargetLowering::SimplifySetCC(EVT VT, SDValue N0, SDValue N1,
3879                                       ISD::CondCode Cond, bool foldBooleans,
3880                                       DAGCombinerInfo &DCI,
3881                                       const SDLoc &dl) const {
3882   SelectionDAG &DAG = DCI.DAG;
3883   const DataLayout &Layout = DAG.getDataLayout();
3884   EVT OpVT = N0.getValueType();
3885 
3886   // Constant fold or commute setcc.
3887   if (SDValue Fold = DAG.FoldSetCC(VT, N0, N1, Cond, dl))
3888     return Fold;
3889 
3890   // Ensure that the constant occurs on the RHS and fold constant comparisons.
3891   // TODO: Handle non-splat vector constants. All undef causes trouble.
3892   // FIXME: We can't yet fold constant scalable vector splats, so avoid an
3893   // infinite loop here when we encounter one.
3894   ISD::CondCode SwappedCC = ISD::getSetCCSwappedOperands(Cond);
3895   if (isConstOrConstSplat(N0) &&
3896       (!OpVT.isScalableVector() || !isConstOrConstSplat(N1)) &&
3897       (DCI.isBeforeLegalizeOps() ||
3898        isCondCodeLegal(SwappedCC, N0.getSimpleValueType())))
3899     return DAG.getSetCC(dl, VT, N1, N0, SwappedCC);
3900 
3901   // If we have a subtract with the same 2 non-constant operands as this setcc
3902   // -- but in reverse order -- then try to commute the operands of this setcc
3903   // to match. A matching pair of setcc (cmp) and sub may be combined into 1
3904   // instruction on some targets.
3905   if (!isConstOrConstSplat(N0) && !isConstOrConstSplat(N1) &&
3906       (DCI.isBeforeLegalizeOps() ||
3907        isCondCodeLegal(SwappedCC, N0.getSimpleValueType())) &&
3908       DAG.doesNodeExist(ISD::SUB, DAG.getVTList(OpVT), {N1, N0}) &&
3909       !DAG.doesNodeExist(ISD::SUB, DAG.getVTList(OpVT), {N0, N1}))
3910     return DAG.getSetCC(dl, VT, N1, N0, SwappedCC);
3911 
3912   if (SDValue V = foldSetCCWithRotate(VT, N0, N1, Cond, dl, DAG))
3913     return V;
3914 
3915   if (auto *N1C = isConstOrConstSplat(N1)) {
3916     const APInt &C1 = N1C->getAPIntValue();
3917 
3918     // Optimize some CTPOP cases.
3919     if (SDValue V = simplifySetCCWithCTPOP(*this, VT, N0, C1, Cond, dl, DAG))
3920       return V;
3921 
3922     // If the LHS is '(srl (ctlz x), 5)', the RHS is 0/1, and this is an
3923     // equality comparison, then we're just comparing whether X itself is
3924     // zero.
3925     if (N0.getOpcode() == ISD::SRL && (C1.isZero() || C1.isOne()) &&
3926         N0.getOperand(0).getOpcode() == ISD::CTLZ &&
3927         isPowerOf2_32(N0.getScalarValueSizeInBits())) {
3928       if (ConstantSDNode *ShAmt = isConstOrConstSplat(N0.getOperand(1))) {
3929         if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
3930             ShAmt->getAPIntValue() == Log2_32(N0.getScalarValueSizeInBits())) {
3931           if ((C1 == 0) == (Cond == ISD::SETEQ)) {
3932             // (srl (ctlz x), 5) == 0  -> X != 0
3933             // (srl (ctlz x), 5) != 1  -> X != 0
3934             Cond = ISD::SETNE;
3935           } else {
3936             // (srl (ctlz x), 5) != 0  -> X == 0
3937             // (srl (ctlz x), 5) == 1  -> X == 0
3938             Cond = ISD::SETEQ;
3939           }
3940           SDValue Zero = DAG.getConstant(0, dl, N0.getValueType());
3941           return DAG.getSetCC(dl, VT, N0.getOperand(0).getOperand(0), Zero,
3942                               Cond);
3943         }
3944       }
3945     }
3946   }
3947 
3948   // FIXME: Support vectors.
3949   if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) {
3950     const APInt &C1 = N1C->getAPIntValue();
3951 
3952     // (zext x) == C --> x == (trunc C)
3953     // (sext x) == C --> x == (trunc C)
3954     if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
3955         DCI.isBeforeLegalize() && N0->hasOneUse()) {
3956       unsigned MinBits = N0.getValueSizeInBits();
3957       SDValue PreExt;
3958       bool Signed = false;
3959       if (N0->getOpcode() == ISD::ZERO_EXTEND) {
3960         // ZExt
3961         MinBits = N0->getOperand(0).getValueSizeInBits();
3962         PreExt = N0->getOperand(0);
3963       } else if (N0->getOpcode() == ISD::AND) {
3964         // DAGCombine turns costly ZExts into ANDs
3965         if (auto *C = dyn_cast<ConstantSDNode>(N0->getOperand(1)))
3966           if ((C->getAPIntValue()+1).isPowerOf2()) {
3967             MinBits = C->getAPIntValue().countTrailingOnes();
3968             PreExt = N0->getOperand(0);
3969           }
3970       } else if (N0->getOpcode() == ISD::SIGN_EXTEND) {
3971         // SExt
3972         MinBits = N0->getOperand(0).getValueSizeInBits();
3973         PreExt = N0->getOperand(0);
3974         Signed = true;
3975       } else if (auto *LN0 = dyn_cast<LoadSDNode>(N0)) {
3976         // ZEXTLOAD / SEXTLOAD
3977         if (LN0->getExtensionType() == ISD::ZEXTLOAD) {
3978           MinBits = LN0->getMemoryVT().getSizeInBits();
3979           PreExt = N0;
3980         } else if (LN0->getExtensionType() == ISD::SEXTLOAD) {
3981           Signed = true;
3982           MinBits = LN0->getMemoryVT().getSizeInBits();
3983           PreExt = N0;
3984         }
3985       }
3986 
3987       // Figure out how many bits we need to preserve this constant.
3988       unsigned ReqdBits = Signed ? C1.getMinSignedBits() : C1.getActiveBits();
3989 
3990       // Make sure we're not losing bits from the constant.
3991       if (MinBits > 0 &&
3992           MinBits < C1.getBitWidth() &&
3993           MinBits >= ReqdBits) {
3994         EVT MinVT = EVT::getIntegerVT(*DAG.getContext(), MinBits);
3995         if (isTypeDesirableForOp(ISD::SETCC, MinVT)) {
3996           // Will get folded away.
3997           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, MinVT, PreExt);
3998           if (MinBits == 1 && C1 == 1)
3999             // Invert the condition.
4000             return DAG.getSetCC(dl, VT, Trunc, DAG.getConstant(0, dl, MVT::i1),
4001                                 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
4002           SDValue C = DAG.getConstant(C1.trunc(MinBits), dl, MinVT);
4003           return DAG.getSetCC(dl, VT, Trunc, C, Cond);
4004         }
4005 
4006         // If truncating the setcc operands is not desirable, we can still
4007         // simplify the expression in some cases:
4008         // setcc ([sz]ext (setcc x, y, cc)), 0, setne) -> setcc (x, y, cc)
4009         // setcc ([sz]ext (setcc x, y, cc)), 0, seteq) -> setcc (x, y, inv(cc))
4010         // setcc (zext (setcc x, y, cc)), 1, setne) -> setcc (x, y, inv(cc))
4011         // setcc (zext (setcc x, y, cc)), 1, seteq) -> setcc (x, y, cc)
4012         // setcc (sext (setcc x, y, cc)), -1, setne) -> setcc (x, y, inv(cc))
4013         // setcc (sext (setcc x, y, cc)), -1, seteq) -> setcc (x, y, cc)
4014         SDValue TopSetCC = N0->getOperand(0);
4015         unsigned N0Opc = N0->getOpcode();
4016         bool SExt = (N0Opc == ISD::SIGN_EXTEND);
4017         if (TopSetCC.getValueType() == MVT::i1 && VT == MVT::i1 &&
4018             TopSetCC.getOpcode() == ISD::SETCC &&
4019             (N0Opc == ISD::ZERO_EXTEND || N0Opc == ISD::SIGN_EXTEND) &&
4020             (isConstFalseVal(N1) ||
4021              isExtendedTrueVal(N1C, N0->getValueType(0), SExt))) {
4022 
4023           bool Inverse = (N1C->isZero() && Cond == ISD::SETEQ) ||
4024                          (!N1C->isZero() && Cond == ISD::SETNE);
4025 
4026           if (!Inverse)
4027             return TopSetCC;
4028 
4029           ISD::CondCode InvCond = ISD::getSetCCInverse(
4030               cast<CondCodeSDNode>(TopSetCC.getOperand(2))->get(),
4031               TopSetCC.getOperand(0).getValueType());
4032           return DAG.getSetCC(dl, VT, TopSetCC.getOperand(0),
4033                                       TopSetCC.getOperand(1),
4034                                       InvCond);
4035         }
4036       }
4037     }
4038 
4039     // If the LHS is '(and load, const)', the RHS is 0, the test is for
4040     // equality or unsigned, and all 1 bits of the const are in the same
4041     // partial word, see if we can shorten the load.
4042     if (DCI.isBeforeLegalize() &&
4043         !ISD::isSignedIntSetCC(Cond) &&
4044         N0.getOpcode() == ISD::AND && C1 == 0 &&
4045         N0.getNode()->hasOneUse() &&
4046         isa<LoadSDNode>(N0.getOperand(0)) &&
4047         N0.getOperand(0).getNode()->hasOneUse() &&
4048         isa<ConstantSDNode>(N0.getOperand(1))) {
4049       LoadSDNode *Lod = cast<LoadSDNode>(N0.getOperand(0));
4050       APInt bestMask;
4051       unsigned bestWidth = 0, bestOffset = 0;
4052       if (Lod->isSimple() && Lod->isUnindexed()) {
4053         unsigned origWidth = N0.getValueSizeInBits();
4054         unsigned maskWidth = origWidth;
4055         // We can narrow (e.g.) 16-bit extending loads on 32-bit target to
4056         // 8 bits, but have to be careful...
4057         if (Lod->getExtensionType() != ISD::NON_EXTLOAD)
4058           origWidth = Lod->getMemoryVT().getSizeInBits();
4059         const APInt &Mask = N0.getConstantOperandAPInt(1);
4060         for (unsigned width = origWidth / 2; width>=8; width /= 2) {
4061           APInt newMask = APInt::getLowBitsSet(maskWidth, width);
4062           for (unsigned offset=0; offset<origWidth/width; offset++) {
4063             if (Mask.isSubsetOf(newMask)) {
4064               if (Layout.isLittleEndian())
4065                 bestOffset = (uint64_t)offset * (width/8);
4066               else
4067                 bestOffset = (origWidth/width - offset - 1) * (width/8);
4068               bestMask = Mask.lshr(offset * (width/8) * 8);
4069               bestWidth = width;
4070               break;
4071             }
4072             newMask <<= width;
4073           }
4074         }
4075       }
4076       if (bestWidth) {
4077         EVT newVT = EVT::getIntegerVT(*DAG.getContext(), bestWidth);
4078         if (newVT.isRound() &&
4079             shouldReduceLoadWidth(Lod, ISD::NON_EXTLOAD, newVT)) {
4080           SDValue Ptr = Lod->getBasePtr();
4081           if (bestOffset != 0)
4082             Ptr =
4083                 DAG.getMemBasePlusOffset(Ptr, TypeSize::Fixed(bestOffset), dl);
4084           SDValue NewLoad =
4085               DAG.getLoad(newVT, dl, Lod->getChain(), Ptr,
4086                           Lod->getPointerInfo().getWithOffset(bestOffset),
4087                           Lod->getOriginalAlign());
4088           return DAG.getSetCC(dl, VT,
4089                               DAG.getNode(ISD::AND, dl, newVT, NewLoad,
4090                                       DAG.getConstant(bestMask.trunc(bestWidth),
4091                                                       dl, newVT)),
4092                               DAG.getConstant(0LL, dl, newVT), Cond);
4093         }
4094       }
4095     }
4096 
4097     // If the LHS is a ZERO_EXTEND, perform the comparison on the input.
4098     if (N0.getOpcode() == ISD::ZERO_EXTEND) {
4099       unsigned InSize = N0.getOperand(0).getValueSizeInBits();
4100 
4101       // If the comparison constant has bits in the upper part, the
4102       // zero-extended value could never match.
4103       if (C1.intersects(APInt::getHighBitsSet(C1.getBitWidth(),
4104                                               C1.getBitWidth() - InSize))) {
4105         switch (Cond) {
4106         case ISD::SETUGT:
4107         case ISD::SETUGE:
4108         case ISD::SETEQ:
4109           return DAG.getConstant(0, dl, VT);
4110         case ISD::SETULT:
4111         case ISD::SETULE:
4112         case ISD::SETNE:
4113           return DAG.getConstant(1, dl, VT);
4114         case ISD::SETGT:
4115         case ISD::SETGE:
4116           // True if the sign bit of C1 is set.
4117           return DAG.getConstant(C1.isNegative(), dl, VT);
4118         case ISD::SETLT:
4119         case ISD::SETLE:
4120           // True if the sign bit of C1 isn't set.
4121           return DAG.getConstant(C1.isNonNegative(), dl, VT);
4122         default:
4123           break;
4124         }
4125       }
4126 
4127       // Otherwise, we can perform the comparison with the low bits.
4128       switch (Cond) {
4129       case ISD::SETEQ:
4130       case ISD::SETNE:
4131       case ISD::SETUGT:
4132       case ISD::SETUGE:
4133       case ISD::SETULT:
4134       case ISD::SETULE: {
4135         EVT newVT = N0.getOperand(0).getValueType();
4136         if (DCI.isBeforeLegalizeOps() ||
4137             (isOperationLegal(ISD::SETCC, newVT) &&
4138              isCondCodeLegal(Cond, newVT.getSimpleVT()))) {
4139           EVT NewSetCCVT = getSetCCResultType(Layout, *DAG.getContext(), newVT);
4140           SDValue NewConst = DAG.getConstant(C1.trunc(InSize), dl, newVT);
4141 
4142           SDValue NewSetCC = DAG.getSetCC(dl, NewSetCCVT, N0.getOperand(0),
4143                                           NewConst, Cond);
4144           return DAG.getBoolExtOrTrunc(NewSetCC, dl, VT, N0.getValueType());
4145         }
4146         break;
4147       }
4148       default:
4149         break; // todo, be more careful with signed comparisons
4150       }
4151     } else if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
4152                (Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
4153                !isSExtCheaperThanZExt(cast<VTSDNode>(N0.getOperand(1))->getVT(),
4154                                       OpVT)) {
4155       EVT ExtSrcTy = cast<VTSDNode>(N0.getOperand(1))->getVT();
4156       unsigned ExtSrcTyBits = ExtSrcTy.getSizeInBits();
4157       EVT ExtDstTy = N0.getValueType();
4158       unsigned ExtDstTyBits = ExtDstTy.getSizeInBits();
4159 
4160       // If the constant doesn't fit into the number of bits for the source of
4161       // the sign extension, it is impossible for both sides to be equal.
4162       if (C1.getMinSignedBits() > ExtSrcTyBits)
4163         return DAG.getBoolConstant(Cond == ISD::SETNE, dl, VT, OpVT);
4164 
4165       assert(ExtDstTy == N0.getOperand(0).getValueType() &&
4166              ExtDstTy != ExtSrcTy && "Unexpected types!");
4167       APInt Imm = APInt::getLowBitsSet(ExtDstTyBits, ExtSrcTyBits);
4168       SDValue ZextOp = DAG.getNode(ISD::AND, dl, ExtDstTy, N0.getOperand(0),
4169                                    DAG.getConstant(Imm, dl, ExtDstTy));
4170       if (!DCI.isCalledByLegalizer())
4171         DCI.AddToWorklist(ZextOp.getNode());
4172       // Otherwise, make this a use of a zext.
4173       return DAG.getSetCC(dl, VT, ZextOp,
4174                           DAG.getConstant(C1 & Imm, dl, ExtDstTy), Cond);
4175     } else if ((N1C->isZero() || N1C->isOne()) &&
4176                (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
4177       // SETCC (SETCC), [0|1], [EQ|NE]  -> SETCC
4178       if (N0.getOpcode() == ISD::SETCC &&
4179           isTypeLegal(VT) && VT.bitsLE(N0.getValueType()) &&
4180           (N0.getValueType() == MVT::i1 ||
4181            getBooleanContents(N0.getOperand(0).getValueType()) ==
4182                        ZeroOrOneBooleanContent)) {
4183         bool TrueWhenTrue = (Cond == ISD::SETEQ) ^ (!N1C->isOne());
4184         if (TrueWhenTrue)
4185           return DAG.getNode(ISD::TRUNCATE, dl, VT, N0);
4186         // Invert the condition.
4187         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4188         CC = ISD::getSetCCInverse(CC, N0.getOperand(0).getValueType());
4189         if (DCI.isBeforeLegalizeOps() ||
4190             isCondCodeLegal(CC, N0.getOperand(0).getSimpleValueType()))
4191           return DAG.getSetCC(dl, VT, N0.getOperand(0), N0.getOperand(1), CC);
4192       }
4193 
4194       if ((N0.getOpcode() == ISD::XOR ||
4195            (N0.getOpcode() == ISD::AND &&
4196             N0.getOperand(0).getOpcode() == ISD::XOR &&
4197             N0.getOperand(1) == N0.getOperand(0).getOperand(1))) &&
4198           isOneConstant(N0.getOperand(1))) {
4199         // If this is (X^1) == 0/1, swap the RHS and eliminate the xor.  We
4200         // can only do this if the top bits are known zero.
4201         unsigned BitWidth = N0.getValueSizeInBits();
4202         if (DAG.MaskedValueIsZero(N0,
4203                                   APInt::getHighBitsSet(BitWidth,
4204                                                         BitWidth-1))) {
4205           // Okay, get the un-inverted input value.
4206           SDValue Val;
4207           if (N0.getOpcode() == ISD::XOR) {
4208             Val = N0.getOperand(0);
4209           } else {
4210             assert(N0.getOpcode() == ISD::AND &&
4211                     N0.getOperand(0).getOpcode() == ISD::XOR);
4212             // ((X^1)&1)^1 -> X & 1
4213             Val = DAG.getNode(ISD::AND, dl, N0.getValueType(),
4214                               N0.getOperand(0).getOperand(0),
4215                               N0.getOperand(1));
4216           }
4217 
4218           return DAG.getSetCC(dl, VT, Val, N1,
4219                               Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
4220         }
4221       } else if (N1C->isOne()) {
4222         SDValue Op0 = N0;
4223         if (Op0.getOpcode() == ISD::TRUNCATE)
4224           Op0 = Op0.getOperand(0);
4225 
4226         if ((Op0.getOpcode() == ISD::XOR) &&
4227             Op0.getOperand(0).getOpcode() == ISD::SETCC &&
4228             Op0.getOperand(1).getOpcode() == ISD::SETCC) {
4229           SDValue XorLHS = Op0.getOperand(0);
4230           SDValue XorRHS = Op0.getOperand(1);
4231           // Ensure that the input setccs return an i1 type or 0/1 value.
4232           if (Op0.getValueType() == MVT::i1 ||
4233               (getBooleanContents(XorLHS.getOperand(0).getValueType()) ==
4234                       ZeroOrOneBooleanContent &&
4235                getBooleanContents(XorRHS.getOperand(0).getValueType()) ==
4236                         ZeroOrOneBooleanContent)) {
4237             // (xor (setcc), (setcc)) == / != 1 -> (setcc) != / == (setcc)
4238             Cond = (Cond == ISD::SETEQ) ? ISD::SETNE : ISD::SETEQ;
4239             return DAG.getSetCC(dl, VT, XorLHS, XorRHS, Cond);
4240           }
4241         }
4242         if (Op0.getOpcode() == ISD::AND && isOneConstant(Op0.getOperand(1))) {
4243           // If this is (X&1) == / != 1, normalize it to (X&1) != / == 0.
4244           if (Op0.getValueType().bitsGT(VT))
4245             Op0 = DAG.getNode(ISD::AND, dl, VT,
4246                           DAG.getNode(ISD::TRUNCATE, dl, VT, Op0.getOperand(0)),
4247                           DAG.getConstant(1, dl, VT));
4248           else if (Op0.getValueType().bitsLT(VT))
4249             Op0 = DAG.getNode(ISD::AND, dl, VT,
4250                         DAG.getNode(ISD::ANY_EXTEND, dl, VT, Op0.getOperand(0)),
4251                         DAG.getConstant(1, dl, VT));
4252 
4253           return DAG.getSetCC(dl, VT, Op0,
4254                               DAG.getConstant(0, dl, Op0.getValueType()),
4255                               Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
4256         }
4257         if (Op0.getOpcode() == ISD::AssertZext &&
4258             cast<VTSDNode>(Op0.getOperand(1))->getVT() == MVT::i1)
4259           return DAG.getSetCC(dl, VT, Op0,
4260                               DAG.getConstant(0, dl, Op0.getValueType()),
4261                               Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
4262       }
4263     }
4264 
4265     // Given:
4266     //   icmp eq/ne (urem %x, %y), 0
4267     // Iff %x has 0 or 1 bits set, and %y has at least 2 bits set, omit 'urem':
4268     //   icmp eq/ne %x, 0
4269     if (N0.getOpcode() == ISD::UREM && N1C->isZero() &&
4270         (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
4271       KnownBits XKnown = DAG.computeKnownBits(N0.getOperand(0));
4272       KnownBits YKnown = DAG.computeKnownBits(N0.getOperand(1));
4273       if (XKnown.countMaxPopulation() == 1 && YKnown.countMinPopulation() >= 2)
4274         return DAG.getSetCC(dl, VT, N0.getOperand(0), N1, Cond);
4275     }
4276 
4277     // Fold set_cc seteq (ashr X, BW-1), -1 -> set_cc setlt X, 0
4278     //  and set_cc setne (ashr X, BW-1), -1 -> set_cc setge X, 0
4279     if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
4280         N0.getOpcode() == ISD::SRA && isa<ConstantSDNode>(N0.getOperand(1)) &&
4281         N0.getConstantOperandAPInt(1) == OpVT.getScalarSizeInBits() - 1 &&
4282         N1C && N1C->isAllOnes()) {
4283       return DAG.getSetCC(dl, VT, N0.getOperand(0),
4284                           DAG.getConstant(0, dl, OpVT),
4285                           Cond == ISD::SETEQ ? ISD::SETLT : ISD::SETGE);
4286     }
4287 
4288     if (SDValue V =
4289             optimizeSetCCOfSignedTruncationCheck(VT, N0, N1, Cond, DCI, dl))
4290       return V;
4291   }
4292 
4293   // These simplifications apply to splat vectors as well.
4294   // TODO: Handle more splat vector cases.
4295   if (auto *N1C = isConstOrConstSplat(N1)) {
4296     const APInt &C1 = N1C->getAPIntValue();
4297 
4298     APInt MinVal, MaxVal;
4299     unsigned OperandBitSize = N1C->getValueType(0).getScalarSizeInBits();
4300     if (ISD::isSignedIntSetCC(Cond)) {
4301       MinVal = APInt::getSignedMinValue(OperandBitSize);
4302       MaxVal = APInt::getSignedMaxValue(OperandBitSize);
4303     } else {
4304       MinVal = APInt::getMinValue(OperandBitSize);
4305       MaxVal = APInt::getMaxValue(OperandBitSize);
4306     }
4307 
4308     // Canonicalize GE/LE comparisons to use GT/LT comparisons.
4309     if (Cond == ISD::SETGE || Cond == ISD::SETUGE) {
4310       // X >= MIN --> true
4311       if (C1 == MinVal)
4312         return DAG.getBoolConstant(true, dl, VT, OpVT);
4313 
4314       if (!VT.isVector()) { // TODO: Support this for vectors.
4315         // X >= C0 --> X > (C0 - 1)
4316         APInt C = C1 - 1;
4317         ISD::CondCode NewCC = (Cond == ISD::SETGE) ? ISD::SETGT : ISD::SETUGT;
4318         if ((DCI.isBeforeLegalizeOps() ||
4319              isCondCodeLegal(NewCC, VT.getSimpleVT())) &&
4320             (!N1C->isOpaque() || (C.getBitWidth() <= 64 &&
4321                                   isLegalICmpImmediate(C.getSExtValue())))) {
4322           return DAG.getSetCC(dl, VT, N0,
4323                               DAG.getConstant(C, dl, N1.getValueType()),
4324                               NewCC);
4325         }
4326       }
4327     }
4328 
4329     if (Cond == ISD::SETLE || Cond == ISD::SETULE) {
4330       // X <= MAX --> true
4331       if (C1 == MaxVal)
4332         return DAG.getBoolConstant(true, dl, VT, OpVT);
4333 
4334       // X <= C0 --> X < (C0 + 1)
4335       if (!VT.isVector()) { // TODO: Support this for vectors.
4336         APInt C = C1 + 1;
4337         ISD::CondCode NewCC = (Cond == ISD::SETLE) ? ISD::SETLT : ISD::SETULT;
4338         if ((DCI.isBeforeLegalizeOps() ||
4339              isCondCodeLegal(NewCC, VT.getSimpleVT())) &&
4340             (!N1C->isOpaque() || (C.getBitWidth() <= 64 &&
4341                                   isLegalICmpImmediate(C.getSExtValue())))) {
4342           return DAG.getSetCC(dl, VT, N0,
4343                               DAG.getConstant(C, dl, N1.getValueType()),
4344                               NewCC);
4345         }
4346       }
4347     }
4348 
4349     if (Cond == ISD::SETLT || Cond == ISD::SETULT) {
4350       if (C1 == MinVal)
4351         return DAG.getBoolConstant(false, dl, VT, OpVT); // X < MIN --> false
4352 
4353       // TODO: Support this for vectors after legalize ops.
4354       if (!VT.isVector() || DCI.isBeforeLegalizeOps()) {
4355         // Canonicalize setlt X, Max --> setne X, Max
4356         if (C1 == MaxVal)
4357           return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE);
4358 
4359         // If we have setult X, 1, turn it into seteq X, 0
4360         if (C1 == MinVal+1)
4361           return DAG.getSetCC(dl, VT, N0,
4362                               DAG.getConstant(MinVal, dl, N0.getValueType()),
4363                               ISD::SETEQ);
4364       }
4365     }
4366 
4367     if (Cond == ISD::SETGT || Cond == ISD::SETUGT) {
4368       if (C1 == MaxVal)
4369         return DAG.getBoolConstant(false, dl, VT, OpVT); // X > MAX --> false
4370 
4371       // TODO: Support this for vectors after legalize ops.
4372       if (!VT.isVector() || DCI.isBeforeLegalizeOps()) {
4373         // Canonicalize setgt X, Min --> setne X, Min
4374         if (C1 == MinVal)
4375           return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE);
4376 
4377         // If we have setugt X, Max-1, turn it into seteq X, Max
4378         if (C1 == MaxVal-1)
4379           return DAG.getSetCC(dl, VT, N0,
4380                               DAG.getConstant(MaxVal, dl, N0.getValueType()),
4381                               ISD::SETEQ);
4382       }
4383     }
4384 
4385     if (Cond == ISD::SETEQ || Cond == ISD::SETNE) {
4386       // (X & (C l>>/<< Y)) ==/!= 0  -->  ((X <</l>> Y) & C) ==/!= 0
4387       if (C1.isZero())
4388         if (SDValue CC = optimizeSetCCByHoistingAndByConstFromLogicalShift(
4389                 VT, N0, N1, Cond, DCI, dl))
4390           return CC;
4391 
4392       // For all/any comparisons, replace or(x,shl(y,bw/2)) with and/or(x,y).
4393       // For example, when high 32-bits of i64 X are known clear:
4394       // all bits clear: (X | (Y<<32)) ==  0 --> (X | Y) ==  0
4395       // all bits set:   (X | (Y<<32)) == -1 --> (X & Y) == -1
4396       bool CmpZero = N1C->getAPIntValue().isZero();
4397       bool CmpNegOne = N1C->getAPIntValue().isAllOnes();
4398       if ((CmpZero || CmpNegOne) && N0.hasOneUse()) {
4399         // Match or(lo,shl(hi,bw/2)) pattern.
4400         auto IsConcat = [&](SDValue V, SDValue &Lo, SDValue &Hi) {
4401           unsigned EltBits = V.getScalarValueSizeInBits();
4402           if (V.getOpcode() != ISD::OR || (EltBits % 2) != 0)
4403             return false;
4404           SDValue LHS = V.getOperand(0);
4405           SDValue RHS = V.getOperand(1);
4406           APInt HiBits = APInt::getHighBitsSet(EltBits, EltBits / 2);
4407           // Unshifted element must have zero upperbits.
4408           if (RHS.getOpcode() == ISD::SHL &&
4409               isa<ConstantSDNode>(RHS.getOperand(1)) &&
4410               RHS.getConstantOperandAPInt(1) == (EltBits / 2) &&
4411               DAG.MaskedValueIsZero(LHS, HiBits)) {
4412             Lo = LHS;
4413             Hi = RHS.getOperand(0);
4414             return true;
4415           }
4416           if (LHS.getOpcode() == ISD::SHL &&
4417               isa<ConstantSDNode>(LHS.getOperand(1)) &&
4418               LHS.getConstantOperandAPInt(1) == (EltBits / 2) &&
4419               DAG.MaskedValueIsZero(RHS, HiBits)) {
4420             Lo = RHS;
4421             Hi = LHS.getOperand(0);
4422             return true;
4423           }
4424           return false;
4425         };
4426 
4427         auto MergeConcat = [&](SDValue Lo, SDValue Hi) {
4428           unsigned EltBits = N0.getScalarValueSizeInBits();
4429           unsigned HalfBits = EltBits / 2;
4430           APInt HiBits = APInt::getHighBitsSet(EltBits, HalfBits);
4431           SDValue LoBits = DAG.getConstant(~HiBits, dl, OpVT);
4432           SDValue HiMask = DAG.getNode(ISD::AND, dl, OpVT, Hi, LoBits);
4433           SDValue NewN0 =
4434               DAG.getNode(CmpZero ? ISD::OR : ISD::AND, dl, OpVT, Lo, HiMask);
4435           SDValue NewN1 = CmpZero ? DAG.getConstant(0, dl, OpVT) : LoBits;
4436           return DAG.getSetCC(dl, VT, NewN0, NewN1, Cond);
4437         };
4438 
4439         SDValue Lo, Hi;
4440         if (IsConcat(N0, Lo, Hi))
4441           return MergeConcat(Lo, Hi);
4442 
4443         if (N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR) {
4444           SDValue Lo0, Lo1, Hi0, Hi1;
4445           if (IsConcat(N0.getOperand(0), Lo0, Hi0) &&
4446               IsConcat(N0.getOperand(1), Lo1, Hi1)) {
4447             return MergeConcat(DAG.getNode(N0.getOpcode(), dl, OpVT, Lo0, Lo1),
4448                                DAG.getNode(N0.getOpcode(), dl, OpVT, Hi0, Hi1));
4449           }
4450         }
4451       }
4452     }
4453 
4454     // If we have "setcc X, C0", check to see if we can shrink the immediate
4455     // by changing cc.
4456     // TODO: Support this for vectors after legalize ops.
4457     if (!VT.isVector() || DCI.isBeforeLegalizeOps()) {
4458       // SETUGT X, SINTMAX  -> SETLT X, 0
4459       // SETUGE X, SINTMIN -> SETLT X, 0
4460       if ((Cond == ISD::SETUGT && C1.isMaxSignedValue()) ||
4461           (Cond == ISD::SETUGE && C1.isMinSignedValue()))
4462         return DAG.getSetCC(dl, VT, N0,
4463                             DAG.getConstant(0, dl, N1.getValueType()),
4464                             ISD::SETLT);
4465 
4466       // SETULT X, SINTMIN  -> SETGT X, -1
4467       // SETULE X, SINTMAX  -> SETGT X, -1
4468       if ((Cond == ISD::SETULT && C1.isMinSignedValue()) ||
4469           (Cond == ISD::SETULE && C1.isMaxSignedValue()))
4470         return DAG.getSetCC(dl, VT, N0,
4471                             DAG.getAllOnesConstant(dl, N1.getValueType()),
4472                             ISD::SETGT);
4473     }
4474   }
4475 
4476   // Back to non-vector simplifications.
4477   // TODO: Can we do these for vector splats?
4478   if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) {
4479     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4480     const APInt &C1 = N1C->getAPIntValue();
4481     EVT ShValTy = N0.getValueType();
4482 
4483     // Fold bit comparisons when we can. This will result in an
4484     // incorrect value when boolean false is negative one, unless
4485     // the bitsize is 1 in which case the false value is the same
4486     // in practice regardless of the representation.
4487     if ((VT.getSizeInBits() == 1 ||
4488          getBooleanContents(N0.getValueType()) == ZeroOrOneBooleanContent) &&
4489         (Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
4490         (VT == ShValTy || (isTypeLegal(VT) && VT.bitsLE(ShValTy))) &&
4491         N0.getOpcode() == ISD::AND) {
4492       if (auto *AndRHS = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
4493         EVT ShiftTy =
4494             getShiftAmountTy(ShValTy, Layout, !DCI.isBeforeLegalize());
4495         if (Cond == ISD::SETNE && C1 == 0) {// (X & 8) != 0  -->  (X & 8) >> 3
4496           // Perform the xform if the AND RHS is a single bit.
4497           unsigned ShCt = AndRHS->getAPIntValue().logBase2();
4498           if (AndRHS->getAPIntValue().isPowerOf2() &&
4499               !TLI.shouldAvoidTransformToShift(ShValTy, ShCt)) {
4500             return DAG.getNode(ISD::TRUNCATE, dl, VT,
4501                                DAG.getNode(ISD::SRL, dl, ShValTy, N0,
4502                                            DAG.getConstant(ShCt, dl, ShiftTy)));
4503           }
4504         } else if (Cond == ISD::SETEQ && C1 == AndRHS->getAPIntValue()) {
4505           // (X & 8) == 8  -->  (X & 8) >> 3
4506           // Perform the xform if C1 is a single bit.
4507           unsigned ShCt = C1.logBase2();
4508           if (C1.isPowerOf2() &&
4509               !TLI.shouldAvoidTransformToShift(ShValTy, ShCt)) {
4510             return DAG.getNode(ISD::TRUNCATE, dl, VT,
4511                                DAG.getNode(ISD::SRL, dl, ShValTy, N0,
4512                                            DAG.getConstant(ShCt, dl, ShiftTy)));
4513           }
4514         }
4515       }
4516     }
4517 
4518     if (C1.getMinSignedBits() <= 64 &&
4519         !isLegalICmpImmediate(C1.getSExtValue())) {
4520       EVT ShiftTy = getShiftAmountTy(ShValTy, Layout, !DCI.isBeforeLegalize());
4521       // (X & -256) == 256 -> (X >> 8) == 1
4522       if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
4523           N0.getOpcode() == ISD::AND && N0.hasOneUse()) {
4524         if (auto *AndRHS = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
4525           const APInt &AndRHSC = AndRHS->getAPIntValue();
4526           if (AndRHSC.isNegatedPowerOf2() && (AndRHSC & C1) == C1) {
4527             unsigned ShiftBits = AndRHSC.countTrailingZeros();
4528             if (!TLI.shouldAvoidTransformToShift(ShValTy, ShiftBits)) {
4529               SDValue Shift =
4530                 DAG.getNode(ISD::SRL, dl, ShValTy, N0.getOperand(0),
4531                             DAG.getConstant(ShiftBits, dl, ShiftTy));
4532               SDValue CmpRHS = DAG.getConstant(C1.lshr(ShiftBits), dl, ShValTy);
4533               return DAG.getSetCC(dl, VT, Shift, CmpRHS, Cond);
4534             }
4535           }
4536         }
4537       } else if (Cond == ISD::SETULT || Cond == ISD::SETUGE ||
4538                  Cond == ISD::SETULE || Cond == ISD::SETUGT) {
4539         bool AdjOne = (Cond == ISD::SETULE || Cond == ISD::SETUGT);
4540         // X <  0x100000000 -> (X >> 32) <  1
4541         // X >= 0x100000000 -> (X >> 32) >= 1
4542         // X <= 0x0ffffffff -> (X >> 32) <  1
4543         // X >  0x0ffffffff -> (X >> 32) >= 1
4544         unsigned ShiftBits;
4545         APInt NewC = C1;
4546         ISD::CondCode NewCond = Cond;
4547         if (AdjOne) {
4548           ShiftBits = C1.countTrailingOnes();
4549           NewC = NewC + 1;
4550           NewCond = (Cond == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
4551         } else {
4552           ShiftBits = C1.countTrailingZeros();
4553         }
4554         NewC.lshrInPlace(ShiftBits);
4555         if (ShiftBits && NewC.getMinSignedBits() <= 64 &&
4556             isLegalICmpImmediate(NewC.getSExtValue()) &&
4557             !TLI.shouldAvoidTransformToShift(ShValTy, ShiftBits)) {
4558           SDValue Shift = DAG.getNode(ISD::SRL, dl, ShValTy, N0,
4559                                       DAG.getConstant(ShiftBits, dl, ShiftTy));
4560           SDValue CmpRHS = DAG.getConstant(NewC, dl, ShValTy);
4561           return DAG.getSetCC(dl, VT, Shift, CmpRHS, NewCond);
4562         }
4563       }
4564     }
4565   }
4566 
4567   if (!isa<ConstantFPSDNode>(N0) && isa<ConstantFPSDNode>(N1)) {
4568     auto *CFP = cast<ConstantFPSDNode>(N1);
4569     assert(!CFP->getValueAPF().isNaN() && "Unexpected NaN value");
4570 
4571     // Otherwise, we know the RHS is not a NaN.  Simplify the node to drop the
4572     // constant if knowing that the operand is non-nan is enough.  We prefer to
4573     // have SETO(x,x) instead of SETO(x, 0.0) because this avoids having to
4574     // materialize 0.0.
4575     if (Cond == ISD::SETO || Cond == ISD::SETUO)
4576       return DAG.getSetCC(dl, VT, N0, N0, Cond);
4577 
4578     // setcc (fneg x), C -> setcc swap(pred) x, -C
4579     if (N0.getOpcode() == ISD::FNEG) {
4580       ISD::CondCode SwapCond = ISD::getSetCCSwappedOperands(Cond);
4581       if (DCI.isBeforeLegalizeOps() ||
4582           isCondCodeLegal(SwapCond, N0.getSimpleValueType())) {
4583         SDValue NegN1 = DAG.getNode(ISD::FNEG, dl, N0.getValueType(), N1);
4584         return DAG.getSetCC(dl, VT, N0.getOperand(0), NegN1, SwapCond);
4585       }
4586     }
4587 
4588     // If the condition is not legal, see if we can find an equivalent one
4589     // which is legal.
4590     if (!isCondCodeLegal(Cond, N0.getSimpleValueType())) {
4591       // If the comparison was an awkward floating-point == or != and one of
4592       // the comparison operands is infinity or negative infinity, convert the
4593       // condition to a less-awkward <= or >=.
4594       if (CFP->getValueAPF().isInfinity()) {
4595         bool IsNegInf = CFP->getValueAPF().isNegative();
4596         ISD::CondCode NewCond = ISD::SETCC_INVALID;
4597         switch (Cond) {
4598         case ISD::SETOEQ: NewCond = IsNegInf ? ISD::SETOLE : ISD::SETOGE; break;
4599         case ISD::SETUEQ: NewCond = IsNegInf ? ISD::SETULE : ISD::SETUGE; break;
4600         case ISD::SETUNE: NewCond = IsNegInf ? ISD::SETUGT : ISD::SETULT; break;
4601         case ISD::SETONE: NewCond = IsNegInf ? ISD::SETOGT : ISD::SETOLT; break;
4602         default: break;
4603         }
4604         if (NewCond != ISD::SETCC_INVALID &&
4605             isCondCodeLegal(NewCond, N0.getSimpleValueType()))
4606           return DAG.getSetCC(dl, VT, N0, N1, NewCond);
4607       }
4608     }
4609   }
4610 
4611   if (N0 == N1) {
4612     // The sext(setcc()) => setcc() optimization relies on the appropriate
4613     // constant being emitted.
4614     assert(!N0.getValueType().isInteger() &&
4615            "Integer types should be handled by FoldSetCC");
4616 
4617     bool EqTrue = ISD::isTrueWhenEqual(Cond);
4618     unsigned UOF = ISD::getUnorderedFlavor(Cond);
4619     if (UOF == 2) // FP operators that are undefined on NaNs.
4620       return DAG.getBoolConstant(EqTrue, dl, VT, OpVT);
4621     if (UOF == unsigned(EqTrue))
4622       return DAG.getBoolConstant(EqTrue, dl, VT, OpVT);
4623     // Otherwise, we can't fold it.  However, we can simplify it to SETUO/SETO
4624     // if it is not already.
4625     ISD::CondCode NewCond = UOF == 0 ? ISD::SETO : ISD::SETUO;
4626     if (NewCond != Cond &&
4627         (DCI.isBeforeLegalizeOps() ||
4628                             isCondCodeLegal(NewCond, N0.getSimpleValueType())))
4629       return DAG.getSetCC(dl, VT, N0, N1, NewCond);
4630   }
4631 
4632   if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
4633       N0.getValueType().isInteger()) {
4634     if (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::SUB ||
4635         N0.getOpcode() == ISD::XOR) {
4636       // Simplify (X+Y) == (X+Z) -->  Y == Z
4637       if (N0.getOpcode() == N1.getOpcode()) {
4638         if (N0.getOperand(0) == N1.getOperand(0))
4639           return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(1), Cond);
4640         if (N0.getOperand(1) == N1.getOperand(1))
4641           return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(0), Cond);
4642         if (isCommutativeBinOp(N0.getOpcode())) {
4643           // If X op Y == Y op X, try other combinations.
4644           if (N0.getOperand(0) == N1.getOperand(1))
4645             return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(0),
4646                                 Cond);
4647           if (N0.getOperand(1) == N1.getOperand(0))
4648             return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(1),
4649                                 Cond);
4650         }
4651       }
4652 
4653       // If RHS is a legal immediate value for a compare instruction, we need
4654       // to be careful about increasing register pressure needlessly.
4655       bool LegalRHSImm = false;
4656 
4657       if (auto *RHSC = dyn_cast<ConstantSDNode>(N1)) {
4658         if (auto *LHSR = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
4659           // Turn (X+C1) == C2 --> X == C2-C1
4660           if (N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse())
4661             return DAG.getSetCC(
4662                 dl, VT, N0.getOperand(0),
4663                 DAG.getConstant(RHSC->getAPIntValue() - LHSR->getAPIntValue(),
4664                                 dl, N0.getValueType()),
4665                 Cond);
4666 
4667           // Turn (X^C1) == C2 --> X == C1^C2
4668           if (N0.getOpcode() == ISD::XOR && N0.getNode()->hasOneUse())
4669             return DAG.getSetCC(
4670                 dl, VT, N0.getOperand(0),
4671                 DAG.getConstant(LHSR->getAPIntValue() ^ RHSC->getAPIntValue(),
4672                                 dl, N0.getValueType()),
4673                 Cond);
4674         }
4675 
4676         // Turn (C1-X) == C2 --> X == C1-C2
4677         if (auto *SUBC = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
4678           if (N0.getOpcode() == ISD::SUB && N0.getNode()->hasOneUse())
4679             return DAG.getSetCC(
4680                 dl, VT, N0.getOperand(1),
4681                 DAG.getConstant(SUBC->getAPIntValue() - RHSC->getAPIntValue(),
4682                                 dl, N0.getValueType()),
4683                 Cond);
4684 
4685         // Could RHSC fold directly into a compare?
4686         if (RHSC->getValueType(0).getSizeInBits() <= 64)
4687           LegalRHSImm = isLegalICmpImmediate(RHSC->getSExtValue());
4688       }
4689 
4690       // (X+Y) == X --> Y == 0 and similar folds.
4691       // Don't do this if X is an immediate that can fold into a cmp
4692       // instruction and X+Y has other uses. It could be an induction variable
4693       // chain, and the transform would increase register pressure.
4694       if (!LegalRHSImm || N0.hasOneUse())
4695         if (SDValue V = foldSetCCWithBinOp(VT, N0, N1, Cond, dl, DCI))
4696           return V;
4697     }
4698 
4699     if (N1.getOpcode() == ISD::ADD || N1.getOpcode() == ISD::SUB ||
4700         N1.getOpcode() == ISD::XOR)
4701       if (SDValue V = foldSetCCWithBinOp(VT, N1, N0, Cond, dl, DCI))
4702         return V;
4703 
4704     if (SDValue V = foldSetCCWithAnd(VT, N0, N1, Cond, dl, DCI))
4705       return V;
4706   }
4707 
4708   // Fold remainder of division by a constant.
4709   if ((N0.getOpcode() == ISD::UREM || N0.getOpcode() == ISD::SREM) &&
4710       N0.hasOneUse() && (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
4711     AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
4712 
4713     // When division is cheap or optimizing for minimum size,
4714     // fall through to DIVREM creation by skipping this fold.
4715     if (!isIntDivCheap(VT, Attr) && !Attr.hasFnAttr(Attribute::MinSize)) {
4716       if (N0.getOpcode() == ISD::UREM) {
4717         if (SDValue Folded = buildUREMEqFold(VT, N0, N1, Cond, DCI, dl))
4718           return Folded;
4719       } else if (N0.getOpcode() == ISD::SREM) {
4720         if (SDValue Folded = buildSREMEqFold(VT, N0, N1, Cond, DCI, dl))
4721           return Folded;
4722       }
4723     }
4724   }
4725 
4726   // Fold away ALL boolean setcc's.
4727   if (N0.getValueType().getScalarType() == MVT::i1 && foldBooleans) {
4728     SDValue Temp;
4729     switch (Cond) {
4730     default: llvm_unreachable("Unknown integer setcc!");
4731     case ISD::SETEQ:  // X == Y  -> ~(X^Y)
4732       Temp = DAG.getNode(ISD::XOR, dl, OpVT, N0, N1);
4733       N0 = DAG.getNOT(dl, Temp, OpVT);
4734       if (!DCI.isCalledByLegalizer())
4735         DCI.AddToWorklist(Temp.getNode());
4736       break;
4737     case ISD::SETNE:  // X != Y   -->  (X^Y)
4738       N0 = DAG.getNode(ISD::XOR, dl, OpVT, N0, N1);
4739       break;
4740     case ISD::SETGT:  // X >s Y   -->  X == 0 & Y == 1  -->  ~X & Y
4741     case ISD::SETULT: // X <u Y   -->  X == 0 & Y == 1  -->  ~X & Y
4742       Temp = DAG.getNOT(dl, N0, OpVT);
4743       N0 = DAG.getNode(ISD::AND, dl, OpVT, N1, Temp);
4744       if (!DCI.isCalledByLegalizer())
4745         DCI.AddToWorklist(Temp.getNode());
4746       break;
4747     case ISD::SETLT:  // X <s Y   --> X == 1 & Y == 0  -->  ~Y & X
4748     case ISD::SETUGT: // X >u Y   --> X == 1 & Y == 0  -->  ~Y & X
4749       Temp = DAG.getNOT(dl, N1, OpVT);
4750       N0 = DAG.getNode(ISD::AND, dl, OpVT, N0, Temp);
4751       if (!DCI.isCalledByLegalizer())
4752         DCI.AddToWorklist(Temp.getNode());
4753       break;
4754     case ISD::SETULE: // X <=u Y  --> X == 0 | Y == 1  -->  ~X | Y
4755     case ISD::SETGE:  // X >=s Y  --> X == 0 | Y == 1  -->  ~X | Y
4756       Temp = DAG.getNOT(dl, N0, OpVT);
4757       N0 = DAG.getNode(ISD::OR, dl, OpVT, N1, Temp);
4758       if (!DCI.isCalledByLegalizer())
4759         DCI.AddToWorklist(Temp.getNode());
4760       break;
4761     case ISD::SETUGE: // X >=u Y  --> X == 1 | Y == 0  -->  ~Y | X
4762     case ISD::SETLE:  // X <=s Y  --> X == 1 | Y == 0  -->  ~Y | X
4763       Temp = DAG.getNOT(dl, N1, OpVT);
4764       N0 = DAG.getNode(ISD::OR, dl, OpVT, N0, Temp);
4765       break;
4766     }
4767     if (VT.getScalarType() != MVT::i1) {
4768       if (!DCI.isCalledByLegalizer())
4769         DCI.AddToWorklist(N0.getNode());
4770       // FIXME: If running after legalize, we probably can't do this.
4771       ISD::NodeType ExtendCode = getExtendForContent(getBooleanContents(OpVT));
4772       N0 = DAG.getNode(ExtendCode, dl, VT, N0);
4773     }
4774     return N0;
4775   }
4776 
4777   // Could not fold it.
4778   return SDValue();
4779 }
4780 
4781 /// Returns true (and the GlobalValue and the offset) if the node is a
4782 /// GlobalAddress + offset.
4783 bool TargetLowering::isGAPlusOffset(SDNode *WN, const GlobalValue *&GA,
4784                                     int64_t &Offset) const {
4785 
4786   SDNode *N = unwrapAddress(SDValue(WN, 0)).getNode();
4787 
4788   if (auto *GASD = dyn_cast<GlobalAddressSDNode>(N)) {
4789     GA = GASD->getGlobal();
4790     Offset += GASD->getOffset();
4791     return true;
4792   }
4793 
4794   if (N->getOpcode() == ISD::ADD) {
4795     SDValue N1 = N->getOperand(0);
4796     SDValue N2 = N->getOperand(1);
4797     if (isGAPlusOffset(N1.getNode(), GA, Offset)) {
4798       if (auto *V = dyn_cast<ConstantSDNode>(N2)) {
4799         Offset += V->getSExtValue();
4800         return true;
4801       }
4802     } else if (isGAPlusOffset(N2.getNode(), GA, Offset)) {
4803       if (auto *V = dyn_cast<ConstantSDNode>(N1)) {
4804         Offset += V->getSExtValue();
4805         return true;
4806       }
4807     }
4808   }
4809 
4810   return false;
4811 }
4812 
4813 SDValue TargetLowering::PerformDAGCombine(SDNode *N,
4814                                           DAGCombinerInfo &DCI) const {
4815   // Default implementation: no optimization.
4816   return SDValue();
4817 }
4818 
4819 //===----------------------------------------------------------------------===//
4820 //  Inline Assembler Implementation Methods
4821 //===----------------------------------------------------------------------===//
4822 
4823 TargetLowering::ConstraintType
4824 TargetLowering::getConstraintType(StringRef Constraint) const {
4825   unsigned S = Constraint.size();
4826 
4827   if (S == 1) {
4828     switch (Constraint[0]) {
4829     default: break;
4830     case 'r':
4831       return C_RegisterClass;
4832     case 'm': // memory
4833     case 'o': // offsetable
4834     case 'V': // not offsetable
4835       return C_Memory;
4836     case 'n': // Simple Integer
4837     case 'E': // Floating Point Constant
4838     case 'F': // Floating Point Constant
4839       return C_Immediate;
4840     case 'i': // Simple Integer or Relocatable Constant
4841     case 's': // Relocatable Constant
4842     case 'p': // Address.
4843     case 'X': // Allow ANY value.
4844     case 'I': // Target registers.
4845     case 'J':
4846     case 'K':
4847     case 'L':
4848     case 'M':
4849     case 'N':
4850     case 'O':
4851     case 'P':
4852     case '<':
4853     case '>':
4854       return C_Other;
4855     }
4856   }
4857 
4858   if (S > 1 && Constraint[0] == '{' && Constraint[S - 1] == '}') {
4859     if (S == 8 && Constraint.substr(1, 6) == "memory") // "{memory}"
4860       return C_Memory;
4861     return C_Register;
4862   }
4863   return C_Unknown;
4864 }
4865 
4866 /// Try to replace an X constraint, which matches anything, with another that
4867 /// has more specific requirements based on the type of the corresponding
4868 /// operand.
4869 const char *TargetLowering::LowerXConstraint(EVT ConstraintVT) const {
4870   if (ConstraintVT.isInteger())
4871     return "r";
4872   if (ConstraintVT.isFloatingPoint())
4873     return "f"; // works for many targets
4874   return nullptr;
4875 }
4876 
4877 SDValue TargetLowering::LowerAsmOutputForConstraint(
4878     SDValue &Chain, SDValue &Flag, const SDLoc &DL,
4879     const AsmOperandInfo &OpInfo, SelectionDAG &DAG) const {
4880   return SDValue();
4881 }
4882 
4883 /// Lower the specified operand into the Ops vector.
4884 /// If it is invalid, don't add anything to Ops.
4885 void TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
4886                                                   std::string &Constraint,
4887                                                   std::vector<SDValue> &Ops,
4888                                                   SelectionDAG &DAG) const {
4889 
4890   if (Constraint.length() > 1) return;
4891 
4892   char ConstraintLetter = Constraint[0];
4893   switch (ConstraintLetter) {
4894   default: break;
4895   case 'X':    // Allows any operand
4896   case 'i':    // Simple Integer or Relocatable Constant
4897   case 'n':    // Simple Integer
4898   case 's': {  // Relocatable Constant
4899 
4900     ConstantSDNode *C;
4901     uint64_t Offset = 0;
4902 
4903     // Match (GA) or (C) or (GA+C) or (GA-C) or ((GA+C)+C) or (((GA+C)+C)+C),
4904     // etc., since getelementpointer is variadic. We can't use
4905     // SelectionDAG::FoldSymbolOffset because it expects the GA to be accessible
4906     // while in this case the GA may be furthest from the root node which is
4907     // likely an ISD::ADD.
4908     while (true) {
4909       if ((C = dyn_cast<ConstantSDNode>(Op)) && ConstraintLetter != 's') {
4910         // gcc prints these as sign extended.  Sign extend value to 64 bits
4911         // now; without this it would get ZExt'd later in
4912         // ScheduleDAGSDNodes::EmitNode, which is very generic.
4913         bool IsBool = C->getConstantIntValue()->getBitWidth() == 1;
4914         BooleanContent BCont = getBooleanContents(MVT::i64);
4915         ISD::NodeType ExtOpc =
4916             IsBool ? getExtendForContent(BCont) : ISD::SIGN_EXTEND;
4917         int64_t ExtVal =
4918             ExtOpc == ISD::ZERO_EXTEND ? C->getZExtValue() : C->getSExtValue();
4919         Ops.push_back(
4920             DAG.getTargetConstant(Offset + ExtVal, SDLoc(C), MVT::i64));
4921         return;
4922       }
4923       if (ConstraintLetter != 'n') {
4924         if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
4925           Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
4926                                                    GA->getValueType(0),
4927                                                    Offset + GA->getOffset()));
4928           return;
4929         }
4930         if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) {
4931           Ops.push_back(DAG.getTargetBlockAddress(
4932               BA->getBlockAddress(), BA->getValueType(0),
4933               Offset + BA->getOffset(), BA->getTargetFlags()));
4934           return;
4935         }
4936         if (isa<BasicBlockSDNode>(Op)) {
4937           Ops.push_back(Op);
4938           return;
4939         }
4940       }
4941       const unsigned OpCode = Op.getOpcode();
4942       if (OpCode == ISD::ADD || OpCode == ISD::SUB) {
4943         if ((C = dyn_cast<ConstantSDNode>(Op.getOperand(0))))
4944           Op = Op.getOperand(1);
4945         // Subtraction is not commutative.
4946         else if (OpCode == ISD::ADD &&
4947                  (C = dyn_cast<ConstantSDNode>(Op.getOperand(1))))
4948           Op = Op.getOperand(0);
4949         else
4950           return;
4951         Offset += (OpCode == ISD::ADD ? 1 : -1) * C->getSExtValue();
4952         continue;
4953       }
4954       return;
4955     }
4956     break;
4957   }
4958   }
4959 }
4960 
4961 std::pair<unsigned, const TargetRegisterClass *>
4962 TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *RI,
4963                                              StringRef Constraint,
4964                                              MVT VT) const {
4965   if (Constraint.empty() || Constraint[0] != '{')
4966     return std::make_pair(0u, static_cast<TargetRegisterClass *>(nullptr));
4967   assert(*(Constraint.end() - 1) == '}' && "Not a brace enclosed constraint?");
4968 
4969   // Remove the braces from around the name.
4970   StringRef RegName(Constraint.data() + 1, Constraint.size() - 2);
4971 
4972   std::pair<unsigned, const TargetRegisterClass *> R =
4973       std::make_pair(0u, static_cast<const TargetRegisterClass *>(nullptr));
4974 
4975   // Figure out which register class contains this reg.
4976   for (const TargetRegisterClass *RC : RI->regclasses()) {
4977     // If none of the value types for this register class are valid, we
4978     // can't use it.  For example, 64-bit reg classes on 32-bit targets.
4979     if (!isLegalRC(*RI, *RC))
4980       continue;
4981 
4982     for (const MCPhysReg &PR : *RC) {
4983       if (RegName.equals_insensitive(RI->getRegAsmName(PR))) {
4984         std::pair<unsigned, const TargetRegisterClass *> S =
4985             std::make_pair(PR, RC);
4986 
4987         // If this register class has the requested value type, return it,
4988         // otherwise keep searching and return the first class found
4989         // if no other is found which explicitly has the requested type.
4990         if (RI->isTypeLegalForClass(*RC, VT))
4991           return S;
4992         if (!R.second)
4993           R = S;
4994       }
4995     }
4996   }
4997 
4998   return R;
4999 }
5000 
5001 //===----------------------------------------------------------------------===//
5002 // Constraint Selection.
5003 
5004 /// Return true of this is an input operand that is a matching constraint like
5005 /// "4".
5006 bool TargetLowering::AsmOperandInfo::isMatchingInputConstraint() const {
5007   assert(!ConstraintCode.empty() && "No known constraint!");
5008   return isdigit(static_cast<unsigned char>(ConstraintCode[0]));
5009 }
5010 
5011 /// If this is an input matching constraint, this method returns the output
5012 /// operand it matches.
5013 unsigned TargetLowering::AsmOperandInfo::getMatchedOperand() const {
5014   assert(!ConstraintCode.empty() && "No known constraint!");
5015   return atoi(ConstraintCode.c_str());
5016 }
5017 
5018 /// Split up the constraint string from the inline assembly value into the
5019 /// specific constraints and their prefixes, and also tie in the associated
5020 /// operand values.
5021 /// If this returns an empty vector, and if the constraint string itself
5022 /// isn't empty, there was an error parsing.
5023 TargetLowering::AsmOperandInfoVector
5024 TargetLowering::ParseConstraints(const DataLayout &DL,
5025                                  const TargetRegisterInfo *TRI,
5026                                  const CallBase &Call) const {
5027   /// Information about all of the constraints.
5028   AsmOperandInfoVector ConstraintOperands;
5029   const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
5030   unsigned maCount = 0; // Largest number of multiple alternative constraints.
5031 
5032   // Do a prepass over the constraints, canonicalizing them, and building up the
5033   // ConstraintOperands list.
5034   unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
5035   unsigned ResNo = 0; // ResNo - The result number of the next output.
5036 
5037   for (InlineAsm::ConstraintInfo &CI : IA->ParseConstraints()) {
5038     ConstraintOperands.emplace_back(std::move(CI));
5039     AsmOperandInfo &OpInfo = ConstraintOperands.back();
5040 
5041     // Update multiple alternative constraint count.
5042     if (OpInfo.multipleAlternatives.size() > maCount)
5043       maCount = OpInfo.multipleAlternatives.size();
5044 
5045     OpInfo.ConstraintVT = MVT::Other;
5046 
5047     // Compute the value type for each operand.
5048     switch (OpInfo.Type) {
5049     case InlineAsm::isOutput:
5050       // Indirect outputs just consume an argument.
5051       if (OpInfo.isIndirect) {
5052         OpInfo.CallOperandVal = Call.getArgOperand(ArgNo);
5053         break;
5054       }
5055 
5056       // The return value of the call is this value.  As such, there is no
5057       // corresponding argument.
5058       assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
5059       if (StructType *STy = dyn_cast<StructType>(Call.getType())) {
5060         OpInfo.ConstraintVT =
5061             getSimpleValueType(DL, STy->getElementType(ResNo));
5062       } else {
5063         assert(ResNo == 0 && "Asm only has one result!");
5064         OpInfo.ConstraintVT =
5065             getAsmOperandValueType(DL, Call.getType()).getSimpleVT();
5066       }
5067       ++ResNo;
5068       break;
5069     case InlineAsm::isInput:
5070       OpInfo.CallOperandVal = Call.getArgOperand(ArgNo);
5071       break;
5072     case InlineAsm::isClobber:
5073       // Nothing to do.
5074       break;
5075     }
5076 
5077     if (OpInfo.CallOperandVal) {
5078       llvm::Type *OpTy = OpInfo.CallOperandVal->getType();
5079       if (OpInfo.isIndirect) {
5080         OpTy = Call.getParamElementType(ArgNo);
5081         assert(OpTy && "Indirect operand must have elementtype attribute");
5082       }
5083 
5084       // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
5085       if (StructType *STy = dyn_cast<StructType>(OpTy))
5086         if (STy->getNumElements() == 1)
5087           OpTy = STy->getElementType(0);
5088 
5089       // If OpTy is not a single value, it may be a struct/union that we
5090       // can tile with integers.
5091       if (!OpTy->isSingleValueType() && OpTy->isSized()) {
5092         unsigned BitSize = DL.getTypeSizeInBits(OpTy);
5093         switch (BitSize) {
5094         default: break;
5095         case 1:
5096         case 8:
5097         case 16:
5098         case 32:
5099         case 64:
5100         case 128:
5101           OpInfo.ConstraintVT =
5102               MVT::getVT(IntegerType::get(OpTy->getContext(), BitSize), true);
5103           break;
5104         }
5105       } else if (PointerType *PT = dyn_cast<PointerType>(OpTy)) {
5106         unsigned PtrSize = DL.getPointerSizeInBits(PT->getAddressSpace());
5107         OpInfo.ConstraintVT = MVT::getIntegerVT(PtrSize);
5108       } else {
5109         OpInfo.ConstraintVT = MVT::getVT(OpTy, true);
5110       }
5111 
5112       ArgNo++;
5113     }
5114   }
5115 
5116   // If we have multiple alternative constraints, select the best alternative.
5117   if (!ConstraintOperands.empty()) {
5118     if (maCount) {
5119       unsigned bestMAIndex = 0;
5120       int bestWeight = -1;
5121       // weight:  -1 = invalid match, and 0 = so-so match to 5 = good match.
5122       int weight = -1;
5123       unsigned maIndex;
5124       // Compute the sums of the weights for each alternative, keeping track
5125       // of the best (highest weight) one so far.
5126       for (maIndex = 0; maIndex < maCount; ++maIndex) {
5127         int weightSum = 0;
5128         for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
5129              cIndex != eIndex; ++cIndex) {
5130           AsmOperandInfo &OpInfo = ConstraintOperands[cIndex];
5131           if (OpInfo.Type == InlineAsm::isClobber)
5132             continue;
5133 
5134           // If this is an output operand with a matching input operand,
5135           // look up the matching input. If their types mismatch, e.g. one
5136           // is an integer, the other is floating point, or their sizes are
5137           // different, flag it as an maCantMatch.
5138           if (OpInfo.hasMatchingInput()) {
5139             AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
5140             if (OpInfo.ConstraintVT != Input.ConstraintVT) {
5141               if ((OpInfo.ConstraintVT.isInteger() !=
5142                    Input.ConstraintVT.isInteger()) ||
5143                   (OpInfo.ConstraintVT.getSizeInBits() !=
5144                    Input.ConstraintVT.getSizeInBits())) {
5145                 weightSum = -1; // Can't match.
5146                 break;
5147               }
5148             }
5149           }
5150           weight = getMultipleConstraintMatchWeight(OpInfo, maIndex);
5151           if (weight == -1) {
5152             weightSum = -1;
5153             break;
5154           }
5155           weightSum += weight;
5156         }
5157         // Update best.
5158         if (weightSum > bestWeight) {
5159           bestWeight = weightSum;
5160           bestMAIndex = maIndex;
5161         }
5162       }
5163 
5164       // Now select chosen alternative in each constraint.
5165       for (AsmOperandInfo &cInfo : ConstraintOperands)
5166         if (cInfo.Type != InlineAsm::isClobber)
5167           cInfo.selectAlternative(bestMAIndex);
5168     }
5169   }
5170 
5171   // Check and hook up tied operands, choose constraint code to use.
5172   for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
5173        cIndex != eIndex; ++cIndex) {
5174     AsmOperandInfo &OpInfo = ConstraintOperands[cIndex];
5175 
5176     // If this is an output operand with a matching input operand, look up the
5177     // matching input. If their types mismatch, e.g. one is an integer, the
5178     // other is floating point, or their sizes are different, flag it as an
5179     // error.
5180     if (OpInfo.hasMatchingInput()) {
5181       AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
5182 
5183       if (OpInfo.ConstraintVT != Input.ConstraintVT) {
5184         std::pair<unsigned, const TargetRegisterClass *> MatchRC =
5185             getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
5186                                          OpInfo.ConstraintVT);
5187         std::pair<unsigned, const TargetRegisterClass *> InputRC =
5188             getRegForInlineAsmConstraint(TRI, Input.ConstraintCode,
5189                                          Input.ConstraintVT);
5190         if ((OpInfo.ConstraintVT.isInteger() !=
5191              Input.ConstraintVT.isInteger()) ||
5192             (MatchRC.second != InputRC.second)) {
5193           report_fatal_error("Unsupported asm: input constraint"
5194                              " with a matching output constraint of"
5195                              " incompatible type!");
5196         }
5197       }
5198     }
5199   }
5200 
5201   return ConstraintOperands;
5202 }
5203 
5204 /// Return an integer indicating how general CT is.
5205 static unsigned getConstraintGenerality(TargetLowering::ConstraintType CT) {
5206   switch (CT) {
5207   case TargetLowering::C_Immediate:
5208   case TargetLowering::C_Other:
5209   case TargetLowering::C_Unknown:
5210     return 0;
5211   case TargetLowering::C_Register:
5212     return 1;
5213   case TargetLowering::C_RegisterClass:
5214     return 2;
5215   case TargetLowering::C_Memory:
5216     return 3;
5217   }
5218   llvm_unreachable("Invalid constraint type");
5219 }
5220 
5221 /// Examine constraint type and operand type and determine a weight value.
5222 /// This object must already have been set up with the operand type
5223 /// and the current alternative constraint selected.
5224 TargetLowering::ConstraintWeight
5225   TargetLowering::getMultipleConstraintMatchWeight(
5226     AsmOperandInfo &info, int maIndex) const {
5227   InlineAsm::ConstraintCodeVector *rCodes;
5228   if (maIndex >= (int)info.multipleAlternatives.size())
5229     rCodes = &info.Codes;
5230   else
5231     rCodes = &info.multipleAlternatives[maIndex].Codes;
5232   ConstraintWeight BestWeight = CW_Invalid;
5233 
5234   // Loop over the options, keeping track of the most general one.
5235   for (const std::string &rCode : *rCodes) {
5236     ConstraintWeight weight =
5237         getSingleConstraintMatchWeight(info, rCode.c_str());
5238     if (weight > BestWeight)
5239       BestWeight = weight;
5240   }
5241 
5242   return BestWeight;
5243 }
5244 
5245 /// Examine constraint type and operand type and determine a weight value.
5246 /// This object must already have been set up with the operand type
5247 /// and the current alternative constraint selected.
5248 TargetLowering::ConstraintWeight
5249   TargetLowering::getSingleConstraintMatchWeight(
5250     AsmOperandInfo &info, const char *constraint) const {
5251   ConstraintWeight weight = CW_Invalid;
5252   Value *CallOperandVal = info.CallOperandVal;
5253     // If we don't have a value, we can't do a match,
5254     // but allow it at the lowest weight.
5255   if (!CallOperandVal)
5256     return CW_Default;
5257   // Look at the constraint type.
5258   switch (*constraint) {
5259     case 'i': // immediate integer.
5260     case 'n': // immediate integer with a known value.
5261       if (isa<ConstantInt>(CallOperandVal))
5262         weight = CW_Constant;
5263       break;
5264     case 's': // non-explicit intregal immediate.
5265       if (isa<GlobalValue>(CallOperandVal))
5266         weight = CW_Constant;
5267       break;
5268     case 'E': // immediate float if host format.
5269     case 'F': // immediate float.
5270       if (isa<ConstantFP>(CallOperandVal))
5271         weight = CW_Constant;
5272       break;
5273     case '<': // memory operand with autodecrement.
5274     case '>': // memory operand with autoincrement.
5275     case 'm': // memory operand.
5276     case 'o': // offsettable memory operand
5277     case 'V': // non-offsettable memory operand
5278       weight = CW_Memory;
5279       break;
5280     case 'r': // general register.
5281     case 'g': // general register, memory operand or immediate integer.
5282               // note: Clang converts "g" to "imr".
5283       if (CallOperandVal->getType()->isIntegerTy())
5284         weight = CW_Register;
5285       break;
5286     case 'X': // any operand.
5287   default:
5288     weight = CW_Default;
5289     break;
5290   }
5291   return weight;
5292 }
5293 
5294 /// If there are multiple different constraints that we could pick for this
5295 /// operand (e.g. "imr") try to pick the 'best' one.
5296 /// This is somewhat tricky: constraints fall into four classes:
5297 ///    Other         -> immediates and magic values
5298 ///    Register      -> one specific register
5299 ///    RegisterClass -> a group of regs
5300 ///    Memory        -> memory
5301 /// Ideally, we would pick the most specific constraint possible: if we have
5302 /// something that fits into a register, we would pick it.  The problem here
5303 /// is that if we have something that could either be in a register or in
5304 /// memory that use of the register could cause selection of *other*
5305 /// operands to fail: they might only succeed if we pick memory.  Because of
5306 /// this the heuristic we use is:
5307 ///
5308 ///  1) If there is an 'other' constraint, and if the operand is valid for
5309 ///     that constraint, use it.  This makes us take advantage of 'i'
5310 ///     constraints when available.
5311 ///  2) Otherwise, pick the most general constraint present.  This prefers
5312 ///     'm' over 'r', for example.
5313 ///
5314 static void ChooseConstraint(TargetLowering::AsmOperandInfo &OpInfo,
5315                              const TargetLowering &TLI,
5316                              SDValue Op, SelectionDAG *DAG) {
5317   assert(OpInfo.Codes.size() > 1 && "Doesn't have multiple constraint options");
5318   unsigned BestIdx = 0;
5319   TargetLowering::ConstraintType BestType = TargetLowering::C_Unknown;
5320   int BestGenerality = -1;
5321 
5322   // Loop over the options, keeping track of the most general one.
5323   for (unsigned i = 0, e = OpInfo.Codes.size(); i != e; ++i) {
5324     TargetLowering::ConstraintType CType =
5325       TLI.getConstraintType(OpInfo.Codes[i]);
5326 
5327     // Indirect 'other' or 'immediate' constraints are not allowed.
5328     if (OpInfo.isIndirect && !(CType == TargetLowering::C_Memory ||
5329                                CType == TargetLowering::C_Register ||
5330                                CType == TargetLowering::C_RegisterClass))
5331       continue;
5332 
5333     // If this is an 'other' or 'immediate' constraint, see if the operand is
5334     // valid for it. For example, on X86 we might have an 'rI' constraint. If
5335     // the operand is an integer in the range [0..31] we want to use I (saving a
5336     // load of a register), otherwise we must use 'r'.
5337     if ((CType == TargetLowering::C_Other ||
5338          CType == TargetLowering::C_Immediate) && Op.getNode()) {
5339       assert(OpInfo.Codes[i].size() == 1 &&
5340              "Unhandled multi-letter 'other' constraint");
5341       std::vector<SDValue> ResultOps;
5342       TLI.LowerAsmOperandForConstraint(Op, OpInfo.Codes[i],
5343                                        ResultOps, *DAG);
5344       if (!ResultOps.empty()) {
5345         BestType = CType;
5346         BestIdx = i;
5347         break;
5348       }
5349     }
5350 
5351     // Things with matching constraints can only be registers, per gcc
5352     // documentation.  This mainly affects "g" constraints.
5353     if (CType == TargetLowering::C_Memory && OpInfo.hasMatchingInput())
5354       continue;
5355 
5356     // This constraint letter is more general than the previous one, use it.
5357     int Generality = getConstraintGenerality(CType);
5358     if (Generality > BestGenerality) {
5359       BestType = CType;
5360       BestIdx = i;
5361       BestGenerality = Generality;
5362     }
5363   }
5364 
5365   OpInfo.ConstraintCode = OpInfo.Codes[BestIdx];
5366   OpInfo.ConstraintType = BestType;
5367 }
5368 
5369 /// Determines the constraint code and constraint type to use for the specific
5370 /// AsmOperandInfo, setting OpInfo.ConstraintCode and OpInfo.ConstraintType.
5371 void TargetLowering::ComputeConstraintToUse(AsmOperandInfo &OpInfo,
5372                                             SDValue Op,
5373                                             SelectionDAG *DAG) const {
5374   assert(!OpInfo.Codes.empty() && "Must have at least one constraint");
5375 
5376   // Single-letter constraints ('r') are very common.
5377   if (OpInfo.Codes.size() == 1) {
5378     OpInfo.ConstraintCode = OpInfo.Codes[0];
5379     OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode);
5380   } else {
5381     ChooseConstraint(OpInfo, *this, Op, DAG);
5382   }
5383 
5384   // 'X' matches anything.
5385   if (OpInfo.ConstraintCode == "X" && OpInfo.CallOperandVal) {
5386     // Constants are handled elsewhere.  For Functions, the type here is the
5387     // type of the result, which is not what we want to look at; leave them
5388     // alone.
5389     Value *v = OpInfo.CallOperandVal;
5390     if (isa<ConstantInt>(v) || isa<Function>(v)) {
5391       return;
5392     }
5393 
5394     if (isa<BasicBlock>(v) || isa<BlockAddress>(v)) {
5395       OpInfo.ConstraintCode = "i";
5396       return;
5397     }
5398 
5399     // Otherwise, try to resolve it to something we know about by looking at
5400     // the actual operand type.
5401     if (const char *Repl = LowerXConstraint(OpInfo.ConstraintVT)) {
5402       OpInfo.ConstraintCode = Repl;
5403       OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode);
5404     }
5405   }
5406 }
5407 
5408 /// Given an exact SDIV by a constant, create a multiplication
5409 /// with the multiplicative inverse of the constant.
5410 static SDValue BuildExactSDIV(const TargetLowering &TLI, SDNode *N,
5411                               const SDLoc &dl, SelectionDAG &DAG,
5412                               SmallVectorImpl<SDNode *> &Created) {
5413   SDValue Op0 = N->getOperand(0);
5414   SDValue Op1 = N->getOperand(1);
5415   EVT VT = N->getValueType(0);
5416   EVT SVT = VT.getScalarType();
5417   EVT ShVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout());
5418   EVT ShSVT = ShVT.getScalarType();
5419 
5420   bool UseSRA = false;
5421   SmallVector<SDValue, 16> Shifts, Factors;
5422 
5423   auto BuildSDIVPattern = [&](ConstantSDNode *C) {
5424     if (C->isZero())
5425       return false;
5426     APInt Divisor = C->getAPIntValue();
5427     unsigned Shift = Divisor.countTrailingZeros();
5428     if (Shift) {
5429       Divisor.ashrInPlace(Shift);
5430       UseSRA = true;
5431     }
5432     // Calculate the multiplicative inverse, using Newton's method.
5433     APInt t;
5434     APInt Factor = Divisor;
5435     while ((t = Divisor * Factor) != 1)
5436       Factor *= APInt(Divisor.getBitWidth(), 2) - t;
5437     Shifts.push_back(DAG.getConstant(Shift, dl, ShSVT));
5438     Factors.push_back(DAG.getConstant(Factor, dl, SVT));
5439     return true;
5440   };
5441 
5442   // Collect all magic values from the build vector.
5443   if (!ISD::matchUnaryPredicate(Op1, BuildSDIVPattern))
5444     return SDValue();
5445 
5446   SDValue Shift, Factor;
5447   if (Op1.getOpcode() == ISD::BUILD_VECTOR) {
5448     Shift = DAG.getBuildVector(ShVT, dl, Shifts);
5449     Factor = DAG.getBuildVector(VT, dl, Factors);
5450   } else if (Op1.getOpcode() == ISD::SPLAT_VECTOR) {
5451     assert(Shifts.size() == 1 && Factors.size() == 1 &&
5452            "Expected matchUnaryPredicate to return one element for scalable "
5453            "vectors");
5454     Shift = DAG.getSplatVector(ShVT, dl, Shifts[0]);
5455     Factor = DAG.getSplatVector(VT, dl, Factors[0]);
5456   } else {
5457     assert(isa<ConstantSDNode>(Op1) && "Expected a constant");
5458     Shift = Shifts[0];
5459     Factor = Factors[0];
5460   }
5461 
5462   SDValue Res = Op0;
5463 
5464   // Shift the value upfront if it is even, so the LSB is one.
5465   if (UseSRA) {
5466     // TODO: For UDIV use SRL instead of SRA.
5467     SDNodeFlags Flags;
5468     Flags.setExact(true);
5469     Res = DAG.getNode(ISD::SRA, dl, VT, Res, Shift, Flags);
5470     Created.push_back(Res.getNode());
5471   }
5472 
5473   return DAG.getNode(ISD::MUL, dl, VT, Res, Factor);
5474 }
5475 
5476 SDValue TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
5477                               SelectionDAG &DAG,
5478                               SmallVectorImpl<SDNode *> &Created) const {
5479   AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
5480   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5481   if (TLI.isIntDivCheap(N->getValueType(0), Attr))
5482     return SDValue(N, 0); // Lower SDIV as SDIV
5483   return SDValue();
5484 }
5485 
5486 /// Given an ISD::SDIV node expressing a divide by constant,
5487 /// return a DAG expression to select that will generate the same value by
5488 /// multiplying by a magic number.
5489 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
5490 SDValue TargetLowering::BuildSDIV(SDNode *N, SelectionDAG &DAG,
5491                                   bool IsAfterLegalization,
5492                                   SmallVectorImpl<SDNode *> &Created) const {
5493   SDLoc dl(N);
5494   EVT VT = N->getValueType(0);
5495   EVT SVT = VT.getScalarType();
5496   EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
5497   EVT ShSVT = ShVT.getScalarType();
5498   unsigned EltBits = VT.getScalarSizeInBits();
5499   EVT MulVT;
5500 
5501   // Check to see if we can do this.
5502   // FIXME: We should be more aggressive here.
5503   if (!isTypeLegal(VT)) {
5504     // Limit this to simple scalars for now.
5505     if (VT.isVector() || !VT.isSimple())
5506       return SDValue();
5507 
5508     // If this type will be promoted to a large enough type with a legal
5509     // multiply operation, we can go ahead and do this transform.
5510     if (getTypeAction(VT.getSimpleVT()) != TypePromoteInteger)
5511       return SDValue();
5512 
5513     MulVT = getTypeToTransformTo(*DAG.getContext(), VT);
5514     if (MulVT.getSizeInBits() < (2 * EltBits) ||
5515         !isOperationLegal(ISD::MUL, MulVT))
5516       return SDValue();
5517   }
5518 
5519   // If the sdiv has an 'exact' bit we can use a simpler lowering.
5520   if (N->getFlags().hasExact())
5521     return BuildExactSDIV(*this, N, dl, DAG, Created);
5522 
5523   SmallVector<SDValue, 16> MagicFactors, Factors, Shifts, ShiftMasks;
5524 
5525   auto BuildSDIVPattern = [&](ConstantSDNode *C) {
5526     if (C->isZero())
5527       return false;
5528 
5529     const APInt &Divisor = C->getAPIntValue();
5530     SignedDivisionByConstantInfo magics = SignedDivisionByConstantInfo::get(Divisor);
5531     int NumeratorFactor = 0;
5532     int ShiftMask = -1;
5533 
5534     if (Divisor.isOne() || Divisor.isAllOnes()) {
5535       // If d is +1/-1, we just multiply the numerator by +1/-1.
5536       NumeratorFactor = Divisor.getSExtValue();
5537       magics.Magic = 0;
5538       magics.ShiftAmount = 0;
5539       ShiftMask = 0;
5540     } else if (Divisor.isStrictlyPositive() && magics.Magic.isNegative()) {
5541       // If d > 0 and m < 0, add the numerator.
5542       NumeratorFactor = 1;
5543     } else if (Divisor.isNegative() && magics.Magic.isStrictlyPositive()) {
5544       // If d < 0 and m > 0, subtract the numerator.
5545       NumeratorFactor = -1;
5546     }
5547 
5548     MagicFactors.push_back(DAG.getConstant(magics.Magic, dl, SVT));
5549     Factors.push_back(DAG.getConstant(NumeratorFactor, dl, SVT));
5550     Shifts.push_back(DAG.getConstant(magics.ShiftAmount, dl, ShSVT));
5551     ShiftMasks.push_back(DAG.getConstant(ShiftMask, dl, SVT));
5552     return true;
5553   };
5554 
5555   SDValue N0 = N->getOperand(0);
5556   SDValue N1 = N->getOperand(1);
5557 
5558   // Collect the shifts / magic values from each element.
5559   if (!ISD::matchUnaryPredicate(N1, BuildSDIVPattern))
5560     return SDValue();
5561 
5562   SDValue MagicFactor, Factor, Shift, ShiftMask;
5563   if (N1.getOpcode() == ISD::BUILD_VECTOR) {
5564     MagicFactor = DAG.getBuildVector(VT, dl, MagicFactors);
5565     Factor = DAG.getBuildVector(VT, dl, Factors);
5566     Shift = DAG.getBuildVector(ShVT, dl, Shifts);
5567     ShiftMask = DAG.getBuildVector(VT, dl, ShiftMasks);
5568   } else if (N1.getOpcode() == ISD::SPLAT_VECTOR) {
5569     assert(MagicFactors.size() == 1 && Factors.size() == 1 &&
5570            Shifts.size() == 1 && ShiftMasks.size() == 1 &&
5571            "Expected matchUnaryPredicate to return one element for scalable "
5572            "vectors");
5573     MagicFactor = DAG.getSplatVector(VT, dl, MagicFactors[0]);
5574     Factor = DAG.getSplatVector(VT, dl, Factors[0]);
5575     Shift = DAG.getSplatVector(ShVT, dl, Shifts[0]);
5576     ShiftMask = DAG.getSplatVector(VT, dl, ShiftMasks[0]);
5577   } else {
5578     assert(isa<ConstantSDNode>(N1) && "Expected a constant");
5579     MagicFactor = MagicFactors[0];
5580     Factor = Factors[0];
5581     Shift = Shifts[0];
5582     ShiftMask = ShiftMasks[0];
5583   }
5584 
5585   // Multiply the numerator (operand 0) by the magic value.
5586   // FIXME: We should support doing a MUL in a wider type.
5587   auto GetMULHS = [&](SDValue X, SDValue Y) {
5588     // If the type isn't legal, use a wider mul of the the type calculated
5589     // earlier.
5590     if (!isTypeLegal(VT)) {
5591       X = DAG.getNode(ISD::SIGN_EXTEND, dl, MulVT, X);
5592       Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MulVT, Y);
5593       Y = DAG.getNode(ISD::MUL, dl, MulVT, X, Y);
5594       Y = DAG.getNode(ISD::SRL, dl, MulVT, Y,
5595                       DAG.getShiftAmountConstant(EltBits, MulVT, dl));
5596       return DAG.getNode(ISD::TRUNCATE, dl, VT, Y);
5597     }
5598 
5599     if (isOperationLegalOrCustom(ISD::MULHS, VT, IsAfterLegalization))
5600       return DAG.getNode(ISD::MULHS, dl, VT, X, Y);
5601     if (isOperationLegalOrCustom(ISD::SMUL_LOHI, VT, IsAfterLegalization)) {
5602       SDValue LoHi =
5603           DAG.getNode(ISD::SMUL_LOHI, dl, DAG.getVTList(VT, VT), X, Y);
5604       return SDValue(LoHi.getNode(), 1);
5605     }
5606     return SDValue();
5607   };
5608 
5609   SDValue Q = GetMULHS(N0, MagicFactor);
5610   if (!Q)
5611     return SDValue();
5612 
5613   Created.push_back(Q.getNode());
5614 
5615   // (Optionally) Add/subtract the numerator using Factor.
5616   Factor = DAG.getNode(ISD::MUL, dl, VT, N0, Factor);
5617   Created.push_back(Factor.getNode());
5618   Q = DAG.getNode(ISD::ADD, dl, VT, Q, Factor);
5619   Created.push_back(Q.getNode());
5620 
5621   // Shift right algebraic by shift value.
5622   Q = DAG.getNode(ISD::SRA, dl, VT, Q, Shift);
5623   Created.push_back(Q.getNode());
5624 
5625   // Extract the sign bit, mask it and add it to the quotient.
5626   SDValue SignShift = DAG.getConstant(EltBits - 1, dl, ShVT);
5627   SDValue T = DAG.getNode(ISD::SRL, dl, VT, Q, SignShift);
5628   Created.push_back(T.getNode());
5629   T = DAG.getNode(ISD::AND, dl, VT, T, ShiftMask);
5630   Created.push_back(T.getNode());
5631   return DAG.getNode(ISD::ADD, dl, VT, Q, T);
5632 }
5633 
5634 /// Given an ISD::UDIV node expressing a divide by constant,
5635 /// return a DAG expression to select that will generate the same value by
5636 /// multiplying by a magic number.
5637 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
5638 SDValue TargetLowering::BuildUDIV(SDNode *N, SelectionDAG &DAG,
5639                                   bool IsAfterLegalization,
5640                                   SmallVectorImpl<SDNode *> &Created) const {
5641   SDLoc dl(N);
5642   EVT VT = N->getValueType(0);
5643   EVT SVT = VT.getScalarType();
5644   EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
5645   EVT ShSVT = ShVT.getScalarType();
5646   unsigned EltBits = VT.getScalarSizeInBits();
5647   EVT MulVT;
5648 
5649   // Check to see if we can do this.
5650   // FIXME: We should be more aggressive here.
5651   if (!isTypeLegal(VT)) {
5652     // Limit this to simple scalars for now.
5653     if (VT.isVector() || !VT.isSimple())
5654       return SDValue();
5655 
5656     // If this type will be promoted to a large enough type with a legal
5657     // multiply operation, we can go ahead and do this transform.
5658     if (getTypeAction(VT.getSimpleVT()) != TypePromoteInteger)
5659       return SDValue();
5660 
5661     MulVT = getTypeToTransformTo(*DAG.getContext(), VT);
5662     if (MulVT.getSizeInBits() < (2 * EltBits) ||
5663         !isOperationLegal(ISD::MUL, MulVT))
5664       return SDValue();
5665   }
5666 
5667   bool UseNPQ = false;
5668   SmallVector<SDValue, 16> PreShifts, PostShifts, MagicFactors, NPQFactors;
5669 
5670   auto BuildUDIVPattern = [&](ConstantSDNode *C) {
5671     if (C->isZero())
5672       return false;
5673     // FIXME: We should use a narrower constant when the upper
5674     // bits are known to be zero.
5675     const APInt& Divisor = C->getAPIntValue();
5676     UnsignedDivisonByConstantInfo magics = UnsignedDivisonByConstantInfo::get(Divisor);
5677     unsigned PreShift = 0, PostShift = 0;
5678 
5679     // If the divisor is even, we can avoid using the expensive fixup by
5680     // shifting the divided value upfront.
5681     if (magics.IsAdd != 0 && !Divisor[0]) {
5682       PreShift = Divisor.countTrailingZeros();
5683       // Get magic number for the shifted divisor.
5684       magics = UnsignedDivisonByConstantInfo::get(Divisor.lshr(PreShift), PreShift);
5685       assert(magics.IsAdd == 0 && "Should use cheap fixup now");
5686     }
5687 
5688     APInt Magic = magics.Magic;
5689 
5690     unsigned SelNPQ;
5691     if (magics.IsAdd == 0 || Divisor.isOne()) {
5692       assert(magics.ShiftAmount < Divisor.getBitWidth() &&
5693              "We shouldn't generate an undefined shift!");
5694       PostShift = magics.ShiftAmount;
5695       SelNPQ = false;
5696     } else {
5697       PostShift = magics.ShiftAmount - 1;
5698       SelNPQ = true;
5699     }
5700 
5701     PreShifts.push_back(DAG.getConstant(PreShift, dl, ShSVT));
5702     MagicFactors.push_back(DAG.getConstant(Magic, dl, SVT));
5703     NPQFactors.push_back(
5704         DAG.getConstant(SelNPQ ? APInt::getOneBitSet(EltBits, EltBits - 1)
5705                                : APInt::getZero(EltBits),
5706                         dl, SVT));
5707     PostShifts.push_back(DAG.getConstant(PostShift, dl, ShSVT));
5708     UseNPQ |= SelNPQ;
5709     return true;
5710   };
5711 
5712   SDValue N0 = N->getOperand(0);
5713   SDValue N1 = N->getOperand(1);
5714 
5715   // Collect the shifts/magic values from each element.
5716   if (!ISD::matchUnaryPredicate(N1, BuildUDIVPattern))
5717     return SDValue();
5718 
5719   SDValue PreShift, PostShift, MagicFactor, NPQFactor;
5720   if (N1.getOpcode() == ISD::BUILD_VECTOR) {
5721     PreShift = DAG.getBuildVector(ShVT, dl, PreShifts);
5722     MagicFactor = DAG.getBuildVector(VT, dl, MagicFactors);
5723     NPQFactor = DAG.getBuildVector(VT, dl, NPQFactors);
5724     PostShift = DAG.getBuildVector(ShVT, dl, PostShifts);
5725   } else if (N1.getOpcode() == ISD::SPLAT_VECTOR) {
5726     assert(PreShifts.size() == 1 && MagicFactors.size() == 1 &&
5727            NPQFactors.size() == 1 && PostShifts.size() == 1 &&
5728            "Expected matchUnaryPredicate to return one for scalable vectors");
5729     PreShift = DAG.getSplatVector(ShVT, dl, PreShifts[0]);
5730     MagicFactor = DAG.getSplatVector(VT, dl, MagicFactors[0]);
5731     NPQFactor = DAG.getSplatVector(VT, dl, NPQFactors[0]);
5732     PostShift = DAG.getSplatVector(ShVT, dl, PostShifts[0]);
5733   } else {
5734     assert(isa<ConstantSDNode>(N1) && "Expected a constant");
5735     PreShift = PreShifts[0];
5736     MagicFactor = MagicFactors[0];
5737     PostShift = PostShifts[0];
5738   }
5739 
5740   SDValue Q = N0;
5741   Q = DAG.getNode(ISD::SRL, dl, VT, Q, PreShift);
5742   Created.push_back(Q.getNode());
5743 
5744   // FIXME: We should support doing a MUL in a wider type.
5745   auto GetMULHU = [&](SDValue X, SDValue Y) {
5746     // If the type isn't legal, use a wider mul of the the type calculated
5747     // earlier.
5748     if (!isTypeLegal(VT)) {
5749       X = DAG.getNode(ISD::ZERO_EXTEND, dl, MulVT, X);
5750       Y = DAG.getNode(ISD::ZERO_EXTEND, dl, MulVT, Y);
5751       Y = DAG.getNode(ISD::MUL, dl, MulVT, X, Y);
5752       Y = DAG.getNode(ISD::SRL, dl, MulVT, Y,
5753                       DAG.getShiftAmountConstant(EltBits, MulVT, dl));
5754       return DAG.getNode(ISD::TRUNCATE, dl, VT, Y);
5755     }
5756 
5757     if (isOperationLegalOrCustom(ISD::MULHU, VT, IsAfterLegalization))
5758       return DAG.getNode(ISD::MULHU, dl, VT, X, Y);
5759     if (isOperationLegalOrCustom(ISD::UMUL_LOHI, VT, IsAfterLegalization)) {
5760       SDValue LoHi =
5761           DAG.getNode(ISD::UMUL_LOHI, dl, DAG.getVTList(VT, VT), X, Y);
5762       return SDValue(LoHi.getNode(), 1);
5763     }
5764     return SDValue(); // No mulhu or equivalent
5765   };
5766 
5767   // Multiply the numerator (operand 0) by the magic value.
5768   Q = GetMULHU(Q, MagicFactor);
5769   if (!Q)
5770     return SDValue();
5771 
5772   Created.push_back(Q.getNode());
5773 
5774   if (UseNPQ) {
5775     SDValue NPQ = DAG.getNode(ISD::SUB, dl, VT, N0, Q);
5776     Created.push_back(NPQ.getNode());
5777 
5778     // For vectors we might have a mix of non-NPQ/NPQ paths, so use
5779     // MULHU to act as a SRL-by-1 for NPQ, else multiply by zero.
5780     if (VT.isVector())
5781       NPQ = GetMULHU(NPQ, NPQFactor);
5782     else
5783       NPQ = DAG.getNode(ISD::SRL, dl, VT, NPQ, DAG.getConstant(1, dl, ShVT));
5784 
5785     Created.push_back(NPQ.getNode());
5786 
5787     Q = DAG.getNode(ISD::ADD, dl, VT, NPQ, Q);
5788     Created.push_back(Q.getNode());
5789   }
5790 
5791   Q = DAG.getNode(ISD::SRL, dl, VT, Q, PostShift);
5792   Created.push_back(Q.getNode());
5793 
5794   EVT SetCCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
5795 
5796   SDValue One = DAG.getConstant(1, dl, VT);
5797   SDValue IsOne = DAG.getSetCC(dl, SetCCVT, N1, One, ISD::SETEQ);
5798   return DAG.getSelect(dl, VT, IsOne, N0, Q);
5799 }
5800 
5801 /// If all values in Values that *don't* match the predicate are same 'splat'
5802 /// value, then replace all values with that splat value.
5803 /// Else, if AlternativeReplacement was provided, then replace all values that
5804 /// do match predicate with AlternativeReplacement value.
5805 static void
5806 turnVectorIntoSplatVector(MutableArrayRef<SDValue> Values,
5807                           std::function<bool(SDValue)> Predicate,
5808                           SDValue AlternativeReplacement = SDValue()) {
5809   SDValue Replacement;
5810   // Is there a value for which the Predicate does *NOT* match? What is it?
5811   auto SplatValue = llvm::find_if_not(Values, Predicate);
5812   if (SplatValue != Values.end()) {
5813     // Does Values consist only of SplatValue's and values matching Predicate?
5814     if (llvm::all_of(Values, [Predicate, SplatValue](SDValue Value) {
5815           return Value == *SplatValue || Predicate(Value);
5816         })) // Then we shall replace values matching predicate with SplatValue.
5817       Replacement = *SplatValue;
5818   }
5819   if (!Replacement) {
5820     // Oops, we did not find the "baseline" splat value.
5821     if (!AlternativeReplacement)
5822       return; // Nothing to do.
5823     // Let's replace with provided value then.
5824     Replacement = AlternativeReplacement;
5825   }
5826   std::replace_if(Values.begin(), Values.end(), Predicate, Replacement);
5827 }
5828 
5829 /// Given an ISD::UREM used only by an ISD::SETEQ or ISD::SETNE
5830 /// where the divisor is constant and the comparison target is zero,
5831 /// return a DAG expression that will generate the same comparison result
5832 /// using only multiplications, additions and shifts/rotations.
5833 /// Ref: "Hacker's Delight" 10-17.
5834 SDValue TargetLowering::buildUREMEqFold(EVT SETCCVT, SDValue REMNode,
5835                                         SDValue CompTargetNode,
5836                                         ISD::CondCode Cond,
5837                                         DAGCombinerInfo &DCI,
5838                                         const SDLoc &DL) const {
5839   SmallVector<SDNode *, 5> Built;
5840   if (SDValue Folded = prepareUREMEqFold(SETCCVT, REMNode, CompTargetNode, Cond,
5841                                          DCI, DL, Built)) {
5842     for (SDNode *N : Built)
5843       DCI.AddToWorklist(N);
5844     return Folded;
5845   }
5846 
5847   return SDValue();
5848 }
5849 
5850 SDValue
5851 TargetLowering::prepareUREMEqFold(EVT SETCCVT, SDValue REMNode,
5852                                   SDValue CompTargetNode, ISD::CondCode Cond,
5853                                   DAGCombinerInfo &DCI, const SDLoc &DL,
5854                                   SmallVectorImpl<SDNode *> &Created) const {
5855   // fold (seteq/ne (urem N, D), 0) -> (setule/ugt (rotr (mul N, P), K), Q)
5856   // - D must be constant, with D = D0 * 2^K where D0 is odd
5857   // - P is the multiplicative inverse of D0 modulo 2^W
5858   // - Q = floor(((2^W) - 1) / D)
5859   // where W is the width of the common type of N and D.
5860   assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
5861          "Only applicable for (in)equality comparisons.");
5862 
5863   SelectionDAG &DAG = DCI.DAG;
5864 
5865   EVT VT = REMNode.getValueType();
5866   EVT SVT = VT.getScalarType();
5867   EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout(), !DCI.isBeforeLegalize());
5868   EVT ShSVT = ShVT.getScalarType();
5869 
5870   // If MUL is unavailable, we cannot proceed in any case.
5871   if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::MUL, VT))
5872     return SDValue();
5873 
5874   bool ComparingWithAllZeros = true;
5875   bool AllComparisonsWithNonZerosAreTautological = true;
5876   bool HadTautologicalLanes = false;
5877   bool AllLanesAreTautological = true;
5878   bool HadEvenDivisor = false;
5879   bool AllDivisorsArePowerOfTwo = true;
5880   bool HadTautologicalInvertedLanes = false;
5881   SmallVector<SDValue, 16> PAmts, KAmts, QAmts, IAmts;
5882 
5883   auto BuildUREMPattern = [&](ConstantSDNode *CDiv, ConstantSDNode *CCmp) {
5884     // Division by 0 is UB. Leave it to be constant-folded elsewhere.
5885     if (CDiv->isZero())
5886       return false;
5887 
5888     const APInt &D = CDiv->getAPIntValue();
5889     const APInt &Cmp = CCmp->getAPIntValue();
5890 
5891     ComparingWithAllZeros &= Cmp.isZero();
5892 
5893     // x u% C1` is *always* less than C1. So given `x u% C1 == C2`,
5894     // if C2 is not less than C1, the comparison is always false.
5895     // But we will only be able to produce the comparison that will give the
5896     // opposive tautological answer. So this lane would need to be fixed up.
5897     bool TautologicalInvertedLane = D.ule(Cmp);
5898     HadTautologicalInvertedLanes |= TautologicalInvertedLane;
5899 
5900     // If all lanes are tautological (either all divisors are ones, or divisor
5901     // is not greater than the constant we are comparing with),
5902     // we will prefer to avoid the fold.
5903     bool TautologicalLane = D.isOne() || TautologicalInvertedLane;
5904     HadTautologicalLanes |= TautologicalLane;
5905     AllLanesAreTautological &= TautologicalLane;
5906 
5907     // If we are comparing with non-zero, we need'll need  to subtract said
5908     // comparison value from the LHS. But there is no point in doing that if
5909     // every lane where we are comparing with non-zero is tautological..
5910     if (!Cmp.isZero())
5911       AllComparisonsWithNonZerosAreTautological &= TautologicalLane;
5912 
5913     // Decompose D into D0 * 2^K
5914     unsigned K = D.countTrailingZeros();
5915     assert((!D.isOne() || (K == 0)) && "For divisor '1' we won't rotate.");
5916     APInt D0 = D.lshr(K);
5917 
5918     // D is even if it has trailing zeros.
5919     HadEvenDivisor |= (K != 0);
5920     // D is a power-of-two if D0 is one.
5921     // If all divisors are power-of-two, we will prefer to avoid the fold.
5922     AllDivisorsArePowerOfTwo &= D0.isOne();
5923 
5924     // P = inv(D0, 2^W)
5925     // 2^W requires W + 1 bits, so we have to extend and then truncate.
5926     unsigned W = D.getBitWidth();
5927     APInt P = D0.zext(W + 1)
5928                   .multiplicativeInverse(APInt::getSignedMinValue(W + 1))
5929                   .trunc(W);
5930     assert(!P.isZero() && "No multiplicative inverse!"); // unreachable
5931     assert((D0 * P).isOne() && "Multiplicative inverse basic check failed.");
5932 
5933     // Q = floor((2^W - 1) u/ D)
5934     // R = ((2^W - 1) u% D)
5935     APInt Q, R;
5936     APInt::udivrem(APInt::getAllOnes(W), D, Q, R);
5937 
5938     // If we are comparing with zero, then that comparison constant is okay,
5939     // else it may need to be one less than that.
5940     if (Cmp.ugt(R))
5941       Q -= 1;
5942 
5943     assert(APInt::getAllOnes(ShSVT.getSizeInBits()).ugt(K) &&
5944            "We are expecting that K is always less than all-ones for ShSVT");
5945 
5946     // If the lane is tautological the result can be constant-folded.
5947     if (TautologicalLane) {
5948       // Set P and K amount to a bogus values so we can try to splat them.
5949       P = 0;
5950       K = -1;
5951       // And ensure that comparison constant is tautological,
5952       // it will always compare true/false.
5953       Q = -1;
5954     }
5955 
5956     PAmts.push_back(DAG.getConstant(P, DL, SVT));
5957     KAmts.push_back(
5958         DAG.getConstant(APInt(ShSVT.getSizeInBits(), K), DL, ShSVT));
5959     QAmts.push_back(DAG.getConstant(Q, DL, SVT));
5960     return true;
5961   };
5962 
5963   SDValue N = REMNode.getOperand(0);
5964   SDValue D = REMNode.getOperand(1);
5965 
5966   // Collect the values from each element.
5967   if (!ISD::matchBinaryPredicate(D, CompTargetNode, BuildUREMPattern))
5968     return SDValue();
5969 
5970   // If all lanes are tautological, the result can be constant-folded.
5971   if (AllLanesAreTautological)
5972     return SDValue();
5973 
5974   // If this is a urem by a powers-of-two, avoid the fold since it can be
5975   // best implemented as a bit test.
5976   if (AllDivisorsArePowerOfTwo)
5977     return SDValue();
5978 
5979   SDValue PVal, KVal, QVal;
5980   if (D.getOpcode() == ISD::BUILD_VECTOR) {
5981     if (HadTautologicalLanes) {
5982       // Try to turn PAmts into a splat, since we don't care about the values
5983       // that are currently '0'. If we can't, just keep '0'`s.
5984       turnVectorIntoSplatVector(PAmts, isNullConstant);
5985       // Try to turn KAmts into a splat, since we don't care about the values
5986       // that are currently '-1'. If we can't, change them to '0'`s.
5987       turnVectorIntoSplatVector(KAmts, isAllOnesConstant,
5988                                 DAG.getConstant(0, DL, ShSVT));
5989     }
5990 
5991     PVal = DAG.getBuildVector(VT, DL, PAmts);
5992     KVal = DAG.getBuildVector(ShVT, DL, KAmts);
5993     QVal = DAG.getBuildVector(VT, DL, QAmts);
5994   } else if (D.getOpcode() == ISD::SPLAT_VECTOR) {
5995     assert(PAmts.size() == 1 && KAmts.size() == 1 && QAmts.size() == 1 &&
5996            "Expected matchBinaryPredicate to return one element for "
5997            "SPLAT_VECTORs");
5998     PVal = DAG.getSplatVector(VT, DL, PAmts[0]);
5999     KVal = DAG.getSplatVector(ShVT, DL, KAmts[0]);
6000     QVal = DAG.getSplatVector(VT, DL, QAmts[0]);
6001   } else {
6002     PVal = PAmts[0];
6003     KVal = KAmts[0];
6004     QVal = QAmts[0];
6005   }
6006 
6007   if (!ComparingWithAllZeros && !AllComparisonsWithNonZerosAreTautological) {
6008     if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::SUB, VT))
6009       return SDValue(); // FIXME: Could/should use `ISD::ADD`?
6010     assert(CompTargetNode.getValueType() == N.getValueType() &&
6011            "Expecting that the types on LHS and RHS of comparisons match.");
6012     N = DAG.getNode(ISD::SUB, DL, VT, N, CompTargetNode);
6013   }
6014 
6015   // (mul N, P)
6016   SDValue Op0 = DAG.getNode(ISD::MUL, DL, VT, N, PVal);
6017   Created.push_back(Op0.getNode());
6018 
6019   // Rotate right only if any divisor was even. We avoid rotates for all-odd
6020   // divisors as a performance improvement, since rotating by 0 is a no-op.
6021   if (HadEvenDivisor) {
6022     // We need ROTR to do this.
6023     if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::ROTR, VT))
6024       return SDValue();
6025     // UREM: (rotr (mul N, P), K)
6026     Op0 = DAG.getNode(ISD::ROTR, DL, VT, Op0, KVal);
6027     Created.push_back(Op0.getNode());
6028   }
6029 
6030   // UREM: (setule/setugt (rotr (mul N, P), K), Q)
6031   SDValue NewCC =
6032       DAG.getSetCC(DL, SETCCVT, Op0, QVal,
6033                    ((Cond == ISD::SETEQ) ? ISD::SETULE : ISD::SETUGT));
6034   if (!HadTautologicalInvertedLanes)
6035     return NewCC;
6036 
6037   // If any lanes previously compared always-false, the NewCC will give
6038   // always-true result for them, so we need to fixup those lanes.
6039   // Or the other way around for inequality predicate.
6040   assert(VT.isVector() && "Can/should only get here for vectors.");
6041   Created.push_back(NewCC.getNode());
6042 
6043   // x u% C1` is *always* less than C1. So given `x u% C1 == C2`,
6044   // if C2 is not less than C1, the comparison is always false.
6045   // But we have produced the comparison that will give the
6046   // opposive tautological answer. So these lanes would need to be fixed up.
6047   SDValue TautologicalInvertedChannels =
6048       DAG.getSetCC(DL, SETCCVT, D, CompTargetNode, ISD::SETULE);
6049   Created.push_back(TautologicalInvertedChannels.getNode());
6050 
6051   // NOTE: we avoid letting illegal types through even if we're before legalize
6052   // ops – legalization has a hard time producing good code for this.
6053   if (isOperationLegalOrCustom(ISD::VSELECT, SETCCVT)) {
6054     // If we have a vector select, let's replace the comparison results in the
6055     // affected lanes with the correct tautological result.
6056     SDValue Replacement = DAG.getBoolConstant(Cond == ISD::SETEQ ? false : true,
6057                                               DL, SETCCVT, SETCCVT);
6058     return DAG.getNode(ISD::VSELECT, DL, SETCCVT, TautologicalInvertedChannels,
6059                        Replacement, NewCC);
6060   }
6061 
6062   // Else, we can just invert the comparison result in the appropriate lanes.
6063   //
6064   // NOTE: see the note above VSELECT above.
6065   if (isOperationLegalOrCustom(ISD::XOR, SETCCVT))
6066     return DAG.getNode(ISD::XOR, DL, SETCCVT, NewCC,
6067                        TautologicalInvertedChannels);
6068 
6069   return SDValue(); // Don't know how to lower.
6070 }
6071 
6072 /// Given an ISD::SREM used only by an ISD::SETEQ or ISD::SETNE
6073 /// where the divisor is constant and the comparison target is zero,
6074 /// return a DAG expression that will generate the same comparison result
6075 /// using only multiplications, additions and shifts/rotations.
6076 /// Ref: "Hacker's Delight" 10-17.
6077 SDValue TargetLowering::buildSREMEqFold(EVT SETCCVT, SDValue REMNode,
6078                                         SDValue CompTargetNode,
6079                                         ISD::CondCode Cond,
6080                                         DAGCombinerInfo &DCI,
6081                                         const SDLoc &DL) const {
6082   SmallVector<SDNode *, 7> Built;
6083   if (SDValue Folded = prepareSREMEqFold(SETCCVT, REMNode, CompTargetNode, Cond,
6084                                          DCI, DL, Built)) {
6085     assert(Built.size() <= 7 && "Max size prediction failed.");
6086     for (SDNode *N : Built)
6087       DCI.AddToWorklist(N);
6088     return Folded;
6089   }
6090 
6091   return SDValue();
6092 }
6093 
6094 SDValue
6095 TargetLowering::prepareSREMEqFold(EVT SETCCVT, SDValue REMNode,
6096                                   SDValue CompTargetNode, ISD::CondCode Cond,
6097                                   DAGCombinerInfo &DCI, const SDLoc &DL,
6098                                   SmallVectorImpl<SDNode *> &Created) const {
6099   // Fold:
6100   //   (seteq/ne (srem N, D), 0)
6101   // To:
6102   //   (setule/ugt (rotr (add (mul N, P), A), K), Q)
6103   //
6104   // - D must be constant, with D = D0 * 2^K where D0 is odd
6105   // - P is the multiplicative inverse of D0 modulo 2^W
6106   // - A = bitwiseand(floor((2^(W - 1) - 1) / D0), (-(2^k)))
6107   // - Q = floor((2 * A) / (2^K))
6108   // where W is the width of the common type of N and D.
6109   assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
6110          "Only applicable for (in)equality comparisons.");
6111 
6112   SelectionDAG &DAG = DCI.DAG;
6113 
6114   EVT VT = REMNode.getValueType();
6115   EVT SVT = VT.getScalarType();
6116   EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout(), !DCI.isBeforeLegalize());
6117   EVT ShSVT = ShVT.getScalarType();
6118 
6119   // If we are after ops legalization, and MUL is unavailable, we can not
6120   // proceed.
6121   if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::MUL, VT))
6122     return SDValue();
6123 
6124   // TODO: Could support comparing with non-zero too.
6125   ConstantSDNode *CompTarget = isConstOrConstSplat(CompTargetNode);
6126   if (!CompTarget || !CompTarget->isZero())
6127     return SDValue();
6128 
6129   bool HadIntMinDivisor = false;
6130   bool HadOneDivisor = false;
6131   bool AllDivisorsAreOnes = true;
6132   bool HadEvenDivisor = false;
6133   bool NeedToApplyOffset = false;
6134   bool AllDivisorsArePowerOfTwo = true;
6135   SmallVector<SDValue, 16> PAmts, AAmts, KAmts, QAmts;
6136 
6137   auto BuildSREMPattern = [&](ConstantSDNode *C) {
6138     // Division by 0 is UB. Leave it to be constant-folded elsewhere.
6139     if (C->isZero())
6140       return false;
6141 
6142     // FIXME: we don't fold `rem %X, -C` to `rem %X, C` in DAGCombine.
6143 
6144     // WARNING: this fold is only valid for positive divisors!
6145     APInt D = C->getAPIntValue();
6146     if (D.isNegative())
6147       D.negate(); //  `rem %X, -C` is equivalent to `rem %X, C`
6148 
6149     HadIntMinDivisor |= D.isMinSignedValue();
6150 
6151     // If all divisors are ones, we will prefer to avoid the fold.
6152     HadOneDivisor |= D.isOne();
6153     AllDivisorsAreOnes &= D.isOne();
6154 
6155     // Decompose D into D0 * 2^K
6156     unsigned K = D.countTrailingZeros();
6157     assert((!D.isOne() || (K == 0)) && "For divisor '1' we won't rotate.");
6158     APInt D0 = D.lshr(K);
6159 
6160     if (!D.isMinSignedValue()) {
6161       // D is even if it has trailing zeros; unless it's INT_MIN, in which case
6162       // we don't care about this lane in this fold, we'll special-handle it.
6163       HadEvenDivisor |= (K != 0);
6164     }
6165 
6166     // D is a power-of-two if D0 is one. This includes INT_MIN.
6167     // If all divisors are power-of-two, we will prefer to avoid the fold.
6168     AllDivisorsArePowerOfTwo &= D0.isOne();
6169 
6170     // P = inv(D0, 2^W)
6171     // 2^W requires W + 1 bits, so we have to extend and then truncate.
6172     unsigned W = D.getBitWidth();
6173     APInt P = D0.zext(W + 1)
6174                   .multiplicativeInverse(APInt::getSignedMinValue(W + 1))
6175                   .trunc(W);
6176     assert(!P.isZero() && "No multiplicative inverse!"); // unreachable
6177     assert((D0 * P).isOne() && "Multiplicative inverse basic check failed.");
6178 
6179     // A = floor((2^(W - 1) - 1) / D0) & -2^K
6180     APInt A = APInt::getSignedMaxValue(W).udiv(D0);
6181     A.clearLowBits(K);
6182 
6183     if (!D.isMinSignedValue()) {
6184       // If divisor INT_MIN, then we don't care about this lane in this fold,
6185       // we'll special-handle it.
6186       NeedToApplyOffset |= A != 0;
6187     }
6188 
6189     // Q = floor((2 * A) / (2^K))
6190     APInt Q = (2 * A).udiv(APInt::getOneBitSet(W, K));
6191 
6192     assert(APInt::getAllOnes(SVT.getSizeInBits()).ugt(A) &&
6193            "We are expecting that A is always less than all-ones for SVT");
6194     assert(APInt::getAllOnes(ShSVT.getSizeInBits()).ugt(K) &&
6195            "We are expecting that K is always less than all-ones for ShSVT");
6196 
6197     // If the divisor is 1 the result can be constant-folded. Likewise, we
6198     // don't care about INT_MIN lanes, those can be set to undef if appropriate.
6199     if (D.isOne()) {
6200       // Set P, A and K to a bogus values so we can try to splat them.
6201       P = 0;
6202       A = -1;
6203       K = -1;
6204 
6205       // x ?% 1 == 0  <-->  true  <-->  x u<= -1
6206       Q = -1;
6207     }
6208 
6209     PAmts.push_back(DAG.getConstant(P, DL, SVT));
6210     AAmts.push_back(DAG.getConstant(A, DL, SVT));
6211     KAmts.push_back(
6212         DAG.getConstant(APInt(ShSVT.getSizeInBits(), K), DL, ShSVT));
6213     QAmts.push_back(DAG.getConstant(Q, DL, SVT));
6214     return true;
6215   };
6216 
6217   SDValue N = REMNode.getOperand(0);
6218   SDValue D = REMNode.getOperand(1);
6219 
6220   // Collect the values from each element.
6221   if (!ISD::matchUnaryPredicate(D, BuildSREMPattern))
6222     return SDValue();
6223 
6224   // If this is a srem by a one, avoid the fold since it can be constant-folded.
6225   if (AllDivisorsAreOnes)
6226     return SDValue();
6227 
6228   // If this is a srem by a powers-of-two (including INT_MIN), avoid the fold
6229   // since it can be best implemented as a bit test.
6230   if (AllDivisorsArePowerOfTwo)
6231     return SDValue();
6232 
6233   SDValue PVal, AVal, KVal, QVal;
6234   if (D.getOpcode() == ISD::BUILD_VECTOR) {
6235     if (HadOneDivisor) {
6236       // Try to turn PAmts into a splat, since we don't care about the values
6237       // that are currently '0'. If we can't, just keep '0'`s.
6238       turnVectorIntoSplatVector(PAmts, isNullConstant);
6239       // Try to turn AAmts into a splat, since we don't care about the
6240       // values that are currently '-1'. If we can't, change them to '0'`s.
6241       turnVectorIntoSplatVector(AAmts, isAllOnesConstant,
6242                                 DAG.getConstant(0, DL, SVT));
6243       // Try to turn KAmts into a splat, since we don't care about the values
6244       // that are currently '-1'. If we can't, change them to '0'`s.
6245       turnVectorIntoSplatVector(KAmts, isAllOnesConstant,
6246                                 DAG.getConstant(0, DL, ShSVT));
6247     }
6248 
6249     PVal = DAG.getBuildVector(VT, DL, PAmts);
6250     AVal = DAG.getBuildVector(VT, DL, AAmts);
6251     KVal = DAG.getBuildVector(ShVT, DL, KAmts);
6252     QVal = DAG.getBuildVector(VT, DL, QAmts);
6253   } else if (D.getOpcode() == ISD::SPLAT_VECTOR) {
6254     assert(PAmts.size() == 1 && AAmts.size() == 1 && KAmts.size() == 1 &&
6255            QAmts.size() == 1 &&
6256            "Expected matchUnaryPredicate to return one element for scalable "
6257            "vectors");
6258     PVal = DAG.getSplatVector(VT, DL, PAmts[0]);
6259     AVal = DAG.getSplatVector(VT, DL, AAmts[0]);
6260     KVal = DAG.getSplatVector(ShVT, DL, KAmts[0]);
6261     QVal = DAG.getSplatVector(VT, DL, QAmts[0]);
6262   } else {
6263     assert(isa<ConstantSDNode>(D) && "Expected a constant");
6264     PVal = PAmts[0];
6265     AVal = AAmts[0];
6266     KVal = KAmts[0];
6267     QVal = QAmts[0];
6268   }
6269 
6270   // (mul N, P)
6271   SDValue Op0 = DAG.getNode(ISD::MUL, DL, VT, N, PVal);
6272   Created.push_back(Op0.getNode());
6273 
6274   if (NeedToApplyOffset) {
6275     // We need ADD to do this.
6276     if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::ADD, VT))
6277       return SDValue();
6278 
6279     // (add (mul N, P), A)
6280     Op0 = DAG.getNode(ISD::ADD, DL, VT, Op0, AVal);
6281     Created.push_back(Op0.getNode());
6282   }
6283 
6284   // Rotate right only if any divisor was even. We avoid rotates for all-odd
6285   // divisors as a performance improvement, since rotating by 0 is a no-op.
6286   if (HadEvenDivisor) {
6287     // We need ROTR to do this.
6288     if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::ROTR, VT))
6289       return SDValue();
6290     // SREM: (rotr (add (mul N, P), A), K)
6291     Op0 = DAG.getNode(ISD::ROTR, DL, VT, Op0, KVal);
6292     Created.push_back(Op0.getNode());
6293   }
6294 
6295   // SREM: (setule/setugt (rotr (add (mul N, P), A), K), Q)
6296   SDValue Fold =
6297       DAG.getSetCC(DL, SETCCVT, Op0, QVal,
6298                    ((Cond == ISD::SETEQ) ? ISD::SETULE : ISD::SETUGT));
6299 
6300   // If we didn't have lanes with INT_MIN divisor, then we're done.
6301   if (!HadIntMinDivisor)
6302     return Fold;
6303 
6304   // That fold is only valid for positive divisors. Which effectively means,
6305   // it is invalid for INT_MIN divisors. So if we have such a lane,
6306   // we must fix-up results for said lanes.
6307   assert(VT.isVector() && "Can/should only get here for vectors.");
6308 
6309   // NOTE: we avoid letting illegal types through even if we're before legalize
6310   // ops – legalization has a hard time producing good code for the code that
6311   // follows.
6312   if (!isOperationLegalOrCustom(ISD::SETEQ, VT) ||
6313       !isOperationLegalOrCustom(ISD::AND, VT) ||
6314       !isOperationLegalOrCustom(Cond, VT) ||
6315       !isOperationLegalOrCustom(ISD::VSELECT, SETCCVT))
6316     return SDValue();
6317 
6318   Created.push_back(Fold.getNode());
6319 
6320   SDValue IntMin = DAG.getConstant(
6321       APInt::getSignedMinValue(SVT.getScalarSizeInBits()), DL, VT);
6322   SDValue IntMax = DAG.getConstant(
6323       APInt::getSignedMaxValue(SVT.getScalarSizeInBits()), DL, VT);
6324   SDValue Zero =
6325       DAG.getConstant(APInt::getZero(SVT.getScalarSizeInBits()), DL, VT);
6326 
6327   // Which lanes had INT_MIN divisors? Divisor is constant, so const-folded.
6328   SDValue DivisorIsIntMin = DAG.getSetCC(DL, SETCCVT, D, IntMin, ISD::SETEQ);
6329   Created.push_back(DivisorIsIntMin.getNode());
6330 
6331   // (N s% INT_MIN) ==/!= 0  <-->  (N & INT_MAX) ==/!= 0
6332   SDValue Masked = DAG.getNode(ISD::AND, DL, VT, N, IntMax);
6333   Created.push_back(Masked.getNode());
6334   SDValue MaskedIsZero = DAG.getSetCC(DL, SETCCVT, Masked, Zero, Cond);
6335   Created.push_back(MaskedIsZero.getNode());
6336 
6337   // To produce final result we need to blend 2 vectors: 'SetCC' and
6338   // 'MaskedIsZero'. If the divisor for channel was *NOT* INT_MIN, we pick
6339   // from 'Fold', else pick from 'MaskedIsZero'. Since 'DivisorIsIntMin' is
6340   // constant-folded, select can get lowered to a shuffle with constant mask.
6341   SDValue Blended = DAG.getNode(ISD::VSELECT, DL, SETCCVT, DivisorIsIntMin,
6342                                 MaskedIsZero, Fold);
6343 
6344   return Blended;
6345 }
6346 
6347 bool TargetLowering::
6348 verifyReturnAddressArgumentIsConstant(SDValue Op, SelectionDAG &DAG) const {
6349   if (!isa<ConstantSDNode>(Op.getOperand(0))) {
6350     DAG.getContext()->emitError("argument to '__builtin_return_address' must "
6351                                 "be a constant integer");
6352     return true;
6353   }
6354 
6355   return false;
6356 }
6357 
6358 SDValue TargetLowering::getSqrtInputTest(SDValue Op, SelectionDAG &DAG,
6359                                          const DenormalMode &Mode) const {
6360   SDLoc DL(Op);
6361   EVT VT = Op.getValueType();
6362   EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
6363   SDValue FPZero = DAG.getConstantFP(0.0, DL, VT);
6364   // Testing it with denormal inputs to avoid wrong estimate.
6365   if (Mode.Input == DenormalMode::IEEE) {
6366     // This is specifically a check for the handling of denormal inputs,
6367     // not the result.
6368 
6369     // Test = fabs(X) < SmallestNormal
6370     const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT);
6371     APFloat SmallestNorm = APFloat::getSmallestNormalized(FltSem);
6372     SDValue NormC = DAG.getConstantFP(SmallestNorm, DL, VT);
6373     SDValue Fabs = DAG.getNode(ISD::FABS, DL, VT, Op);
6374     return DAG.getSetCC(DL, CCVT, Fabs, NormC, ISD::SETLT);
6375   }
6376   // Test = X == 0.0
6377   return DAG.getSetCC(DL, CCVT, Op, FPZero, ISD::SETEQ);
6378 }
6379 
6380 SDValue TargetLowering::getNegatedExpression(SDValue Op, SelectionDAG &DAG,
6381                                              bool LegalOps, bool OptForSize,
6382                                              NegatibleCost &Cost,
6383                                              unsigned Depth) const {
6384   // fneg is removable even if it has multiple uses.
6385   if (Op.getOpcode() == ISD::FNEG) {
6386     Cost = NegatibleCost::Cheaper;
6387     return Op.getOperand(0);
6388   }
6389 
6390   // Don't recurse exponentially.
6391   if (Depth > SelectionDAG::MaxRecursionDepth)
6392     return SDValue();
6393 
6394   // Pre-increment recursion depth for use in recursive calls.
6395   ++Depth;
6396   const SDNodeFlags Flags = Op->getFlags();
6397   const TargetOptions &Options = DAG.getTarget().Options;
6398   EVT VT = Op.getValueType();
6399   unsigned Opcode = Op.getOpcode();
6400 
6401   // Don't allow anything with multiple uses unless we know it is free.
6402   if (!Op.hasOneUse() && Opcode != ISD::ConstantFP) {
6403     bool IsFreeExtend = Opcode == ISD::FP_EXTEND &&
6404                         isFPExtFree(VT, Op.getOperand(0).getValueType());
6405     if (!IsFreeExtend)
6406       return SDValue();
6407   }
6408 
6409   auto RemoveDeadNode = [&](SDValue N) {
6410     if (N && N.getNode()->use_empty())
6411       DAG.RemoveDeadNode(N.getNode());
6412   };
6413 
6414   SDLoc DL(Op);
6415 
6416   // Because getNegatedExpression can delete nodes we need a handle to keep
6417   // temporary nodes alive in case the recursion manages to create an identical
6418   // node.
6419   std::list<HandleSDNode> Handles;
6420 
6421   switch (Opcode) {
6422   case ISD::ConstantFP: {
6423     // Don't invert constant FP values after legalization unless the target says
6424     // the negated constant is legal.
6425     bool IsOpLegal =
6426         isOperationLegal(ISD::ConstantFP, VT) ||
6427         isFPImmLegal(neg(cast<ConstantFPSDNode>(Op)->getValueAPF()), VT,
6428                      OptForSize);
6429 
6430     if (LegalOps && !IsOpLegal)
6431       break;
6432 
6433     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
6434     V.changeSign();
6435     SDValue CFP = DAG.getConstantFP(V, DL, VT);
6436 
6437     // If we already have the use of the negated floating constant, it is free
6438     // to negate it even it has multiple uses.
6439     if (!Op.hasOneUse() && CFP.use_empty())
6440       break;
6441     Cost = NegatibleCost::Neutral;
6442     return CFP;
6443   }
6444   case ISD::BUILD_VECTOR: {
6445     // Only permit BUILD_VECTOR of constants.
6446     if (llvm::any_of(Op->op_values(), [&](SDValue N) {
6447           return !N.isUndef() && !isa<ConstantFPSDNode>(N);
6448         }))
6449       break;
6450 
6451     bool IsOpLegal =
6452         (isOperationLegal(ISD::ConstantFP, VT) &&
6453          isOperationLegal(ISD::BUILD_VECTOR, VT)) ||
6454         llvm::all_of(Op->op_values(), [&](SDValue N) {
6455           return N.isUndef() ||
6456                  isFPImmLegal(neg(cast<ConstantFPSDNode>(N)->getValueAPF()), VT,
6457                               OptForSize);
6458         });
6459 
6460     if (LegalOps && !IsOpLegal)
6461       break;
6462 
6463     SmallVector<SDValue, 4> Ops;
6464     for (SDValue C : Op->op_values()) {
6465       if (C.isUndef()) {
6466         Ops.push_back(C);
6467         continue;
6468       }
6469       APFloat V = cast<ConstantFPSDNode>(C)->getValueAPF();
6470       V.changeSign();
6471       Ops.push_back(DAG.getConstantFP(V, DL, C.getValueType()));
6472     }
6473     Cost = NegatibleCost::Neutral;
6474     return DAG.getBuildVector(VT, DL, Ops);
6475   }
6476   case ISD::FADD: {
6477     if (!Options.NoSignedZerosFPMath && !Flags.hasNoSignedZeros())
6478       break;
6479 
6480     // After operation legalization, it might not be legal to create new FSUBs.
6481     if (LegalOps && !isOperationLegalOrCustom(ISD::FSUB, VT))
6482       break;
6483     SDValue X = Op.getOperand(0), Y = Op.getOperand(1);
6484 
6485     // fold (fneg (fadd X, Y)) -> (fsub (fneg X), Y)
6486     NegatibleCost CostX = NegatibleCost::Expensive;
6487     SDValue NegX =
6488         getNegatedExpression(X, DAG, LegalOps, OptForSize, CostX, Depth);
6489     // Prevent this node from being deleted by the next call.
6490     if (NegX)
6491       Handles.emplace_back(NegX);
6492 
6493     // fold (fneg (fadd X, Y)) -> (fsub (fneg Y), X)
6494     NegatibleCost CostY = NegatibleCost::Expensive;
6495     SDValue NegY =
6496         getNegatedExpression(Y, DAG, LegalOps, OptForSize, CostY, Depth);
6497 
6498     // We're done with the handles.
6499     Handles.clear();
6500 
6501     // Negate the X if its cost is less or equal than Y.
6502     if (NegX && (CostX <= CostY)) {
6503       Cost = CostX;
6504       SDValue N = DAG.getNode(ISD::FSUB, DL, VT, NegX, Y, Flags);
6505       if (NegY != N)
6506         RemoveDeadNode(NegY);
6507       return N;
6508     }
6509 
6510     // Negate the Y if it is not expensive.
6511     if (NegY) {
6512       Cost = CostY;
6513       SDValue N = DAG.getNode(ISD::FSUB, DL, VT, NegY, X, Flags);
6514       if (NegX != N)
6515         RemoveDeadNode(NegX);
6516       return N;
6517     }
6518     break;
6519   }
6520   case ISD::FSUB: {
6521     // We can't turn -(A-B) into B-A when we honor signed zeros.
6522     if (!Options.NoSignedZerosFPMath && !Flags.hasNoSignedZeros())
6523       break;
6524 
6525     SDValue X = Op.getOperand(0), Y = Op.getOperand(1);
6526     // fold (fneg (fsub 0, Y)) -> Y
6527     if (ConstantFPSDNode *C = isConstOrConstSplatFP(X, /*AllowUndefs*/ true))
6528       if (C->isZero()) {
6529         Cost = NegatibleCost::Cheaper;
6530         return Y;
6531       }
6532 
6533     // fold (fneg (fsub X, Y)) -> (fsub Y, X)
6534     Cost = NegatibleCost::Neutral;
6535     return DAG.getNode(ISD::FSUB, DL, VT, Y, X, Flags);
6536   }
6537   case ISD::FMUL:
6538   case ISD::FDIV: {
6539     SDValue X = Op.getOperand(0), Y = Op.getOperand(1);
6540 
6541     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
6542     NegatibleCost CostX = NegatibleCost::Expensive;
6543     SDValue NegX =
6544         getNegatedExpression(X, DAG, LegalOps, OptForSize, CostX, Depth);
6545     // Prevent this node from being deleted by the next call.
6546     if (NegX)
6547       Handles.emplace_back(NegX);
6548 
6549     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
6550     NegatibleCost CostY = NegatibleCost::Expensive;
6551     SDValue NegY =
6552         getNegatedExpression(Y, DAG, LegalOps, OptForSize, CostY, Depth);
6553 
6554     // We're done with the handles.
6555     Handles.clear();
6556 
6557     // Negate the X if its cost is less or equal than Y.
6558     if (NegX && (CostX <= CostY)) {
6559       Cost = CostX;
6560       SDValue N = DAG.getNode(Opcode, DL, VT, NegX, Y, Flags);
6561       if (NegY != N)
6562         RemoveDeadNode(NegY);
6563       return N;
6564     }
6565 
6566     // Ignore X * 2.0 because that is expected to be canonicalized to X + X.
6567     if (auto *C = isConstOrConstSplatFP(Op.getOperand(1)))
6568       if (C->isExactlyValue(2.0) && Op.getOpcode() == ISD::FMUL)
6569         break;
6570 
6571     // Negate the Y if it is not expensive.
6572     if (NegY) {
6573       Cost = CostY;
6574       SDValue N = DAG.getNode(Opcode, DL, VT, X, NegY, Flags);
6575       if (NegX != N)
6576         RemoveDeadNode(NegX);
6577       return N;
6578     }
6579     break;
6580   }
6581   case ISD::FMA:
6582   case ISD::FMAD: {
6583     if (!Options.NoSignedZerosFPMath && !Flags.hasNoSignedZeros())
6584       break;
6585 
6586     SDValue X = Op.getOperand(0), Y = Op.getOperand(1), Z = Op.getOperand(2);
6587     NegatibleCost CostZ = NegatibleCost::Expensive;
6588     SDValue NegZ =
6589         getNegatedExpression(Z, DAG, LegalOps, OptForSize, CostZ, Depth);
6590     // Give up if fail to negate the Z.
6591     if (!NegZ)
6592       break;
6593 
6594     // Prevent this node from being deleted by the next two calls.
6595     Handles.emplace_back(NegZ);
6596 
6597     // fold (fneg (fma X, Y, Z)) -> (fma (fneg X), Y, (fneg Z))
6598     NegatibleCost CostX = NegatibleCost::Expensive;
6599     SDValue NegX =
6600         getNegatedExpression(X, DAG, LegalOps, OptForSize, CostX, Depth);
6601     // Prevent this node from being deleted by the next call.
6602     if (NegX)
6603       Handles.emplace_back(NegX);
6604 
6605     // fold (fneg (fma X, Y, Z)) -> (fma X, (fneg Y), (fneg Z))
6606     NegatibleCost CostY = NegatibleCost::Expensive;
6607     SDValue NegY =
6608         getNegatedExpression(Y, DAG, LegalOps, OptForSize, CostY, Depth);
6609 
6610     // We're done with the handles.
6611     Handles.clear();
6612 
6613     // Negate the X if its cost is less or equal than Y.
6614     if (NegX && (CostX <= CostY)) {
6615       Cost = std::min(CostX, CostZ);
6616       SDValue N = DAG.getNode(Opcode, DL, VT, NegX, Y, NegZ, Flags);
6617       if (NegY != N)
6618         RemoveDeadNode(NegY);
6619       return N;
6620     }
6621 
6622     // Negate the Y if it is not expensive.
6623     if (NegY) {
6624       Cost = std::min(CostY, CostZ);
6625       SDValue N = DAG.getNode(Opcode, DL, VT, X, NegY, NegZ, Flags);
6626       if (NegX != N)
6627         RemoveDeadNode(NegX);
6628       return N;
6629     }
6630     break;
6631   }
6632 
6633   case ISD::FP_EXTEND:
6634   case ISD::FSIN:
6635     if (SDValue NegV = getNegatedExpression(Op.getOperand(0), DAG, LegalOps,
6636                                             OptForSize, Cost, Depth))
6637       return DAG.getNode(Opcode, DL, VT, NegV);
6638     break;
6639   case ISD::FP_ROUND:
6640     if (SDValue NegV = getNegatedExpression(Op.getOperand(0), DAG, LegalOps,
6641                                             OptForSize, Cost, Depth))
6642       return DAG.getNode(ISD::FP_ROUND, DL, VT, NegV, Op.getOperand(1));
6643     break;
6644   }
6645 
6646   return SDValue();
6647 }
6648 
6649 //===----------------------------------------------------------------------===//
6650 // Legalization Utilities
6651 //===----------------------------------------------------------------------===//
6652 
6653 bool TargetLowering::expandMUL_LOHI(unsigned Opcode, EVT VT, const SDLoc &dl,
6654                                     SDValue LHS, SDValue RHS,
6655                                     SmallVectorImpl<SDValue> &Result,
6656                                     EVT HiLoVT, SelectionDAG &DAG,
6657                                     MulExpansionKind Kind, SDValue LL,
6658                                     SDValue LH, SDValue RL, SDValue RH) const {
6659   assert(Opcode == ISD::MUL || Opcode == ISD::UMUL_LOHI ||
6660          Opcode == ISD::SMUL_LOHI);
6661 
6662   bool HasMULHS = (Kind == MulExpansionKind::Always) ||
6663                   isOperationLegalOrCustom(ISD::MULHS, HiLoVT);
6664   bool HasMULHU = (Kind == MulExpansionKind::Always) ||
6665                   isOperationLegalOrCustom(ISD::MULHU, HiLoVT);
6666   bool HasSMUL_LOHI = (Kind == MulExpansionKind::Always) ||
6667                       isOperationLegalOrCustom(ISD::SMUL_LOHI, HiLoVT);
6668   bool HasUMUL_LOHI = (Kind == MulExpansionKind::Always) ||
6669                       isOperationLegalOrCustom(ISD::UMUL_LOHI, HiLoVT);
6670 
6671   if (!HasMULHU && !HasMULHS && !HasUMUL_LOHI && !HasSMUL_LOHI)
6672     return false;
6673 
6674   unsigned OuterBitSize = VT.getScalarSizeInBits();
6675   unsigned InnerBitSize = HiLoVT.getScalarSizeInBits();
6676 
6677   // LL, LH, RL, and RH must be either all NULL or all set to a value.
6678   assert((LL.getNode() && LH.getNode() && RL.getNode() && RH.getNode()) ||
6679          (!LL.getNode() && !LH.getNode() && !RL.getNode() && !RH.getNode()));
6680 
6681   SDVTList VTs = DAG.getVTList(HiLoVT, HiLoVT);
6682   auto MakeMUL_LOHI = [&](SDValue L, SDValue R, SDValue &Lo, SDValue &Hi,
6683                           bool Signed) -> bool {
6684     if ((Signed && HasSMUL_LOHI) || (!Signed && HasUMUL_LOHI)) {
6685       Lo = DAG.getNode(Signed ? ISD::SMUL_LOHI : ISD::UMUL_LOHI, dl, VTs, L, R);
6686       Hi = SDValue(Lo.getNode(), 1);
6687       return true;
6688     }
6689     if ((Signed && HasMULHS) || (!Signed && HasMULHU)) {
6690       Lo = DAG.getNode(ISD::MUL, dl, HiLoVT, L, R);
6691       Hi = DAG.getNode(Signed ? ISD::MULHS : ISD::MULHU, dl, HiLoVT, L, R);
6692       return true;
6693     }
6694     return false;
6695   };
6696 
6697   SDValue Lo, Hi;
6698 
6699   if (!LL.getNode() && !RL.getNode() &&
6700       isOperationLegalOrCustom(ISD::TRUNCATE, HiLoVT)) {
6701     LL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, LHS);
6702     RL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, RHS);
6703   }
6704 
6705   if (!LL.getNode())
6706     return false;
6707 
6708   APInt HighMask = APInt::getHighBitsSet(OuterBitSize, InnerBitSize);
6709   if (DAG.MaskedValueIsZero(LHS, HighMask) &&
6710       DAG.MaskedValueIsZero(RHS, HighMask)) {
6711     // The inputs are both zero-extended.
6712     if (MakeMUL_LOHI(LL, RL, Lo, Hi, false)) {
6713       Result.push_back(Lo);
6714       Result.push_back(Hi);
6715       if (Opcode != ISD::MUL) {
6716         SDValue Zero = DAG.getConstant(0, dl, HiLoVT);
6717         Result.push_back(Zero);
6718         Result.push_back(Zero);
6719       }
6720       return true;
6721     }
6722   }
6723 
6724   if (!VT.isVector() && Opcode == ISD::MUL &&
6725       DAG.ComputeNumSignBits(LHS) > InnerBitSize &&
6726       DAG.ComputeNumSignBits(RHS) > InnerBitSize) {
6727     // The input values are both sign-extended.
6728     // TODO non-MUL case?
6729     if (MakeMUL_LOHI(LL, RL, Lo, Hi, true)) {
6730       Result.push_back(Lo);
6731       Result.push_back(Hi);
6732       return true;
6733     }
6734   }
6735 
6736   unsigned ShiftAmount = OuterBitSize - InnerBitSize;
6737   EVT ShiftAmountTy = getShiftAmountTy(VT, DAG.getDataLayout());
6738   SDValue Shift = DAG.getConstant(ShiftAmount, dl, ShiftAmountTy);
6739 
6740   if (!LH.getNode() && !RH.getNode() &&
6741       isOperationLegalOrCustom(ISD::SRL, VT) &&
6742       isOperationLegalOrCustom(ISD::TRUNCATE, HiLoVT)) {
6743     LH = DAG.getNode(ISD::SRL, dl, VT, LHS, Shift);
6744     LH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, LH);
6745     RH = DAG.getNode(ISD::SRL, dl, VT, RHS, Shift);
6746     RH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, RH);
6747   }
6748 
6749   if (!LH.getNode())
6750     return false;
6751 
6752   if (!MakeMUL_LOHI(LL, RL, Lo, Hi, false))
6753     return false;
6754 
6755   Result.push_back(Lo);
6756 
6757   if (Opcode == ISD::MUL) {
6758     RH = DAG.getNode(ISD::MUL, dl, HiLoVT, LL, RH);
6759     LH = DAG.getNode(ISD::MUL, dl, HiLoVT, LH, RL);
6760     Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, RH);
6761     Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, LH);
6762     Result.push_back(Hi);
6763     return true;
6764   }
6765 
6766   // Compute the full width result.
6767   auto Merge = [&](SDValue Lo, SDValue Hi) -> SDValue {
6768     Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Lo);
6769     Hi = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Hi);
6770     Hi = DAG.getNode(ISD::SHL, dl, VT, Hi, Shift);
6771     return DAG.getNode(ISD::OR, dl, VT, Lo, Hi);
6772   };
6773 
6774   SDValue Next = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Hi);
6775   if (!MakeMUL_LOHI(LL, RH, Lo, Hi, false))
6776     return false;
6777 
6778   // This is effectively the add part of a multiply-add of half-sized operands,
6779   // so it cannot overflow.
6780   Next = DAG.getNode(ISD::ADD, dl, VT, Next, Merge(Lo, Hi));
6781 
6782   if (!MakeMUL_LOHI(LH, RL, Lo, Hi, false))
6783     return false;
6784 
6785   SDValue Zero = DAG.getConstant(0, dl, HiLoVT);
6786   EVT BoolType = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
6787 
6788   bool UseGlue = (isOperationLegalOrCustom(ISD::ADDC, VT) &&
6789                   isOperationLegalOrCustom(ISD::ADDE, VT));
6790   if (UseGlue)
6791     Next = DAG.getNode(ISD::ADDC, dl, DAG.getVTList(VT, MVT::Glue), Next,
6792                        Merge(Lo, Hi));
6793   else
6794     Next = DAG.getNode(ISD::ADDCARRY, dl, DAG.getVTList(VT, BoolType), Next,
6795                        Merge(Lo, Hi), DAG.getConstant(0, dl, BoolType));
6796 
6797   SDValue Carry = Next.getValue(1);
6798   Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next));
6799   Next = DAG.getNode(ISD::SRL, dl, VT, Next, Shift);
6800 
6801   if (!MakeMUL_LOHI(LH, RH, Lo, Hi, Opcode == ISD::SMUL_LOHI))
6802     return false;
6803 
6804   if (UseGlue)
6805     Hi = DAG.getNode(ISD::ADDE, dl, DAG.getVTList(HiLoVT, MVT::Glue), Hi, Zero,
6806                      Carry);
6807   else
6808     Hi = DAG.getNode(ISD::ADDCARRY, dl, DAG.getVTList(HiLoVT, BoolType), Hi,
6809                      Zero, Carry);
6810 
6811   Next = DAG.getNode(ISD::ADD, dl, VT, Next, Merge(Lo, Hi));
6812 
6813   if (Opcode == ISD::SMUL_LOHI) {
6814     SDValue NextSub = DAG.getNode(ISD::SUB, dl, VT, Next,
6815                                   DAG.getNode(ISD::ZERO_EXTEND, dl, VT, RL));
6816     Next = DAG.getSelectCC(dl, LH, Zero, NextSub, Next, ISD::SETLT);
6817 
6818     NextSub = DAG.getNode(ISD::SUB, dl, VT, Next,
6819                           DAG.getNode(ISD::ZERO_EXTEND, dl, VT, LL));
6820     Next = DAG.getSelectCC(dl, RH, Zero, NextSub, Next, ISD::SETLT);
6821   }
6822 
6823   Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next));
6824   Next = DAG.getNode(ISD::SRL, dl, VT, Next, Shift);
6825   Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next));
6826   return true;
6827 }
6828 
6829 bool TargetLowering::expandMUL(SDNode *N, SDValue &Lo, SDValue &Hi, EVT HiLoVT,
6830                                SelectionDAG &DAG, MulExpansionKind Kind,
6831                                SDValue LL, SDValue LH, SDValue RL,
6832                                SDValue RH) const {
6833   SmallVector<SDValue, 2> Result;
6834   bool Ok = expandMUL_LOHI(N->getOpcode(), N->getValueType(0), SDLoc(N),
6835                            N->getOperand(0), N->getOperand(1), Result, HiLoVT,
6836                            DAG, Kind, LL, LH, RL, RH);
6837   if (Ok) {
6838     assert(Result.size() == 2);
6839     Lo = Result[0];
6840     Hi = Result[1];
6841   }
6842   return Ok;
6843 }
6844 
6845 // Check that (every element of) Z is undef or not an exact multiple of BW.
6846 static bool isNonZeroModBitWidthOrUndef(SDValue Z, unsigned BW) {
6847   return ISD::matchUnaryPredicate(
6848       Z,
6849       [=](ConstantSDNode *C) { return !C || C->getAPIntValue().urem(BW) != 0; },
6850       true);
6851 }
6852 
6853 SDValue TargetLowering::expandFunnelShift(SDNode *Node,
6854                                           SelectionDAG &DAG) const {
6855   EVT VT = Node->getValueType(0);
6856 
6857   if (VT.isVector() && (!isOperationLegalOrCustom(ISD::SHL, VT) ||
6858                         !isOperationLegalOrCustom(ISD::SRL, VT) ||
6859                         !isOperationLegalOrCustom(ISD::SUB, VT) ||
6860                         !isOperationLegalOrCustomOrPromote(ISD::OR, VT)))
6861     return SDValue();
6862 
6863   SDValue X = Node->getOperand(0);
6864   SDValue Y = Node->getOperand(1);
6865   SDValue Z = Node->getOperand(2);
6866 
6867   unsigned BW = VT.getScalarSizeInBits();
6868   bool IsFSHL = Node->getOpcode() == ISD::FSHL;
6869   SDLoc DL(SDValue(Node, 0));
6870 
6871   EVT ShVT = Z.getValueType();
6872 
6873   // If a funnel shift in the other direction is more supported, use it.
6874   unsigned RevOpcode = IsFSHL ? ISD::FSHR : ISD::FSHL;
6875   if (!isOperationLegalOrCustom(Node->getOpcode(), VT) &&
6876       isOperationLegalOrCustom(RevOpcode, VT) && isPowerOf2_32(BW)) {
6877     if (isNonZeroModBitWidthOrUndef(Z, BW)) {
6878       // fshl X, Y, Z -> fshr X, Y, -Z
6879       // fshr X, Y, Z -> fshl X, Y, -Z
6880       SDValue Zero = DAG.getConstant(0, DL, ShVT);
6881       Z = DAG.getNode(ISD::SUB, DL, VT, Zero, Z);
6882     } else {
6883       // fshl X, Y, Z -> fshr (srl X, 1), (fshr X, Y, 1), ~Z
6884       // fshr X, Y, Z -> fshl (fshl X, Y, 1), (shl Y, 1), ~Z
6885       SDValue One = DAG.getConstant(1, DL, ShVT);
6886       if (IsFSHL) {
6887         Y = DAG.getNode(RevOpcode, DL, VT, X, Y, One);
6888         X = DAG.getNode(ISD::SRL, DL, VT, X, One);
6889       } else {
6890         X = DAG.getNode(RevOpcode, DL, VT, X, Y, One);
6891         Y = DAG.getNode(ISD::SHL, DL, VT, Y, One);
6892       }
6893       Z = DAG.getNOT(DL, Z, ShVT);
6894     }
6895     return DAG.getNode(RevOpcode, DL, VT, X, Y, Z);
6896   }
6897 
6898   SDValue ShX, ShY;
6899   SDValue ShAmt, InvShAmt;
6900   if (isNonZeroModBitWidthOrUndef(Z, BW)) {
6901     // fshl: X << C | Y >> (BW - C)
6902     // fshr: X << (BW - C) | Y >> C
6903     // where C = Z % BW is not zero
6904     SDValue BitWidthC = DAG.getConstant(BW, DL, ShVT);
6905     ShAmt = DAG.getNode(ISD::UREM, DL, ShVT, Z, BitWidthC);
6906     InvShAmt = DAG.getNode(ISD::SUB, DL, ShVT, BitWidthC, ShAmt);
6907     ShX = DAG.getNode(ISD::SHL, DL, VT, X, IsFSHL ? ShAmt : InvShAmt);
6908     ShY = DAG.getNode(ISD::SRL, DL, VT, Y, IsFSHL ? InvShAmt : ShAmt);
6909   } else {
6910     // fshl: X << (Z % BW) | Y >> 1 >> (BW - 1 - (Z % BW))
6911     // fshr: X << 1 << (BW - 1 - (Z % BW)) | Y >> (Z % BW)
6912     SDValue Mask = DAG.getConstant(BW - 1, DL, ShVT);
6913     if (isPowerOf2_32(BW)) {
6914       // Z % BW -> Z & (BW - 1)
6915       ShAmt = DAG.getNode(ISD::AND, DL, ShVT, Z, Mask);
6916       // (BW - 1) - (Z % BW) -> ~Z & (BW - 1)
6917       InvShAmt = DAG.getNode(ISD::AND, DL, ShVT, DAG.getNOT(DL, Z, ShVT), Mask);
6918     } else {
6919       SDValue BitWidthC = DAG.getConstant(BW, DL, ShVT);
6920       ShAmt = DAG.getNode(ISD::UREM, DL, ShVT, Z, BitWidthC);
6921       InvShAmt = DAG.getNode(ISD::SUB, DL, ShVT, Mask, ShAmt);
6922     }
6923 
6924     SDValue One = DAG.getConstant(1, DL, ShVT);
6925     if (IsFSHL) {
6926       ShX = DAG.getNode(ISD::SHL, DL, VT, X, ShAmt);
6927       SDValue ShY1 = DAG.getNode(ISD::SRL, DL, VT, Y, One);
6928       ShY = DAG.getNode(ISD::SRL, DL, VT, ShY1, InvShAmt);
6929     } else {
6930       SDValue ShX1 = DAG.getNode(ISD::SHL, DL, VT, X, One);
6931       ShX = DAG.getNode(ISD::SHL, DL, VT, ShX1, InvShAmt);
6932       ShY = DAG.getNode(ISD::SRL, DL, VT, Y, ShAmt);
6933     }
6934   }
6935   return DAG.getNode(ISD::OR, DL, VT, ShX, ShY);
6936 }
6937 
6938 // TODO: Merge with expandFunnelShift.
6939 SDValue TargetLowering::expandROT(SDNode *Node, bool AllowVectorOps,
6940                                   SelectionDAG &DAG) const {
6941   EVT VT = Node->getValueType(0);
6942   unsigned EltSizeInBits = VT.getScalarSizeInBits();
6943   bool IsLeft = Node->getOpcode() == ISD::ROTL;
6944   SDValue Op0 = Node->getOperand(0);
6945   SDValue Op1 = Node->getOperand(1);
6946   SDLoc DL(SDValue(Node, 0));
6947 
6948   EVT ShVT = Op1.getValueType();
6949   SDValue Zero = DAG.getConstant(0, DL, ShVT);
6950 
6951   // If a rotate in the other direction is more supported, use it.
6952   unsigned RevRot = IsLeft ? ISD::ROTR : ISD::ROTL;
6953   if (!isOperationLegalOrCustom(Node->getOpcode(), VT) &&
6954       isOperationLegalOrCustom(RevRot, VT) && isPowerOf2_32(EltSizeInBits)) {
6955     SDValue Sub = DAG.getNode(ISD::SUB, DL, ShVT, Zero, Op1);
6956     return DAG.getNode(RevRot, DL, VT, Op0, Sub);
6957   }
6958 
6959   if (!AllowVectorOps && VT.isVector() &&
6960       (!isOperationLegalOrCustom(ISD::SHL, VT) ||
6961        !isOperationLegalOrCustom(ISD::SRL, VT) ||
6962        !isOperationLegalOrCustom(ISD::SUB, VT) ||
6963        !isOperationLegalOrCustomOrPromote(ISD::OR, VT) ||
6964        !isOperationLegalOrCustomOrPromote(ISD::AND, VT)))
6965     return SDValue();
6966 
6967   unsigned ShOpc = IsLeft ? ISD::SHL : ISD::SRL;
6968   unsigned HsOpc = IsLeft ? ISD::SRL : ISD::SHL;
6969   SDValue BitWidthMinusOneC = DAG.getConstant(EltSizeInBits - 1, DL, ShVT);
6970   SDValue ShVal;
6971   SDValue HsVal;
6972   if (isPowerOf2_32(EltSizeInBits)) {
6973     // (rotl x, c) -> x << (c & (w - 1)) | x >> (-c & (w - 1))
6974     // (rotr x, c) -> x >> (c & (w - 1)) | x << (-c & (w - 1))
6975     SDValue NegOp1 = DAG.getNode(ISD::SUB, DL, ShVT, Zero, Op1);
6976     SDValue ShAmt = DAG.getNode(ISD::AND, DL, ShVT, Op1, BitWidthMinusOneC);
6977     ShVal = DAG.getNode(ShOpc, DL, VT, Op0, ShAmt);
6978     SDValue HsAmt = DAG.getNode(ISD::AND, DL, ShVT, NegOp1, BitWidthMinusOneC);
6979     HsVal = DAG.getNode(HsOpc, DL, VT, Op0, HsAmt);
6980   } else {
6981     // (rotl x, c) -> x << (c % w) | x >> 1 >> (w - 1 - (c % w))
6982     // (rotr x, c) -> x >> (c % w) | x << 1 << (w - 1 - (c % w))
6983     SDValue BitWidthC = DAG.getConstant(EltSizeInBits, DL, ShVT);
6984     SDValue ShAmt = DAG.getNode(ISD::UREM, DL, ShVT, Op1, BitWidthC);
6985     ShVal = DAG.getNode(ShOpc, DL, VT, Op0, ShAmt);
6986     SDValue HsAmt = DAG.getNode(ISD::SUB, DL, ShVT, BitWidthMinusOneC, ShAmt);
6987     SDValue One = DAG.getConstant(1, DL, ShVT);
6988     HsVal =
6989         DAG.getNode(HsOpc, DL, VT, DAG.getNode(HsOpc, DL, VT, Op0, One), HsAmt);
6990   }
6991   return DAG.getNode(ISD::OR, DL, VT, ShVal, HsVal);
6992 }
6993 
6994 void TargetLowering::expandShiftParts(SDNode *Node, SDValue &Lo, SDValue &Hi,
6995                                       SelectionDAG &DAG) const {
6996   assert(Node->getNumOperands() == 3 && "Not a double-shift!");
6997   EVT VT = Node->getValueType(0);
6998   unsigned VTBits = VT.getScalarSizeInBits();
6999   assert(isPowerOf2_32(VTBits) && "Power-of-two integer type expected");
7000 
7001   bool IsSHL = Node->getOpcode() == ISD::SHL_PARTS;
7002   bool IsSRA = Node->getOpcode() == ISD::SRA_PARTS;
7003   SDValue ShOpLo = Node->getOperand(0);
7004   SDValue ShOpHi = Node->getOperand(1);
7005   SDValue ShAmt = Node->getOperand(2);
7006   EVT ShAmtVT = ShAmt.getValueType();
7007   EVT ShAmtCCVT =
7008       getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), ShAmtVT);
7009   SDLoc dl(Node);
7010 
7011   // ISD::FSHL and ISD::FSHR have defined overflow behavior but ISD::SHL and
7012   // ISD::SRA/L nodes haven't. Insert an AND to be safe, it's usually optimized
7013   // away during isel.
7014   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, ShAmtVT, ShAmt,
7015                                   DAG.getConstant(VTBits - 1, dl, ShAmtVT));
7016   SDValue Tmp1 = IsSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7017                                      DAG.getConstant(VTBits - 1, dl, ShAmtVT))
7018                        : DAG.getConstant(0, dl, VT);
7019 
7020   SDValue Tmp2, Tmp3;
7021   if (IsSHL) {
7022     Tmp2 = DAG.getNode(ISD::FSHL, dl, VT, ShOpHi, ShOpLo, ShAmt);
7023     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
7024   } else {
7025     Tmp2 = DAG.getNode(ISD::FSHR, dl, VT, ShOpHi, ShOpLo, ShAmt);
7026     Tmp3 = DAG.getNode(IsSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
7027   }
7028 
7029   // If the shift amount is larger or equal than the width of a part we don't
7030   // use the result from the FSHL/FSHR. Insert a test and select the appropriate
7031   // values for large shift amounts.
7032   SDValue AndNode = DAG.getNode(ISD::AND, dl, ShAmtVT, ShAmt,
7033                                 DAG.getConstant(VTBits, dl, ShAmtVT));
7034   SDValue Cond = DAG.getSetCC(dl, ShAmtCCVT, AndNode,
7035                               DAG.getConstant(0, dl, ShAmtVT), ISD::SETNE);
7036 
7037   if (IsSHL) {
7038     Hi = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp3, Tmp2);
7039     Lo = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp1, Tmp3);
7040   } else {
7041     Lo = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp3, Tmp2);
7042     Hi = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp1, Tmp3);
7043   }
7044 }
7045 
7046 bool TargetLowering::expandFP_TO_SINT(SDNode *Node, SDValue &Result,
7047                                       SelectionDAG &DAG) const {
7048   unsigned OpNo = Node->isStrictFPOpcode() ? 1 : 0;
7049   SDValue Src = Node->getOperand(OpNo);
7050   EVT SrcVT = Src.getValueType();
7051   EVT DstVT = Node->getValueType(0);
7052   SDLoc dl(SDValue(Node, 0));
7053 
7054   // FIXME: Only f32 to i64 conversions are supported.
7055   if (SrcVT != MVT::f32 || DstVT != MVT::i64)
7056     return false;
7057 
7058   if (Node->isStrictFPOpcode())
7059     // When a NaN is converted to an integer a trap is allowed. We can't
7060     // use this expansion here because it would eliminate that trap. Other
7061     // traps are also allowed and cannot be eliminated. See
7062     // IEEE 754-2008 sec 5.8.
7063     return false;
7064 
7065   // Expand f32 -> i64 conversion
7066   // This algorithm comes from compiler-rt's implementation of fixsfdi:
7067   // https://github.com/llvm/llvm-project/blob/main/compiler-rt/lib/builtins/fixsfdi.c
7068   unsigned SrcEltBits = SrcVT.getScalarSizeInBits();
7069   EVT IntVT = SrcVT.changeTypeToInteger();
7070   EVT IntShVT = getShiftAmountTy(IntVT, DAG.getDataLayout());
7071 
7072   SDValue ExponentMask = DAG.getConstant(0x7F800000, dl, IntVT);
7073   SDValue ExponentLoBit = DAG.getConstant(23, dl, IntVT);
7074   SDValue Bias = DAG.getConstant(127, dl, IntVT);
7075   SDValue SignMask = DAG.getConstant(APInt::getSignMask(SrcEltBits), dl, IntVT);
7076   SDValue SignLowBit = DAG.getConstant(SrcEltBits - 1, dl, IntVT);
7077   SDValue MantissaMask = DAG.getConstant(0x007FFFFF, dl, IntVT);
7078 
7079   SDValue Bits = DAG.getNode(ISD::BITCAST, dl, IntVT, Src);
7080 
7081   SDValue ExponentBits = DAG.getNode(
7082       ISD::SRL, dl, IntVT, DAG.getNode(ISD::AND, dl, IntVT, Bits, ExponentMask),
7083       DAG.getZExtOrTrunc(ExponentLoBit, dl, IntShVT));
7084   SDValue Exponent = DAG.getNode(ISD::SUB, dl, IntVT, ExponentBits, Bias);
7085 
7086   SDValue Sign = DAG.getNode(ISD::SRA, dl, IntVT,
7087                              DAG.getNode(ISD::AND, dl, IntVT, Bits, SignMask),
7088                              DAG.getZExtOrTrunc(SignLowBit, dl, IntShVT));
7089   Sign = DAG.getSExtOrTrunc(Sign, dl, DstVT);
7090 
7091   SDValue R = DAG.getNode(ISD::OR, dl, IntVT,
7092                           DAG.getNode(ISD::AND, dl, IntVT, Bits, MantissaMask),
7093                           DAG.getConstant(0x00800000, dl, IntVT));
7094 
7095   R = DAG.getZExtOrTrunc(R, dl, DstVT);
7096 
7097   R = DAG.getSelectCC(
7098       dl, Exponent, ExponentLoBit,
7099       DAG.getNode(ISD::SHL, dl, DstVT, R,
7100                   DAG.getZExtOrTrunc(
7101                       DAG.getNode(ISD::SUB, dl, IntVT, Exponent, ExponentLoBit),
7102                       dl, IntShVT)),
7103       DAG.getNode(ISD::SRL, dl, DstVT, R,
7104                   DAG.getZExtOrTrunc(
7105                       DAG.getNode(ISD::SUB, dl, IntVT, ExponentLoBit, Exponent),
7106                       dl, IntShVT)),
7107       ISD::SETGT);
7108 
7109   SDValue Ret = DAG.getNode(ISD::SUB, dl, DstVT,
7110                             DAG.getNode(ISD::XOR, dl, DstVT, R, Sign), Sign);
7111 
7112   Result = DAG.getSelectCC(dl, Exponent, DAG.getConstant(0, dl, IntVT),
7113                            DAG.getConstant(0, dl, DstVT), Ret, ISD::SETLT);
7114   return true;
7115 }
7116 
7117 bool TargetLowering::expandFP_TO_UINT(SDNode *Node, SDValue &Result,
7118                                       SDValue &Chain,
7119                                       SelectionDAG &DAG) const {
7120   SDLoc dl(SDValue(Node, 0));
7121   unsigned OpNo = Node->isStrictFPOpcode() ? 1 : 0;
7122   SDValue Src = Node->getOperand(OpNo);
7123 
7124   EVT SrcVT = Src.getValueType();
7125   EVT DstVT = Node->getValueType(0);
7126   EVT SetCCVT =
7127       getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT);
7128   EVT DstSetCCVT =
7129       getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), DstVT);
7130 
7131   // Only expand vector types if we have the appropriate vector bit operations.
7132   unsigned SIntOpcode = Node->isStrictFPOpcode() ? ISD::STRICT_FP_TO_SINT :
7133                                                    ISD::FP_TO_SINT;
7134   if (DstVT.isVector() && (!isOperationLegalOrCustom(SIntOpcode, DstVT) ||
7135                            !isOperationLegalOrCustomOrPromote(ISD::XOR, SrcVT)))
7136     return false;
7137 
7138   // If the maximum float value is smaller then the signed integer range,
7139   // the destination signmask can't be represented by the float, so we can
7140   // just use FP_TO_SINT directly.
7141   const fltSemantics &APFSem = DAG.EVTToAPFloatSemantics(SrcVT);
7142   APFloat APF(APFSem, APInt::getZero(SrcVT.getScalarSizeInBits()));
7143   APInt SignMask = APInt::getSignMask(DstVT.getScalarSizeInBits());
7144   if (APFloat::opOverflow &
7145       APF.convertFromAPInt(SignMask, false, APFloat::rmNearestTiesToEven)) {
7146     if (Node->isStrictFPOpcode()) {
7147       Result = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, { DstVT, MVT::Other },
7148                            { Node->getOperand(0), Src });
7149       Chain = Result.getValue(1);
7150     } else
7151       Result = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, Src);
7152     return true;
7153   }
7154 
7155   // Don't expand it if there isn't cheap fsub instruction.
7156   if (!isOperationLegalOrCustom(
7157           Node->isStrictFPOpcode() ? ISD::STRICT_FSUB : ISD::FSUB, SrcVT))
7158     return false;
7159 
7160   SDValue Cst = DAG.getConstantFP(APF, dl, SrcVT);
7161   SDValue Sel;
7162 
7163   if (Node->isStrictFPOpcode()) {
7164     Sel = DAG.getSetCC(dl, SetCCVT, Src, Cst, ISD::SETLT,
7165                        Node->getOperand(0), /*IsSignaling*/ true);
7166     Chain = Sel.getValue(1);
7167   } else {
7168     Sel = DAG.getSetCC(dl, SetCCVT, Src, Cst, ISD::SETLT);
7169   }
7170 
7171   bool Strict = Node->isStrictFPOpcode() ||
7172                 shouldUseStrictFP_TO_INT(SrcVT, DstVT, /*IsSigned*/ false);
7173 
7174   if (Strict) {
7175     // Expand based on maximum range of FP_TO_SINT, if the value exceeds the
7176     // signmask then offset (the result of which should be fully representable).
7177     // Sel = Src < 0x8000000000000000
7178     // FltOfs = select Sel, 0, 0x8000000000000000
7179     // IntOfs = select Sel, 0, 0x8000000000000000
7180     // Result = fp_to_sint(Src - FltOfs) ^ IntOfs
7181 
7182     // TODO: Should any fast-math-flags be set for the FSUB?
7183     SDValue FltOfs = DAG.getSelect(dl, SrcVT, Sel,
7184                                    DAG.getConstantFP(0.0, dl, SrcVT), Cst);
7185     Sel = DAG.getBoolExtOrTrunc(Sel, dl, DstSetCCVT, DstVT);
7186     SDValue IntOfs = DAG.getSelect(dl, DstVT, Sel,
7187                                    DAG.getConstant(0, dl, DstVT),
7188                                    DAG.getConstant(SignMask, dl, DstVT));
7189     SDValue SInt;
7190     if (Node->isStrictFPOpcode()) {
7191       SDValue Val = DAG.getNode(ISD::STRICT_FSUB, dl, { SrcVT, MVT::Other },
7192                                 { Chain, Src, FltOfs });
7193       SInt = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, { DstVT, MVT::Other },
7194                          { Val.getValue(1), Val });
7195       Chain = SInt.getValue(1);
7196     } else {
7197       SDValue Val = DAG.getNode(ISD::FSUB, dl, SrcVT, Src, FltOfs);
7198       SInt = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, Val);
7199     }
7200     Result = DAG.getNode(ISD::XOR, dl, DstVT, SInt, IntOfs);
7201   } else {
7202     // Expand based on maximum range of FP_TO_SINT:
7203     // True = fp_to_sint(Src)
7204     // False = 0x8000000000000000 + fp_to_sint(Src - 0x8000000000000000)
7205     // Result = select (Src < 0x8000000000000000), True, False
7206 
7207     SDValue True = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, Src);
7208     // TODO: Should any fast-math-flags be set for the FSUB?
7209     SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT,
7210                                 DAG.getNode(ISD::FSUB, dl, SrcVT, Src, Cst));
7211     False = DAG.getNode(ISD::XOR, dl, DstVT, False,
7212                         DAG.getConstant(SignMask, dl, DstVT));
7213     Sel = DAG.getBoolExtOrTrunc(Sel, dl, DstSetCCVT, DstVT);
7214     Result = DAG.getSelect(dl, DstVT, Sel, True, False);
7215   }
7216   return true;
7217 }
7218 
7219 bool TargetLowering::expandUINT_TO_FP(SDNode *Node, SDValue &Result,
7220                                       SDValue &Chain,
7221                                       SelectionDAG &DAG) const {
7222   // This transform is not correct for converting 0 when rounding mode is set
7223   // to round toward negative infinity which will produce -0.0. So disable under
7224   // strictfp.
7225   if (Node->isStrictFPOpcode())
7226     return false;
7227 
7228   SDValue Src = Node->getOperand(0);
7229   EVT SrcVT = Src.getValueType();
7230   EVT DstVT = Node->getValueType(0);
7231 
7232   if (SrcVT.getScalarType() != MVT::i64 || DstVT.getScalarType() != MVT::f64)
7233     return false;
7234 
7235   // Only expand vector types if we have the appropriate vector bit operations.
7236   if (SrcVT.isVector() && (!isOperationLegalOrCustom(ISD::SRL, SrcVT) ||
7237                            !isOperationLegalOrCustom(ISD::FADD, DstVT) ||
7238                            !isOperationLegalOrCustom(ISD::FSUB, DstVT) ||
7239                            !isOperationLegalOrCustomOrPromote(ISD::OR, SrcVT) ||
7240                            !isOperationLegalOrCustomOrPromote(ISD::AND, SrcVT)))
7241     return false;
7242 
7243   SDLoc dl(SDValue(Node, 0));
7244   EVT ShiftVT = getShiftAmountTy(SrcVT, DAG.getDataLayout());
7245 
7246   // Implementation of unsigned i64 to f64 following the algorithm in
7247   // __floatundidf in compiler_rt.  This implementation performs rounding
7248   // correctly in all rounding modes with the exception of converting 0
7249   // when rounding toward negative infinity. In that case the fsub will produce
7250   // -0.0. This will be added to +0.0 and produce -0.0 which is incorrect.
7251   SDValue TwoP52 = DAG.getConstant(UINT64_C(0x4330000000000000), dl, SrcVT);
7252   SDValue TwoP84PlusTwoP52 = DAG.getConstantFP(
7253       BitsToDouble(UINT64_C(0x4530000000100000)), dl, DstVT);
7254   SDValue TwoP84 = DAG.getConstant(UINT64_C(0x4530000000000000), dl, SrcVT);
7255   SDValue LoMask = DAG.getConstant(UINT64_C(0x00000000FFFFFFFF), dl, SrcVT);
7256   SDValue HiShift = DAG.getConstant(32, dl, ShiftVT);
7257 
7258   SDValue Lo = DAG.getNode(ISD::AND, dl, SrcVT, Src, LoMask);
7259   SDValue Hi = DAG.getNode(ISD::SRL, dl, SrcVT, Src, HiShift);
7260   SDValue LoOr = DAG.getNode(ISD::OR, dl, SrcVT, Lo, TwoP52);
7261   SDValue HiOr = DAG.getNode(ISD::OR, dl, SrcVT, Hi, TwoP84);
7262   SDValue LoFlt = DAG.getBitcast(DstVT, LoOr);
7263   SDValue HiFlt = DAG.getBitcast(DstVT, HiOr);
7264   SDValue HiSub =
7265       DAG.getNode(ISD::FSUB, dl, DstVT, HiFlt, TwoP84PlusTwoP52);
7266   Result = DAG.getNode(ISD::FADD, dl, DstVT, LoFlt, HiSub);
7267   return true;
7268 }
7269 
7270 SDValue
7271 TargetLowering::createSelectForFMINNUM_FMAXNUM(SDNode *Node,
7272                                                SelectionDAG &DAG) const {
7273   unsigned Opcode = Node->getOpcode();
7274   assert((Opcode == ISD::FMINNUM || Opcode == ISD::FMAXNUM ||
7275           Opcode == ISD::STRICT_FMINNUM || Opcode == ISD::STRICT_FMAXNUM) &&
7276          "Wrong opcode");
7277 
7278   if (Node->getFlags().hasNoNaNs()) {
7279     ISD::CondCode Pred = Opcode == ISD::FMINNUM ? ISD::SETLT : ISD::SETGT;
7280     SDValue Op1 = Node->getOperand(0);
7281     SDValue Op2 = Node->getOperand(1);
7282     SDValue SelCC = DAG.getSelectCC(SDLoc(Node), Op1, Op2, Op1, Op2, Pred);
7283     // Copy FMF flags, but always set the no-signed-zeros flag
7284     // as this is implied by the FMINNUM/FMAXNUM semantics.
7285     SDNodeFlags Flags = Node->getFlags();
7286     Flags.setNoSignedZeros(true);
7287     SelCC->setFlags(Flags);
7288     return SelCC;
7289   }
7290 
7291   return SDValue();
7292 }
7293 
7294 SDValue TargetLowering::expandFMINNUM_FMAXNUM(SDNode *Node,
7295                                               SelectionDAG &DAG) const {
7296   SDLoc dl(Node);
7297   unsigned NewOp = Node->getOpcode() == ISD::FMINNUM ?
7298     ISD::FMINNUM_IEEE : ISD::FMAXNUM_IEEE;
7299   EVT VT = Node->getValueType(0);
7300 
7301   if (VT.isScalableVector())
7302     report_fatal_error(
7303         "Expanding fminnum/fmaxnum for scalable vectors is undefined.");
7304 
7305   if (isOperationLegalOrCustom(NewOp, VT)) {
7306     SDValue Quiet0 = Node->getOperand(0);
7307     SDValue Quiet1 = Node->getOperand(1);
7308 
7309     if (!Node->getFlags().hasNoNaNs()) {
7310       // Insert canonicalizes if it's possible we need to quiet to get correct
7311       // sNaN behavior.
7312       if (!DAG.isKnownNeverSNaN(Quiet0)) {
7313         Quiet0 = DAG.getNode(ISD::FCANONICALIZE, dl, VT, Quiet0,
7314                              Node->getFlags());
7315       }
7316       if (!DAG.isKnownNeverSNaN(Quiet1)) {
7317         Quiet1 = DAG.getNode(ISD::FCANONICALIZE, dl, VT, Quiet1,
7318                              Node->getFlags());
7319       }
7320     }
7321 
7322     return DAG.getNode(NewOp, dl, VT, Quiet0, Quiet1, Node->getFlags());
7323   }
7324 
7325   // If the target has FMINIMUM/FMAXIMUM but not FMINNUM/FMAXNUM use that
7326   // instead if there are no NaNs.
7327   if (Node->getFlags().hasNoNaNs()) {
7328     unsigned IEEE2018Op =
7329         Node->getOpcode() == ISD::FMINNUM ? ISD::FMINIMUM : ISD::FMAXIMUM;
7330     if (isOperationLegalOrCustom(IEEE2018Op, VT)) {
7331       return DAG.getNode(IEEE2018Op, dl, VT, Node->getOperand(0),
7332                          Node->getOperand(1), Node->getFlags());
7333     }
7334   }
7335 
7336   if (SDValue SelCC = createSelectForFMINNUM_FMAXNUM(Node, DAG))
7337     return SelCC;
7338 
7339   return SDValue();
7340 }
7341 
7342 // Only expand vector types if we have the appropriate vector bit operations.
7343 static bool canExpandVectorCTPOP(const TargetLowering &TLI, EVT VT) {
7344   assert(VT.isVector() && "Expected vector type");
7345   unsigned Len = VT.getScalarSizeInBits();
7346   return TLI.isOperationLegalOrCustom(ISD::ADD, VT) &&
7347          TLI.isOperationLegalOrCustom(ISD::SUB, VT) &&
7348          TLI.isOperationLegalOrCustom(ISD::SRL, VT) &&
7349          (Len == 8 || TLI.isOperationLegalOrCustom(ISD::MUL, VT)) &&
7350          TLI.isOperationLegalOrCustomOrPromote(ISD::AND, VT);
7351 }
7352 
7353 SDValue TargetLowering::expandCTPOP(SDNode *Node, SelectionDAG &DAG) const {
7354   SDLoc dl(Node);
7355   EVT VT = Node->getValueType(0);
7356   EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
7357   SDValue Op = Node->getOperand(0);
7358   unsigned Len = VT.getScalarSizeInBits();
7359   assert(VT.isInteger() && "CTPOP not implemented for this type.");
7360 
7361   // TODO: Add support for irregular type lengths.
7362   if (!(Len <= 128 && Len % 8 == 0))
7363     return SDValue();
7364 
7365   // Only expand vector types if we have the appropriate vector bit operations.
7366   if (VT.isVector() && !canExpandVectorCTPOP(*this, VT))
7367     return SDValue();
7368 
7369   // This is the "best" algorithm from
7370   // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
7371   SDValue Mask55 =
7372       DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x55)), dl, VT);
7373   SDValue Mask33 =
7374       DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x33)), dl, VT);
7375   SDValue Mask0F =
7376       DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x0F)), dl, VT);
7377   SDValue Mask01 =
7378       DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x01)), dl, VT);
7379 
7380   // v = v - ((v >> 1) & 0x55555555...)
7381   Op = DAG.getNode(ISD::SUB, dl, VT, Op,
7382                    DAG.getNode(ISD::AND, dl, VT,
7383                                DAG.getNode(ISD::SRL, dl, VT, Op,
7384                                            DAG.getConstant(1, dl, ShVT)),
7385                                Mask55));
7386   // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
7387   Op = DAG.getNode(ISD::ADD, dl, VT, DAG.getNode(ISD::AND, dl, VT, Op, Mask33),
7388                    DAG.getNode(ISD::AND, dl, VT,
7389                                DAG.getNode(ISD::SRL, dl, VT, Op,
7390                                            DAG.getConstant(2, dl, ShVT)),
7391                                Mask33));
7392   // v = (v + (v >> 4)) & 0x0F0F0F0F...
7393   Op = DAG.getNode(ISD::AND, dl, VT,
7394                    DAG.getNode(ISD::ADD, dl, VT, Op,
7395                                DAG.getNode(ISD::SRL, dl, VT, Op,
7396                                            DAG.getConstant(4, dl, ShVT))),
7397                    Mask0F);
7398   // v = (v * 0x01010101...) >> (Len - 8)
7399   if (Len > 8)
7400     Op =
7401         DAG.getNode(ISD::SRL, dl, VT, DAG.getNode(ISD::MUL, dl, VT, Op, Mask01),
7402                     DAG.getConstant(Len - 8, dl, ShVT));
7403 
7404   return Op;
7405 }
7406 
7407 SDValue TargetLowering::expandCTLZ(SDNode *Node, SelectionDAG &DAG) const {
7408   SDLoc dl(Node);
7409   EVT VT = Node->getValueType(0);
7410   EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
7411   SDValue Op = Node->getOperand(0);
7412   unsigned NumBitsPerElt = VT.getScalarSizeInBits();
7413 
7414   // If the non-ZERO_UNDEF version is supported we can use that instead.
7415   if (Node->getOpcode() == ISD::CTLZ_ZERO_UNDEF &&
7416       isOperationLegalOrCustom(ISD::CTLZ, VT))
7417     return DAG.getNode(ISD::CTLZ, dl, VT, Op);
7418 
7419   // If the ZERO_UNDEF version is supported use that and handle the zero case.
7420   if (isOperationLegalOrCustom(ISD::CTLZ_ZERO_UNDEF, VT)) {
7421     EVT SetCCVT =
7422         getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
7423     SDValue CTLZ = DAG.getNode(ISD::CTLZ_ZERO_UNDEF, dl, VT, Op);
7424     SDValue Zero = DAG.getConstant(0, dl, VT);
7425     SDValue SrcIsZero = DAG.getSetCC(dl, SetCCVT, Op, Zero, ISD::SETEQ);
7426     return DAG.getSelect(dl, VT, SrcIsZero,
7427                          DAG.getConstant(NumBitsPerElt, dl, VT), CTLZ);
7428   }
7429 
7430   // Only expand vector types if we have the appropriate vector bit operations.
7431   // This includes the operations needed to expand CTPOP if it isn't supported.
7432   if (VT.isVector() && (!isPowerOf2_32(NumBitsPerElt) ||
7433                         (!isOperationLegalOrCustom(ISD::CTPOP, VT) &&
7434                          !canExpandVectorCTPOP(*this, VT)) ||
7435                         !isOperationLegalOrCustom(ISD::SRL, VT) ||
7436                         !isOperationLegalOrCustomOrPromote(ISD::OR, VT)))
7437     return SDValue();
7438 
7439   // for now, we do this:
7440   // x = x | (x >> 1);
7441   // x = x | (x >> 2);
7442   // ...
7443   // x = x | (x >>16);
7444   // x = x | (x >>32); // for 64-bit input
7445   // return popcount(~x);
7446   //
7447   // Ref: "Hacker's Delight" by Henry Warren
7448   for (unsigned i = 0; (1U << i) <= (NumBitsPerElt / 2); ++i) {
7449     SDValue Tmp = DAG.getConstant(1ULL << i, dl, ShVT);
7450     Op = DAG.getNode(ISD::OR, dl, VT, Op,
7451                      DAG.getNode(ISD::SRL, dl, VT, Op, Tmp));
7452   }
7453   Op = DAG.getNOT(dl, Op, VT);
7454   return DAG.getNode(ISD::CTPOP, dl, VT, Op);
7455 }
7456 
7457 SDValue TargetLowering::expandCTTZ(SDNode *Node, SelectionDAG &DAG) const {
7458   SDLoc dl(Node);
7459   EVT VT = Node->getValueType(0);
7460   SDValue Op = Node->getOperand(0);
7461   unsigned NumBitsPerElt = VT.getScalarSizeInBits();
7462 
7463   // If the non-ZERO_UNDEF version is supported we can use that instead.
7464   if (Node->getOpcode() == ISD::CTTZ_ZERO_UNDEF &&
7465       isOperationLegalOrCustom(ISD::CTTZ, VT))
7466     return DAG.getNode(ISD::CTTZ, dl, VT, Op);
7467 
7468   // If the ZERO_UNDEF version is supported use that and handle the zero case.
7469   if (isOperationLegalOrCustom(ISD::CTTZ_ZERO_UNDEF, VT)) {
7470     EVT SetCCVT =
7471         getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
7472     SDValue CTTZ = DAG.getNode(ISD::CTTZ_ZERO_UNDEF, dl, VT, Op);
7473     SDValue Zero = DAG.getConstant(0, dl, VT);
7474     SDValue SrcIsZero = DAG.getSetCC(dl, SetCCVT, Op, Zero, ISD::SETEQ);
7475     return DAG.getSelect(dl, VT, SrcIsZero,
7476                          DAG.getConstant(NumBitsPerElt, dl, VT), CTTZ);
7477   }
7478 
7479   // Only expand vector types if we have the appropriate vector bit operations.
7480   // This includes the operations needed to expand CTPOP if it isn't supported.
7481   if (VT.isVector() && (!isPowerOf2_32(NumBitsPerElt) ||
7482                         (!isOperationLegalOrCustom(ISD::CTPOP, VT) &&
7483                          !isOperationLegalOrCustom(ISD::CTLZ, VT) &&
7484                          !canExpandVectorCTPOP(*this, VT)) ||
7485                         !isOperationLegalOrCustom(ISD::SUB, VT) ||
7486                         !isOperationLegalOrCustomOrPromote(ISD::AND, VT) ||
7487                         !isOperationLegalOrCustomOrPromote(ISD::XOR, VT)))
7488     return SDValue();
7489 
7490   // for now, we use: { return popcount(~x & (x - 1)); }
7491   // unless the target has ctlz but not ctpop, in which case we use:
7492   // { return 32 - nlz(~x & (x-1)); }
7493   // Ref: "Hacker's Delight" by Henry Warren
7494   SDValue Tmp = DAG.getNode(
7495       ISD::AND, dl, VT, DAG.getNOT(dl, Op, VT),
7496       DAG.getNode(ISD::SUB, dl, VT, Op, DAG.getConstant(1, dl, VT)));
7497 
7498   // If ISD::CTLZ is legal and CTPOP isn't, then do that instead.
7499   if (isOperationLegal(ISD::CTLZ, VT) && !isOperationLegal(ISD::CTPOP, VT)) {
7500     return DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(NumBitsPerElt, dl, VT),
7501                        DAG.getNode(ISD::CTLZ, dl, VT, Tmp));
7502   }
7503 
7504   return DAG.getNode(ISD::CTPOP, dl, VT, Tmp);
7505 }
7506 
7507 SDValue TargetLowering::expandABS(SDNode *N, SelectionDAG &DAG,
7508                                   bool IsNegative) const {
7509   SDLoc dl(N);
7510   EVT VT = N->getValueType(0);
7511   EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
7512   SDValue Op = N->getOperand(0);
7513 
7514   // abs(x) -> smax(x,sub(0,x))
7515   if (!IsNegative && isOperationLegal(ISD::SUB, VT) &&
7516       isOperationLegal(ISD::SMAX, VT)) {
7517     SDValue Zero = DAG.getConstant(0, dl, VT);
7518     return DAG.getNode(ISD::SMAX, dl, VT, Op,
7519                        DAG.getNode(ISD::SUB, dl, VT, Zero, Op));
7520   }
7521 
7522   // abs(x) -> umin(x,sub(0,x))
7523   if (!IsNegative && isOperationLegal(ISD::SUB, VT) &&
7524       isOperationLegal(ISD::UMIN, VT)) {
7525     SDValue Zero = DAG.getConstant(0, dl, VT);
7526     return DAG.getNode(ISD::UMIN, dl, VT, Op,
7527                        DAG.getNode(ISD::SUB, dl, VT, Zero, Op));
7528   }
7529 
7530   // 0 - abs(x) -> smin(x, sub(0,x))
7531   if (IsNegative && isOperationLegal(ISD::SUB, VT) &&
7532       isOperationLegal(ISD::SMIN, VT)) {
7533     SDValue Zero = DAG.getConstant(0, dl, VT);
7534     return DAG.getNode(ISD::SMIN, dl, VT, Op,
7535                        DAG.getNode(ISD::SUB, dl, VT, Zero, Op));
7536   }
7537 
7538   // Only expand vector types if we have the appropriate vector operations.
7539   if (VT.isVector() &&
7540       (!isOperationLegalOrCustom(ISD::SRA, VT) ||
7541        (!IsNegative && !isOperationLegalOrCustom(ISD::ADD, VT)) ||
7542        (IsNegative && !isOperationLegalOrCustom(ISD::SUB, VT)) ||
7543        !isOperationLegalOrCustomOrPromote(ISD::XOR, VT)))
7544     return SDValue();
7545 
7546   SDValue Shift =
7547       DAG.getNode(ISD::SRA, dl, VT, Op,
7548                   DAG.getConstant(VT.getScalarSizeInBits() - 1, dl, ShVT));
7549   SDValue Xor = DAG.getNode(ISD::XOR, dl, VT, Op, Shift);
7550 
7551   // abs(x) -> Y = sra (X, size(X)-1); sub (xor (X, Y), Y)
7552   if (!IsNegative)
7553     return DAG.getNode(ISD::SUB, dl, VT, Xor, Shift);
7554 
7555   // 0 - abs(x) -> Y = sra (X, size(X)-1); sub (Y, xor (X, Y))
7556   return DAG.getNode(ISD::SUB, dl, VT, Shift, Xor);
7557 }
7558 
7559 SDValue TargetLowering::expandBSWAP(SDNode *N, SelectionDAG &DAG) const {
7560   SDLoc dl(N);
7561   EVT VT = N->getValueType(0);
7562   SDValue Op = N->getOperand(0);
7563 
7564   if (!VT.isSimple())
7565     return SDValue();
7566 
7567   EVT SHVT = getShiftAmountTy(VT, DAG.getDataLayout());
7568   SDValue Tmp1, Tmp2, Tmp3, Tmp4, Tmp5, Tmp6, Tmp7, Tmp8;
7569   switch (VT.getSimpleVT().getScalarType().SimpleTy) {
7570   default:
7571     return SDValue();
7572   case MVT::i16:
7573     // Use a rotate by 8. This can be further expanded if necessary.
7574     return DAG.getNode(ISD::ROTL, dl, VT, Op, DAG.getConstant(8, dl, SHVT));
7575   case MVT::i32:
7576     Tmp4 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(24, dl, SHVT));
7577     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(8, dl, SHVT));
7578     Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, dl, SHVT));
7579     Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(24, dl, SHVT));
7580     Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp3,
7581                        DAG.getConstant(0xFF0000, dl, VT));
7582     Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(0xFF00, dl, VT));
7583     Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp3);
7584     Tmp2 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp1);
7585     return DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp2);
7586   case MVT::i64:
7587     Tmp8 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(56, dl, SHVT));
7588     Tmp7 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(40, dl, SHVT));
7589     Tmp6 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(24, dl, SHVT));
7590     Tmp5 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(8, dl, SHVT));
7591     Tmp4 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, dl, SHVT));
7592     Tmp3 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(24, dl, SHVT));
7593     Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(40, dl, SHVT));
7594     Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(56, dl, SHVT));
7595     Tmp7 = DAG.getNode(ISD::AND, dl, VT, Tmp7,
7596                        DAG.getConstant(255ULL<<48, dl, VT));
7597     Tmp6 = DAG.getNode(ISD::AND, dl, VT, Tmp6,
7598                        DAG.getConstant(255ULL<<40, dl, VT));
7599     Tmp5 = DAG.getNode(ISD::AND, dl, VT, Tmp5,
7600                        DAG.getConstant(255ULL<<32, dl, VT));
7601     Tmp4 = DAG.getNode(ISD::AND, dl, VT, Tmp4,
7602                        DAG.getConstant(255ULL<<24, dl, VT));
7603     Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp3,
7604                        DAG.getConstant(255ULL<<16, dl, VT));
7605     Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2,
7606                        DAG.getConstant(255ULL<<8 , dl, VT));
7607     Tmp8 = DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp7);
7608     Tmp6 = DAG.getNode(ISD::OR, dl, VT, Tmp6, Tmp5);
7609     Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp3);
7610     Tmp2 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp1);
7611     Tmp8 = DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp6);
7612     Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp2);
7613     return DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp4);
7614   }
7615 }
7616 
7617 SDValue TargetLowering::expandBITREVERSE(SDNode *N, SelectionDAG &DAG) const {
7618   SDLoc dl(N);
7619   EVT VT = N->getValueType(0);
7620   SDValue Op = N->getOperand(0);
7621   EVT SHVT = getShiftAmountTy(VT, DAG.getDataLayout());
7622   unsigned Sz = VT.getScalarSizeInBits();
7623 
7624   SDValue Tmp, Tmp2, Tmp3;
7625 
7626   // If we can, perform BSWAP first and then the mask+swap the i4, then i2
7627   // and finally the i1 pairs.
7628   // TODO: We can easily support i4/i2 legal types if any target ever does.
7629   if (Sz >= 8 && isPowerOf2_32(Sz)) {
7630     // Create the masks - repeating the pattern every byte.
7631     APInt Mask4 = APInt::getSplat(Sz, APInt(8, 0x0F));
7632     APInt Mask2 = APInt::getSplat(Sz, APInt(8, 0x33));
7633     APInt Mask1 = APInt::getSplat(Sz, APInt(8, 0x55));
7634 
7635     // BSWAP if the type is wider than a single byte.
7636     Tmp = (Sz > 8 ? DAG.getNode(ISD::BSWAP, dl, VT, Op) : Op);
7637 
7638     // swap i4: ((V >> 4) & 0x0F) | ((V & 0x0F) << 4)
7639     Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Tmp, DAG.getConstant(4, dl, SHVT));
7640     Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Mask4, dl, VT));
7641     Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(Mask4, dl, VT));
7642     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(4, dl, SHVT));
7643     Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
7644 
7645     // swap i2: ((V >> 2) & 0x33) | ((V & 0x33) << 2)
7646     Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Tmp, DAG.getConstant(2, dl, SHVT));
7647     Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Mask2, dl, VT));
7648     Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(Mask2, dl, VT));
7649     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(2, dl, SHVT));
7650     Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
7651 
7652     // swap i1: ((V >> 1) & 0x55) | ((V & 0x55) << 1)
7653     Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Tmp, DAG.getConstant(1, dl, SHVT));
7654     Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Mask1, dl, VT));
7655     Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(Mask1, dl, VT));
7656     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(1, dl, SHVT));
7657     Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
7658     return Tmp;
7659   }
7660 
7661   Tmp = DAG.getConstant(0, dl, VT);
7662   for (unsigned I = 0, J = Sz-1; I < Sz; ++I, --J) {
7663     if (I < J)
7664       Tmp2 =
7665           DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(J - I, dl, SHVT));
7666     else
7667       Tmp2 =
7668           DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(I - J, dl, SHVT));
7669 
7670     APInt Shift(Sz, 1);
7671     Shift <<= J;
7672     Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Shift, dl, VT));
7673     Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp, Tmp2);
7674   }
7675 
7676   return Tmp;
7677 }
7678 
7679 std::pair<SDValue, SDValue>
7680 TargetLowering::scalarizeVectorLoad(LoadSDNode *LD,
7681                                     SelectionDAG &DAG) const {
7682   SDLoc SL(LD);
7683   SDValue Chain = LD->getChain();
7684   SDValue BasePTR = LD->getBasePtr();
7685   EVT SrcVT = LD->getMemoryVT();
7686   EVT DstVT = LD->getValueType(0);
7687   ISD::LoadExtType ExtType = LD->getExtensionType();
7688 
7689   if (SrcVT.isScalableVector())
7690     report_fatal_error("Cannot scalarize scalable vector loads");
7691 
7692   unsigned NumElem = SrcVT.getVectorNumElements();
7693 
7694   EVT SrcEltVT = SrcVT.getScalarType();
7695   EVT DstEltVT = DstVT.getScalarType();
7696 
7697   // A vector must always be stored in memory as-is, i.e. without any padding
7698   // between the elements, since various code depend on it, e.g. in the
7699   // handling of a bitcast of a vector type to int, which may be done with a
7700   // vector store followed by an integer load. A vector that does not have
7701   // elements that are byte-sized must therefore be stored as an integer
7702   // built out of the extracted vector elements.
7703   if (!SrcEltVT.isByteSized()) {
7704     unsigned NumLoadBits = SrcVT.getStoreSizeInBits();
7705     EVT LoadVT = EVT::getIntegerVT(*DAG.getContext(), NumLoadBits);
7706 
7707     unsigned NumSrcBits = SrcVT.getSizeInBits();
7708     EVT SrcIntVT = EVT::getIntegerVT(*DAG.getContext(), NumSrcBits);
7709 
7710     unsigned SrcEltBits = SrcEltVT.getSizeInBits();
7711     SDValue SrcEltBitMask = DAG.getConstant(
7712         APInt::getLowBitsSet(NumLoadBits, SrcEltBits), SL, LoadVT);
7713 
7714     // Load the whole vector and avoid masking off the top bits as it makes
7715     // the codegen worse.
7716     SDValue Load =
7717         DAG.getExtLoad(ISD::EXTLOAD, SL, LoadVT, Chain, BasePTR,
7718                        LD->getPointerInfo(), SrcIntVT, LD->getOriginalAlign(),
7719                        LD->getMemOperand()->getFlags(), LD->getAAInfo());
7720 
7721     SmallVector<SDValue, 8> Vals;
7722     for (unsigned Idx = 0; Idx < NumElem; ++Idx) {
7723       unsigned ShiftIntoIdx =
7724           (DAG.getDataLayout().isBigEndian() ? (NumElem - 1) - Idx : Idx);
7725       SDValue ShiftAmount =
7726           DAG.getShiftAmountConstant(ShiftIntoIdx * SrcEltVT.getSizeInBits(),
7727                                      LoadVT, SL, /*LegalTypes=*/false);
7728       SDValue ShiftedElt = DAG.getNode(ISD::SRL, SL, LoadVT, Load, ShiftAmount);
7729       SDValue Elt =
7730           DAG.getNode(ISD::AND, SL, LoadVT, ShiftedElt, SrcEltBitMask);
7731       SDValue Scalar = DAG.getNode(ISD::TRUNCATE, SL, SrcEltVT, Elt);
7732 
7733       if (ExtType != ISD::NON_EXTLOAD) {
7734         unsigned ExtendOp = ISD::getExtForLoadExtType(false, ExtType);
7735         Scalar = DAG.getNode(ExtendOp, SL, DstEltVT, Scalar);
7736       }
7737 
7738       Vals.push_back(Scalar);
7739     }
7740 
7741     SDValue Value = DAG.getBuildVector(DstVT, SL, Vals);
7742     return std::make_pair(Value, Load.getValue(1));
7743   }
7744 
7745   unsigned Stride = SrcEltVT.getSizeInBits() / 8;
7746   assert(SrcEltVT.isByteSized());
7747 
7748   SmallVector<SDValue, 8> Vals;
7749   SmallVector<SDValue, 8> LoadChains;
7750 
7751   for (unsigned Idx = 0; Idx < NumElem; ++Idx) {
7752     SDValue ScalarLoad =
7753         DAG.getExtLoad(ExtType, SL, DstEltVT, Chain, BasePTR,
7754                        LD->getPointerInfo().getWithOffset(Idx * Stride),
7755                        SrcEltVT, LD->getOriginalAlign(),
7756                        LD->getMemOperand()->getFlags(), LD->getAAInfo());
7757 
7758     BasePTR = DAG.getObjectPtrOffset(SL, BasePTR, TypeSize::Fixed(Stride));
7759 
7760     Vals.push_back(ScalarLoad.getValue(0));
7761     LoadChains.push_back(ScalarLoad.getValue(1));
7762   }
7763 
7764   SDValue NewChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, LoadChains);
7765   SDValue Value = DAG.getBuildVector(DstVT, SL, Vals);
7766 
7767   return std::make_pair(Value, NewChain);
7768 }
7769 
7770 SDValue TargetLowering::scalarizeVectorStore(StoreSDNode *ST,
7771                                              SelectionDAG &DAG) const {
7772   SDLoc SL(ST);
7773 
7774   SDValue Chain = ST->getChain();
7775   SDValue BasePtr = ST->getBasePtr();
7776   SDValue Value = ST->getValue();
7777   EVT StVT = ST->getMemoryVT();
7778 
7779   if (StVT.isScalableVector())
7780     report_fatal_error("Cannot scalarize scalable vector stores");
7781 
7782   // The type of the data we want to save
7783   EVT RegVT = Value.getValueType();
7784   EVT RegSclVT = RegVT.getScalarType();
7785 
7786   // The type of data as saved in memory.
7787   EVT MemSclVT = StVT.getScalarType();
7788 
7789   unsigned NumElem = StVT.getVectorNumElements();
7790 
7791   // A vector must always be stored in memory as-is, i.e. without any padding
7792   // between the elements, since various code depend on it, e.g. in the
7793   // handling of a bitcast of a vector type to int, which may be done with a
7794   // vector store followed by an integer load. A vector that does not have
7795   // elements that are byte-sized must therefore be stored as an integer
7796   // built out of the extracted vector elements.
7797   if (!MemSclVT.isByteSized()) {
7798     unsigned NumBits = StVT.getSizeInBits();
7799     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), NumBits);
7800 
7801     SDValue CurrVal = DAG.getConstant(0, SL, IntVT);
7802 
7803     for (unsigned Idx = 0; Idx < NumElem; ++Idx) {
7804       SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, RegSclVT, Value,
7805                                 DAG.getVectorIdxConstant(Idx, SL));
7806       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, MemSclVT, Elt);
7807       SDValue ExtElt = DAG.getNode(ISD::ZERO_EXTEND, SL, IntVT, Trunc);
7808       unsigned ShiftIntoIdx =
7809           (DAG.getDataLayout().isBigEndian() ? (NumElem - 1) - Idx : Idx);
7810       SDValue ShiftAmount =
7811           DAG.getConstant(ShiftIntoIdx * MemSclVT.getSizeInBits(), SL, IntVT);
7812       SDValue ShiftedElt =
7813           DAG.getNode(ISD::SHL, SL, IntVT, ExtElt, ShiftAmount);
7814       CurrVal = DAG.getNode(ISD::OR, SL, IntVT, CurrVal, ShiftedElt);
7815     }
7816 
7817     return DAG.getStore(Chain, SL, CurrVal, BasePtr, ST->getPointerInfo(),
7818                         ST->getOriginalAlign(), ST->getMemOperand()->getFlags(),
7819                         ST->getAAInfo());
7820   }
7821 
7822   // Store Stride in bytes
7823   unsigned Stride = MemSclVT.getSizeInBits() / 8;
7824   assert(Stride && "Zero stride!");
7825   // Extract each of the elements from the original vector and save them into
7826   // memory individually.
7827   SmallVector<SDValue, 8> Stores;
7828   for (unsigned Idx = 0; Idx < NumElem; ++Idx) {
7829     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, RegSclVT, Value,
7830                               DAG.getVectorIdxConstant(Idx, SL));
7831 
7832     SDValue Ptr =
7833         DAG.getObjectPtrOffset(SL, BasePtr, TypeSize::Fixed(Idx * Stride));
7834 
7835     // This scalar TruncStore may be illegal, but we legalize it later.
7836     SDValue Store = DAG.getTruncStore(
7837         Chain, SL, Elt, Ptr, ST->getPointerInfo().getWithOffset(Idx * Stride),
7838         MemSclVT, ST->getOriginalAlign(), ST->getMemOperand()->getFlags(),
7839         ST->getAAInfo());
7840 
7841     Stores.push_back(Store);
7842   }
7843 
7844   return DAG.getNode(ISD::TokenFactor, SL, MVT::Other, Stores);
7845 }
7846 
7847 std::pair<SDValue, SDValue>
7848 TargetLowering::expandUnalignedLoad(LoadSDNode *LD, SelectionDAG &DAG) const {
7849   assert(LD->getAddressingMode() == ISD::UNINDEXED &&
7850          "unaligned indexed loads not implemented!");
7851   SDValue Chain = LD->getChain();
7852   SDValue Ptr = LD->getBasePtr();
7853   EVT VT = LD->getValueType(0);
7854   EVT LoadedVT = LD->getMemoryVT();
7855   SDLoc dl(LD);
7856   auto &MF = DAG.getMachineFunction();
7857 
7858   if (VT.isFloatingPoint() || VT.isVector()) {
7859     EVT intVT = EVT::getIntegerVT(*DAG.getContext(), LoadedVT.getSizeInBits());
7860     if (isTypeLegal(intVT) && isTypeLegal(LoadedVT)) {
7861       if (!isOperationLegalOrCustom(ISD::LOAD, intVT) &&
7862           LoadedVT.isVector()) {
7863         // Scalarize the load and let the individual components be handled.
7864         return scalarizeVectorLoad(LD, DAG);
7865       }
7866 
7867       // Expand to a (misaligned) integer load of the same size,
7868       // then bitconvert to floating point or vector.
7869       SDValue newLoad = DAG.getLoad(intVT, dl, Chain, Ptr,
7870                                     LD->getMemOperand());
7871       SDValue Result = DAG.getNode(ISD::BITCAST, dl, LoadedVT, newLoad);
7872       if (LoadedVT != VT)
7873         Result = DAG.getNode(VT.isFloatingPoint() ? ISD::FP_EXTEND :
7874                              ISD::ANY_EXTEND, dl, VT, Result);
7875 
7876       return std::make_pair(Result, newLoad.getValue(1));
7877     }
7878 
7879     // Copy the value to a (aligned) stack slot using (unaligned) integer
7880     // loads and stores, then do a (aligned) load from the stack slot.
7881     MVT RegVT = getRegisterType(*DAG.getContext(), intVT);
7882     unsigned LoadedBytes = LoadedVT.getStoreSize();
7883     unsigned RegBytes = RegVT.getSizeInBits() / 8;
7884     unsigned NumRegs = (LoadedBytes + RegBytes - 1) / RegBytes;
7885 
7886     // Make sure the stack slot is also aligned for the register type.
7887     SDValue StackBase = DAG.CreateStackTemporary(LoadedVT, RegVT);
7888     auto FrameIndex = cast<FrameIndexSDNode>(StackBase.getNode())->getIndex();
7889     SmallVector<SDValue, 8> Stores;
7890     SDValue StackPtr = StackBase;
7891     unsigned Offset = 0;
7892 
7893     EVT PtrVT = Ptr.getValueType();
7894     EVT StackPtrVT = StackPtr.getValueType();
7895 
7896     SDValue PtrIncrement = DAG.getConstant(RegBytes, dl, PtrVT);
7897     SDValue StackPtrIncrement = DAG.getConstant(RegBytes, dl, StackPtrVT);
7898 
7899     // Do all but one copies using the full register width.
7900     for (unsigned i = 1; i < NumRegs; i++) {
7901       // Load one integer register's worth from the original location.
7902       SDValue Load = DAG.getLoad(
7903           RegVT, dl, Chain, Ptr, LD->getPointerInfo().getWithOffset(Offset),
7904           LD->getOriginalAlign(), LD->getMemOperand()->getFlags(),
7905           LD->getAAInfo());
7906       // Follow the load with a store to the stack slot.  Remember the store.
7907       Stores.push_back(DAG.getStore(
7908           Load.getValue(1), dl, Load, StackPtr,
7909           MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset)));
7910       // Increment the pointers.
7911       Offset += RegBytes;
7912 
7913       Ptr = DAG.getObjectPtrOffset(dl, Ptr, PtrIncrement);
7914       StackPtr = DAG.getObjectPtrOffset(dl, StackPtr, StackPtrIncrement);
7915     }
7916 
7917     // The last copy may be partial.  Do an extending load.
7918     EVT MemVT = EVT::getIntegerVT(*DAG.getContext(),
7919                                   8 * (LoadedBytes - Offset));
7920     SDValue Load =
7921         DAG.getExtLoad(ISD::EXTLOAD, dl, RegVT, Chain, Ptr,
7922                        LD->getPointerInfo().getWithOffset(Offset), MemVT,
7923                        LD->getOriginalAlign(), LD->getMemOperand()->getFlags(),
7924                        LD->getAAInfo());
7925     // Follow the load with a store to the stack slot.  Remember the store.
7926     // On big-endian machines this requires a truncating store to ensure
7927     // that the bits end up in the right place.
7928     Stores.push_back(DAG.getTruncStore(
7929         Load.getValue(1), dl, Load, StackPtr,
7930         MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset), MemVT));
7931 
7932     // The order of the stores doesn't matter - say it with a TokenFactor.
7933     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
7934 
7935     // Finally, perform the original load only redirected to the stack slot.
7936     Load = DAG.getExtLoad(LD->getExtensionType(), dl, VT, TF, StackBase,
7937                           MachinePointerInfo::getFixedStack(MF, FrameIndex, 0),
7938                           LoadedVT);
7939 
7940     // Callers expect a MERGE_VALUES node.
7941     return std::make_pair(Load, TF);
7942   }
7943 
7944   assert(LoadedVT.isInteger() && !LoadedVT.isVector() &&
7945          "Unaligned load of unsupported type.");
7946 
7947   // Compute the new VT that is half the size of the old one.  This is an
7948   // integer MVT.
7949   unsigned NumBits = LoadedVT.getSizeInBits();
7950   EVT NewLoadedVT;
7951   NewLoadedVT = EVT::getIntegerVT(*DAG.getContext(), NumBits/2);
7952   NumBits >>= 1;
7953 
7954   Align Alignment = LD->getOriginalAlign();
7955   unsigned IncrementSize = NumBits / 8;
7956   ISD::LoadExtType HiExtType = LD->getExtensionType();
7957 
7958   // If the original load is NON_EXTLOAD, the hi part load must be ZEXTLOAD.
7959   if (HiExtType == ISD::NON_EXTLOAD)
7960     HiExtType = ISD::ZEXTLOAD;
7961 
7962   // Load the value in two parts
7963   SDValue Lo, Hi;
7964   if (DAG.getDataLayout().isLittleEndian()) {
7965     Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr, LD->getPointerInfo(),
7966                         NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(),
7967                         LD->getAAInfo());
7968 
7969     Ptr = DAG.getObjectPtrOffset(dl, Ptr, TypeSize::Fixed(IncrementSize));
7970     Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr,
7971                         LD->getPointerInfo().getWithOffset(IncrementSize),
7972                         NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(),
7973                         LD->getAAInfo());
7974   } else {
7975     Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr, LD->getPointerInfo(),
7976                         NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(),
7977                         LD->getAAInfo());
7978 
7979     Ptr = DAG.getObjectPtrOffset(dl, Ptr, TypeSize::Fixed(IncrementSize));
7980     Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr,
7981                         LD->getPointerInfo().getWithOffset(IncrementSize),
7982                         NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(),
7983                         LD->getAAInfo());
7984   }
7985 
7986   // aggregate the two parts
7987   SDValue ShiftAmount =
7988       DAG.getConstant(NumBits, dl, getShiftAmountTy(Hi.getValueType(),
7989                                                     DAG.getDataLayout()));
7990   SDValue Result = DAG.getNode(ISD::SHL, dl, VT, Hi, ShiftAmount);
7991   Result = DAG.getNode(ISD::OR, dl, VT, Result, Lo);
7992 
7993   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
7994                              Hi.getValue(1));
7995 
7996   return std::make_pair(Result, TF);
7997 }
7998 
7999 SDValue TargetLowering::expandUnalignedStore(StoreSDNode *ST,
8000                                              SelectionDAG &DAG) const {
8001   assert(ST->getAddressingMode() == ISD::UNINDEXED &&
8002          "unaligned indexed stores not implemented!");
8003   SDValue Chain = ST->getChain();
8004   SDValue Ptr = ST->getBasePtr();
8005   SDValue Val = ST->getValue();
8006   EVT VT = Val.getValueType();
8007   Align Alignment = ST->getOriginalAlign();
8008   auto &MF = DAG.getMachineFunction();
8009   EVT StoreMemVT = ST->getMemoryVT();
8010 
8011   SDLoc dl(ST);
8012   if (StoreMemVT.isFloatingPoint() || StoreMemVT.isVector()) {
8013     EVT intVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
8014     if (isTypeLegal(intVT)) {
8015       if (!isOperationLegalOrCustom(ISD::STORE, intVT) &&
8016           StoreMemVT.isVector()) {
8017         // Scalarize the store and let the individual components be handled.
8018         SDValue Result = scalarizeVectorStore(ST, DAG);
8019         return Result;
8020       }
8021       // Expand to a bitconvert of the value to the integer type of the
8022       // same size, then a (misaligned) int store.
8023       // FIXME: Does not handle truncating floating point stores!
8024       SDValue Result = DAG.getNode(ISD::BITCAST, dl, intVT, Val);
8025       Result = DAG.getStore(Chain, dl, Result, Ptr, ST->getPointerInfo(),
8026                             Alignment, ST->getMemOperand()->getFlags());
8027       return Result;
8028     }
8029     // Do a (aligned) store to a stack slot, then copy from the stack slot
8030     // to the final destination using (unaligned) integer loads and stores.
8031     MVT RegVT = getRegisterType(
8032         *DAG.getContext(),
8033         EVT::getIntegerVT(*DAG.getContext(), StoreMemVT.getSizeInBits()));
8034     EVT PtrVT = Ptr.getValueType();
8035     unsigned StoredBytes = StoreMemVT.getStoreSize();
8036     unsigned RegBytes = RegVT.getSizeInBits() / 8;
8037     unsigned NumRegs = (StoredBytes + RegBytes - 1) / RegBytes;
8038 
8039     // Make sure the stack slot is also aligned for the register type.
8040     SDValue StackPtr = DAG.CreateStackTemporary(StoreMemVT, RegVT);
8041     auto FrameIndex = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
8042 
8043     // Perform the original store, only redirected to the stack slot.
8044     SDValue Store = DAG.getTruncStore(
8045         Chain, dl, Val, StackPtr,
8046         MachinePointerInfo::getFixedStack(MF, FrameIndex, 0), StoreMemVT);
8047 
8048     EVT StackPtrVT = StackPtr.getValueType();
8049 
8050     SDValue PtrIncrement = DAG.getConstant(RegBytes, dl, PtrVT);
8051     SDValue StackPtrIncrement = DAG.getConstant(RegBytes, dl, StackPtrVT);
8052     SmallVector<SDValue, 8> Stores;
8053     unsigned Offset = 0;
8054 
8055     // Do all but one copies using the full register width.
8056     for (unsigned i = 1; i < NumRegs; i++) {
8057       // Load one integer register's worth from the stack slot.
8058       SDValue Load = DAG.getLoad(
8059           RegVT, dl, Store, StackPtr,
8060           MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset));
8061       // Store it to the final location.  Remember the store.
8062       Stores.push_back(DAG.getStore(Load.getValue(1), dl, Load, Ptr,
8063                                     ST->getPointerInfo().getWithOffset(Offset),
8064                                     ST->getOriginalAlign(),
8065                                     ST->getMemOperand()->getFlags()));
8066       // Increment the pointers.
8067       Offset += RegBytes;
8068       StackPtr = DAG.getObjectPtrOffset(dl, StackPtr, StackPtrIncrement);
8069       Ptr = DAG.getObjectPtrOffset(dl, Ptr, PtrIncrement);
8070     }
8071 
8072     // The last store may be partial.  Do a truncating store.  On big-endian
8073     // machines this requires an extending load from the stack slot to ensure
8074     // that the bits are in the right place.
8075     EVT LoadMemVT =
8076         EVT::getIntegerVT(*DAG.getContext(), 8 * (StoredBytes - Offset));
8077 
8078     // Load from the stack slot.
8079     SDValue Load = DAG.getExtLoad(
8080         ISD::EXTLOAD, dl, RegVT, Store, StackPtr,
8081         MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset), LoadMemVT);
8082 
8083     Stores.push_back(
8084         DAG.getTruncStore(Load.getValue(1), dl, Load, Ptr,
8085                           ST->getPointerInfo().getWithOffset(Offset), LoadMemVT,
8086                           ST->getOriginalAlign(),
8087                           ST->getMemOperand()->getFlags(), ST->getAAInfo()));
8088     // The order of the stores doesn't matter - say it with a TokenFactor.
8089     SDValue Result = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
8090     return Result;
8091   }
8092 
8093   assert(StoreMemVT.isInteger() && !StoreMemVT.isVector() &&
8094          "Unaligned store of unknown type.");
8095   // Get the half-size VT
8096   EVT NewStoredVT = StoreMemVT.getHalfSizedIntegerVT(*DAG.getContext());
8097   unsigned NumBits = NewStoredVT.getFixedSizeInBits();
8098   unsigned IncrementSize = NumBits / 8;
8099 
8100   // Divide the stored value in two parts.
8101   SDValue ShiftAmount = DAG.getConstant(
8102       NumBits, dl, getShiftAmountTy(Val.getValueType(), DAG.getDataLayout()));
8103   SDValue Lo = Val;
8104   SDValue Hi = DAG.getNode(ISD::SRL, dl, VT, Val, ShiftAmount);
8105 
8106   // Store the two parts
8107   SDValue Store1, Store2;
8108   Store1 = DAG.getTruncStore(Chain, dl,
8109                              DAG.getDataLayout().isLittleEndian() ? Lo : Hi,
8110                              Ptr, ST->getPointerInfo(), NewStoredVT, Alignment,
8111                              ST->getMemOperand()->getFlags());
8112 
8113   Ptr = DAG.getObjectPtrOffset(dl, Ptr, TypeSize::Fixed(IncrementSize));
8114   Store2 = DAG.getTruncStore(
8115       Chain, dl, DAG.getDataLayout().isLittleEndian() ? Hi : Lo, Ptr,
8116       ST->getPointerInfo().getWithOffset(IncrementSize), NewStoredVT, Alignment,
8117       ST->getMemOperand()->getFlags(), ST->getAAInfo());
8118 
8119   SDValue Result =
8120       DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Store1, Store2);
8121   return Result;
8122 }
8123 
8124 SDValue
8125 TargetLowering::IncrementMemoryAddress(SDValue Addr, SDValue Mask,
8126                                        const SDLoc &DL, EVT DataVT,
8127                                        SelectionDAG &DAG,
8128                                        bool IsCompressedMemory) const {
8129   SDValue Increment;
8130   EVT AddrVT = Addr.getValueType();
8131   EVT MaskVT = Mask.getValueType();
8132   assert(DataVT.getVectorElementCount() == MaskVT.getVectorElementCount() &&
8133          "Incompatible types of Data and Mask");
8134   if (IsCompressedMemory) {
8135     if (DataVT.isScalableVector())
8136       report_fatal_error(
8137           "Cannot currently handle compressed memory with scalable vectors");
8138     // Incrementing the pointer according to number of '1's in the mask.
8139     EVT MaskIntVT = EVT::getIntegerVT(*DAG.getContext(), MaskVT.getSizeInBits());
8140     SDValue MaskInIntReg = DAG.getBitcast(MaskIntVT, Mask);
8141     if (MaskIntVT.getSizeInBits() < 32) {
8142       MaskInIntReg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, MaskInIntReg);
8143       MaskIntVT = MVT::i32;
8144     }
8145 
8146     // Count '1's with POPCNT.
8147     Increment = DAG.getNode(ISD::CTPOP, DL, MaskIntVT, MaskInIntReg);
8148     Increment = DAG.getZExtOrTrunc(Increment, DL, AddrVT);
8149     // Scale is an element size in bytes.
8150     SDValue Scale = DAG.getConstant(DataVT.getScalarSizeInBits() / 8, DL,
8151                                     AddrVT);
8152     Increment = DAG.getNode(ISD::MUL, DL, AddrVT, Increment, Scale);
8153   } else if (DataVT.isScalableVector()) {
8154     Increment = DAG.getVScale(DL, AddrVT,
8155                               APInt(AddrVT.getFixedSizeInBits(),
8156                                     DataVT.getStoreSize().getKnownMinSize()));
8157   } else
8158     Increment = DAG.getConstant(DataVT.getStoreSize(), DL, AddrVT);
8159 
8160   return DAG.getNode(ISD::ADD, DL, AddrVT, Addr, Increment);
8161 }
8162 
8163 static SDValue clampDynamicVectorIndex(SelectionDAG &DAG, SDValue Idx,
8164                                        EVT VecVT, const SDLoc &dl,
8165                                        ElementCount SubEC) {
8166   assert(!(SubEC.isScalable() && VecVT.isFixedLengthVector()) &&
8167          "Cannot index a scalable vector within a fixed-width vector");
8168 
8169   unsigned NElts = VecVT.getVectorMinNumElements();
8170   unsigned NumSubElts = SubEC.getKnownMinValue();
8171   EVT IdxVT = Idx.getValueType();
8172 
8173   if (VecVT.isScalableVector() && !SubEC.isScalable()) {
8174     // If this is a constant index and we know the value plus the number of the
8175     // elements in the subvector minus one is less than the minimum number of
8176     // elements then it's safe to return Idx.
8177     if (auto *IdxCst = dyn_cast<ConstantSDNode>(Idx))
8178       if (IdxCst->getZExtValue() + (NumSubElts - 1) < NElts)
8179         return Idx;
8180     SDValue VS =
8181         DAG.getVScale(dl, IdxVT, APInt(IdxVT.getFixedSizeInBits(), NElts));
8182     unsigned SubOpcode = NumSubElts <= NElts ? ISD::SUB : ISD::USUBSAT;
8183     SDValue Sub = DAG.getNode(SubOpcode, dl, IdxVT, VS,
8184                               DAG.getConstant(NumSubElts, dl, IdxVT));
8185     return DAG.getNode(ISD::UMIN, dl, IdxVT, Idx, Sub);
8186   }
8187   if (isPowerOf2_32(NElts) && NumSubElts == 1) {
8188     APInt Imm = APInt::getLowBitsSet(IdxVT.getSizeInBits(), Log2_32(NElts));
8189     return DAG.getNode(ISD::AND, dl, IdxVT, Idx,
8190                        DAG.getConstant(Imm, dl, IdxVT));
8191   }
8192   unsigned MaxIndex = NumSubElts < NElts ? NElts - NumSubElts : 0;
8193   return DAG.getNode(ISD::UMIN, dl, IdxVT, Idx,
8194                      DAG.getConstant(MaxIndex, dl, IdxVT));
8195 }
8196 
8197 SDValue TargetLowering::getVectorElementPointer(SelectionDAG &DAG,
8198                                                 SDValue VecPtr, EVT VecVT,
8199                                                 SDValue Index) const {
8200   return getVectorSubVecPointer(
8201       DAG, VecPtr, VecVT,
8202       EVT::getVectorVT(*DAG.getContext(), VecVT.getVectorElementType(), 1),
8203       Index);
8204 }
8205 
8206 SDValue TargetLowering::getVectorSubVecPointer(SelectionDAG &DAG,
8207                                                SDValue VecPtr, EVT VecVT,
8208                                                EVT SubVecVT,
8209                                                SDValue Index) const {
8210   SDLoc dl(Index);
8211   // Make sure the index type is big enough to compute in.
8212   Index = DAG.getZExtOrTrunc(Index, dl, VecPtr.getValueType());
8213 
8214   EVT EltVT = VecVT.getVectorElementType();
8215 
8216   // Calculate the element offset and add it to the pointer.
8217   unsigned EltSize = EltVT.getFixedSizeInBits() / 8; // FIXME: should be ABI size.
8218   assert(EltSize * 8 == EltVT.getFixedSizeInBits() &&
8219          "Converting bits to bytes lost precision");
8220   assert(SubVecVT.getVectorElementType() == EltVT &&
8221          "Sub-vector must be a vector with matching element type");
8222   Index = clampDynamicVectorIndex(DAG, Index, VecVT, dl,
8223                                   SubVecVT.getVectorElementCount());
8224 
8225   EVT IdxVT = Index.getValueType();
8226   if (SubVecVT.isScalableVector())
8227     Index =
8228         DAG.getNode(ISD::MUL, dl, IdxVT, Index,
8229                     DAG.getVScale(dl, IdxVT, APInt(IdxVT.getSizeInBits(), 1)));
8230 
8231   Index = DAG.getNode(ISD::MUL, dl, IdxVT, Index,
8232                       DAG.getConstant(EltSize, dl, IdxVT));
8233   return DAG.getMemBasePlusOffset(VecPtr, Index, dl);
8234 }
8235 
8236 //===----------------------------------------------------------------------===//
8237 // Implementation of Emulated TLS Model
8238 //===----------------------------------------------------------------------===//
8239 
8240 SDValue TargetLowering::LowerToTLSEmulatedModel(const GlobalAddressSDNode *GA,
8241                                                 SelectionDAG &DAG) const {
8242   // Access to address of TLS varialbe xyz is lowered to a function call:
8243   //   __emutls_get_address( address of global variable named "__emutls_v.xyz" )
8244   EVT PtrVT = getPointerTy(DAG.getDataLayout());
8245   PointerType *VoidPtrType = Type::getInt8PtrTy(*DAG.getContext());
8246   SDLoc dl(GA);
8247 
8248   ArgListTy Args;
8249   ArgListEntry Entry;
8250   std::string NameString = ("__emutls_v." + GA->getGlobal()->getName()).str();
8251   Module *VariableModule = const_cast<Module*>(GA->getGlobal()->getParent());
8252   StringRef EmuTlsVarName(NameString);
8253   GlobalVariable *EmuTlsVar = VariableModule->getNamedGlobal(EmuTlsVarName);
8254   assert(EmuTlsVar && "Cannot find EmuTlsVar ");
8255   Entry.Node = DAG.getGlobalAddress(EmuTlsVar, dl, PtrVT);
8256   Entry.Ty = VoidPtrType;
8257   Args.push_back(Entry);
8258 
8259   SDValue EmuTlsGetAddr = DAG.getExternalSymbol("__emutls_get_address", PtrVT);
8260 
8261   TargetLowering::CallLoweringInfo CLI(DAG);
8262   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode());
8263   CLI.setLibCallee(CallingConv::C, VoidPtrType, EmuTlsGetAddr, std::move(Args));
8264   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
8265 
8266   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
8267   // At last for X86 targets, maybe good for other targets too?
8268   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
8269   MFI.setAdjustsStack(true); // Is this only for X86 target?
8270   MFI.setHasCalls(true);
8271 
8272   assert((GA->getOffset() == 0) &&
8273          "Emulated TLS must have zero offset in GlobalAddressSDNode");
8274   return CallResult.first;
8275 }
8276 
8277 SDValue TargetLowering::lowerCmpEqZeroToCtlzSrl(SDValue Op,
8278                                                 SelectionDAG &DAG) const {
8279   assert((Op->getOpcode() == ISD::SETCC) && "Input has to be a SETCC node.");
8280   if (!isCtlzFast())
8281     return SDValue();
8282   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8283   SDLoc dl(Op);
8284   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
8285     if (C->isZero() && CC == ISD::SETEQ) {
8286       EVT VT = Op.getOperand(0).getValueType();
8287       SDValue Zext = Op.getOperand(0);
8288       if (VT.bitsLT(MVT::i32)) {
8289         VT = MVT::i32;
8290         Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0));
8291       }
8292       unsigned Log2b = Log2_32(VT.getSizeInBits());
8293       SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext);
8294       SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz,
8295                                 DAG.getConstant(Log2b, dl, MVT::i32));
8296       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc);
8297     }
8298   }
8299   return SDValue();
8300 }
8301 
8302 // Convert redundant addressing modes (e.g. scaling is redundant
8303 // when accessing bytes).
8304 ISD::MemIndexType
8305 TargetLowering::getCanonicalIndexType(ISD::MemIndexType IndexType, EVT MemVT,
8306                                       SDValue Offsets) const {
8307   bool IsScaledIndex =
8308       (IndexType == ISD::SIGNED_SCALED) || (IndexType == ISD::UNSIGNED_SCALED);
8309   bool IsSignedIndex =
8310       (IndexType == ISD::SIGNED_SCALED) || (IndexType == ISD::SIGNED_UNSCALED);
8311 
8312   // Scaling is unimportant for bytes, canonicalize to unscaled.
8313   if (IsScaledIndex && MemVT.getScalarType() == MVT::i8)
8314     return IsSignedIndex ? ISD::SIGNED_UNSCALED : ISD::UNSIGNED_UNSCALED;
8315 
8316   return IndexType;
8317 }
8318 
8319 SDValue TargetLowering::expandIntMINMAX(SDNode *Node, SelectionDAG &DAG) const {
8320   SDValue Op0 = Node->getOperand(0);
8321   SDValue Op1 = Node->getOperand(1);
8322   EVT VT = Op0.getValueType();
8323   unsigned Opcode = Node->getOpcode();
8324   SDLoc DL(Node);
8325 
8326   // umin(x,y) -> sub(x,usubsat(x,y))
8327   if (Opcode == ISD::UMIN && isOperationLegal(ISD::SUB, VT) &&
8328       isOperationLegal(ISD::USUBSAT, VT)) {
8329     return DAG.getNode(ISD::SUB, DL, VT, Op0,
8330                        DAG.getNode(ISD::USUBSAT, DL, VT, Op0, Op1));
8331   }
8332 
8333   // umax(x,y) -> add(x,usubsat(y,x))
8334   if (Opcode == ISD::UMAX && isOperationLegal(ISD::ADD, VT) &&
8335       isOperationLegal(ISD::USUBSAT, VT)) {
8336     return DAG.getNode(ISD::ADD, DL, VT, Op0,
8337                        DAG.getNode(ISD::USUBSAT, DL, VT, Op1, Op0));
8338   }
8339 
8340   // Expand Y = MAX(A, B) -> Y = (A > B) ? A : B
8341   ISD::CondCode CC;
8342   switch (Opcode) {
8343   default: llvm_unreachable("How did we get here?");
8344   case ISD::SMAX: CC = ISD::SETGT; break;
8345   case ISD::SMIN: CC = ISD::SETLT; break;
8346   case ISD::UMAX: CC = ISD::SETUGT; break;
8347   case ISD::UMIN: CC = ISD::SETULT; break;
8348   }
8349 
8350   // FIXME: Should really try to split the vector in case it's legal on a
8351   // subvector.
8352   if (VT.isVector() && !isOperationLegalOrCustom(ISD::VSELECT, VT))
8353     return DAG.UnrollVectorOp(Node);
8354 
8355   EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
8356   SDValue Cond = DAG.getSetCC(DL, BoolVT, Op0, Op1, CC);
8357   return DAG.getSelect(DL, VT, Cond, Op0, Op1);
8358 }
8359 
8360 SDValue TargetLowering::expandAddSubSat(SDNode *Node, SelectionDAG &DAG) const {
8361   unsigned Opcode = Node->getOpcode();
8362   SDValue LHS = Node->getOperand(0);
8363   SDValue RHS = Node->getOperand(1);
8364   EVT VT = LHS.getValueType();
8365   SDLoc dl(Node);
8366 
8367   assert(VT == RHS.getValueType() && "Expected operands to be the same type");
8368   assert(VT.isInteger() && "Expected operands to be integers");
8369 
8370   // usub.sat(a, b) -> umax(a, b) - b
8371   if (Opcode == ISD::USUBSAT && isOperationLegal(ISD::UMAX, VT)) {
8372     SDValue Max = DAG.getNode(ISD::UMAX, dl, VT, LHS, RHS);
8373     return DAG.getNode(ISD::SUB, dl, VT, Max, RHS);
8374   }
8375 
8376   // uadd.sat(a, b) -> umin(a, ~b) + b
8377   if (Opcode == ISD::UADDSAT && isOperationLegal(ISD::UMIN, VT)) {
8378     SDValue InvRHS = DAG.getNOT(dl, RHS, VT);
8379     SDValue Min = DAG.getNode(ISD::UMIN, dl, VT, LHS, InvRHS);
8380     return DAG.getNode(ISD::ADD, dl, VT, Min, RHS);
8381   }
8382 
8383   unsigned OverflowOp;
8384   switch (Opcode) {
8385   case ISD::SADDSAT:
8386     OverflowOp = ISD::SADDO;
8387     break;
8388   case ISD::UADDSAT:
8389     OverflowOp = ISD::UADDO;
8390     break;
8391   case ISD::SSUBSAT:
8392     OverflowOp = ISD::SSUBO;
8393     break;
8394   case ISD::USUBSAT:
8395     OverflowOp = ISD::USUBO;
8396     break;
8397   default:
8398     llvm_unreachable("Expected method to receive signed or unsigned saturation "
8399                      "addition or subtraction node.");
8400   }
8401 
8402   // FIXME: Should really try to split the vector in case it's legal on a
8403   // subvector.
8404   if (VT.isVector() && !isOperationLegalOrCustom(ISD::VSELECT, VT))
8405     return DAG.UnrollVectorOp(Node);
8406 
8407   unsigned BitWidth = LHS.getScalarValueSizeInBits();
8408   EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
8409   SDValue Result = DAG.getNode(OverflowOp, dl, DAG.getVTList(VT, BoolVT), LHS, RHS);
8410   SDValue SumDiff = Result.getValue(0);
8411   SDValue Overflow = Result.getValue(1);
8412   SDValue Zero = DAG.getConstant(0, dl, VT);
8413   SDValue AllOnes = DAG.getAllOnesConstant(dl, VT);
8414 
8415   if (Opcode == ISD::UADDSAT) {
8416     if (getBooleanContents(VT) == ZeroOrNegativeOneBooleanContent) {
8417       // (LHS + RHS) | OverflowMask
8418       SDValue OverflowMask = DAG.getSExtOrTrunc(Overflow, dl, VT);
8419       return DAG.getNode(ISD::OR, dl, VT, SumDiff, OverflowMask);
8420     }
8421     // Overflow ? 0xffff.... : (LHS + RHS)
8422     return DAG.getSelect(dl, VT, Overflow, AllOnes, SumDiff);
8423   }
8424 
8425   if (Opcode == ISD::USUBSAT) {
8426     if (getBooleanContents(VT) == ZeroOrNegativeOneBooleanContent) {
8427       // (LHS - RHS) & ~OverflowMask
8428       SDValue OverflowMask = DAG.getSExtOrTrunc(Overflow, dl, VT);
8429       SDValue Not = DAG.getNOT(dl, OverflowMask, VT);
8430       return DAG.getNode(ISD::AND, dl, VT, SumDiff, Not);
8431     }
8432     // Overflow ? 0 : (LHS - RHS)
8433     return DAG.getSelect(dl, VT, Overflow, Zero, SumDiff);
8434   }
8435 
8436   // Overflow ? (SumDiff >> BW) ^ MinVal : SumDiff
8437   APInt MinVal = APInt::getSignedMinValue(BitWidth);
8438   SDValue SatMin = DAG.getConstant(MinVal, dl, VT);
8439   SDValue Shift = DAG.getNode(ISD::SRA, dl, VT, SumDiff,
8440                               DAG.getConstant(BitWidth - 1, dl, VT));
8441   Result = DAG.getNode(ISD::XOR, dl, VT, Shift, SatMin);
8442   return DAG.getSelect(dl, VT, Overflow, Result, SumDiff);
8443 }
8444 
8445 SDValue TargetLowering::expandShlSat(SDNode *Node, SelectionDAG &DAG) const {
8446   unsigned Opcode = Node->getOpcode();
8447   bool IsSigned = Opcode == ISD::SSHLSAT;
8448   SDValue LHS = Node->getOperand(0);
8449   SDValue RHS = Node->getOperand(1);
8450   EVT VT = LHS.getValueType();
8451   SDLoc dl(Node);
8452 
8453   assert((Node->getOpcode() == ISD::SSHLSAT ||
8454           Node->getOpcode() == ISD::USHLSAT) &&
8455           "Expected a SHLSAT opcode");
8456   assert(VT == RHS.getValueType() && "Expected operands to be the same type");
8457   assert(VT.isInteger() && "Expected operands to be integers");
8458 
8459   // If LHS != (LHS << RHS) >> RHS, we have overflow and must saturate.
8460 
8461   unsigned BW = VT.getScalarSizeInBits();
8462   SDValue Result = DAG.getNode(ISD::SHL, dl, VT, LHS, RHS);
8463   SDValue Orig =
8464       DAG.getNode(IsSigned ? ISD::SRA : ISD::SRL, dl, VT, Result, RHS);
8465 
8466   SDValue SatVal;
8467   if (IsSigned) {
8468     SDValue SatMin = DAG.getConstant(APInt::getSignedMinValue(BW), dl, VT);
8469     SDValue SatMax = DAG.getConstant(APInt::getSignedMaxValue(BW), dl, VT);
8470     SatVal = DAG.getSelectCC(dl, LHS, DAG.getConstant(0, dl, VT),
8471                              SatMin, SatMax, ISD::SETLT);
8472   } else {
8473     SatVal = DAG.getConstant(APInt::getMaxValue(BW), dl, VT);
8474   }
8475   Result = DAG.getSelectCC(dl, LHS, Orig, SatVal, Result, ISD::SETNE);
8476 
8477   return Result;
8478 }
8479 
8480 SDValue
8481 TargetLowering::expandFixedPointMul(SDNode *Node, SelectionDAG &DAG) const {
8482   assert((Node->getOpcode() == ISD::SMULFIX ||
8483           Node->getOpcode() == ISD::UMULFIX ||
8484           Node->getOpcode() == ISD::SMULFIXSAT ||
8485           Node->getOpcode() == ISD::UMULFIXSAT) &&
8486          "Expected a fixed point multiplication opcode");
8487 
8488   SDLoc dl(Node);
8489   SDValue LHS = Node->getOperand(0);
8490   SDValue RHS = Node->getOperand(1);
8491   EVT VT = LHS.getValueType();
8492   unsigned Scale = Node->getConstantOperandVal(2);
8493   bool Saturating = (Node->getOpcode() == ISD::SMULFIXSAT ||
8494                      Node->getOpcode() == ISD::UMULFIXSAT);
8495   bool Signed = (Node->getOpcode() == ISD::SMULFIX ||
8496                  Node->getOpcode() == ISD::SMULFIXSAT);
8497   EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
8498   unsigned VTSize = VT.getScalarSizeInBits();
8499 
8500   if (!Scale) {
8501     // [us]mul.fix(a, b, 0) -> mul(a, b)
8502     if (!Saturating) {
8503       if (isOperationLegalOrCustom(ISD::MUL, VT))
8504         return DAG.getNode(ISD::MUL, dl, VT, LHS, RHS);
8505     } else if (Signed && isOperationLegalOrCustom(ISD::SMULO, VT)) {
8506       SDValue Result =
8507           DAG.getNode(ISD::SMULO, dl, DAG.getVTList(VT, BoolVT), LHS, RHS);
8508       SDValue Product = Result.getValue(0);
8509       SDValue Overflow = Result.getValue(1);
8510       SDValue Zero = DAG.getConstant(0, dl, VT);
8511 
8512       APInt MinVal = APInt::getSignedMinValue(VTSize);
8513       APInt MaxVal = APInt::getSignedMaxValue(VTSize);
8514       SDValue SatMin = DAG.getConstant(MinVal, dl, VT);
8515       SDValue SatMax = DAG.getConstant(MaxVal, dl, VT);
8516       // Xor the inputs, if resulting sign bit is 0 the product will be
8517       // positive, else negative.
8518       SDValue Xor = DAG.getNode(ISD::XOR, dl, VT, LHS, RHS);
8519       SDValue ProdNeg = DAG.getSetCC(dl, BoolVT, Xor, Zero, ISD::SETLT);
8520       Result = DAG.getSelect(dl, VT, ProdNeg, SatMin, SatMax);
8521       return DAG.getSelect(dl, VT, Overflow, Result, Product);
8522     } else if (!Signed && isOperationLegalOrCustom(ISD::UMULO, VT)) {
8523       SDValue Result =
8524           DAG.getNode(ISD::UMULO, dl, DAG.getVTList(VT, BoolVT), LHS, RHS);
8525       SDValue Product = Result.getValue(0);
8526       SDValue Overflow = Result.getValue(1);
8527 
8528       APInt MaxVal = APInt::getMaxValue(VTSize);
8529       SDValue SatMax = DAG.getConstant(MaxVal, dl, VT);
8530       return DAG.getSelect(dl, VT, Overflow, SatMax, Product);
8531     }
8532   }
8533 
8534   assert(((Signed && Scale < VTSize) || (!Signed && Scale <= VTSize)) &&
8535          "Expected scale to be less than the number of bits if signed or at "
8536          "most the number of bits if unsigned.");
8537   assert(LHS.getValueType() == RHS.getValueType() &&
8538          "Expected both operands to be the same type");
8539 
8540   // Get the upper and lower bits of the result.
8541   SDValue Lo, Hi;
8542   unsigned LoHiOp = Signed ? ISD::SMUL_LOHI : ISD::UMUL_LOHI;
8543   unsigned HiOp = Signed ? ISD::MULHS : ISD::MULHU;
8544   if (isOperationLegalOrCustom(LoHiOp, VT)) {
8545     SDValue Result = DAG.getNode(LoHiOp, dl, DAG.getVTList(VT, VT), LHS, RHS);
8546     Lo = Result.getValue(0);
8547     Hi = Result.getValue(1);
8548   } else if (isOperationLegalOrCustom(HiOp, VT)) {
8549     Lo = DAG.getNode(ISD::MUL, dl, VT, LHS, RHS);
8550     Hi = DAG.getNode(HiOp, dl, VT, LHS, RHS);
8551   } else if (VT.isVector()) {
8552     return SDValue();
8553   } else {
8554     report_fatal_error("Unable to expand fixed point multiplication.");
8555   }
8556 
8557   if (Scale == VTSize)
8558     // Result is just the top half since we'd be shifting by the width of the
8559     // operand. Overflow impossible so this works for both UMULFIX and
8560     // UMULFIXSAT.
8561     return Hi;
8562 
8563   // The result will need to be shifted right by the scale since both operands
8564   // are scaled. The result is given to us in 2 halves, so we only want part of
8565   // both in the result.
8566   EVT ShiftTy = getShiftAmountTy(VT, DAG.getDataLayout());
8567   SDValue Result = DAG.getNode(ISD::FSHR, dl, VT, Hi, Lo,
8568                                DAG.getConstant(Scale, dl, ShiftTy));
8569   if (!Saturating)
8570     return Result;
8571 
8572   if (!Signed) {
8573     // Unsigned overflow happened if the upper (VTSize - Scale) bits (of the
8574     // widened multiplication) aren't all zeroes.
8575 
8576     // Saturate to max if ((Hi >> Scale) != 0),
8577     // which is the same as if (Hi > ((1 << Scale) - 1))
8578     APInt MaxVal = APInt::getMaxValue(VTSize);
8579     SDValue LowMask = DAG.getConstant(APInt::getLowBitsSet(VTSize, Scale),
8580                                       dl, VT);
8581     Result = DAG.getSelectCC(dl, Hi, LowMask,
8582                              DAG.getConstant(MaxVal, dl, VT), Result,
8583                              ISD::SETUGT);
8584 
8585     return Result;
8586   }
8587 
8588   // Signed overflow happened if the upper (VTSize - Scale + 1) bits (of the
8589   // widened multiplication) aren't all ones or all zeroes.
8590 
8591   SDValue SatMin = DAG.getConstant(APInt::getSignedMinValue(VTSize), dl, VT);
8592   SDValue SatMax = DAG.getConstant(APInt::getSignedMaxValue(VTSize), dl, VT);
8593 
8594   if (Scale == 0) {
8595     SDValue Sign = DAG.getNode(ISD::SRA, dl, VT, Lo,
8596                                DAG.getConstant(VTSize - 1, dl, ShiftTy));
8597     SDValue Overflow = DAG.getSetCC(dl, BoolVT, Hi, Sign, ISD::SETNE);
8598     // Saturated to SatMin if wide product is negative, and SatMax if wide
8599     // product is positive ...
8600     SDValue Zero = DAG.getConstant(0, dl, VT);
8601     SDValue ResultIfOverflow = DAG.getSelectCC(dl, Hi, Zero, SatMin, SatMax,
8602                                                ISD::SETLT);
8603     // ... but only if we overflowed.
8604     return DAG.getSelect(dl, VT, Overflow, ResultIfOverflow, Result);
8605   }
8606 
8607   //  We handled Scale==0 above so all the bits to examine is in Hi.
8608 
8609   // Saturate to max if ((Hi >> (Scale - 1)) > 0),
8610   // which is the same as if (Hi > (1 << (Scale - 1)) - 1)
8611   SDValue LowMask = DAG.getConstant(APInt::getLowBitsSet(VTSize, Scale - 1),
8612                                     dl, VT);
8613   Result = DAG.getSelectCC(dl, Hi, LowMask, SatMax, Result, ISD::SETGT);
8614   // Saturate to min if (Hi >> (Scale - 1)) < -1),
8615   // which is the same as if (HI < (-1 << (Scale - 1))
8616   SDValue HighMask =
8617       DAG.getConstant(APInt::getHighBitsSet(VTSize, VTSize - Scale + 1),
8618                       dl, VT);
8619   Result = DAG.getSelectCC(dl, Hi, HighMask, SatMin, Result, ISD::SETLT);
8620   return Result;
8621 }
8622 
8623 SDValue
8624 TargetLowering::expandFixedPointDiv(unsigned Opcode, const SDLoc &dl,
8625                                     SDValue LHS, SDValue RHS,
8626                                     unsigned Scale, SelectionDAG &DAG) const {
8627   assert((Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT ||
8628           Opcode == ISD::UDIVFIX || Opcode == ISD::UDIVFIXSAT) &&
8629          "Expected a fixed point division opcode");
8630 
8631   EVT VT = LHS.getValueType();
8632   bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT;
8633   bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT;
8634   EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
8635 
8636   // If there is enough room in the type to upscale the LHS or downscale the
8637   // RHS before the division, we can perform it in this type without having to
8638   // resize. For signed operations, the LHS headroom is the number of
8639   // redundant sign bits, and for unsigned ones it is the number of zeroes.
8640   // The headroom for the RHS is the number of trailing zeroes.
8641   unsigned LHSLead = Signed ? DAG.ComputeNumSignBits(LHS) - 1
8642                             : DAG.computeKnownBits(LHS).countMinLeadingZeros();
8643   unsigned RHSTrail = DAG.computeKnownBits(RHS).countMinTrailingZeros();
8644 
8645   // For signed saturating operations, we need to be able to detect true integer
8646   // division overflow; that is, when you have MIN / -EPS. However, this
8647   // is undefined behavior and if we emit divisions that could take such
8648   // values it may cause undesired behavior (arithmetic exceptions on x86, for
8649   // example).
8650   // Avoid this by requiring an extra bit so that we never get this case.
8651   // FIXME: This is a bit unfortunate as it means that for an 8-bit 7-scale
8652   // signed saturating division, we need to emit a whopping 32-bit division.
8653   if (LHSLead + RHSTrail < Scale + (unsigned)(Saturating && Signed))
8654     return SDValue();
8655 
8656   unsigned LHSShift = std::min(LHSLead, Scale);
8657   unsigned RHSShift = Scale - LHSShift;
8658 
8659   // At this point, we know that if we shift the LHS up by LHSShift and the
8660   // RHS down by RHSShift, we can emit a regular division with a final scaling
8661   // factor of Scale.
8662 
8663   EVT ShiftTy = getShiftAmountTy(VT, DAG.getDataLayout());
8664   if (LHSShift)
8665     LHS = DAG.getNode(ISD::SHL, dl, VT, LHS,
8666                       DAG.getConstant(LHSShift, dl, ShiftTy));
8667   if (RHSShift)
8668     RHS = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, dl, VT, RHS,
8669                       DAG.getConstant(RHSShift, dl, ShiftTy));
8670 
8671   SDValue Quot;
8672   if (Signed) {
8673     // For signed operations, if the resulting quotient is negative and the
8674     // remainder is nonzero, subtract 1 from the quotient to round towards
8675     // negative infinity.
8676     SDValue Rem;
8677     // FIXME: Ideally we would always produce an SDIVREM here, but if the
8678     // type isn't legal, SDIVREM cannot be expanded. There is no reason why
8679     // we couldn't just form a libcall, but the type legalizer doesn't do it.
8680     if (isTypeLegal(VT) &&
8681         isOperationLegalOrCustom(ISD::SDIVREM, VT)) {
8682       Quot = DAG.getNode(ISD::SDIVREM, dl,
8683                          DAG.getVTList(VT, VT),
8684                          LHS, RHS);
8685       Rem = Quot.getValue(1);
8686       Quot = Quot.getValue(0);
8687     } else {
8688       Quot = DAG.getNode(ISD::SDIV, dl, VT,
8689                          LHS, RHS);
8690       Rem = DAG.getNode(ISD::SREM, dl, VT,
8691                         LHS, RHS);
8692     }
8693     SDValue Zero = DAG.getConstant(0, dl, VT);
8694     SDValue RemNonZero = DAG.getSetCC(dl, BoolVT, Rem, Zero, ISD::SETNE);
8695     SDValue LHSNeg = DAG.getSetCC(dl, BoolVT, LHS, Zero, ISD::SETLT);
8696     SDValue RHSNeg = DAG.getSetCC(dl, BoolVT, RHS, Zero, ISD::SETLT);
8697     SDValue QuotNeg = DAG.getNode(ISD::XOR, dl, BoolVT, LHSNeg, RHSNeg);
8698     SDValue Sub1 = DAG.getNode(ISD::SUB, dl, VT, Quot,
8699                                DAG.getConstant(1, dl, VT));
8700     Quot = DAG.getSelect(dl, VT,
8701                          DAG.getNode(ISD::AND, dl, BoolVT, RemNonZero, QuotNeg),
8702                          Sub1, Quot);
8703   } else
8704     Quot = DAG.getNode(ISD::UDIV, dl, VT,
8705                        LHS, RHS);
8706 
8707   return Quot;
8708 }
8709 
8710 void TargetLowering::expandUADDSUBO(
8711     SDNode *Node, SDValue &Result, SDValue &Overflow, SelectionDAG &DAG) const {
8712   SDLoc dl(Node);
8713   SDValue LHS = Node->getOperand(0);
8714   SDValue RHS = Node->getOperand(1);
8715   bool IsAdd = Node->getOpcode() == ISD::UADDO;
8716 
8717   // If ADD/SUBCARRY is legal, use that instead.
8718   unsigned OpcCarry = IsAdd ? ISD::ADDCARRY : ISD::SUBCARRY;
8719   if (isOperationLegalOrCustom(OpcCarry, Node->getValueType(0))) {
8720     SDValue CarryIn = DAG.getConstant(0, dl, Node->getValueType(1));
8721     SDValue NodeCarry = DAG.getNode(OpcCarry, dl, Node->getVTList(),
8722                                     { LHS, RHS, CarryIn });
8723     Result = SDValue(NodeCarry.getNode(), 0);
8724     Overflow = SDValue(NodeCarry.getNode(), 1);
8725     return;
8726   }
8727 
8728   Result = DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, dl,
8729                             LHS.getValueType(), LHS, RHS);
8730 
8731   EVT ResultType = Node->getValueType(1);
8732   EVT SetCCType = getSetCCResultType(
8733       DAG.getDataLayout(), *DAG.getContext(), Node->getValueType(0));
8734   SDValue SetCC;
8735   if (IsAdd && isOneConstant(RHS)) {
8736     // Special case: uaddo X, 1 overflowed if X+1 is 0. This potential reduces
8737     // the live range of X. We assume comparing with 0 is cheap.
8738     // TODO: This generalizes to (X + C) < C.
8739     SetCC =
8740         DAG.getSetCC(dl, SetCCType, Result,
8741                      DAG.getConstant(0, dl, Node->getValueType(0)), ISD::SETEQ);
8742   } else {
8743     ISD::CondCode CC = IsAdd ? ISD::SETULT : ISD::SETUGT;
8744     SetCC = DAG.getSetCC(dl, SetCCType, Result, LHS, CC);
8745   }
8746   Overflow = DAG.getBoolExtOrTrunc(SetCC, dl, ResultType, ResultType);
8747 }
8748 
8749 void TargetLowering::expandSADDSUBO(
8750     SDNode *Node, SDValue &Result, SDValue &Overflow, SelectionDAG &DAG) const {
8751   SDLoc dl(Node);
8752   SDValue LHS = Node->getOperand(0);
8753   SDValue RHS = Node->getOperand(1);
8754   bool IsAdd = Node->getOpcode() == ISD::SADDO;
8755 
8756   Result = DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, dl,
8757                             LHS.getValueType(), LHS, RHS);
8758 
8759   EVT ResultType = Node->getValueType(1);
8760   EVT OType = getSetCCResultType(
8761       DAG.getDataLayout(), *DAG.getContext(), Node->getValueType(0));
8762 
8763   // If SADDSAT/SSUBSAT is legal, compare results to detect overflow.
8764   unsigned OpcSat = IsAdd ? ISD::SADDSAT : ISD::SSUBSAT;
8765   if (isOperationLegal(OpcSat, LHS.getValueType())) {
8766     SDValue Sat = DAG.getNode(OpcSat, dl, LHS.getValueType(), LHS, RHS);
8767     SDValue SetCC = DAG.getSetCC(dl, OType, Result, Sat, ISD::SETNE);
8768     Overflow = DAG.getBoolExtOrTrunc(SetCC, dl, ResultType, ResultType);
8769     return;
8770   }
8771 
8772   SDValue Zero = DAG.getConstant(0, dl, LHS.getValueType());
8773 
8774   // For an addition, the result should be less than one of the operands (LHS)
8775   // if and only if the other operand (RHS) is negative, otherwise there will
8776   // be overflow.
8777   // For a subtraction, the result should be less than one of the operands
8778   // (LHS) if and only if the other operand (RHS) is (non-zero) positive,
8779   // otherwise there will be overflow.
8780   SDValue ResultLowerThanLHS = DAG.getSetCC(dl, OType, Result, LHS, ISD::SETLT);
8781   SDValue ConditionRHS =
8782       DAG.getSetCC(dl, OType, RHS, Zero, IsAdd ? ISD::SETLT : ISD::SETGT);
8783 
8784   Overflow = DAG.getBoolExtOrTrunc(
8785       DAG.getNode(ISD::XOR, dl, OType, ConditionRHS, ResultLowerThanLHS), dl,
8786       ResultType, ResultType);
8787 }
8788 
8789 bool TargetLowering::expandMULO(SDNode *Node, SDValue &Result,
8790                                 SDValue &Overflow, SelectionDAG &DAG) const {
8791   SDLoc dl(Node);
8792   EVT VT = Node->getValueType(0);
8793   EVT SetCCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
8794   SDValue LHS = Node->getOperand(0);
8795   SDValue RHS = Node->getOperand(1);
8796   bool isSigned = Node->getOpcode() == ISD::SMULO;
8797 
8798   // For power-of-two multiplications we can use a simpler shift expansion.
8799   if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) {
8800     const APInt &C = RHSC->getAPIntValue();
8801     // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X }
8802     if (C.isPowerOf2()) {
8803       // smulo(x, signed_min) is same as umulo(x, signed_min).
8804       bool UseArithShift = isSigned && !C.isMinSignedValue();
8805       EVT ShiftAmtTy = getShiftAmountTy(VT, DAG.getDataLayout());
8806       SDValue ShiftAmt = DAG.getConstant(C.logBase2(), dl, ShiftAmtTy);
8807       Result = DAG.getNode(ISD::SHL, dl, VT, LHS, ShiftAmt);
8808       Overflow = DAG.getSetCC(dl, SetCCVT,
8809           DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL,
8810                       dl, VT, Result, ShiftAmt),
8811           LHS, ISD::SETNE);
8812       return true;
8813     }
8814   }
8815 
8816   EVT WideVT = EVT::getIntegerVT(*DAG.getContext(), VT.getScalarSizeInBits() * 2);
8817   if (VT.isVector())
8818     WideVT =
8819         EVT::getVectorVT(*DAG.getContext(), WideVT, VT.getVectorElementCount());
8820 
8821   SDValue BottomHalf;
8822   SDValue TopHalf;
8823   static const unsigned Ops[2][3] =
8824       { { ISD::MULHU, ISD::UMUL_LOHI, ISD::ZERO_EXTEND },
8825         { ISD::MULHS, ISD::SMUL_LOHI, ISD::SIGN_EXTEND }};
8826   if (isOperationLegalOrCustom(Ops[isSigned][0], VT)) {
8827     BottomHalf = DAG.getNode(ISD::MUL, dl, VT, LHS, RHS);
8828     TopHalf = DAG.getNode(Ops[isSigned][0], dl, VT, LHS, RHS);
8829   } else if (isOperationLegalOrCustom(Ops[isSigned][1], VT)) {
8830     BottomHalf = DAG.getNode(Ops[isSigned][1], dl, DAG.getVTList(VT, VT), LHS,
8831                              RHS);
8832     TopHalf = BottomHalf.getValue(1);
8833   } else if (isTypeLegal(WideVT)) {
8834     LHS = DAG.getNode(Ops[isSigned][2], dl, WideVT, LHS);
8835     RHS = DAG.getNode(Ops[isSigned][2], dl, WideVT, RHS);
8836     SDValue Mul = DAG.getNode(ISD::MUL, dl, WideVT, LHS, RHS);
8837     BottomHalf = DAG.getNode(ISD::TRUNCATE, dl, VT, Mul);
8838     SDValue ShiftAmt = DAG.getConstant(VT.getScalarSizeInBits(), dl,
8839         getShiftAmountTy(WideVT, DAG.getDataLayout()));
8840     TopHalf = DAG.getNode(ISD::TRUNCATE, dl, VT,
8841                           DAG.getNode(ISD::SRL, dl, WideVT, Mul, ShiftAmt));
8842   } else {
8843     if (VT.isVector())
8844       return false;
8845 
8846     // We can fall back to a libcall with an illegal type for the MUL if we
8847     // have a libcall big enough.
8848     // Also, we can fall back to a division in some cases, but that's a big
8849     // performance hit in the general case.
8850     RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
8851     if (WideVT == MVT::i16)
8852       LC = RTLIB::MUL_I16;
8853     else if (WideVT == MVT::i32)
8854       LC = RTLIB::MUL_I32;
8855     else if (WideVT == MVT::i64)
8856       LC = RTLIB::MUL_I64;
8857     else if (WideVT == MVT::i128)
8858       LC = RTLIB::MUL_I128;
8859     assert(LC != RTLIB::UNKNOWN_LIBCALL && "Cannot expand this operation!");
8860 
8861     SDValue HiLHS;
8862     SDValue HiRHS;
8863     if (isSigned) {
8864       // The high part is obtained by SRA'ing all but one of the bits of low
8865       // part.
8866       unsigned LoSize = VT.getFixedSizeInBits();
8867       HiLHS =
8868           DAG.getNode(ISD::SRA, dl, VT, LHS,
8869                       DAG.getConstant(LoSize - 1, dl,
8870                                       getPointerTy(DAG.getDataLayout())));
8871       HiRHS =
8872           DAG.getNode(ISD::SRA, dl, VT, RHS,
8873                       DAG.getConstant(LoSize - 1, dl,
8874                                       getPointerTy(DAG.getDataLayout())));
8875     } else {
8876         HiLHS = DAG.getConstant(0, dl, VT);
8877         HiRHS = DAG.getConstant(0, dl, VT);
8878     }
8879 
8880     // Here we're passing the 2 arguments explicitly as 4 arguments that are
8881     // pre-lowered to the correct types. This all depends upon WideVT not
8882     // being a legal type for the architecture and thus has to be split to
8883     // two arguments.
8884     SDValue Ret;
8885     TargetLowering::MakeLibCallOptions CallOptions;
8886     CallOptions.setSExt(isSigned);
8887     CallOptions.setIsPostTypeLegalization(true);
8888     if (shouldSplitFunctionArgumentsAsLittleEndian(DAG.getDataLayout())) {
8889       // Halves of WideVT are packed into registers in different order
8890       // depending on platform endianness. This is usually handled by
8891       // the C calling convention, but we can't defer to it in
8892       // the legalizer.
8893       SDValue Args[] = { LHS, HiLHS, RHS, HiRHS };
8894       Ret = makeLibCall(DAG, LC, WideVT, Args, CallOptions, dl).first;
8895     } else {
8896       SDValue Args[] = { HiLHS, LHS, HiRHS, RHS };
8897       Ret = makeLibCall(DAG, LC, WideVT, Args, CallOptions, dl).first;
8898     }
8899     assert(Ret.getOpcode() == ISD::MERGE_VALUES &&
8900            "Ret value is a collection of constituent nodes holding result.");
8901     if (DAG.getDataLayout().isLittleEndian()) {
8902       // Same as above.
8903       BottomHalf = Ret.getOperand(0);
8904       TopHalf = Ret.getOperand(1);
8905     } else {
8906       BottomHalf = Ret.getOperand(1);
8907       TopHalf = Ret.getOperand(0);
8908     }
8909   }
8910 
8911   Result = BottomHalf;
8912   if (isSigned) {
8913     SDValue ShiftAmt = DAG.getConstant(
8914         VT.getScalarSizeInBits() - 1, dl,
8915         getShiftAmountTy(BottomHalf.getValueType(), DAG.getDataLayout()));
8916     SDValue Sign = DAG.getNode(ISD::SRA, dl, VT, BottomHalf, ShiftAmt);
8917     Overflow = DAG.getSetCC(dl, SetCCVT, TopHalf, Sign, ISD::SETNE);
8918   } else {
8919     Overflow = DAG.getSetCC(dl, SetCCVT, TopHalf,
8920                             DAG.getConstant(0, dl, VT), ISD::SETNE);
8921   }
8922 
8923   // Truncate the result if SetCC returns a larger type than needed.
8924   EVT RType = Node->getValueType(1);
8925   if (RType.bitsLT(Overflow.getValueType()))
8926     Overflow = DAG.getNode(ISD::TRUNCATE, dl, RType, Overflow);
8927 
8928   assert(RType.getSizeInBits() == Overflow.getValueSizeInBits() &&
8929          "Unexpected result type for S/UMULO legalization");
8930   return true;
8931 }
8932 
8933 SDValue TargetLowering::expandVecReduce(SDNode *Node, SelectionDAG &DAG) const {
8934   SDLoc dl(Node);
8935   unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Node->getOpcode());
8936   SDValue Op = Node->getOperand(0);
8937   EVT VT = Op.getValueType();
8938 
8939   if (VT.isScalableVector())
8940     report_fatal_error(
8941         "Expanding reductions for scalable vectors is undefined.");
8942 
8943   // Try to use a shuffle reduction for power of two vectors.
8944   if (VT.isPow2VectorType()) {
8945     while (VT.getVectorNumElements() > 1) {
8946       EVT HalfVT = VT.getHalfNumVectorElementsVT(*DAG.getContext());
8947       if (!isOperationLegalOrCustom(BaseOpcode, HalfVT))
8948         break;
8949 
8950       SDValue Lo, Hi;
8951       std::tie(Lo, Hi) = DAG.SplitVector(Op, dl);
8952       Op = DAG.getNode(BaseOpcode, dl, HalfVT, Lo, Hi);
8953       VT = HalfVT;
8954     }
8955   }
8956 
8957   EVT EltVT = VT.getVectorElementType();
8958   unsigned NumElts = VT.getVectorNumElements();
8959 
8960   SmallVector<SDValue, 8> Ops;
8961   DAG.ExtractVectorElements(Op, Ops, 0, NumElts);
8962 
8963   SDValue Res = Ops[0];
8964   for (unsigned i = 1; i < NumElts; i++)
8965     Res = DAG.getNode(BaseOpcode, dl, EltVT, Res, Ops[i], Node->getFlags());
8966 
8967   // Result type may be wider than element type.
8968   if (EltVT != Node->getValueType(0))
8969     Res = DAG.getNode(ISD::ANY_EXTEND, dl, Node->getValueType(0), Res);
8970   return Res;
8971 }
8972 
8973 SDValue TargetLowering::expandVecReduceSeq(SDNode *Node, SelectionDAG &DAG) const {
8974   SDLoc dl(Node);
8975   SDValue AccOp = Node->getOperand(0);
8976   SDValue VecOp = Node->getOperand(1);
8977   SDNodeFlags Flags = Node->getFlags();
8978 
8979   EVT VT = VecOp.getValueType();
8980   EVT EltVT = VT.getVectorElementType();
8981 
8982   if (VT.isScalableVector())
8983     report_fatal_error(
8984         "Expanding reductions for scalable vectors is undefined.");
8985 
8986   unsigned NumElts = VT.getVectorNumElements();
8987 
8988   SmallVector<SDValue, 8> Ops;
8989   DAG.ExtractVectorElements(VecOp, Ops, 0, NumElts);
8990 
8991   unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Node->getOpcode());
8992 
8993   SDValue Res = AccOp;
8994   for (unsigned i = 0; i < NumElts; i++)
8995     Res = DAG.getNode(BaseOpcode, dl, EltVT, Res, Ops[i], Flags);
8996 
8997   return Res;
8998 }
8999 
9000 bool TargetLowering::expandREM(SDNode *Node, SDValue &Result,
9001                                SelectionDAG &DAG) const {
9002   EVT VT = Node->getValueType(0);
9003   SDLoc dl(Node);
9004   bool isSigned = Node->getOpcode() == ISD::SREM;
9005   unsigned DivOpc = isSigned ? ISD::SDIV : ISD::UDIV;
9006   unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
9007   SDValue Dividend = Node->getOperand(0);
9008   SDValue Divisor = Node->getOperand(1);
9009   if (isOperationLegalOrCustom(DivRemOpc, VT)) {
9010     SDVTList VTs = DAG.getVTList(VT, VT);
9011     Result = DAG.getNode(DivRemOpc, dl, VTs, Dividend, Divisor).getValue(1);
9012     return true;
9013   }
9014   if (isOperationLegalOrCustom(DivOpc, VT)) {
9015     // X % Y -> X-X/Y*Y
9016     SDValue Divide = DAG.getNode(DivOpc, dl, VT, Dividend, Divisor);
9017     SDValue Mul = DAG.getNode(ISD::MUL, dl, VT, Divide, Divisor);
9018     Result = DAG.getNode(ISD::SUB, dl, VT, Dividend, Mul);
9019     return true;
9020   }
9021   return false;
9022 }
9023 
9024 SDValue TargetLowering::expandFP_TO_INT_SAT(SDNode *Node,
9025                                             SelectionDAG &DAG) const {
9026   bool IsSigned = Node->getOpcode() == ISD::FP_TO_SINT_SAT;
9027   SDLoc dl(SDValue(Node, 0));
9028   SDValue Src = Node->getOperand(0);
9029 
9030   // DstVT is the result type, while SatVT is the size to which we saturate
9031   EVT SrcVT = Src.getValueType();
9032   EVT DstVT = Node->getValueType(0);
9033 
9034   EVT SatVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
9035   unsigned SatWidth = SatVT.getScalarSizeInBits();
9036   unsigned DstWidth = DstVT.getScalarSizeInBits();
9037   assert(SatWidth <= DstWidth &&
9038          "Expected saturation width smaller than result width");
9039 
9040   // Determine minimum and maximum integer values and their corresponding
9041   // floating-point values.
9042   APInt MinInt, MaxInt;
9043   if (IsSigned) {
9044     MinInt = APInt::getSignedMinValue(SatWidth).sextOrSelf(DstWidth);
9045     MaxInt = APInt::getSignedMaxValue(SatWidth).sextOrSelf(DstWidth);
9046   } else {
9047     MinInt = APInt::getMinValue(SatWidth).zextOrSelf(DstWidth);
9048     MaxInt = APInt::getMaxValue(SatWidth).zextOrSelf(DstWidth);
9049   }
9050 
9051   // We cannot risk emitting FP_TO_XINT nodes with a source VT of f16, as
9052   // libcall emission cannot handle this. Large result types will fail.
9053   if (SrcVT == MVT::f16) {
9054     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, Src);
9055     SrcVT = Src.getValueType();
9056   }
9057 
9058   APFloat MinFloat(DAG.EVTToAPFloatSemantics(SrcVT));
9059   APFloat MaxFloat(DAG.EVTToAPFloatSemantics(SrcVT));
9060 
9061   APFloat::opStatus MinStatus =
9062       MinFloat.convertFromAPInt(MinInt, IsSigned, APFloat::rmTowardZero);
9063   APFloat::opStatus MaxStatus =
9064       MaxFloat.convertFromAPInt(MaxInt, IsSigned, APFloat::rmTowardZero);
9065   bool AreExactFloatBounds = !(MinStatus & APFloat::opStatus::opInexact) &&
9066                              !(MaxStatus & APFloat::opStatus::opInexact);
9067 
9068   SDValue MinFloatNode = DAG.getConstantFP(MinFloat, dl, SrcVT);
9069   SDValue MaxFloatNode = DAG.getConstantFP(MaxFloat, dl, SrcVT);
9070 
9071   // If the integer bounds are exactly representable as floats and min/max are
9072   // legal, emit a min+max+fptoi sequence. Otherwise we have to use a sequence
9073   // of comparisons and selects.
9074   bool MinMaxLegal = isOperationLegal(ISD::FMINNUM, SrcVT) &&
9075                      isOperationLegal(ISD::FMAXNUM, SrcVT);
9076   if (AreExactFloatBounds && MinMaxLegal) {
9077     SDValue Clamped = Src;
9078 
9079     // Clamp Src by MinFloat from below. If Src is NaN the result is MinFloat.
9080     Clamped = DAG.getNode(ISD::FMAXNUM, dl, SrcVT, Clamped, MinFloatNode);
9081     // Clamp by MaxFloat from above. NaN cannot occur.
9082     Clamped = DAG.getNode(ISD::FMINNUM, dl, SrcVT, Clamped, MaxFloatNode);
9083     // Convert clamped value to integer.
9084     SDValue FpToInt = DAG.getNode(IsSigned ? ISD::FP_TO_SINT : ISD::FP_TO_UINT,
9085                                   dl, DstVT, Clamped);
9086 
9087     // In the unsigned case we're done, because we mapped NaN to MinFloat,
9088     // which will cast to zero.
9089     if (!IsSigned)
9090       return FpToInt;
9091 
9092     // Otherwise, select 0 if Src is NaN.
9093     SDValue ZeroInt = DAG.getConstant(0, dl, DstVT);
9094     return DAG.getSelectCC(dl, Src, Src, ZeroInt, FpToInt,
9095                            ISD::CondCode::SETUO);
9096   }
9097 
9098   SDValue MinIntNode = DAG.getConstant(MinInt, dl, DstVT);
9099   SDValue MaxIntNode = DAG.getConstant(MaxInt, dl, DstVT);
9100 
9101   // Result of direct conversion. The assumption here is that the operation is
9102   // non-trapping and it's fine to apply it to an out-of-range value if we
9103   // select it away later.
9104   SDValue FpToInt =
9105       DAG.getNode(IsSigned ? ISD::FP_TO_SINT : ISD::FP_TO_UINT, dl, DstVT, Src);
9106 
9107   SDValue Select = FpToInt;
9108 
9109   // If Src ULT MinFloat, select MinInt. In particular, this also selects
9110   // MinInt if Src is NaN.
9111   Select = DAG.getSelectCC(dl, Src, MinFloatNode, MinIntNode, Select,
9112                            ISD::CondCode::SETULT);
9113   // If Src OGT MaxFloat, select MaxInt.
9114   Select = DAG.getSelectCC(dl, Src, MaxFloatNode, MaxIntNode, Select,
9115                            ISD::CondCode::SETOGT);
9116 
9117   // In the unsigned case we are done, because we mapped NaN to MinInt, which
9118   // is already zero.
9119   if (!IsSigned)
9120     return Select;
9121 
9122   // Otherwise, select 0 if Src is NaN.
9123   SDValue ZeroInt = DAG.getConstant(0, dl, DstVT);
9124   return DAG.getSelectCC(dl, Src, Src, ZeroInt, Select, ISD::CondCode::SETUO);
9125 }
9126 
9127 SDValue TargetLowering::expandVectorSplice(SDNode *Node,
9128                                            SelectionDAG &DAG) const {
9129   assert(Node->getOpcode() == ISD::VECTOR_SPLICE && "Unexpected opcode!");
9130   assert(Node->getValueType(0).isScalableVector() &&
9131          "Fixed length vector types expected to use SHUFFLE_VECTOR!");
9132 
9133   EVT VT = Node->getValueType(0);
9134   SDValue V1 = Node->getOperand(0);
9135   SDValue V2 = Node->getOperand(1);
9136   int64_t Imm = cast<ConstantSDNode>(Node->getOperand(2))->getSExtValue();
9137   SDLoc DL(Node);
9138 
9139   // Expand through memory thusly:
9140   //  Alloca CONCAT_VECTORS_TYPES(V1, V2) Ptr
9141   //  Store V1, Ptr
9142   //  Store V2, Ptr + sizeof(V1)
9143   //  If (Imm < 0)
9144   //    TrailingElts = -Imm
9145   //    Ptr = Ptr + sizeof(V1) - (TrailingElts * sizeof(VT.Elt))
9146   //  else
9147   //    Ptr = Ptr + (Imm * sizeof(VT.Elt))
9148   //  Res = Load Ptr
9149 
9150   Align Alignment = DAG.getReducedAlign(VT, /*UseABI=*/false);
9151 
9152   EVT MemVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
9153                                VT.getVectorElementCount() * 2);
9154   SDValue StackPtr = DAG.CreateStackTemporary(MemVT.getStoreSize(), Alignment);
9155   EVT PtrVT = StackPtr.getValueType();
9156   auto &MF = DAG.getMachineFunction();
9157   auto FrameIndex = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
9158   auto PtrInfo = MachinePointerInfo::getFixedStack(MF, FrameIndex);
9159 
9160   // Store the lo part of CONCAT_VECTORS(V1, V2)
9161   SDValue StoreV1 = DAG.getStore(DAG.getEntryNode(), DL, V1, StackPtr, PtrInfo);
9162   // Store the hi part of CONCAT_VECTORS(V1, V2)
9163   SDValue OffsetToV2 = DAG.getVScale(
9164       DL, PtrVT,
9165       APInt(PtrVT.getFixedSizeInBits(), VT.getStoreSize().getKnownMinSize()));
9166   SDValue StackPtr2 = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, OffsetToV2);
9167   SDValue StoreV2 = DAG.getStore(StoreV1, DL, V2, StackPtr2, PtrInfo);
9168 
9169   if (Imm >= 0) {
9170     // Load back the required element. getVectorElementPointer takes care of
9171     // clamping the index if it's out-of-bounds.
9172     StackPtr = getVectorElementPointer(DAG, StackPtr, VT, Node->getOperand(2));
9173     // Load the spliced result
9174     return DAG.getLoad(VT, DL, StoreV2, StackPtr,
9175                        MachinePointerInfo::getUnknownStack(MF));
9176   }
9177 
9178   uint64_t TrailingElts = -Imm;
9179 
9180   // NOTE: TrailingElts must be clamped so as not to read outside of V1:V2.
9181   TypeSize EltByteSize = VT.getVectorElementType().getStoreSize();
9182   SDValue TrailingBytes =
9183       DAG.getConstant(TrailingElts * EltByteSize, DL, PtrVT);
9184 
9185   if (TrailingElts > VT.getVectorMinNumElements()) {
9186     SDValue VLBytes = DAG.getVScale(
9187         DL, PtrVT,
9188         APInt(PtrVT.getFixedSizeInBits(), VT.getStoreSize().getKnownMinSize()));
9189     TrailingBytes = DAG.getNode(ISD::UMIN, DL, PtrVT, TrailingBytes, VLBytes);
9190   }
9191 
9192   // Calculate the start address of the spliced result.
9193   StackPtr2 = DAG.getNode(ISD::SUB, DL, PtrVT, StackPtr2, TrailingBytes);
9194 
9195   // Load the spliced result
9196   return DAG.getLoad(VT, DL, StoreV2, StackPtr2,
9197                      MachinePointerInfo::getUnknownStack(MF));
9198 }
9199 
9200 bool TargetLowering::LegalizeSetCCCondCode(SelectionDAG &DAG, EVT VT,
9201                                            SDValue &LHS, SDValue &RHS,
9202                                            SDValue &CC, SDValue Mask,
9203                                            SDValue EVL, bool &NeedInvert,
9204                                            const SDLoc &dl, SDValue &Chain,
9205                                            bool IsSignaling) const {
9206   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9207   MVT OpVT = LHS.getSimpleValueType();
9208   ISD::CondCode CCCode = cast<CondCodeSDNode>(CC)->get();
9209   NeedInvert = false;
9210   assert(!EVL == !Mask && "VP Mask and EVL must either both be set or unset");
9211   bool IsNonVP = !EVL;
9212   switch (TLI.getCondCodeAction(CCCode, OpVT)) {
9213   default:
9214     llvm_unreachable("Unknown condition code action!");
9215   case TargetLowering::Legal:
9216     // Nothing to do.
9217     break;
9218   case TargetLowering::Expand: {
9219     ISD::CondCode InvCC = ISD::getSetCCSwappedOperands(CCCode);
9220     if (TLI.isCondCodeLegalOrCustom(InvCC, OpVT)) {
9221       std::swap(LHS, RHS);
9222       CC = DAG.getCondCode(InvCC);
9223       return true;
9224     }
9225     // Swapping operands didn't work. Try inverting the condition.
9226     bool NeedSwap = false;
9227     InvCC = getSetCCInverse(CCCode, OpVT);
9228     if (!TLI.isCondCodeLegalOrCustom(InvCC, OpVT)) {
9229       // If inverting the condition is not enough, try swapping operands
9230       // on top of it.
9231       InvCC = ISD::getSetCCSwappedOperands(InvCC);
9232       NeedSwap = true;
9233     }
9234     if (TLI.isCondCodeLegalOrCustom(InvCC, OpVT)) {
9235       CC = DAG.getCondCode(InvCC);
9236       NeedInvert = true;
9237       if (NeedSwap)
9238         std::swap(LHS, RHS);
9239       return true;
9240     }
9241 
9242     ISD::CondCode CC1 = ISD::SETCC_INVALID, CC2 = ISD::SETCC_INVALID;
9243     unsigned Opc = 0;
9244     switch (CCCode) {
9245     default:
9246       llvm_unreachable("Don't know how to expand this condition!");
9247     case ISD::SETUO:
9248       if (TLI.isCondCodeLegal(ISD::SETUNE, OpVT)) {
9249         CC1 = ISD::SETUNE;
9250         CC2 = ISD::SETUNE;
9251         Opc = ISD::OR;
9252         break;
9253       }
9254       assert(TLI.isCondCodeLegal(ISD::SETOEQ, OpVT) &&
9255              "If SETUE is expanded, SETOEQ or SETUNE must be legal!");
9256       NeedInvert = true;
9257       LLVM_FALLTHROUGH;
9258     case ISD::SETO:
9259       assert(TLI.isCondCodeLegal(ISD::SETOEQ, OpVT) &&
9260              "If SETO is expanded, SETOEQ must be legal!");
9261       CC1 = ISD::SETOEQ;
9262       CC2 = ISD::SETOEQ;
9263       Opc = ISD::AND;
9264       break;
9265     case ISD::SETONE:
9266     case ISD::SETUEQ:
9267       // If the SETUO or SETO CC isn't legal, we might be able to use
9268       // SETOGT || SETOLT, inverting the result for SETUEQ. We only need one
9269       // of SETOGT/SETOLT to be legal, the other can be emulated by swapping
9270       // the operands.
9271       CC2 = ((unsigned)CCCode & 0x8U) ? ISD::SETUO : ISD::SETO;
9272       if (!TLI.isCondCodeLegal(CC2, OpVT) &&
9273           (TLI.isCondCodeLegal(ISD::SETOGT, OpVT) ||
9274            TLI.isCondCodeLegal(ISD::SETOLT, OpVT))) {
9275         CC1 = ISD::SETOGT;
9276         CC2 = ISD::SETOLT;
9277         Opc = ISD::OR;
9278         NeedInvert = ((unsigned)CCCode & 0x8U);
9279         break;
9280       }
9281       LLVM_FALLTHROUGH;
9282     case ISD::SETOEQ:
9283     case ISD::SETOGT:
9284     case ISD::SETOGE:
9285     case ISD::SETOLT:
9286     case ISD::SETOLE:
9287     case ISD::SETUNE:
9288     case ISD::SETUGT:
9289     case ISD::SETUGE:
9290     case ISD::SETULT:
9291     case ISD::SETULE:
9292       // If we are floating point, assign and break, otherwise fall through.
9293       if (!OpVT.isInteger()) {
9294         // We can use the 4th bit to tell if we are the unordered
9295         // or ordered version of the opcode.
9296         CC2 = ((unsigned)CCCode & 0x8U) ? ISD::SETUO : ISD::SETO;
9297         Opc = ((unsigned)CCCode & 0x8U) ? ISD::OR : ISD::AND;
9298         CC1 = (ISD::CondCode)(((int)CCCode & 0x7) | 0x10);
9299         break;
9300       }
9301       // Fallthrough if we are unsigned integer.
9302       LLVM_FALLTHROUGH;
9303     case ISD::SETLE:
9304     case ISD::SETGT:
9305     case ISD::SETGE:
9306     case ISD::SETLT:
9307     case ISD::SETNE:
9308     case ISD::SETEQ:
9309       // If all combinations of inverting the condition and swapping operands
9310       // didn't work then we have no means to expand the condition.
9311       llvm_unreachable("Don't know how to expand this condition!");
9312     }
9313 
9314     SDValue SetCC1, SetCC2;
9315     if (CCCode != ISD::SETO && CCCode != ISD::SETUO) {
9316       // If we aren't the ordered or unorder operation,
9317       // then the pattern is (LHS CC1 RHS) Opc (LHS CC2 RHS).
9318       if (IsNonVP) {
9319         SetCC1 = DAG.getSetCC(dl, VT, LHS, RHS, CC1, Chain, IsSignaling);
9320         SetCC2 = DAG.getSetCC(dl, VT, LHS, RHS, CC2, Chain, IsSignaling);
9321       } else {
9322         SetCC1 = DAG.getSetCCVP(dl, VT, LHS, RHS, CC1, Mask, EVL);
9323         SetCC2 = DAG.getSetCCVP(dl, VT, LHS, RHS, CC2, Mask, EVL);
9324       }
9325     } else {
9326       // Otherwise, the pattern is (LHS CC1 LHS) Opc (RHS CC2 RHS)
9327       if (IsNonVP) {
9328         SetCC1 = DAG.getSetCC(dl, VT, LHS, LHS, CC1, Chain, IsSignaling);
9329         SetCC2 = DAG.getSetCC(dl, VT, RHS, RHS, CC2, Chain, IsSignaling);
9330       } else {
9331         SetCC1 = DAG.getSetCCVP(dl, VT, LHS, LHS, CC1, Mask, EVL);
9332         SetCC2 = DAG.getSetCCVP(dl, VT, RHS, RHS, CC2, Mask, EVL);
9333       }
9334     }
9335     if (Chain)
9336       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, SetCC1.getValue(1),
9337                           SetCC2.getValue(1));
9338     if (IsNonVP)
9339       LHS = DAG.getNode(Opc, dl, VT, SetCC1, SetCC2);
9340     else {
9341       // Transform the binary opcode to the VP equivalent.
9342       assert((Opc == ISD::OR || Opc == ISD::AND) && "Unexpected opcode");
9343       Opc = Opc == ISD::OR ? ISD::VP_OR : ISD::VP_AND;
9344       LHS = DAG.getNode(Opc, dl, VT, SetCC1, SetCC2, Mask, EVL);
9345     }
9346     RHS = SDValue();
9347     CC = SDValue();
9348     return true;
9349   }
9350   }
9351   return false;
9352 }
9353